@crvouga/mockingbird-service-slack 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 +130 -0
- package/dist/chunk-H2VZTZFJ.js +354 -0
- package/dist/chunk-H2VZTZFJ.js.map +7 -0
- package/dist/chunk-HYPQOQ27.js +2911 -0
- package/dist/chunk-HYPQOQ27.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +991 -0
- package/dist/index.js +29 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1325 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +88 -0
|
@@ -0,0 +1,2911 @@
|
|
|
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 text2 = await request.text();
|
|
165
|
+
if (text2.trim() === "")
|
|
166
|
+
return void 0;
|
|
167
|
+
return JSON.parse(text2);
|
|
168
|
+
};
|
|
169
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
170
|
+
var createControlPlane = (context) => {
|
|
171
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
172
|
+
let snapshotCounter = 0;
|
|
173
|
+
const headerNamespace = (request) => request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace;
|
|
174
|
+
const adminNamespace = (request, url) => url.searchParams.get("namespace") ?? headerNamespace(request);
|
|
175
|
+
const builtin = {
|
|
176
|
+
"GET /": () => json(200, {
|
|
177
|
+
service: context.name,
|
|
178
|
+
routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort()
|
|
179
|
+
}),
|
|
180
|
+
"POST /reset": async ({ url, namespace }) => {
|
|
181
|
+
const target = url.searchParams.get("all") === "1" ? "*" : namespace;
|
|
182
|
+
await context.reset(target);
|
|
183
|
+
return json(200, { status: "ok", reset: target === "*" ? context.namespaces() : [target] });
|
|
184
|
+
},
|
|
185
|
+
"GET /namespaces": () => json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),
|
|
186
|
+
"GET /clock": () => json(200, context.clock.state()),
|
|
187
|
+
"POST /clock": ({ body }) => {
|
|
188
|
+
if (!isRecord(body))
|
|
189
|
+
return adminError(400, "expected a JSON object");
|
|
190
|
+
if (body.reset === true)
|
|
191
|
+
context.clock.reset();
|
|
192
|
+
if (body.set !== void 0) {
|
|
193
|
+
const instant = parseInstant(body.set);
|
|
194
|
+
if (instant === void 0)
|
|
195
|
+
return adminError(400, "set: expected epoch ms or ISO-8601");
|
|
196
|
+
context.clock.set(instant);
|
|
197
|
+
}
|
|
198
|
+
if (body.advance !== void 0) {
|
|
199
|
+
const delta = parseDuration(body.advance);
|
|
200
|
+
if (delta === void 0)
|
|
201
|
+
return adminError(400, 'advance: expected ms or "15m"-style');
|
|
202
|
+
context.clock.advance(delta);
|
|
203
|
+
}
|
|
204
|
+
if (body.freeze === true)
|
|
205
|
+
context.clock.freeze();
|
|
206
|
+
if (body.freeze === false)
|
|
207
|
+
context.clock.unfreeze();
|
|
208
|
+
return json(200, context.clock.state());
|
|
209
|
+
},
|
|
210
|
+
"GET /faults": () => json(200, { faults: context.faults.list() }),
|
|
211
|
+
"POST /faults": ({ body, namespace }) => {
|
|
212
|
+
if (isRecord(body) && typeof body.preset === "string") {
|
|
213
|
+
if (!context.applyPreset)
|
|
214
|
+
return adminError(400, `${context.name} has no fault presets`);
|
|
215
|
+
const { preset, ...overrides } = body;
|
|
216
|
+
try {
|
|
217
|
+
return json(201, {
|
|
218
|
+
preset,
|
|
219
|
+
rules: context.applyPreset(preset, namespace, overrides)
|
|
220
|
+
});
|
|
221
|
+
} catch (error) {
|
|
222
|
+
return adminError(404, error instanceof Error ? error.message : String(error));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (!isRecord(body) || typeof body.status !== "number" && typeof body.delayMs !== "number" && typeof body.latencyMs !== "number" && body.drop !== true && typeof body.effect !== "string") {
|
|
226
|
+
return adminError(400, "a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset");
|
|
227
|
+
}
|
|
228
|
+
const rule = {
|
|
229
|
+
// Scoped to the caller's namespace unless it asks for every one, so one worker's
|
|
230
|
+
// injected failure never lands on another's request.
|
|
231
|
+
namespace,
|
|
232
|
+
...body,
|
|
233
|
+
id: typeof body.id === "string" ? body.id : `fault_${context.faults.list().length + 1}`
|
|
234
|
+
};
|
|
235
|
+
return json(201, context.faults.add(rule));
|
|
236
|
+
},
|
|
237
|
+
"DELETE /faults": ({ url }) => {
|
|
238
|
+
const id = url.searchParams.get("id");
|
|
239
|
+
if (id === null) {
|
|
240
|
+
context.faults.clear();
|
|
241
|
+
return json(200, { status: "ok" });
|
|
242
|
+
}
|
|
243
|
+
return context.faults.remove(id) ? json(200, { status: "ok" }) : adminError(404, `no fault ${id}`);
|
|
244
|
+
},
|
|
245
|
+
"POST /snapshots": ({ namespace }) => {
|
|
246
|
+
const point = context.timeTravel.checkpoint(namespace, "main");
|
|
247
|
+
context.timeTravel.retain(namespace, point.id);
|
|
248
|
+
snapshotCounter++;
|
|
249
|
+
const id = `snap_${snapshotCounter}`;
|
|
250
|
+
snapshots.set(id, { namespace, checkpoint: point.id });
|
|
251
|
+
return json(201, { id, namespace, records: point.records ?? 0 });
|
|
252
|
+
},
|
|
253
|
+
"POST /snapshots/:id/restore": ({ params, namespace }) => {
|
|
254
|
+
const alias = snapshots.get(params.id);
|
|
255
|
+
if (!alias)
|
|
256
|
+
return adminError(404, `no snapshot ${params.id}`);
|
|
257
|
+
if (alias.namespace !== namespace) {
|
|
258
|
+
return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`);
|
|
259
|
+
}
|
|
260
|
+
context.timeTravel.checkout(alias.checkpoint, { namespace, branch: "main" });
|
|
261
|
+
return json(200, { status: "ok", id: params.id, namespace });
|
|
262
|
+
},
|
|
263
|
+
"DELETE /snapshots/:id": ({ params }) => {
|
|
264
|
+
const id = params.id;
|
|
265
|
+
const alias = snapshots.get(id);
|
|
266
|
+
if (!alias)
|
|
267
|
+
return adminError(404, `no snapshot ${id}`);
|
|
268
|
+
snapshots.delete(id);
|
|
269
|
+
context.timeTravel.release(alias.namespace, alias.checkpoint);
|
|
270
|
+
return json(200, { status: "ok" });
|
|
271
|
+
},
|
|
272
|
+
"GET /timeline": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),
|
|
273
|
+
"POST /checkpoints": ({ body, namespace }) => {
|
|
274
|
+
const branch = isRecord(body) && typeof body.branch === "string" ? body.branch : "main";
|
|
275
|
+
try {
|
|
276
|
+
return json(201, context.timeTravel.checkpoint(namespace, branch));
|
|
277
|
+
} catch (error) {
|
|
278
|
+
return adminError(409, error instanceof Error ? error.message : String(error));
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
"POST /branches/:name": ({ params, body, namespace }) => {
|
|
282
|
+
const at = isRecord(body) && typeof body.at === "string" ? body.at : void 0;
|
|
283
|
+
try {
|
|
284
|
+
return json(201, context.timeTravel.branch(params.name, {
|
|
285
|
+
namespace,
|
|
286
|
+
...at !== void 0 ? { at } : {}
|
|
287
|
+
}));
|
|
288
|
+
} catch (error) {
|
|
289
|
+
return adminError(409, error instanceof Error ? error.message : String(error));
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
"POST /branches/:name/checkout": ({ params, body, namespace }) => {
|
|
293
|
+
if (!isRecord(body) || typeof body.checkpoint !== "string") {
|
|
294
|
+
return adminError(400, 'expected {"checkpoint":"cp_..."}');
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
context.timeTravel.checkout(body.checkpoint, {
|
|
298
|
+
namespace,
|
|
299
|
+
branch: params.name
|
|
300
|
+
});
|
|
301
|
+
return json(200, { status: "ok", branch: params.name, checkpoint: body.checkpoint });
|
|
302
|
+
} catch (error) {
|
|
303
|
+
return adminError(409, error instanceof Error ? error.message : String(error));
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
"GET /requests": ({ url, namespace }) => {
|
|
307
|
+
const status = url.searchParams.get("status");
|
|
308
|
+
const since = url.searchParams.get("since");
|
|
309
|
+
const limit = url.searchParams.get("limit");
|
|
310
|
+
const sinceMs = since === null ? void 0 : parseInstant(/^\d+$/.test(since) ? Number(since) : since);
|
|
311
|
+
if (since !== null && sinceMs === void 0) {
|
|
312
|
+
return adminError(400, "since: expected epoch ms or ISO-8601");
|
|
313
|
+
}
|
|
314
|
+
if (status !== null && !/^\d{3}$/.test(status))
|
|
315
|
+
return adminError(400, "status: expected an HTTP status");
|
|
316
|
+
if (limit !== null && !/^\d+$/.test(limit))
|
|
317
|
+
return adminError(400, "limit: expected a count");
|
|
318
|
+
const operationId = url.searchParams.get("operationId");
|
|
319
|
+
const everyNamespace = url.searchParams.get("all") === "1";
|
|
320
|
+
return json(200, {
|
|
321
|
+
size: context.journal.size,
|
|
322
|
+
requests: context.journal.list({
|
|
323
|
+
...everyNamespace ? {} : { namespace },
|
|
324
|
+
...operationId !== null ? { operationId } : {},
|
|
325
|
+
...status !== null ? { status: Number(status) } : {},
|
|
326
|
+
...sinceMs !== void 0 ? { since: sinceMs } : {},
|
|
327
|
+
...limit !== null ? { limit: Number(limit) } : {}
|
|
328
|
+
})
|
|
329
|
+
});
|
|
330
|
+
},
|
|
331
|
+
"DELETE /requests": ({ url, namespace }) => {
|
|
332
|
+
context.journal.clear(url.searchParams.get("all") === "1" ? void 0 : namespace);
|
|
333
|
+
return json(200, { status: "ok" });
|
|
334
|
+
},
|
|
335
|
+
"GET /metrics": () => json(200, context.metrics.report()),
|
|
336
|
+
"DELETE /metrics": () => {
|
|
337
|
+
context.metrics.reset();
|
|
338
|
+
return json(200, { status: "ok" });
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(([key, handler]) => {
|
|
342
|
+
const space = key.indexOf(" ");
|
|
343
|
+
return { method: key.slice(0, space), pattern: key.slice(space + 1), handler };
|
|
344
|
+
});
|
|
345
|
+
return {
|
|
346
|
+
namespaceOf: headerNamespace,
|
|
347
|
+
async handle(request) {
|
|
348
|
+
const url = new URL(request.url);
|
|
349
|
+
if (url.pathname === HEALTH_PATH && request.method === "GET") {
|
|
350
|
+
return json(200, {
|
|
351
|
+
status: "ok",
|
|
352
|
+
service: context.name,
|
|
353
|
+
uptimeMs: context.wallNow() - context.startedAt,
|
|
354
|
+
clock: context.clock.state(),
|
|
355
|
+
namespaces: context.namespaces().length,
|
|
356
|
+
...context.describe()
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
|
|
360
|
+
return void 0;
|
|
361
|
+
}
|
|
362
|
+
if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
|
|
363
|
+
return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
|
|
364
|
+
}
|
|
365
|
+
const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
|
|
366
|
+
for (const route of routes) {
|
|
367
|
+
if (route.method !== request.method)
|
|
368
|
+
continue;
|
|
369
|
+
const params = matchRoute(route.pattern, path);
|
|
370
|
+
if (!params)
|
|
371
|
+
continue;
|
|
372
|
+
let body;
|
|
373
|
+
try {
|
|
374
|
+
body = await readJson(request);
|
|
375
|
+
} catch {
|
|
376
|
+
return adminError(400, "request body is not valid JSON");
|
|
377
|
+
}
|
|
378
|
+
return route.handler({
|
|
379
|
+
request,
|
|
380
|
+
url,
|
|
381
|
+
params,
|
|
382
|
+
namespace: adminNamespace(request, url),
|
|
383
|
+
body
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
return adminError(404, `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
// ../core/dist/credentials.js
|
|
392
|
+
var 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
|
+
// ../../http/codec/dist/form.js
|
|
619
|
+
var parsePath = (rawKey) => {
|
|
620
|
+
const open = rawKey.indexOf("[");
|
|
621
|
+
if (open === -1)
|
|
622
|
+
return [rawKey];
|
|
623
|
+
const path = [rawKey.slice(0, open)];
|
|
624
|
+
const rest = rawKey.slice(open);
|
|
625
|
+
const pattern = /\[([^\]]*)\]/g;
|
|
626
|
+
let match = pattern.exec(rest);
|
|
627
|
+
let consumed = 0;
|
|
628
|
+
while (match !== null) {
|
|
629
|
+
if (match.index !== consumed)
|
|
630
|
+
return [rawKey];
|
|
631
|
+
path.push(match[1] ?? "");
|
|
632
|
+
consumed = match.index + match[0].length;
|
|
633
|
+
match = pattern.exec(rest);
|
|
634
|
+
}
|
|
635
|
+
if (consumed !== rest.length)
|
|
636
|
+
return [rawKey];
|
|
637
|
+
return path;
|
|
638
|
+
};
|
|
639
|
+
var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
|
|
640
|
+
var put = (target, key, value) => {
|
|
641
|
+
if (key === "__proto__") {
|
|
642
|
+
Object.defineProperty(target, key, {
|
|
643
|
+
value,
|
|
644
|
+
enumerable: true,
|
|
645
|
+
writable: true,
|
|
646
|
+
configurable: true
|
|
647
|
+
});
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
;
|
|
651
|
+
target[key] = value;
|
|
652
|
+
};
|
|
653
|
+
var assign = (target, path, value) => {
|
|
654
|
+
let cursor = target;
|
|
655
|
+
for (let i = 0; i < path.length; i++) {
|
|
656
|
+
const segment = path[i];
|
|
657
|
+
const last = i === path.length - 1;
|
|
658
|
+
if (Array.isArray(cursor)) {
|
|
659
|
+
const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
|
|
660
|
+
if (index === void 0)
|
|
661
|
+
return;
|
|
662
|
+
if (last) {
|
|
663
|
+
put(cursor, index, value);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
|
|
667
|
+
if (next === void 0 || typeof next === "string") {
|
|
668
|
+
const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
|
|
669
|
+
put(cursor, index, created);
|
|
670
|
+
cursor = created;
|
|
671
|
+
} else {
|
|
672
|
+
cursor = next;
|
|
673
|
+
}
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
if (typeof cursor === "string")
|
|
677
|
+
return;
|
|
678
|
+
if (last) {
|
|
679
|
+
put(cursor, segment, value);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
const nextSegment = path[i + 1];
|
|
683
|
+
const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
684
|
+
if (existing === void 0 || typeof existing === "string") {
|
|
685
|
+
const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
|
|
686
|
+
put(cursor, segment, created);
|
|
687
|
+
cursor = created;
|
|
688
|
+
} else {
|
|
689
|
+
cursor = existing;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
var decodeFormPairs = (pairs) => {
|
|
694
|
+
const out = {};
|
|
695
|
+
for (const [rawKey, value] of pairs)
|
|
696
|
+
assign(out, parsePath(rawKey), value);
|
|
697
|
+
return densify(out);
|
|
698
|
+
};
|
|
699
|
+
var densify = (value) => {
|
|
700
|
+
if (typeof value === "string")
|
|
701
|
+
return value;
|
|
702
|
+
if (Array.isArray(value))
|
|
703
|
+
return value.filter((item) => item !== void 0).map(densify);
|
|
704
|
+
const out = {};
|
|
705
|
+
for (const [key, item] of Object.entries(value))
|
|
706
|
+
put(out, key, densify(item));
|
|
707
|
+
return out;
|
|
708
|
+
};
|
|
709
|
+
var decodeForm = (text2) => {
|
|
710
|
+
const source = text2.startsWith("?") ? text2.slice(1) : text2;
|
|
711
|
+
return decodeFormPairs(new URLSearchParams(source).entries());
|
|
712
|
+
};
|
|
713
|
+
|
|
714
|
+
// ../../http/codec/dist/content.js
|
|
715
|
+
var JSON_MEDIA_TYPE = "application/json";
|
|
716
|
+
var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
|
|
717
|
+
var mediaTypeOf = (contentType) => {
|
|
718
|
+
if (!contentType)
|
|
719
|
+
return void 0;
|
|
720
|
+
const essence = contentType.split(";")[0]?.trim().toLowerCase();
|
|
721
|
+
return essence ? essence : void 0;
|
|
722
|
+
};
|
|
723
|
+
var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
|
|
724
|
+
var utf8 = new TextDecoder("utf-8", { fatal: false });
|
|
725
|
+
var decodeBody = (contentType, bytes) => {
|
|
726
|
+
if (bytes.byteLength === 0)
|
|
727
|
+
return { kind: "empty" };
|
|
728
|
+
const mediaType = mediaTypeOf(contentType);
|
|
729
|
+
if (mediaType === void 0)
|
|
730
|
+
return { kind: "bytes", value: bytes };
|
|
731
|
+
if (isJsonMediaType(mediaType)) {
|
|
732
|
+
const text2 = utf8.decode(bytes);
|
|
733
|
+
try {
|
|
734
|
+
return { kind: "json", value: JSON.parse(text2) };
|
|
735
|
+
} catch (error) {
|
|
736
|
+
return {
|
|
737
|
+
kind: "invalid",
|
|
738
|
+
mediaType,
|
|
739
|
+
text: text2,
|
|
740
|
+
error: error instanceof Error ? error.message : String(error)
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
if (mediaType === FORM_MEDIA_TYPE) {
|
|
745
|
+
return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
|
|
746
|
+
}
|
|
747
|
+
if (mediaType.startsWith("text/"))
|
|
748
|
+
return { kind: "text", value: utf8.decode(bytes) };
|
|
749
|
+
return { kind: "bytes", value: bytes };
|
|
750
|
+
};
|
|
751
|
+
var readBody = async (message) => {
|
|
752
|
+
const bytes = new Uint8Array(await message.arrayBuffer());
|
|
753
|
+
return decodeBody(message.headers.get("content-type"), bytes);
|
|
754
|
+
};
|
|
755
|
+
|
|
756
|
+
// ../core/dist/http.js
|
|
757
|
+
var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
|
|
758
|
+
status,
|
|
759
|
+
headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
|
|
760
|
+
});
|
|
761
|
+
var HttpError = class extends Error {
|
|
762
|
+
status;
|
|
763
|
+
body;
|
|
764
|
+
headers;
|
|
765
|
+
constructor(status, body, headers = {}) {
|
|
766
|
+
super(`HTTP ${status}`);
|
|
767
|
+
this.status = status;
|
|
768
|
+
this.body = body;
|
|
769
|
+
this.headers = headers;
|
|
770
|
+
this.name = "HttpError";
|
|
771
|
+
}
|
|
772
|
+
toResponse() {
|
|
773
|
+
const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
|
|
774
|
+
if (contentType === "text/plain") {
|
|
775
|
+
return new Response(String(this.body), {
|
|
776
|
+
status: this.status,
|
|
777
|
+
headers: this.headers
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
return jsonRes(this.status, this.body, this.headers);
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
|
|
784
|
+
// ../core/dist/ids.js
|
|
785
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
786
|
+
var mix = (input) => {
|
|
787
|
+
let hash = 2166136261;
|
|
788
|
+
for (let i = 0; i < input.length; i++) {
|
|
789
|
+
hash ^= input.charCodeAt(i);
|
|
790
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
791
|
+
}
|
|
792
|
+
hash ^= hash >>> 16;
|
|
793
|
+
hash = Math.imul(hash, 2246822507) >>> 0;
|
|
794
|
+
hash ^= hash >>> 13;
|
|
795
|
+
return hash >>> 0;
|
|
796
|
+
};
|
|
797
|
+
var opaqueToken = (input, length) => {
|
|
798
|
+
let out = "";
|
|
799
|
+
let round = 0;
|
|
800
|
+
while (out.length < length) {
|
|
801
|
+
let hash = mix(`${input}:${round++}`);
|
|
802
|
+
for (let i = 0; i < 5 && out.length < length; i++) {
|
|
803
|
+
out += ALPHABET.charAt(hash % ALPHABET.length);
|
|
804
|
+
hash = Math.floor(hash / ALPHABET.length);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
return out;
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
// ../core/dist/journal.js
|
|
811
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
812
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
813
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
814
|
+
const rings = /* @__PURE__ */ new Map();
|
|
815
|
+
let sequence = 0;
|
|
816
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
817
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
818
|
+
return {
|
|
819
|
+
size: capacity,
|
|
820
|
+
record(entry) {
|
|
821
|
+
if (capacity === 0)
|
|
822
|
+
return;
|
|
823
|
+
order.set(entry, sequence++);
|
|
824
|
+
let ring = rings.get(entry.namespace);
|
|
825
|
+
if (!ring) {
|
|
826
|
+
ring = { entries: [], next: 0 };
|
|
827
|
+
rings.set(entry.namespace, ring);
|
|
828
|
+
}
|
|
829
|
+
if (ring.entries.length < capacity)
|
|
830
|
+
ring.entries.push(entry);
|
|
831
|
+
else {
|
|
832
|
+
ring.entries[ring.next] = entry;
|
|
833
|
+
ring.next = (ring.next + 1) % capacity;
|
|
834
|
+
}
|
|
835
|
+
},
|
|
836
|
+
list(query = {}) {
|
|
837
|
+
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));
|
|
838
|
+
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));
|
|
839
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
840
|
+
},
|
|
841
|
+
clear(namespace) {
|
|
842
|
+
if (namespace === void 0)
|
|
843
|
+
rings.clear();
|
|
844
|
+
else
|
|
845
|
+
rings.delete(namespace);
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
};
|
|
849
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
850
|
+
var annotateResponse = (response, extra) => {
|
|
851
|
+
const existing = notes.get(response);
|
|
852
|
+
notes.set(response, {
|
|
853
|
+
...existing,
|
|
854
|
+
...extra,
|
|
855
|
+
...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
|
|
856
|
+
});
|
|
857
|
+
return response;
|
|
858
|
+
};
|
|
859
|
+
var responseNotes = (response) => notes.get(response);
|
|
860
|
+
|
|
861
|
+
// ../core/dist/metrics.js
|
|
862
|
+
var createMetrics = () => {
|
|
863
|
+
let requests = 0;
|
|
864
|
+
let faults = 0;
|
|
865
|
+
let totalDurationMs = 0;
|
|
866
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
867
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
868
|
+
return {
|
|
869
|
+
record(entry) {
|
|
870
|
+
requests++;
|
|
871
|
+
totalDurationMs += entry.durationMs;
|
|
872
|
+
if (entry.faultId !== void 0)
|
|
873
|
+
faults++;
|
|
874
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
875
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
876
|
+
if (entry.unmatched) {
|
|
877
|
+
const route = `${entry.method} ${entry.path}`;
|
|
878
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
879
|
+
}
|
|
880
|
+
},
|
|
881
|
+
report: () => ({
|
|
882
|
+
requests,
|
|
883
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
884
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
885
|
+
const space = route.indexOf(" ");
|
|
886
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
887
|
+
}),
|
|
888
|
+
faults,
|
|
889
|
+
totalDurationMs
|
|
890
|
+
}),
|
|
891
|
+
reset() {
|
|
892
|
+
requests = 0;
|
|
893
|
+
faults = 0;
|
|
894
|
+
totalDurationMs = 0;
|
|
895
|
+
byOperation.clear();
|
|
896
|
+
unmatched.clear();
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
};
|
|
900
|
+
|
|
901
|
+
// ../core/dist/outbox.js
|
|
902
|
+
var OutboxStore = class {
|
|
903
|
+
items;
|
|
904
|
+
constructor(sqlite, namespace, name = "outbox") {
|
|
905
|
+
this.items = new Collection(sqlite, namespace, name);
|
|
906
|
+
}
|
|
907
|
+
record(item) {
|
|
908
|
+
this.items.insert(item.id, item);
|
|
909
|
+
return item;
|
|
910
|
+
}
|
|
911
|
+
get(id) {
|
|
912
|
+
return this.items.get(id);
|
|
913
|
+
}
|
|
914
|
+
update(id, item) {
|
|
915
|
+
this.items.update(id, item);
|
|
916
|
+
}
|
|
917
|
+
/** Oldest first, so a suite reads messages in the order they were sent. */
|
|
918
|
+
list(query = {}) {
|
|
919
|
+
const to = query.to?.toLowerCase();
|
|
920
|
+
const matched = this.items.list({ order: "oldest" }).map((row) => row.value).filter((item) => {
|
|
921
|
+
if (to !== void 0) {
|
|
922
|
+
const recipients = Array.isArray(item.to) ? item.to : [item.to];
|
|
923
|
+
if (!recipients.some((r) => r.toLowerCase() === to))
|
|
924
|
+
return false;
|
|
925
|
+
}
|
|
926
|
+
if (query.since !== void 0 && Date.parse(item.createdAt) < query.since)
|
|
927
|
+
return false;
|
|
928
|
+
if (query.where && !query.where(item))
|
|
929
|
+
return false;
|
|
930
|
+
return true;
|
|
931
|
+
});
|
|
932
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
936
|
+
var parseSince = (value) => {
|
|
937
|
+
if (value === null)
|
|
938
|
+
return void 0;
|
|
939
|
+
const parsed = /^\d+$/.test(value) ? Number(value) : Date.parse(value);
|
|
940
|
+
return Number.isNaN(parsed) ? null : parsed;
|
|
941
|
+
};
|
|
942
|
+
var outboxAdminRoutes = (runtime, pick, filter) => ({
|
|
943
|
+
"GET /outbox": ({ url, namespace }) => {
|
|
944
|
+
const since = parseSince(url.searchParams.get("since"));
|
|
945
|
+
if (since === null) {
|
|
946
|
+
return json2(400, {
|
|
947
|
+
error: { type: "mockingbird_admin", message: "since: expected epoch ms or ISO-8601" }
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
const limit = url.searchParams.get("limit");
|
|
951
|
+
const where = filter?.(url.searchParams);
|
|
952
|
+
const to = url.searchParams.get("to");
|
|
953
|
+
return json2(200, {
|
|
954
|
+
messages: pick(runtime.instance(namespace)).list({
|
|
955
|
+
...to !== null ? { to } : {},
|
|
956
|
+
...since !== void 0 ? { since } : {},
|
|
957
|
+
...where ? { where } : {},
|
|
958
|
+
...limit !== null && /^\d+$/.test(limit) ? { limit: Number(limit) } : {}
|
|
959
|
+
})
|
|
960
|
+
});
|
|
961
|
+
},
|
|
962
|
+
"GET /outbox/:id": ({ params, namespace }) => {
|
|
963
|
+
const item = pick(runtime.instance(namespace)).get(params.id);
|
|
964
|
+
return item ? json2(200, item) : json2(404, { error: { type: "mockingbird_admin", message: `no message ${params.id}` } });
|
|
965
|
+
}
|
|
966
|
+
});
|
|
967
|
+
|
|
968
|
+
// ../../core/dist/timeline.js
|
|
969
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
970
|
+
var Timeline = class {
|
|
971
|
+
maxCheckpoints;
|
|
972
|
+
now;
|
|
973
|
+
makeId;
|
|
974
|
+
nodes = /* @__PURE__ */ new Map();
|
|
975
|
+
heads = /* @__PURE__ */ new Map();
|
|
976
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
977
|
+
evictable = /* @__PURE__ */ new Set();
|
|
978
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
979
|
+
references = /* @__PURE__ */ new Map();
|
|
980
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
981
|
+
sequence = 0;
|
|
982
|
+
constructor(options = {}) {
|
|
983
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
984
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
985
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
986
|
+
this.maxCheckpoints = max;
|
|
987
|
+
this.now = options.now ?? (() => this.sequence);
|
|
988
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
989
|
+
}
|
|
990
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
991
|
+
commit(value, options = {}) {
|
|
992
|
+
const branch = options.branch ?? "main";
|
|
993
|
+
this.assertBranch(branch);
|
|
994
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
995
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
996
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
997
|
+
const id = this.makeId(++this.sequence);
|
|
998
|
+
if (this.nodes.has(id))
|
|
999
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
1000
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
1001
|
+
this.nodes.set(id, checkpoint);
|
|
1002
|
+
this.moveHead(branch, id);
|
|
1003
|
+
this.collect(this.maxCheckpoints);
|
|
1004
|
+
return checkpoint;
|
|
1005
|
+
}
|
|
1006
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
1007
|
+
fork(branch, options = {}) {
|
|
1008
|
+
this.assertBranch(branch);
|
|
1009
|
+
if (this.heads.has(branch))
|
|
1010
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
1011
|
+
const from = options.from ?? this.heads.get("main");
|
|
1012
|
+
if (from === void 0)
|
|
1013
|
+
return void 0;
|
|
1014
|
+
const checkpoint = this.get(from);
|
|
1015
|
+
this.moveHead(branch, checkpoint.id);
|
|
1016
|
+
return checkpoint;
|
|
1017
|
+
}
|
|
1018
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
1019
|
+
checkout(branch, id) {
|
|
1020
|
+
this.assertBranch(branch);
|
|
1021
|
+
const checkpoint = this.get(id);
|
|
1022
|
+
this.moveHead(branch, checkpoint.id);
|
|
1023
|
+
return checkpoint;
|
|
1024
|
+
}
|
|
1025
|
+
get(id) {
|
|
1026
|
+
const checkpoint = this.nodes.get(id);
|
|
1027
|
+
if (!checkpoint)
|
|
1028
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
1029
|
+
return checkpoint;
|
|
1030
|
+
}
|
|
1031
|
+
head(branch = "main") {
|
|
1032
|
+
const id = this.heads.get(branch);
|
|
1033
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
1034
|
+
}
|
|
1035
|
+
hasBranch(branch) {
|
|
1036
|
+
return this.heads.has(branch);
|
|
1037
|
+
}
|
|
1038
|
+
branches() {
|
|
1039
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
1040
|
+
}
|
|
1041
|
+
checkpoints() {
|
|
1042
|
+
return [...this.nodes.values()];
|
|
1043
|
+
}
|
|
1044
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
1045
|
+
get size() {
|
|
1046
|
+
return this.nodes.size;
|
|
1047
|
+
}
|
|
1048
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
1049
|
+
retain(id) {
|
|
1050
|
+
const checkpoint = this.get(id);
|
|
1051
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
1052
|
+
this.addReference(id);
|
|
1053
|
+
return checkpoint;
|
|
1054
|
+
}
|
|
1055
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
1056
|
+
release(id) {
|
|
1057
|
+
if (!this.nodes.has(id))
|
|
1058
|
+
return false;
|
|
1059
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
1060
|
+
if (pins === 0)
|
|
1061
|
+
return false;
|
|
1062
|
+
if (pins === 1)
|
|
1063
|
+
this.explicitPins.delete(id);
|
|
1064
|
+
else
|
|
1065
|
+
this.explicitPins.set(id, pins - 1);
|
|
1066
|
+
this.removeReference(id);
|
|
1067
|
+
this.collect(this.maxCheckpoints);
|
|
1068
|
+
return true;
|
|
1069
|
+
}
|
|
1070
|
+
deleteBranch(branch) {
|
|
1071
|
+
if (branch === "main")
|
|
1072
|
+
throw new RangeError("cannot delete main branch");
|
|
1073
|
+
const previous = this.heads.get(branch);
|
|
1074
|
+
const deleted = this.heads.delete(branch);
|
|
1075
|
+
if (previous !== void 0)
|
|
1076
|
+
this.removeReference(previous);
|
|
1077
|
+
this.collect(this.maxCheckpoints);
|
|
1078
|
+
return deleted;
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
1082
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
1083
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
1084
|
+
*/
|
|
1085
|
+
gc(max = this.maxCheckpoints) {
|
|
1086
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1087
|
+
throw new RangeError("max must be a positive integer");
|
|
1088
|
+
const removed = [];
|
|
1089
|
+
this.collect(max, removed);
|
|
1090
|
+
return removed;
|
|
1091
|
+
}
|
|
1092
|
+
collect(max, removed) {
|
|
1093
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
1094
|
+
const id = this.evictable.values().next().value;
|
|
1095
|
+
this.evictable.delete(id);
|
|
1096
|
+
this.nodes.delete(id);
|
|
1097
|
+
removed?.push(id);
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
moveHead(branch, id) {
|
|
1101
|
+
const previous = this.heads.get(branch);
|
|
1102
|
+
if (previous === id)
|
|
1103
|
+
return;
|
|
1104
|
+
if (previous !== void 0)
|
|
1105
|
+
this.removeReference(previous);
|
|
1106
|
+
this.heads.set(branch, id);
|
|
1107
|
+
this.addReference(id);
|
|
1108
|
+
}
|
|
1109
|
+
addReference(id) {
|
|
1110
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
1111
|
+
this.evictable.delete(id);
|
|
1112
|
+
}
|
|
1113
|
+
removeReference(id) {
|
|
1114
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
1115
|
+
if (next > 0)
|
|
1116
|
+
this.references.set(id, next);
|
|
1117
|
+
else {
|
|
1118
|
+
this.references.delete(id);
|
|
1119
|
+
if (this.nodes.has(id))
|
|
1120
|
+
this.evictable.add(id);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
assertBranch(branch) {
|
|
1124
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
1125
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
1126
|
+
}
|
|
1127
|
+
};
|
|
1128
|
+
|
|
1129
|
+
// ../../sqlite/dist/default.js
|
|
1130
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
1131
|
+
var createDefaultSqlite = () => new Database();
|
|
1132
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
1133
|
+
|
|
1134
|
+
// ../../sqlite/dist/migrate.js
|
|
1135
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
1136
|
+
sqlite.exec(`
|
|
1137
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1138
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1139
|
+
applied_at INTEGER NOT NULL
|
|
1140
|
+
)
|
|
1141
|
+
`);
|
|
1142
|
+
};
|
|
1143
|
+
var migrate = (sqlite, migrations) => {
|
|
1144
|
+
ensureMigrationsTable(sqlite);
|
|
1145
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
1146
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
1147
|
+
if (pending.length === 0)
|
|
1148
|
+
return;
|
|
1149
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
1150
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1151
|
+
sqlite.transaction(() => {
|
|
1152
|
+
for (const migration of pending) {
|
|
1153
|
+
sqlite.exec(migration.sql);
|
|
1154
|
+
insert.run(migration.id, now);
|
|
1155
|
+
}
|
|
1156
|
+
});
|
|
1157
|
+
};
|
|
1158
|
+
|
|
1159
|
+
// ../../sqlite/dist/schema.js
|
|
1160
|
+
var CORE_MIGRATIONS = [
|
|
1161
|
+
{
|
|
1162
|
+
id: "20260322_core_records_sequences",
|
|
1163
|
+
sql: `
|
|
1164
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
1165
|
+
namespace TEXT NOT NULL,
|
|
1166
|
+
collection TEXT NOT NULL,
|
|
1167
|
+
id TEXT NOT NULL,
|
|
1168
|
+
seq INTEGER NOT NULL,
|
|
1169
|
+
value TEXT NOT NULL,
|
|
1170
|
+
PRIMARY KEY (namespace, collection, id)
|
|
1171
|
+
);
|
|
1172
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
1173
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
1174
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
1175
|
+
namespace TEXT NOT NULL,
|
|
1176
|
+
name TEXT NOT NULL,
|
|
1177
|
+
kind TEXT NOT NULL,
|
|
1178
|
+
value INTEGER NOT NULL,
|
|
1179
|
+
PRIMARY KEY (namespace, name, kind)
|
|
1180
|
+
);
|
|
1181
|
+
`
|
|
1182
|
+
}
|
|
1183
|
+
];
|
|
1184
|
+
var migrateCore = (sqlite) => {
|
|
1185
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
1186
|
+
};
|
|
1187
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
1188
|
+
sqlite.transaction(() => {
|
|
1189
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1190
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1191
|
+
});
|
|
1192
|
+
};
|
|
1193
|
+
|
|
1194
|
+
// ../../openapi/metadata/dist/types.js
|
|
1195
|
+
var EXTENSION_KEYS = {
|
|
1196
|
+
operation: "x-mockingbird",
|
|
1197
|
+
resource: "x-mockingbird-resource",
|
|
1198
|
+
resourceRef: "x-mockingbird-resource-ref",
|
|
1199
|
+
volatile: "x-mockingbird-volatile",
|
|
1200
|
+
scope: "x-mockingbird-scope",
|
|
1201
|
+
unsupported: "x-mockingbird-unsupported",
|
|
1202
|
+
parityHeader: "x-mockingbird-parity-header"
|
|
1203
|
+
};
|
|
1204
|
+
|
|
1205
|
+
// ../../openapi/metadata/dist/read.js
|
|
1206
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1207
|
+
var extensionOf = (holder, key) => holder[key];
|
|
1208
|
+
var operationMetadata = (operation) => {
|
|
1209
|
+
const raw = extensionOf(operation, EXTENSION_KEYS.operation);
|
|
1210
|
+
const ext = isRecord2(raw) ? raw : {};
|
|
1211
|
+
const supported = ext.supported ?? true;
|
|
1212
|
+
const parity = ext.parity ?? {};
|
|
1213
|
+
return {
|
|
1214
|
+
supported,
|
|
1215
|
+
reason: typeof ext.reason === "string" ? ext.reason : void 0,
|
|
1216
|
+
parity: {
|
|
1217
|
+
enabled: supported && (parity.enabled ?? true),
|
|
1218
|
+
safe: parity.safe ?? true,
|
|
1219
|
+
reason: typeof parity.reason === "string" ? parity.reason : void 0
|
|
1220
|
+
}
|
|
1221
|
+
};
|
|
1222
|
+
};
|
|
1223
|
+
|
|
1224
|
+
// ../core/dist/service.js
|
|
1225
|
+
import { Hono } from "hono";
|
|
1226
|
+
var defineOperations = (handlers) => handlers;
|
|
1227
|
+
var OperationRegistryError = class extends Error {
|
|
1228
|
+
problems;
|
|
1229
|
+
constructor(problems) {
|
|
1230
|
+
super(`operation registry is inconsistent:
|
|
1231
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
1232
|
+
this.problems = problems;
|
|
1233
|
+
this.name = "OperationRegistryError";
|
|
1234
|
+
}
|
|
1235
|
+
};
|
|
1236
|
+
var verifyOperations = (document2, handlers) => {
|
|
1237
|
+
const problems = [];
|
|
1238
|
+
const operations = listOperations(document2);
|
|
1239
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1240
|
+
for (const operation of operations) {
|
|
1241
|
+
if (seen.has(operation.operationId))
|
|
1242
|
+
problems.push(`duplicate operationId ${operation.operationId}`);
|
|
1243
|
+
seen.add(operation.operationId);
|
|
1244
|
+
const supported = operationMetadata(operation.operation).supported;
|
|
1245
|
+
const handler = handlers[operation.operationId];
|
|
1246
|
+
if (supported && !handler)
|
|
1247
|
+
problems.push(`supported operation ${operation.operationId} has no handler`);
|
|
1248
|
+
if (!supported && handler)
|
|
1249
|
+
problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
|
|
1250
|
+
}
|
|
1251
|
+
for (const id of Object.keys(handlers)) {
|
|
1252
|
+
if (!seen.has(id))
|
|
1253
|
+
problems.push(`handler ${id} has no OpenAPI operation`);
|
|
1254
|
+
}
|
|
1255
|
+
return problems;
|
|
1256
|
+
};
|
|
1257
|
+
var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
|
|
1258
|
+
var routeOrder = (a, b) => {
|
|
1259
|
+
const sa = a.path.split("/");
|
|
1260
|
+
const sb = b.path.split("/");
|
|
1261
|
+
for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
|
|
1262
|
+
const x = sa[i] ?? "";
|
|
1263
|
+
const y = sb[i] ?? "";
|
|
1264
|
+
const px = x.startsWith("{");
|
|
1265
|
+
const py = y.startsWith("{");
|
|
1266
|
+
if (px !== py)
|
|
1267
|
+
return px ? 1 : -1;
|
|
1268
|
+
if (x !== y)
|
|
1269
|
+
return x < y ? -1 : 1;
|
|
1270
|
+
}
|
|
1271
|
+
return 0;
|
|
1272
|
+
};
|
|
1273
|
+
var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
|
|
1274
|
+
var bootSqlite = (sqlite) => {
|
|
1275
|
+
const client = resolveSqlite(sqlite);
|
|
1276
|
+
migrateCore(client);
|
|
1277
|
+
return client;
|
|
1278
|
+
};
|
|
1279
|
+
var createService = (options) => {
|
|
1280
|
+
const problems = verifyOperations(options.document, options.handlers);
|
|
1281
|
+
if (problems.length > 0)
|
|
1282
|
+
throw new OperationRegistryError(problems);
|
|
1283
|
+
migrateCore(options.sqlite);
|
|
1284
|
+
const now = options.now ?? (() => Date.now());
|
|
1285
|
+
const app = new Hono();
|
|
1286
|
+
app.notFound((c) => options.notFound(c.req.raw));
|
|
1287
|
+
app.onError((error, c) => options.onError(error, c.req.raw));
|
|
1288
|
+
const operations = [...listOperations(options.document)].sort(routeOrder);
|
|
1289
|
+
for (const operation of operations) {
|
|
1290
|
+
const metadata = operationMetadata(operation.operation);
|
|
1291
|
+
const handler = options.handlers[operation.operationId];
|
|
1292
|
+
const route = async (c) => {
|
|
1293
|
+
const request = c.req.raw;
|
|
1294
|
+
if (!metadata.supported || !handler) {
|
|
1295
|
+
return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
|
|
1296
|
+
}
|
|
1297
|
+
const url = new URL(request.url);
|
|
1298
|
+
const context = {
|
|
1299
|
+
request,
|
|
1300
|
+
url,
|
|
1301
|
+
params: c.req.param(),
|
|
1302
|
+
query: queryOf(url),
|
|
1303
|
+
body: await readBody(request),
|
|
1304
|
+
sqlite: options.sqlite,
|
|
1305
|
+
namespace: options.namespace,
|
|
1306
|
+
operation,
|
|
1307
|
+
document: options.document,
|
|
1308
|
+
now
|
|
1309
|
+
};
|
|
1310
|
+
const short = await options.before?.(context);
|
|
1311
|
+
if (short)
|
|
1312
|
+
return short;
|
|
1313
|
+
return handler(context);
|
|
1314
|
+
};
|
|
1315
|
+
app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
|
|
1316
|
+
}
|
|
1317
|
+
return {
|
|
1318
|
+
app,
|
|
1319
|
+
sqlite: options.sqlite,
|
|
1320
|
+
namespace: options.namespace,
|
|
1321
|
+
fetch: async (request) => app.fetch(request),
|
|
1322
|
+
reset: async () => {
|
|
1323
|
+
clearNamespace(options.sqlite, options.namespace);
|
|
1324
|
+
}
|
|
1325
|
+
};
|
|
1326
|
+
};
|
|
1327
|
+
|
|
1328
|
+
// ../core/dist/snapshot.js
|
|
1329
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1330
|
+
namespace,
|
|
1331
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1332
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1333
|
+
});
|
|
1334
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1335
|
+
sqlite.transaction(() => {
|
|
1336
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1337
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1338
|
+
const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1339
|
+
for (const row of snapshot.records) {
|
|
1340
|
+
record.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1341
|
+
}
|
|
1342
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1343
|
+
for (const row of snapshot.sequences) {
|
|
1344
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1345
|
+
}
|
|
1346
|
+
});
|
|
1347
|
+
};
|
|
1348
|
+
|
|
1349
|
+
// ../core/dist/version.js
|
|
1350
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1351
|
+
|
|
1352
|
+
// ../core/dist/webhooks.js
|
|
1353
|
+
var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1354
|
+
var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
|
|
1355
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1356
|
+
var parseEndpoint = (value) => {
|
|
1357
|
+
if (!isRecord3(value) || typeof value.url !== "string")
|
|
1358
|
+
return "each endpoint needs a url";
|
|
1359
|
+
try {
|
|
1360
|
+
new URL(value.url);
|
|
1361
|
+
} catch {
|
|
1362
|
+
return `not a URL: ${value.url}`;
|
|
1363
|
+
}
|
|
1364
|
+
const endpoint = { url: value.url };
|
|
1365
|
+
if (typeof value.id === "string")
|
|
1366
|
+
endpoint.id = value.id;
|
|
1367
|
+
if (typeof value.secret === "string")
|
|
1368
|
+
endpoint.secret = value.secret;
|
|
1369
|
+
if (typeof value.signUrl === "string")
|
|
1370
|
+
endpoint.signUrl = value.signUrl;
|
|
1371
|
+
const events = value.events ?? value.enabledEvents;
|
|
1372
|
+
if (Array.isArray(events))
|
|
1373
|
+
endpoint.events = events.map(String);
|
|
1374
|
+
if (isRecord3(value.tags)) {
|
|
1375
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1376
|
+
}
|
|
1377
|
+
if (typeof value.account === "string")
|
|
1378
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1379
|
+
if (isRecord3(value.headers)) {
|
|
1380
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1381
|
+
}
|
|
1382
|
+
return endpoint;
|
|
1383
|
+
};
|
|
1384
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1385
|
+
"GET /webhooks": ({ url, namespace }) => json3(200, {
|
|
1386
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1387
|
+
const type = url.searchParams.get("type");
|
|
1388
|
+
return type === null || d.type === type;
|
|
1389
|
+
})
|
|
1390
|
+
}),
|
|
1391
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1392
|
+
const type = url.searchParams.get("type");
|
|
1393
|
+
return json3(200, {
|
|
1394
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1395
|
+
});
|
|
1396
|
+
},
|
|
1397
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1398
|
+
const replayed = await hub.replay(params.id);
|
|
1399
|
+
return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1400
|
+
},
|
|
1401
|
+
"POST /webhooks/flush": async () => {
|
|
1402
|
+
await hub.flush();
|
|
1403
|
+
return json3(200, { status: "ok" });
|
|
1404
|
+
},
|
|
1405
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1406
|
+
if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1407
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1408
|
+
}
|
|
1409
|
+
const fault = { mode: body.mode };
|
|
1410
|
+
if (typeof body.count === "number")
|
|
1411
|
+
fault.count = body.count;
|
|
1412
|
+
hub.fault(namespace, fault);
|
|
1413
|
+
return json3(201, { namespace, ...fault });
|
|
1414
|
+
},
|
|
1415
|
+
"GET /webhook-endpoints": ({ namespace }) => json3(200, {
|
|
1416
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1417
|
+
...rest,
|
|
1418
|
+
secret: secret ? "(set)" : null
|
|
1419
|
+
}))
|
|
1420
|
+
}),
|
|
1421
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1422
|
+
const list2 = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
|
|
1423
|
+
if (!Array.isArray(list2))
|
|
1424
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1425
|
+
const parsed = [];
|
|
1426
|
+
for (const each of list2) {
|
|
1427
|
+
const endpoint = parseEndpoint(each);
|
|
1428
|
+
if (typeof endpoint === "string")
|
|
1429
|
+
return adminError2(400, endpoint);
|
|
1430
|
+
parsed.push(endpoint);
|
|
1431
|
+
}
|
|
1432
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1433
|
+
return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1434
|
+
},
|
|
1435
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1436
|
+
hub.setEndpoints(namespace, []);
|
|
1437
|
+
return json3(200, { status: "ok" });
|
|
1438
|
+
}
|
|
1439
|
+
});
|
|
1440
|
+
var parsePayload = (message) => {
|
|
1441
|
+
if (message.contentType.startsWith("application/json")) {
|
|
1442
|
+
try {
|
|
1443
|
+
return JSON.parse(message.body);
|
|
1444
|
+
} catch {
|
|
1445
|
+
return message.body;
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1449
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
1450
|
+
}
|
|
1451
|
+
return message.body;
|
|
1452
|
+
};
|
|
1453
|
+
|
|
1454
|
+
// ../core/dist/runtime.js
|
|
1455
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1456
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1457
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1458
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1459
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1460
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1461
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1462
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1463
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1464
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1465
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1466
|
+
if (!previous || previous.length === 0)
|
|
1467
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1468
|
+
const result = new Array(fresh.length);
|
|
1469
|
+
let unchanged = fresh.length === previous.length;
|
|
1470
|
+
let oldIndex = 0;
|
|
1471
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1472
|
+
const row = fresh[index];
|
|
1473
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1474
|
+
oldIndex++;
|
|
1475
|
+
}
|
|
1476
|
+
const old = previous[oldIndex];
|
|
1477
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1478
|
+
if (result[index] !== previous[index])
|
|
1479
|
+
unchanged = false;
|
|
1480
|
+
}
|
|
1481
|
+
return unchanged ? previous : result;
|
|
1482
|
+
};
|
|
1483
|
+
var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
|
|
1484
|
+
var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
|
|
1485
|
+
var DroppedConnectionError = class extends TypeError {
|
|
1486
|
+
code = "MOCKINGBIRD_DROP";
|
|
1487
|
+
constructor() {
|
|
1488
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
1489
|
+
this.name = "TypeError";
|
|
1490
|
+
}
|
|
1491
|
+
};
|
|
1492
|
+
var operationMatcher = (document2) => {
|
|
1493
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
1494
|
+
operationId: operation.operationId,
|
|
1495
|
+
method: operation.method.toUpperCase(),
|
|
1496
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
1497
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
1498
|
+
})).sort((a, b) => a.params - b.params);
|
|
1499
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
1500
|
+
};
|
|
1501
|
+
var createRuntime = (options) => {
|
|
1502
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
1503
|
+
const clock = options.clock ?? createClock();
|
|
1504
|
+
const rng = createRng(options.seed ?? 0);
|
|
1505
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
1506
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
1507
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1508
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
1509
|
+
const metrics = createMetrics();
|
|
1510
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
1511
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
1512
|
+
const instances = /* @__PURE__ */ new Map();
|
|
1513
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
1514
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
1515
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
1516
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
1517
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1518
|
+
const credentials = createCredentialRegistry();
|
|
1519
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
1520
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
1521
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
1522
|
+
const existing = instances.get(key);
|
|
1523
|
+
if (existing)
|
|
1524
|
+
return existing;
|
|
1525
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
1526
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
1527
|
+
}
|
|
1528
|
+
const created = options.create({
|
|
1529
|
+
namespace: storageNamespace(key),
|
|
1530
|
+
publicNamespace,
|
|
1531
|
+
sqlite,
|
|
1532
|
+
clock,
|
|
1533
|
+
rng: isolatedRng ?? rng
|
|
1534
|
+
});
|
|
1535
|
+
instances.set(key, created);
|
|
1536
|
+
publicNamespaces.add(publicNamespace);
|
|
1537
|
+
if (isolatedRng)
|
|
1538
|
+
branchRngs.set(key, isolatedRng);
|
|
1539
|
+
return created;
|
|
1540
|
+
};
|
|
1541
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
1542
|
+
const capture = (storage) => {
|
|
1543
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
1544
|
+
const previous = captured.get(storage);
|
|
1545
|
+
const snapshot2 = {
|
|
1546
|
+
namespace: fresh.namespace,
|
|
1547
|
+
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),
|
|
1548
|
+
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)
|
|
1549
|
+
};
|
|
1550
|
+
Object.freeze(snapshot2.records);
|
|
1551
|
+
Object.freeze(snapshot2.sequences);
|
|
1552
|
+
Object.freeze(snapshot2);
|
|
1553
|
+
captured.set(storage, snapshot2);
|
|
1554
|
+
return Object.freeze({
|
|
1555
|
+
snapshot: snapshot2,
|
|
1556
|
+
clock: Object.freeze(clock.state()),
|
|
1557
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
1558
|
+
});
|
|
1559
|
+
};
|
|
1560
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
1561
|
+
let found = timelines.get(name);
|
|
1562
|
+
if (found)
|
|
1563
|
+
return found;
|
|
1564
|
+
instance(name);
|
|
1565
|
+
found = new Timeline({
|
|
1566
|
+
now: clock.now,
|
|
1567
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
1568
|
+
});
|
|
1569
|
+
found.commit(capture(name));
|
|
1570
|
+
timelines.set(name, found);
|
|
1571
|
+
return found;
|
|
1572
|
+
};
|
|
1573
|
+
const physicalBranch = (namespace, branch2) => {
|
|
1574
|
+
if (branch2 === "main")
|
|
1575
|
+
return namespace;
|
|
1576
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
1577
|
+
const existing = branchStorage.get(mapKey);
|
|
1578
|
+
if (existing)
|
|
1579
|
+
return existing;
|
|
1580
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
1581
|
+
branchStorage.set(mapKey, key);
|
|
1582
|
+
return key;
|
|
1583
|
+
};
|
|
1584
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
1585
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
1586
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
1587
|
+
const history = timeline(namespace);
|
|
1588
|
+
if (branch2 === "main") {
|
|
1589
|
+
if (at !== void 0) {
|
|
1590
|
+
const point = history.checkout("main", at);
|
|
1591
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
1592
|
+
captured.set(namespace, point.value.snapshot);
|
|
1593
|
+
rng.setState(point.value.rngState);
|
|
1594
|
+
clock.set(point.value.clock.now);
|
|
1595
|
+
if (point.value.clock.frozen)
|
|
1596
|
+
clock.freeze();
|
|
1597
|
+
else
|
|
1598
|
+
clock.unfreeze();
|
|
1599
|
+
}
|
|
1600
|
+
return namespace;
|
|
1601
|
+
}
|
|
1602
|
+
const storage = physicalBranch(namespace, branch2);
|
|
1603
|
+
if (!history.hasBranch(branch2)) {
|
|
1604
|
+
if (at === void 0)
|
|
1605
|
+
history.commit(capture(namespace));
|
|
1606
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
1607
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1608
|
+
if (point)
|
|
1609
|
+
branchRng.setState(point.value.rngState);
|
|
1610
|
+
instanceFor(storage, namespace, branchRng);
|
|
1611
|
+
if (point)
|
|
1612
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1613
|
+
if (point)
|
|
1614
|
+
captured.set(storage, point.value.snapshot);
|
|
1615
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
1616
|
+
const point = history.checkout(branch2, at);
|
|
1617
|
+
if (!instances.has(storage)) {
|
|
1618
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1619
|
+
branchRng.setState(point.value.rngState);
|
|
1620
|
+
instanceFor(storage, namespace, branchRng);
|
|
1621
|
+
}
|
|
1622
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
1623
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1624
|
+
captured.set(storage, point.value.snapshot);
|
|
1625
|
+
} else {
|
|
1626
|
+
if (!instances.has(storage)) {
|
|
1627
|
+
const point = history.head(branch2);
|
|
1628
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1629
|
+
if (point)
|
|
1630
|
+
branchRng.setState(point.value.rngState);
|
|
1631
|
+
instanceFor(storage, namespace, branchRng);
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
return storage;
|
|
1635
|
+
};
|
|
1636
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
1637
|
+
const storage = ensureBranch(namespace, branch2);
|
|
1638
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
1639
|
+
};
|
|
1640
|
+
const branch = (name, branchOptions = {}) => {
|
|
1641
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1642
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
1643
|
+
const head = timeline(namespace).head(name);
|
|
1644
|
+
if (!head)
|
|
1645
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
1646
|
+
return head;
|
|
1647
|
+
};
|
|
1648
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
1649
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1650
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
1651
|
+
const history = timeline(namespace);
|
|
1652
|
+
const point = history.checkout(branchName, checkpointId);
|
|
1653
|
+
const storage = ensureBranch(namespace, branchName);
|
|
1654
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1655
|
+
captured.set(storage, point.value.snapshot);
|
|
1656
|
+
clock.set(point.value.clock.now);
|
|
1657
|
+
if (point.value.clock.frozen)
|
|
1658
|
+
clock.freeze();
|
|
1659
|
+
else
|
|
1660
|
+
clock.unfreeze();
|
|
1661
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
1662
|
+
};
|
|
1663
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
1664
|
+
if (name === "*") {
|
|
1665
|
+
options.webhooks?.clear();
|
|
1666
|
+
for (const each of instances.values())
|
|
1667
|
+
await each.reset();
|
|
1668
|
+
timelines.clear();
|
|
1669
|
+
branchStorage.clear();
|
|
1670
|
+
branchRngs.clear();
|
|
1671
|
+
captured.clear();
|
|
1672
|
+
return;
|
|
1673
|
+
}
|
|
1674
|
+
options.webhooks?.clear(name);
|
|
1675
|
+
const target = instances.get(name);
|
|
1676
|
+
if (target)
|
|
1677
|
+
await target.reset();
|
|
1678
|
+
else
|
|
1679
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
1680
|
+
for (const [mapping, storage] of branchStorage) {
|
|
1681
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
1682
|
+
continue;
|
|
1683
|
+
const branchInstance = instances.get(storage);
|
|
1684
|
+
if (branchInstance)
|
|
1685
|
+
await branchInstance.reset();
|
|
1686
|
+
else
|
|
1687
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
1688
|
+
branchStorage.delete(mapping);
|
|
1689
|
+
branchRngs.delete(storage);
|
|
1690
|
+
captured.delete(storage);
|
|
1691
|
+
}
|
|
1692
|
+
timelines.delete(name);
|
|
1693
|
+
captured.delete(name);
|
|
1694
|
+
};
|
|
1695
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
1696
|
+
return checkpoint(name, "main").value.snapshot;
|
|
1697
|
+
};
|
|
1698
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
1699
|
+
instance(name);
|
|
1700
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
1701
|
+
captured.set(name, from);
|
|
1702
|
+
const history = timelines.get(name);
|
|
1703
|
+
if (history)
|
|
1704
|
+
history.commit(capture(name), { branch: "main" });
|
|
1705
|
+
else
|
|
1706
|
+
timeline(name);
|
|
1707
|
+
};
|
|
1708
|
+
const runtime = {
|
|
1709
|
+
name: options.name,
|
|
1710
|
+
sqlite,
|
|
1711
|
+
clock,
|
|
1712
|
+
faults,
|
|
1713
|
+
metrics,
|
|
1714
|
+
journal,
|
|
1715
|
+
rng,
|
|
1716
|
+
credentials,
|
|
1717
|
+
webhooks: options.webhooks,
|
|
1718
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
1719
|
+
const preset = options.presets?.[name];
|
|
1720
|
+
if (!preset)
|
|
1721
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
1722
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
1723
|
+
namespace,
|
|
1724
|
+
...rule,
|
|
1725
|
+
...overrides,
|
|
1726
|
+
preset: name,
|
|
1727
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
1728
|
+
}));
|
|
1729
|
+
if (preset.webhook && options.webhooks) {
|
|
1730
|
+
options.webhooks.fault(namespace, {
|
|
1731
|
+
...preset.webhook,
|
|
1732
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
1733
|
+
});
|
|
1734
|
+
}
|
|
1735
|
+
return added;
|
|
1736
|
+
},
|
|
1737
|
+
instance,
|
|
1738
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
1739
|
+
reset,
|
|
1740
|
+
snapshot,
|
|
1741
|
+
restore,
|
|
1742
|
+
checkpoint,
|
|
1743
|
+
branch,
|
|
1744
|
+
checkout,
|
|
1745
|
+
timeline,
|
|
1746
|
+
fetch: async (incoming) => {
|
|
1747
|
+
let request = incoming;
|
|
1748
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
1749
|
+
if (prefixed) {
|
|
1750
|
+
const url2 = new URL(request.url);
|
|
1751
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
1752
|
+
const headers = new Headers(request.headers);
|
|
1753
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
1754
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
1755
|
+
}
|
|
1756
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
1757
|
+
request = new Request(url2, {
|
|
1758
|
+
method: request.method,
|
|
1759
|
+
headers,
|
|
1760
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
1761
|
+
signal: request.signal
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
let namespace = control.namespaceOf(request);
|
|
1765
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
1766
|
+
const credential = options.credential(request);
|
|
1767
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
1768
|
+
if (mapped !== void 0)
|
|
1769
|
+
namespace = mapped;
|
|
1770
|
+
}
|
|
1771
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
1772
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
1773
|
+
const stamp = (response2) => {
|
|
1774
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
1775
|
+
try {
|
|
1776
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1777
|
+
return response2;
|
|
1778
|
+
} catch {
|
|
1779
|
+
const copy = new Response(response2.body, response2);
|
|
1780
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1781
|
+
return copy;
|
|
1782
|
+
}
|
|
1783
|
+
};
|
|
1784
|
+
const handled = await control.handle(request);
|
|
1785
|
+
if (handled)
|
|
1786
|
+
return stamp(handled);
|
|
1787
|
+
const started = monotonicNow();
|
|
1788
|
+
const url = new URL(request.url);
|
|
1789
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
1790
|
+
const log = (status, faultId, response2) => {
|
|
1791
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
1792
|
+
const entry = {
|
|
1793
|
+
service: options.name,
|
|
1794
|
+
namespace,
|
|
1795
|
+
operationId,
|
|
1796
|
+
method: request.method,
|
|
1797
|
+
path: url.pathname,
|
|
1798
|
+
status,
|
|
1799
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
1800
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
1801
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
1802
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
1803
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
1804
|
+
};
|
|
1805
|
+
metrics.record(entry);
|
|
1806
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
1807
|
+
options.onLog?.(entry);
|
|
1808
|
+
};
|
|
1809
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
1810
|
+
log(400);
|
|
1811
|
+
return stamp(new Response(JSON.stringify({
|
|
1812
|
+
error: {
|
|
1813
|
+
type: "mockingbird_admin",
|
|
1814
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
1815
|
+
}
|
|
1816
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
1817
|
+
}
|
|
1818
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
1819
|
+
log(400);
|
|
1820
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
1821
|
+
}
|
|
1822
|
+
let storage;
|
|
1823
|
+
try {
|
|
1824
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
1825
|
+
const point = timeline(namespace).get(at);
|
|
1826
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
1827
|
+
let viewRng = branchRngs.get(storage);
|
|
1828
|
+
if (!viewRng) {
|
|
1829
|
+
viewRng = createRng(options.seed ?? 0);
|
|
1830
|
+
instanceFor(storage, namespace, viewRng);
|
|
1831
|
+
}
|
|
1832
|
+
viewRng.setState(point.value.rngState);
|
|
1833
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1834
|
+
captured.set(storage, point.value.snapshot);
|
|
1835
|
+
} else {
|
|
1836
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
1837
|
+
}
|
|
1838
|
+
} catch (error) {
|
|
1839
|
+
log(409);
|
|
1840
|
+
return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
|
|
1841
|
+
}
|
|
1842
|
+
const hits = await faults.take({
|
|
1843
|
+
operationId,
|
|
1844
|
+
method: request.method,
|
|
1845
|
+
path: url.pathname,
|
|
1846
|
+
namespace
|
|
1847
|
+
});
|
|
1848
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
1849
|
+
if (final?.drop) {
|
|
1850
|
+
log(0, final.id);
|
|
1851
|
+
throw new DroppedConnectionError();
|
|
1852
|
+
}
|
|
1853
|
+
if (final?.response) {
|
|
1854
|
+
log(final.response.status, final.id);
|
|
1855
|
+
return stamp(final.response);
|
|
1856
|
+
}
|
|
1857
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
1858
|
+
if (fired.length > 0)
|
|
1859
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
1860
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
1861
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
1862
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
1863
|
+
response = mutableResponse(response);
|
|
1864
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
1865
|
+
}
|
|
1866
|
+
if (selectedBranch !== "main") {
|
|
1867
|
+
response = mutableResponse(response);
|
|
1868
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
1869
|
+
}
|
|
1870
|
+
if (at !== void 0) {
|
|
1871
|
+
response = mutableResponse(response);
|
|
1872
|
+
response.headers.set(AT_HEADER, at);
|
|
1873
|
+
}
|
|
1874
|
+
log(response.status, fired[0]?.id, response);
|
|
1875
|
+
return stamp(response);
|
|
1876
|
+
}
|
|
1877
|
+
};
|
|
1878
|
+
const control = createControlPlane({
|
|
1879
|
+
name: options.name,
|
|
1880
|
+
startedAt: wallNow(),
|
|
1881
|
+
wallNow,
|
|
1882
|
+
clock,
|
|
1883
|
+
faults,
|
|
1884
|
+
metrics,
|
|
1885
|
+
journal,
|
|
1886
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
1887
|
+
namespaces: runtime.namespaces,
|
|
1888
|
+
reset,
|
|
1889
|
+
timeTravel: {
|
|
1890
|
+
checkpoint: (name, branchName) => {
|
|
1891
|
+
const point = checkpoint(name, branchName);
|
|
1892
|
+
return {
|
|
1893
|
+
id: point.id,
|
|
1894
|
+
branch: point.branch,
|
|
1895
|
+
parent: point.parent,
|
|
1896
|
+
at: point.at,
|
|
1897
|
+
records: point.value.snapshot.records.length
|
|
1898
|
+
};
|
|
1899
|
+
},
|
|
1900
|
+
branch: (branchName, branchOptions) => {
|
|
1901
|
+
const point = branch(branchName, branchOptions);
|
|
1902
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
1903
|
+
},
|
|
1904
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
1905
|
+
retain: (name, checkpointId) => {
|
|
1906
|
+
timeline(name).retain(checkpointId);
|
|
1907
|
+
},
|
|
1908
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
1909
|
+
inspect: (name) => {
|
|
1910
|
+
const history = timeline(name);
|
|
1911
|
+
return {
|
|
1912
|
+
branches: history.branches(),
|
|
1913
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
1914
|
+
id,
|
|
1915
|
+
branch: branchName,
|
|
1916
|
+
parent,
|
|
1917
|
+
at
|
|
1918
|
+
}))
|
|
1919
|
+
};
|
|
1920
|
+
}
|
|
1921
|
+
},
|
|
1922
|
+
describe: options.describe ?? (() => ({})),
|
|
1923
|
+
...options.presets ? {
|
|
1924
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
1925
|
+
} : {},
|
|
1926
|
+
routes: {
|
|
1927
|
+
...credentialRoutes(credentials),
|
|
1928
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
1929
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
1930
|
+
...options.admin?.(runtime) ?? {}
|
|
1931
|
+
},
|
|
1932
|
+
adminKey: options.adminKey
|
|
1933
|
+
});
|
|
1934
|
+
return runtime;
|
|
1935
|
+
};
|
|
1936
|
+
var mutableResponse = (response) => {
|
|
1937
|
+
try {
|
|
1938
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
1939
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
1940
|
+
return response;
|
|
1941
|
+
} catch {
|
|
1942
|
+
return new Response(response.body, response);
|
|
1943
|
+
}
|
|
1944
|
+
};
|
|
1945
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1946
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
1947
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1948
|
+
var credentialRoutes = (registry) => ({
|
|
1949
|
+
"GET /credentials": () => adminJson(200, {
|
|
1950
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
1951
|
+
credential: maskCredential(credential),
|
|
1952
|
+
namespace
|
|
1953
|
+
}))
|
|
1954
|
+
}),
|
|
1955
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
1956
|
+
const pairs = [];
|
|
1957
|
+
const list2 = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
1958
|
+
if (Array.isArray(list2)) {
|
|
1959
|
+
for (const each of list2) {
|
|
1960
|
+
if (typeof each === "string")
|
|
1961
|
+
pairs.push([each, namespace]);
|
|
1962
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
1963
|
+
pairs.push([
|
|
1964
|
+
each.credential,
|
|
1965
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
1966
|
+
]);
|
|
1967
|
+
} else
|
|
1968
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
1969
|
+
}
|
|
1970
|
+
} else if (isObject(list2)) {
|
|
1971
|
+
for (const [credential, target] of Object.entries(list2)) {
|
|
1972
|
+
if (typeof target !== "string")
|
|
1973
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
1974
|
+
pairs.push([credential, target]);
|
|
1975
|
+
}
|
|
1976
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
1977
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
1978
|
+
} else {
|
|
1979
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
1980
|
+
}
|
|
1981
|
+
for (const [credential, target] of pairs) {
|
|
1982
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
1983
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
1984
|
+
registry.set(credential, target);
|
|
1985
|
+
}
|
|
1986
|
+
return adminJson(200, { mapped: pairs.length });
|
|
1987
|
+
},
|
|
1988
|
+
"DELETE /credentials": ({ url }) => {
|
|
1989
|
+
const credential = url.searchParams.get("credential");
|
|
1990
|
+
if (credential === null)
|
|
1991
|
+
registry.clear();
|
|
1992
|
+
else
|
|
1993
|
+
registry.remove(credential);
|
|
1994
|
+
return adminJson(200, { status: "ok" });
|
|
1995
|
+
}
|
|
1996
|
+
});
|
|
1997
|
+
var presetRoutes = (presets, runtime) => ({
|
|
1998
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
1999
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2000
|
+
}),
|
|
2001
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2002
|
+
const name = params.name;
|
|
2003
|
+
if (!presets[name])
|
|
2004
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2005
|
+
const overrides = isObject(body) ? body : {};
|
|
2006
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2007
|
+
}
|
|
2008
|
+
});
|
|
2009
|
+
|
|
2010
|
+
// src/generated/openapi.ts
|
|
2011
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Slack incoming webhooks and Web API (Mockingbird subset)","description":"Stateful mock subset of Slack: incoming webhooks (\`POST /services/T/B/X\`) and the Web API\\nmethods our apps call. Every message lands in an outbox a suite can assert on. Hand-authored\\nfrom Slack's documented wire shapes and the consumers (backend \`postSlackWebhook\`, EMR\\n\`slack-web-api.ts\`, request-intake \`SlackClient\`, release-conductor).\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from https://api.slack.com/methods and https://api.slack.com/messaging/webhooks (Slack publishes no maintained OpenAPI for these methods)."}},"servers":[{"url":"https://slack.com"},{"url":"https://hooks.slack.com"}],"security":[{"bearerAuth":[]}],"paths":{"/services/{team}/{bot}/{secret}":{"parameters":[{"name":"team","in":"path","required":true,"schema":{"type":"string","pattern":"^T[A-Z0-9]{2,12}$"}},{"name":"bot","in":"path","required":true,"schema":{"type":"string","pattern":"^B[A-Z0-9]{2,12}$"}},{"name":"secret","in":"path","required":true,"schema":{"type":"string","pattern":"^[A-Za-z0-9]{8,24}$"}}],"post":{"operationId":"PostIncomingWebhook","summary":"Incoming webhook: post a message to the hook's channel","description":"Answers \`200 ok\` (text/plain). Bad payloads get Slack's plain-text error codes (\`invalid_payload\`, \`no_text\`, \`invalid_blocks\`); an unregistered hook is \`404 no_service\` once any hook is registered. Also accepts form bodies with a \`payload=<json>\` field.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"text":{"type":"string","maxLength":400},"blocks":{"type":"array","maxItems":3,"items":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["section","divider","header","context"]},"text":{"type":"object","properties":{"type":{"type":"string","enum":["mrkdwn","plain_text"]},"text":{"type":"string","maxLength":200}}}}}},"thread_ts":{"type":"string","maxLength":24},"username":{"type":"string","maxLength":40},"icon_emoji":{"type":"string","maxLength":40},"unfurl_links":{"type":"boolean"}}}}}},"responses":{"200":{"description":"Posted","content":{"text/plain":{"schema":{"type":"string","enum":["ok"]}}}},"400":{"description":"\`invalid_payload\`, \`no_text\`, \`invalid_blocks\`, \`too_many_attachments\`","content":{"text/plain":{"schema":{"type":"string"}}}},"403":{"description":"\`action_prohibited\`, \`posting_to_general_channel_denied\`","content":{"text/plain":{"schema":{"type":"string"}}}},"404":{"description":"\`no_service\`, \`channel_not_found\`","content":{"text/plain":{"schema":{"type":"string"}}}},"410":{"description":"\`channel_is_archived\`","content":{"text/plain":{"schema":{"type":"string"}}}},"429":{"description":"\`rate_limited\`, with \`retry-after\`","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"text/plain":{"schema":{"type":"string"}}}},"500":{"description":"\`internal_error\`","content":{"text/plain":{"schema":{"type":"string"}}}},"503":{"description":"\`service_unavailable\`","content":{"text/plain":{"schema":{"type":"string"}}}}},"security":[]}},"/api/chat.postMessage":{"post":{"operationId":"ChatPostMessage","summary":"chat.postMessage: post a message (or a thread reply) to a channel","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"text":{"type":"string","maxLength":400},"blocks":{"type":"string","description":"JSON-encoded blocks","maxLength":2000},"thread_ts":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}}},"required":["channel"]}},"application/json":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"text":{"type":"string","maxLength":400},"blocks":{"type":"array","maxItems":3,"items":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["section","divider","header","context"]},"text":{"type":"object","properties":{"type":{"type":"string","enum":["mrkdwn","plain_text"]},"text":{"type":"string","maxLength":200}}}}}},"thread_ts":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}},"mrkdwn":{"type":"boolean"},"unfurl_links":{"type":"boolean"}},"required":["channel"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PostMessageResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/chat.update":{"post":{"operationId":"ChatUpdate","summary":"chat.update: edit a message the bot posted","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"ts":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}},"text":{"type":"string","maxLength":400}},"required":["channel","ts"]}},"application/json":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"ts":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}},"text":{"type":"string","maxLength":400},"blocks":{"type":"array","maxItems":3,"items":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["section","divider","header","context"]},"text":{"type":"object","properties":{"type":{"type":"string","enum":["mrkdwn","plain_text"]},"text":{"type":"string","maxLength":200}}}}}}},"required":["channel","ts"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/chat.postEphemeral":{"post":{"operationId":"ChatPostEphemeral","summary":"chat.postEphemeral: a message only one user sees","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"user":{"type":"string","minLength":1,"maxLength":20,"x-mockingbird-resource-ref":{"type":"user","missing":"U00MISSING"}},"text":{"type":"string","maxLength":400}},"required":["channel","user"]}},"application/json":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"user":{"type":"string","minLength":1,"maxLength":20,"x-mockingbird-resource-ref":{"type":"user","missing":"U00MISSING"}},"text":{"type":"string","maxLength":400},"blocks":{"type":"array","maxItems":3,"items":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["section","divider","header","context"]},"text":{"type":"object","properties":{"type":{"type":"string","enum":["mrkdwn","plain_text"]},"text":{"type":"string","maxLength":200}}}}}},"thread_ts":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}}},"required":["channel","user"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EphemeralResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/chat.getPermalink":{"get":{"operationId":"ChatGetPermalinkGet","summary":"chat.getPermalink (query arguments)","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"channel","in":"query","required":false,"schema":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"}},{"name":"message_ts","in":"query","required":false,"schema":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}}}],"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PermalinkResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}},"post":{"operationId":"ChatGetPermalink","summary":"chat.getPermalink: the permalink of a message","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"message_ts":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}}},"required":["channel","message_ts"]}},"application/json":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"message_ts":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}}},"required":["channel","message_ts"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PermalinkResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/reactions.add":{"post":{"operationId":"ReactionsAdd","summary":"reactions.add: react to a message","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"timestamp":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}},"name":{"type":"string","enum":["eyes","white_check_mark","x","thumbsup","rotating_light"]}},"required":["channel","timestamp","name"]}},"application/json":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"timestamp":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}},"name":{"type":"string","enum":["eyes","white_check_mark","x","thumbsup","rotating_light"]}},"required":["channel","timestamp","name"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Envelope"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/reactions.remove":{"post":{"operationId":"ReactionsRemove","summary":"reactions.remove: take a reaction back","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"timestamp":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}},"name":{"type":"string","enum":["eyes","white_check_mark","x","thumbsup","rotating_light"]}},"required":["name"]}},"application/json":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"timestamp":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}},"name":{"type":"string","enum":["eyes","white_check_mark","x","thumbsup","rotating_light"]}},"required":["name"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Envelope"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/reactions.get":{"get":{"operationId":"ReactionsGetGet","summary":"reactions.get (query arguments)","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"channel","in":"query","required":false,"schema":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"}},{"name":"timestamp","in":"query","required":false,"schema":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}}},{"name":"full","in":"query","required":false,"schema":{"type":"string","enum":["true","false"]}}],"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReactionsGetResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}},"post":{"operationId":"ReactionsGet","summary":"reactions.get: a message and its reactions","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"timestamp":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}},"full":{"type":"string","enum":["true","false"]}},"required":["channel","timestamp"]}},"application/json":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"},"timestamp":{"type":"string","maxLength":24,"x-mockingbird-resource-ref":{"type":"message","missing":"1000000000.000000"}},"full":{"type":"boolean"}},"required":["channel","timestamp"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReactionsGetResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/auth.test":{"get":{"operationId":"AuthTestGet","summary":"auth.test (GET)","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[],"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuthTestResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}},"post":{"operationId":"AuthTest","summary":"auth.test: who the token belongs to","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{}}},"application/json":{"schema":{"type":"object","properties":{}}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuthTestResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/conversations.join":{"post":{"operationId":"ConversationsJoin","summary":"conversations.join: the bot joins a public channel","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"}},"required":["channel"]}},"application/json":{"schema":{"type":"object","properties":{"channel":{"type":"string","minLength":1,"maxLength":40,"description":"Channel id (\`C\u2026\`) or name (\`#alerts\`)"}},"required":["channel"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/JoinResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/users.info":{"get":{"operationId":"UsersInfoGet","summary":"users.info (query arguments)","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"user","in":"query","required":false,"schema":{"type":"string","minLength":1,"maxLength":20,"x-mockingbird-resource-ref":{"type":"user","missing":"U00MISSING"}}}],"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}},"post":{"operationId":"UsersInfo","summary":"users.info: a user's profile","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"user":{"type":"string","minLength":1,"maxLength":20,"x-mockingbird-resource-ref":{"type":"user","missing":"U00MISSING"}}},"required":["user"]}},"application/json":{"schema":{"type":"object","properties":{"user":{"type":"string","minLength":1,"maxLength":20,"x-mockingbird-resource-ref":{"type":"user","missing":"U00MISSING"}}},"required":["user"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/users.lookupByEmail":{"get":{"operationId":"UsersLookupByEmailGet","summary":"users.lookupByEmail (query arguments)","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"email","in":"query","required":false,"schema":{"type":"string","format":"email","maxLength":80}}],"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}},"post":{"operationId":"UsersLookupByEmail","summary":"users.lookupByEmail: find a user by email","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"email":{"type":"string","format":"email","maxLength":80}},"required":["email"]}},"application/json":{"schema":{"type":"object","properties":{"email":{"type":"string","format":"email","maxLength":80}},"required":["email"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/files.info":{"get":{"operationId":"FilesInfoGet","summary":"files.info (query arguments)","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"file","in":"query","required":false,"schema":{"type":"string","minLength":1,"maxLength":20,"x-mockingbird-resource-ref":{"type":"file","missing":"F00MISSING"}}}],"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FileResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}},"post":{"operationId":"FilesInfo","summary":"files.info: a file's metadata and private download URL","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"file":{"type":"string","minLength":1,"maxLength":20,"x-mockingbird-resource-ref":{"type":"file","missing":"F00MISSING"}}},"required":["file"]}},"application/json":{"schema":{"type":"object","properties":{"file":{"type":"string","minLength":1,"maxLength":20,"x-mockingbird-resource-ref":{"type":"file","missing":"F00MISSING"}}},"required":["file"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FileResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}},"/api/views.open":{"post":{"operationId":"ViewsOpen","summary":"views.open: open a modal for a trigger","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":false,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"trigger_id":{"type":"string","minLength":1,"maxLength":40},"view":{"type":"string","description":"JSON-encoded view","maxLength":2000}},"required":["trigger_id","view"]}},"application/json":{"schema":{"type":"object","properties":{"trigger_id":{"type":"string","minLength":1,"maxLength":40},"view":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["modal","home"]},"callback_id":{"type":"string","maxLength":40},"title":{"type":"object","properties":{"type":{"type":"string","enum":["plain_text"]},"text":{"type":"string","maxLength":24}}},"blocks":{"type":"array","maxItems":3,"items":{"type":"object"}},"private_metadata":{"type":"string","maxLength":200}}}},"required":["trigger_id","view"]}}}},"responses":{"200":{"description":"Slack envelope: \`ok: true\` with the method's fields, or \`ok: false\` with an \`error\` code (Slack answers logical failures with HTTP 200)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ViewResponse"}}}},"429":{"description":"Rate limited (\`ratelimited\`), with \`retry-after\` seconds","headers":{"retry-after":{"schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"500":{"description":"Slack is having trouble","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}},"503":{"description":"Slack is unavailable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorEnvelope"}}}}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}},"schemas":{"Envelope":{"type":"object","required":["ok"],"properties":{"ok":{"type":"boolean"},"error":{"type":"string"},"warning":{"type":"string"},"needed":{"type":"string"},"provided":{"type":"string"},"response_metadata":{"type":"object","properties":{"messages":{"type":"array","items":{"type":"string"}},"warnings":{"type":"array","items":{"type":"string"}}}}}},"ErrorEnvelope":{"type":"object","required":["ok","error"],"properties":{"ok":{"type":"boolean","enum":[false]},"error":{"type":"string"}}},"Message":{"type":"object","required":["type","ts"],"properties":{"type":{"type":"string","enum":["message"]},"subtype":{"type":"string"},"text":{"type":"string"},"user":{"type":"string"},"bot_id":{"type":"string"},"app_id":{"type":"string"},"team":{"type":"string"},"ts":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"thread_ts":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"blocks":{"type":"array","items":{"type":"object"}},"edited":{"type":"object","properties":{"user":{"type":"string"},"ts":{"type":"string","x-mockingbird-volatile":{"kind":"id"}}}},"reactions":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"count":{"type":"integer"},"users":{"type":"array","items":{"type":"string"}}}}}}},"PostMessageResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"channel":{"type":"string"},"ts":{"type":"string","x-mockingbird-resource":{"type":"message","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"message":{"$ref":"#/components/schemas/Message"}}}]},"ReactionsGetResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"type":{"type":"string","enum":["message"]},"channel":{"type":"string"},"message":{"$ref":"#/components/schemas/Message"}}}]},"UpdateResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"channel":{"type":"string"},"ts":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"text":{"type":"string"},"message":{"$ref":"#/components/schemas/Message"}}}]},"EphemeralResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"message_ts":{"type":"string","x-mockingbird-volatile":{"kind":"id"}}}}]},"PermalinkResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"channel":{"type":"string"},"permalink":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}}]},"AuthTestResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"url":{"type":"string"},"team":{"type":"string"},"user":{"type":"string"},"team_id":{"type":"string"},"user_id":{"type":"string"},"bot_id":{"type":"string"},"is_enterprise_install":{"type":"boolean"}}}]},"Channel":{"type":"object","required":["id","name"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"is_channel":{"type":"boolean"},"is_private":{"type":"boolean"},"is_archived":{"type":"boolean"},"is_member":{"type":"boolean"},"created":{"type":"integer"}}},"JoinResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"channel":{"$ref":"#/components/schemas/Channel"}}}]},"User":{"type":"object","required":["id","name"],"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"user","identity":true}},"team_id":{"type":"string"},"name":{"type":"string"},"real_name":{"type":"string"},"deleted":{"type":"boolean"},"is_bot":{"type":"boolean"},"tz":{"type":"string"},"profile":{"type":"object","properties":{"email":{"type":"string"},"real_name":{"type":"string"},"display_name":{"type":"string"}}}}},"UserResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"user":{"$ref":"#/components/schemas/User"}}}]},"File":{"type":"object","required":["id"],"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"file","identity":true}},"name":{"type":"string"},"title":{"type":"string"},"mimetype":{"type":"string"},"filetype":{"type":"string"},"size":{"type":"integer"},"created":{"type":"integer"},"url_private":{"type":"string"},"url_private_download":{"type":"string"},"permalink":{"type":"string"}}},"FileResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"file":{"$ref":"#/components/schemas/File"}}}]},"ViewResponse":{"allOf":[{"$ref":"#/components/schemas/Envelope"},{"type":"object","properties":{"view":{"type":"object","properties":{"id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"type":{"type":"string"},"team_id":{"type":"string"},"callback_id":{"type":"string"},"hash":{"type":"string","x-mockingbird-volatile":{"kind":"opaque"}},"blocks":{"type":"array","items":{"type":"object"}},"state":{"type":"object"},"private_metadata":{"type":"string"},"title":{"type":"object"},"app_id":{"type":"string"},"bot_id":{"type":"string"}}}}}]}}}}`);
|
|
2012
|
+
var operationIds = ["PostIncomingWebhook", "ChatPostMessage", "ChatUpdate", "ChatPostEphemeral", "ChatGetPermalinkGet", "ChatGetPermalink", "ReactionsAdd", "ReactionsRemove", "ReactionsGetGet", "ReactionsGet", "AuthTestGet", "AuthTest", "ConversationsJoin", "UsersInfoGet", "UsersInfo", "UsersLookupByEmailGet", "UsersLookupByEmail", "FilesInfoGet", "FilesInfo", "ViewsOpen"];
|
|
2013
|
+
var supportedOperationIds = ["PostIncomingWebhook", "ChatPostMessage", "ChatUpdate", "ChatPostEphemeral", "ChatGetPermalinkGet", "ChatGetPermalink", "ReactionsAdd", "ReactionsRemove", "ReactionsGetGet", "ReactionsGet", "AuthTestGet", "AuthTest", "ConversationsJoin", "UsersInfoGet", "UsersInfo", "UsersLookupByEmailGet", "UsersLookupByEmail", "FilesInfoGet", "FilesInfo", "ViewsOpen"];
|
|
2014
|
+
|
|
2015
|
+
// src/state.ts
|
|
2016
|
+
var DEFAULT_SETTINGS = {
|
|
2017
|
+
teamId: "T0MOCKBIRD",
|
|
2018
|
+
teamName: "Mockingbird",
|
|
2019
|
+
teamDomain: "mockingbird",
|
|
2020
|
+
botUserId: "U0MOCKBOT",
|
|
2021
|
+
botId: "B0MOCKBOT",
|
|
2022
|
+
appId: "A0MOCKAPP",
|
|
2023
|
+
tokens: [],
|
|
2024
|
+
strictChannels: false
|
|
2025
|
+
};
|
|
2026
|
+
var DEFAULT_CHANNELS = [
|
|
2027
|
+
{
|
|
2028
|
+
id: "C0GENERAL",
|
|
2029
|
+
name: "general",
|
|
2030
|
+
is_private: false,
|
|
2031
|
+
is_archived: false,
|
|
2032
|
+
is_member: true,
|
|
2033
|
+
created: 17e8
|
|
2034
|
+
},
|
|
2035
|
+
{
|
|
2036
|
+
id: "C0ALERTS",
|
|
2037
|
+
name: "alerts",
|
|
2038
|
+
is_private: false,
|
|
2039
|
+
is_archived: false,
|
|
2040
|
+
is_member: false,
|
|
2041
|
+
created: 17e8
|
|
2042
|
+
}
|
|
2043
|
+
];
|
|
2044
|
+
var DEFAULT_USERS = [
|
|
2045
|
+
{
|
|
2046
|
+
id: "U0MOCKBOT",
|
|
2047
|
+
name: "mockingbird",
|
|
2048
|
+
real_name: "Mockingbird Bot",
|
|
2049
|
+
email: null,
|
|
2050
|
+
is_bot: true,
|
|
2051
|
+
deleted: false,
|
|
2052
|
+
tz: "America/Los_Angeles"
|
|
2053
|
+
},
|
|
2054
|
+
{
|
|
2055
|
+
id: "U0ADA",
|
|
2056
|
+
name: "ada",
|
|
2057
|
+
real_name: "Ada Lovelace",
|
|
2058
|
+
email: "ada@example.com",
|
|
2059
|
+
is_bot: false,
|
|
2060
|
+
deleted: false,
|
|
2061
|
+
tz: "America/Los_Angeles"
|
|
2062
|
+
}
|
|
2063
|
+
];
|
|
2064
|
+
var DEFAULT_FILES = [
|
|
2065
|
+
{
|
|
2066
|
+
id: "F0REPORT",
|
|
2067
|
+
name: "lab-report.pdf",
|
|
2068
|
+
title: "lab-report.pdf",
|
|
2069
|
+
mimetype: "application/pdf",
|
|
2070
|
+
filetype: "pdf",
|
|
2071
|
+
size: 48213,
|
|
2072
|
+
created: 17e8
|
|
2073
|
+
}
|
|
2074
|
+
];
|
|
2075
|
+
var SlackState = class {
|
|
2076
|
+
constructor(sqlite, namespace, seed) {
|
|
2077
|
+
this.seed = seed;
|
|
2078
|
+
this.outbox = new OutboxStore(sqlite, namespace);
|
|
2079
|
+
this.channels = new Collection(sqlite, namespace, "channels");
|
|
2080
|
+
this.users = new Collection(sqlite, namespace, "users");
|
|
2081
|
+
this.files = new Collection(sqlite, namespace, "files");
|
|
2082
|
+
this.hooks = new Collection(sqlite, namespace, "hooks");
|
|
2083
|
+
this.views = new Collection(sqlite, namespace, "views");
|
|
2084
|
+
this.settings = new Collection(sqlite, namespace, "settings");
|
|
2085
|
+
this.tsCounter = new Collection(sqlite, namespace, "ts");
|
|
2086
|
+
this.ensureSeeded();
|
|
2087
|
+
}
|
|
2088
|
+
seed;
|
|
2089
|
+
outbox;
|
|
2090
|
+
channels;
|
|
2091
|
+
users;
|
|
2092
|
+
files;
|
|
2093
|
+
hooks;
|
|
2094
|
+
views;
|
|
2095
|
+
settings;
|
|
2096
|
+
/** Only its sequence is used: the microsecond part of every `ts`. */
|
|
2097
|
+
tsCounter;
|
|
2098
|
+
/** Re-apply the default workspace after a reset. */
|
|
2099
|
+
ensureSeeded() {
|
|
2100
|
+
if (!this.settings.has("settings")) {
|
|
2101
|
+
this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
|
|
2102
|
+
}
|
|
2103
|
+
if (this.channels.count() === 0) {
|
|
2104
|
+
for (const channel of DEFAULT_CHANNELS) this.channels.insert(channel.id, channel);
|
|
2105
|
+
}
|
|
2106
|
+
if (this.users.count() === 0) {
|
|
2107
|
+
const bot = this.current().botUserId;
|
|
2108
|
+
for (const user of DEFAULT_USERS) {
|
|
2109
|
+
const id = user.is_bot ? bot : user.id;
|
|
2110
|
+
this.users.insert(id, { ...user, id });
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
if (this.files.count() === 0) {
|
|
2114
|
+
for (const file of DEFAULT_FILES) this.files.insert(file.id, file);
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
current() {
|
|
2118
|
+
return this.settings.get("settings") ?? DEFAULT_SETTINGS;
|
|
2119
|
+
}
|
|
2120
|
+
update(patch) {
|
|
2121
|
+
const next = { ...this.current(), ...patch };
|
|
2122
|
+
this.settings.insert("settings", next);
|
|
2123
|
+
return next;
|
|
2124
|
+
}
|
|
2125
|
+
/** `1700000000.000042`: mock-clock seconds, then a per-namespace counter as microseconds. */
|
|
2126
|
+
nextTs(nowMs) {
|
|
2127
|
+
const seq = this.tsCounter.nextSequence() % 1e6;
|
|
2128
|
+
return `${Math.floor(nowMs / 1e3)}.${String(seq).padStart(6, "0")}`;
|
|
2129
|
+
}
|
|
2130
|
+
/** By id (`C…`), or by name with or without `#`. */
|
|
2131
|
+
findChannel(ref) {
|
|
2132
|
+
const byId = this.channels.get(ref);
|
|
2133
|
+
if (byId) return byId;
|
|
2134
|
+
const name = ref.replace(/^#/, "").toLowerCase();
|
|
2135
|
+
return this.channels.list({ where: (c) => c.name === name }).at(0)?.value;
|
|
2136
|
+
}
|
|
2137
|
+
findUserByEmail(email) {
|
|
2138
|
+
const wanted = email.toLowerCase();
|
|
2139
|
+
return this.users.list({ where: (u) => u.email?.toLowerCase() === wanted }).at(0)?.value;
|
|
2140
|
+
}
|
|
2141
|
+
/** The message `ts` in `channel` (webhook posts are addressed by their hook's channel). */
|
|
2142
|
+
findMessage(channel, ts) {
|
|
2143
|
+
return this.outbox.list({ where: (m) => m.ts === ts && !m.ephemeral && m.channel === channel }).at(0);
|
|
2144
|
+
}
|
|
2145
|
+
};
|
|
2146
|
+
|
|
2147
|
+
// src/runtime.ts
|
|
2148
|
+
var SLACK_PRESETS = {
|
|
2149
|
+
rate_limited: {
|
|
2150
|
+
description: "Webhooks answer 429 rate_limited and the Web API 429 {ok:false, error:ratelimited}, both with retry-after (params.retryAfter seconds, default 1)",
|
|
2151
|
+
rules: [{ effect: "rate_limited", params: { retryAfter: 1 } }]
|
|
2152
|
+
},
|
|
2153
|
+
"5xx": {
|
|
2154
|
+
description: "Every call answers 500 internal_error (params.status 503 gives service_unavailable); our clients retry these",
|
|
2155
|
+
rules: [{ effect: "server_error", params: { status: 500 } }]
|
|
2156
|
+
},
|
|
2157
|
+
service_unavailable: {
|
|
2158
|
+
description: "Every call answers 503 service_unavailable",
|
|
2159
|
+
rules: [{ effect: "server_error", params: { status: 503 } }]
|
|
2160
|
+
},
|
|
2161
|
+
channel_not_found: {
|
|
2162
|
+
description: "Webhooks answer 404 channel_not_found; Web API channel methods answer {ok:false, error:channel_not_found}",
|
|
2163
|
+
rules: [{ effect: "channel_not_found" }]
|
|
2164
|
+
},
|
|
2165
|
+
no_service: {
|
|
2166
|
+
description: "Webhooks answer 404 no_service (the hook was revoked): a terminal 4xx",
|
|
2167
|
+
rules: [{ operationId: "PostIncomingWebhook", effect: "no_service" }]
|
|
2168
|
+
},
|
|
2169
|
+
invalid_auth: {
|
|
2170
|
+
description: "Web API calls answer {ok:false, error:invalid_auth} (the bot token was revoked)",
|
|
2171
|
+
rules: [{ pathPrefix: "/api/", effect: "invalid_auth" }]
|
|
2172
|
+
}
|
|
2173
|
+
};
|
|
2174
|
+
var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2175
|
+
var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
|
|
2176
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2177
|
+
var list = (body, key) => Array.isArray(body) ? body : isRecord4(body) && Array.isArray(body[key]) ? body[key] : void 0;
|
|
2178
|
+
var hookSuffix = (value) => {
|
|
2179
|
+
let path = value;
|
|
2180
|
+
try {
|
|
2181
|
+
if (/^https?:\/\//.test(value)) path = new URL(value).pathname;
|
|
2182
|
+
} catch {
|
|
2183
|
+
}
|
|
2184
|
+
return path.replace(/^\/?ns\/[^/]+/, "").replace(/^\/?services\//, "").replace(/^\/|\/$/g, "");
|
|
2185
|
+
};
|
|
2186
|
+
var outboxFilter = (params) => {
|
|
2187
|
+
const webhook = params.get("webhook");
|
|
2188
|
+
const channel = params.get("channel");
|
|
2189
|
+
const thread = params.get("thread_ts");
|
|
2190
|
+
const source = params.get("source");
|
|
2191
|
+
if (webhook === null && channel === null && thread === null && source === null) return void 0;
|
|
2192
|
+
return (item) => {
|
|
2193
|
+
if (webhook !== null && item.webhook !== `/services/${hookSuffix(webhook)}`) return false;
|
|
2194
|
+
if (channel !== null) {
|
|
2195
|
+
const wanted = channel.toLowerCase().replace(/^#/, "");
|
|
2196
|
+
const recipients = item.to.map((t) => t.toLowerCase().replace(/^#/, ""));
|
|
2197
|
+
if (!recipients.includes(wanted)) return false;
|
|
2198
|
+
}
|
|
2199
|
+
if (thread !== null && item.thread_ts !== thread) return false;
|
|
2200
|
+
if (source !== null && item.source !== source) return false;
|
|
2201
|
+
return true;
|
|
2202
|
+
};
|
|
2203
|
+
};
|
|
2204
|
+
var adminRoutes = (runtime) => ({
|
|
2205
|
+
...outboxAdminRoutes(
|
|
2206
|
+
runtime,
|
|
2207
|
+
(api) => api.state.outbox,
|
|
2208
|
+
outboxFilter
|
|
2209
|
+
),
|
|
2210
|
+
"GET /hooks": ({ namespace }) => json4(200, {
|
|
2211
|
+
hooks: runtime.instance(namespace).state.hooks.list({ order: "oldest" }).map((row) => ({ ...row.value, url: `/services/${row.value.path}` }))
|
|
2212
|
+
}),
|
|
2213
|
+
"POST /hooks": ({ body, namespace }) => {
|
|
2214
|
+
const entries = list(body, "hooks") ?? (isRecord4(body) ? [body] : void 0);
|
|
2215
|
+
if (!entries || entries.some((e) => !isRecord4(e) || typeof e.path !== "string")) {
|
|
2216
|
+
return adminError3(400, 'expected {"path": "T\u2026/B\u2026/X\u2026", "channel"?: "C\u2026"} or {"hooks": [...]}');
|
|
2217
|
+
}
|
|
2218
|
+
const api = runtime.instance(namespace);
|
|
2219
|
+
const created = entries.map((entry) => {
|
|
2220
|
+
const path = hookSuffix(entry.path);
|
|
2221
|
+
const hook = {
|
|
2222
|
+
path,
|
|
2223
|
+
channel: typeof entry.channel === "string" ? entry.channel : `/services/${path}`
|
|
2224
|
+
};
|
|
2225
|
+
api.state.hooks.insert(path, hook);
|
|
2226
|
+
return { ...hook, url: `/services/${path}` };
|
|
2227
|
+
});
|
|
2228
|
+
return json4(201, { hooks: created });
|
|
2229
|
+
},
|
|
2230
|
+
"DELETE /hooks": ({ namespace, url }) => {
|
|
2231
|
+
const api = runtime.instance(namespace);
|
|
2232
|
+
const only = url.searchParams.get("path");
|
|
2233
|
+
for (const row of api.state.hooks.list()) {
|
|
2234
|
+
if (only === null || row.id === hookSuffix(only)) api.state.hooks.delete(row.id);
|
|
2235
|
+
}
|
|
2236
|
+
return json4(200, { status: "ok" });
|
|
2237
|
+
},
|
|
2238
|
+
"GET /channels": ({ namespace }) => json4(200, {
|
|
2239
|
+
channels: runtime.instance(namespace).state.channels.list({ order: "oldest" }).map((r) => r.value)
|
|
2240
|
+
}),
|
|
2241
|
+
"POST /channels": ({ body, namespace }) => {
|
|
2242
|
+
const entries = list(body, "channels") ?? (isRecord4(body) ? [body] : void 0);
|
|
2243
|
+
if (!entries || entries.some((e) => !isRecord4(e) || typeof e.name !== "string")) {
|
|
2244
|
+
return adminError3(
|
|
2245
|
+
400,
|
|
2246
|
+
'expected {"id"?, "name", "is_private"?, "is_archived"?, "is_member"?}'
|
|
2247
|
+
);
|
|
2248
|
+
}
|
|
2249
|
+
const api = runtime.instance(namespace);
|
|
2250
|
+
const saved = entries.map((entry) => {
|
|
2251
|
+
const name = entry.name.replace(/^#/, "").toLowerCase();
|
|
2252
|
+
const channel = {
|
|
2253
|
+
id: typeof entry.id === "string" ? entry.id : `C${name.toUpperCase().replace(/[^A-Z0-9]/g, "")}`.slice(0, 11),
|
|
2254
|
+
name,
|
|
2255
|
+
is_private: entry.is_private === true,
|
|
2256
|
+
is_archived: entry.is_archived === true,
|
|
2257
|
+
is_member: entry.is_member !== false,
|
|
2258
|
+
created: Math.floor(runtime.clock.now() / 1e3)
|
|
2259
|
+
};
|
|
2260
|
+
api.state.channels.insert(channel.id, channel);
|
|
2261
|
+
return channel;
|
|
2262
|
+
});
|
|
2263
|
+
return json4(201, { channels: saved });
|
|
2264
|
+
},
|
|
2265
|
+
"GET /users": ({ namespace }) => json4(200, {
|
|
2266
|
+
users: runtime.instance(namespace).state.users.list({ order: "oldest" }).map((r) => r.value)
|
|
2267
|
+
}),
|
|
2268
|
+
"POST /users": ({ body, namespace }) => {
|
|
2269
|
+
const entries = list(body, "users") ?? (isRecord4(body) ? [body] : void 0);
|
|
2270
|
+
if (!entries || entries.some((e) => !isRecord4(e) || typeof e.id !== "string")) {
|
|
2271
|
+
return adminError3(400, 'expected {"id": "U\u2026", "name"?, "real_name"?, "email"?}');
|
|
2272
|
+
}
|
|
2273
|
+
const api = runtime.instance(namespace);
|
|
2274
|
+
const saved = entries.map((entry) => {
|
|
2275
|
+
const id = entry.id;
|
|
2276
|
+
const user = {
|
|
2277
|
+
id,
|
|
2278
|
+
name: typeof entry.name === "string" ? entry.name : id.toLowerCase(),
|
|
2279
|
+
real_name: typeof entry.real_name === "string" ? entry.real_name : id,
|
|
2280
|
+
email: typeof entry.email === "string" ? entry.email : null,
|
|
2281
|
+
is_bot: entry.is_bot === true,
|
|
2282
|
+
deleted: entry.deleted === true,
|
|
2283
|
+
tz: typeof entry.tz === "string" ? entry.tz : "America/Los_Angeles"
|
|
2284
|
+
};
|
|
2285
|
+
api.state.users.insert(id, user);
|
|
2286
|
+
return user;
|
|
2287
|
+
});
|
|
2288
|
+
return json4(201, { users: saved });
|
|
2289
|
+
},
|
|
2290
|
+
"POST /files": ({ body, namespace }) => {
|
|
2291
|
+
const entries = list(body, "files") ?? (isRecord4(body) ? [body] : void 0);
|
|
2292
|
+
if (!entries || entries.some((e) => !isRecord4(e) || typeof e.id !== "string")) {
|
|
2293
|
+
return adminError3(400, 'expected {"id": "F\u2026", "name"?, "mimetype"?, "size"?}');
|
|
2294
|
+
}
|
|
2295
|
+
const api = runtime.instance(namespace);
|
|
2296
|
+
const saved = entries.map((entry) => {
|
|
2297
|
+
const id = entry.id;
|
|
2298
|
+
const name = typeof entry.name === "string" ? entry.name : `${id}.bin`;
|
|
2299
|
+
const file = {
|
|
2300
|
+
id,
|
|
2301
|
+
name,
|
|
2302
|
+
title: typeof entry.title === "string" ? entry.title : name,
|
|
2303
|
+
mimetype: typeof entry.mimetype === "string" ? entry.mimetype : "application/octet-stream",
|
|
2304
|
+
filetype: typeof entry.filetype === "string" ? entry.filetype : "binary",
|
|
2305
|
+
size: typeof entry.size === "number" ? entry.size : 0,
|
|
2306
|
+
created: Math.floor(runtime.clock.now() / 1e3)
|
|
2307
|
+
};
|
|
2308
|
+
api.state.files.insert(id, file);
|
|
2309
|
+
return file;
|
|
2310
|
+
});
|
|
2311
|
+
return json4(201, { files: saved });
|
|
2312
|
+
},
|
|
2313
|
+
"GET /views": ({ namespace }) => json4(200, {
|
|
2314
|
+
views: runtime.instance(namespace).state.views.list({ order: "oldest" }).map((r) => r.value)
|
|
2315
|
+
}),
|
|
2316
|
+
"GET /settings": ({ namespace }) => json4(200, runtime.instance(namespace).state.current()),
|
|
2317
|
+
"PUT /settings": ({ body, namespace }) => {
|
|
2318
|
+
if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
|
|
2319
|
+
const patch = {};
|
|
2320
|
+
for (const key of [
|
|
2321
|
+
"teamId",
|
|
2322
|
+
"teamName",
|
|
2323
|
+
"teamDomain",
|
|
2324
|
+
"botUserId",
|
|
2325
|
+
"botId",
|
|
2326
|
+
"appId"
|
|
2327
|
+
]) {
|
|
2328
|
+
if (body[key] === void 0) continue;
|
|
2329
|
+
if (typeof body[key] !== "string") return adminError3(400, `${key}: string`);
|
|
2330
|
+
patch[key] = body[key];
|
|
2331
|
+
}
|
|
2332
|
+
if (body.tokens !== void 0) {
|
|
2333
|
+
if (!Array.isArray(body.tokens)) return adminError3(400, "tokens: string[]");
|
|
2334
|
+
patch.tokens = body.tokens.map(String);
|
|
2335
|
+
}
|
|
2336
|
+
if (body.strictChannels !== void 0) {
|
|
2337
|
+
if (typeof body.strictChannels !== "boolean")
|
|
2338
|
+
return adminError3(400, "strictChannels: boolean");
|
|
2339
|
+
patch.strictChannels = body.strictChannels;
|
|
2340
|
+
}
|
|
2341
|
+
return json4(200, runtime.instance(namespace).state.update(patch));
|
|
2342
|
+
}
|
|
2343
|
+
});
|
|
2344
|
+
var createRuntime2 = (options = {}) => createRuntime({
|
|
2345
|
+
name: SLACK_NAMESPACE,
|
|
2346
|
+
document,
|
|
2347
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2348
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2349
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2350
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2351
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2352
|
+
credential: slackCredential,
|
|
2353
|
+
presets: SLACK_PRESETS,
|
|
2354
|
+
create: ({ sqlite, namespace, clock }) => new SlackAPI({
|
|
2355
|
+
sqlite,
|
|
2356
|
+
namespace,
|
|
2357
|
+
now: clock.now,
|
|
2358
|
+
...options.settings ? { settings: options.settings } : {}
|
|
2359
|
+
}),
|
|
2360
|
+
admin: adminRoutes
|
|
2361
|
+
});
|
|
2362
|
+
|
|
2363
|
+
// src/index.ts
|
|
2364
|
+
var SLACK_NAMESPACE = "slack";
|
|
2365
|
+
var WEBHOOK_PATH = /^\/services\/([^/]+\/[^/]+\/[^/]+)\/?$/;
|
|
2366
|
+
var slackCredential = (request) => {
|
|
2367
|
+
const token = bearerToken(request);
|
|
2368
|
+
if (token) return token;
|
|
2369
|
+
const path = new URL(request.url).pathname;
|
|
2370
|
+
return WEBHOOK_PATH.exec(path.replace(/^\/ns\/[^/]+/, ""))?.[1];
|
|
2371
|
+
};
|
|
2372
|
+
var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2373
|
+
var text = (status, body, headers = {}) => new Response(body, {
|
|
2374
|
+
status,
|
|
2375
|
+
headers: { "content-type": "text/plain; charset=utf-8", ...headers }
|
|
2376
|
+
});
|
|
2377
|
+
var fail = (error, extra = {}) => jsonRes(200, { ok: false, error, ...extra });
|
|
2378
|
+
var SlackError = class extends Error {
|
|
2379
|
+
constructor(code, extra = {}) {
|
|
2380
|
+
super(code);
|
|
2381
|
+
this.code = code;
|
|
2382
|
+
this.extra = extra;
|
|
2383
|
+
}
|
|
2384
|
+
code;
|
|
2385
|
+
extra;
|
|
2386
|
+
};
|
|
2387
|
+
var reply = (body, ids) => ids ? { body, ids: ids.ids } : { body };
|
|
2388
|
+
var readArgs = (context) => {
|
|
2389
|
+
const args = {};
|
|
2390
|
+
for (const [key, value] of context.url.searchParams) args[key] = value;
|
|
2391
|
+
const body = context.body;
|
|
2392
|
+
const contentType = context.request.headers.get("content-type") ?? "";
|
|
2393
|
+
let json5 = false;
|
|
2394
|
+
if (body.kind === "json") {
|
|
2395
|
+
if (!isRecord5(body.value)) throw new SlackError("invalid_json");
|
|
2396
|
+
Object.assign(args, body.value);
|
|
2397
|
+
json5 = true;
|
|
2398
|
+
} else if (body.kind === "form") {
|
|
2399
|
+
Object.assign(args, body.value);
|
|
2400
|
+
for (const key of ["blocks", "attachments", "view"]) {
|
|
2401
|
+
const raw = args[key];
|
|
2402
|
+
if (typeof raw !== "string") continue;
|
|
2403
|
+
try {
|
|
2404
|
+
args[key] = JSON.parse(raw);
|
|
2405
|
+
} catch {
|
|
2406
|
+
throw new SlackError(key === "blocks" ? "invalid_blocks_format" : "invalid_arguments", {
|
|
2407
|
+
response_metadata: { messages: [`[ERROR] ${key} must be valid JSON`] }
|
|
2408
|
+
});
|
|
2409
|
+
}
|
|
2410
|
+
}
|
|
2411
|
+
} else if (body.kind === "invalid") {
|
|
2412
|
+
throw new SlackError("invalid_json");
|
|
2413
|
+
}
|
|
2414
|
+
return Object.assign(args, { __json: json5, __charset: /charset=/i.test(contentType) });
|
|
2415
|
+
};
|
|
2416
|
+
var str = (value) => typeof value === "string" && value.length > 0 ? value : typeof value === "number" ? String(value) : void 0;
|
|
2417
|
+
var checkBlocks = (blocks) => {
|
|
2418
|
+
if (blocks === void 0 || blocks === null || blocks === "") return null;
|
|
2419
|
+
if (!Array.isArray(blocks) || blocks.length > 50) throw new SlackError("invalid_blocks");
|
|
2420
|
+
for (const block of blocks) {
|
|
2421
|
+
if (!isRecord5(block) || typeof block.type !== "string") throw new SlackError("invalid_blocks");
|
|
2422
|
+
}
|
|
2423
|
+
return blocks;
|
|
2424
|
+
};
|
|
2425
|
+
var SlackAPI = class {
|
|
2426
|
+
app;
|
|
2427
|
+
sqlite;
|
|
2428
|
+
state;
|
|
2429
|
+
service;
|
|
2430
|
+
now;
|
|
2431
|
+
constructor(options = {}) {
|
|
2432
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2433
|
+
const namespace = options.namespace ?? SLACK_NAMESPACE;
|
|
2434
|
+
this.now = options.now ?? (() => Date.now());
|
|
2435
|
+
this.state = new SlackState(sqlite, namespace, { settings: options.settings ?? {} });
|
|
2436
|
+
const api = (fn) => (context) => {
|
|
2437
|
+
try {
|
|
2438
|
+
const args = readArgs(context);
|
|
2439
|
+
const { body, ids } = fn(args, context);
|
|
2440
|
+
const warn = args.__json && !args.__charset;
|
|
2441
|
+
const response = jsonRes(
|
|
2442
|
+
200,
|
|
2443
|
+
warn ? {
|
|
2444
|
+
...body,
|
|
2445
|
+
warning: "missing_charset",
|
|
2446
|
+
response_metadata: { warnings: ["missing_charset"] }
|
|
2447
|
+
} : body
|
|
2448
|
+
);
|
|
2449
|
+
return ids ? annotateResponse(response, { ids }) : response;
|
|
2450
|
+
} catch (error) {
|
|
2451
|
+
if (error instanceof SlackError) return fail(error.code, error.extra);
|
|
2452
|
+
throw error;
|
|
2453
|
+
}
|
|
2454
|
+
};
|
|
2455
|
+
const handlers = defineOperations({
|
|
2456
|
+
PostIncomingWebhook: (context) => this.incomingWebhook(context),
|
|
2457
|
+
ChatPostMessage: api((args, context) => this.postMessage(args, context)),
|
|
2458
|
+
ChatUpdate: api((args, context) => this.update(args, context)),
|
|
2459
|
+
ChatPostEphemeral: api((args, context) => this.postEphemeral(args, context)),
|
|
2460
|
+
ChatGetPermalink: api((args, context) => this.permalink(args, context)),
|
|
2461
|
+
ChatGetPermalinkGet: api((args, context) => this.permalink(args, context)),
|
|
2462
|
+
ReactionsAdd: api((args, context) => this.react(args, context, "add")),
|
|
2463
|
+
ReactionsRemove: api((args, context) => this.react(args, context, "remove")),
|
|
2464
|
+
ReactionsGet: api((args, context) => this.reactions(args, context)),
|
|
2465
|
+
ReactionsGetGet: api((args, context) => this.reactions(args, context)),
|
|
2466
|
+
AuthTest: api(() => this.authTest()),
|
|
2467
|
+
AuthTestGet: api(() => this.authTest()),
|
|
2468
|
+
ConversationsJoin: api((args, context) => this.join(args, context)),
|
|
2469
|
+
UsersInfo: api((args) => this.userInfo(args)),
|
|
2470
|
+
UsersInfoGet: api((args) => this.userInfo(args)),
|
|
2471
|
+
UsersLookupByEmail: api((args) => this.lookupByEmail(args)),
|
|
2472
|
+
UsersLookupByEmailGet: api((args) => this.lookupByEmail(args)),
|
|
2473
|
+
FilesInfo: api((args) => this.fileInfo(args)),
|
|
2474
|
+
FilesInfoGet: api((args) => this.fileInfo(args)),
|
|
2475
|
+
ViewsOpen: api((args) => this.openView(args))
|
|
2476
|
+
});
|
|
2477
|
+
this.service = createService({
|
|
2478
|
+
document,
|
|
2479
|
+
handlers,
|
|
2480
|
+
sqlite,
|
|
2481
|
+
namespace,
|
|
2482
|
+
now: this.now,
|
|
2483
|
+
notFound: (request) => new URL(request.url).pathname.startsWith("/api/") ? fail("unknown_method") : text(404, "no_service"),
|
|
2484
|
+
onError: (error) => {
|
|
2485
|
+
if (error instanceof HttpError) return error.toResponse();
|
|
2486
|
+
throw error;
|
|
2487
|
+
},
|
|
2488
|
+
before: (context) => this.gate(context)
|
|
2489
|
+
});
|
|
2490
|
+
this.app = this.service.app;
|
|
2491
|
+
this.sqlite = this.service.sqlite;
|
|
2492
|
+
}
|
|
2493
|
+
fetch(request) {
|
|
2494
|
+
return this.service.fetch(request);
|
|
2495
|
+
}
|
|
2496
|
+
async reset() {
|
|
2497
|
+
await this.service.reset();
|
|
2498
|
+
this.state.ensureSeeded();
|
|
2499
|
+
}
|
|
2500
|
+
/** Every message in the outbox, oldest first. */
|
|
2501
|
+
messages() {
|
|
2502
|
+
return this.state.outbox.list();
|
|
2503
|
+
}
|
|
2504
|
+
settings() {
|
|
2505
|
+
return this.state.current();
|
|
2506
|
+
}
|
|
2507
|
+
/** Fault effects every surface shares, then Web API authentication. */
|
|
2508
|
+
gate(context) {
|
|
2509
|
+
const webhook = context.operation.operationId === "PostIncomingWebhook";
|
|
2510
|
+
const limited = faultEffect(context.request, "rate_limited");
|
|
2511
|
+
if (limited !== void 0) {
|
|
2512
|
+
const retryAfter = String(limited.retryAfter ?? 1);
|
|
2513
|
+
return webhook ? text(429, "rate_limited", { "retry-after": retryAfter }) : jsonRes(429, { ok: false, error: "ratelimited" }, { "retry-after": retryAfter });
|
|
2514
|
+
}
|
|
2515
|
+
const broken = faultEffect(context.request, "server_error");
|
|
2516
|
+
if (broken !== void 0) {
|
|
2517
|
+
const status = typeof broken.status === "number" ? broken.status : 500;
|
|
2518
|
+
const code = status === 503 ? "service_unavailable" : "internal_error";
|
|
2519
|
+
return webhook ? text(status, code) : jsonRes(status, { ok: false, error: code });
|
|
2520
|
+
}
|
|
2521
|
+
if (webhook) return void 0;
|
|
2522
|
+
if (faultEffect(context.request, "invalid_auth") !== void 0) return fail("invalid_auth");
|
|
2523
|
+
const token = bearerToken(context.request) ?? this.bodyToken(context);
|
|
2524
|
+
if (!token) return fail("not_authed");
|
|
2525
|
+
const accepted = this.settings().tokens;
|
|
2526
|
+
const ok = accepted.length > 0 ? accepted.includes(token) : /^xox[abp]-/.test(token);
|
|
2527
|
+
return ok ? void 0 : fail("invalid_auth");
|
|
2528
|
+
}
|
|
2529
|
+
/** Form posts may carry `token=` instead of the header (Slack's legacy style). */
|
|
2530
|
+
bodyToken(context) {
|
|
2531
|
+
const fromQuery = context.url.searchParams.get("token");
|
|
2532
|
+
if (fromQuery) return fromQuery;
|
|
2533
|
+
return context.body.kind === "form" ? str(context.body.value.token) : void 0;
|
|
2534
|
+
}
|
|
2535
|
+
iso() {
|
|
2536
|
+
return new Date(this.now()).toISOString();
|
|
2537
|
+
}
|
|
2538
|
+
/**
|
|
2539
|
+
* Resolve a channel id or name. Unknown channels are created on first use unless
|
|
2540
|
+
* `strictChannels` is set; the `channel_not_found` preset forces the error.
|
|
2541
|
+
*/
|
|
2542
|
+
channel(ref, context) {
|
|
2543
|
+
const wanted = str(ref);
|
|
2544
|
+
if (!wanted || faultEffect(context.request, "channel_not_found") !== void 0) {
|
|
2545
|
+
throw new SlackError("channel_not_found");
|
|
2546
|
+
}
|
|
2547
|
+
const found = this.state.findChannel(wanted);
|
|
2548
|
+
if (found) return found;
|
|
2549
|
+
if (this.settings().strictChannels) throw new SlackError("channel_not_found");
|
|
2550
|
+
const isId = /^[CGD][A-Z0-9]{2,}$/.test(wanted);
|
|
2551
|
+
const name = isId ? wanted.toLowerCase() : wanted.replace(/^#/, "").toLowerCase();
|
|
2552
|
+
const created = {
|
|
2553
|
+
id: isId ? wanted : `C${opaqueToken(`channel:${name}`, 10).toUpperCase()}`,
|
|
2554
|
+
name,
|
|
2555
|
+
is_private: wanted.startsWith("G"),
|
|
2556
|
+
is_archived: false,
|
|
2557
|
+
is_member: true,
|
|
2558
|
+
created: Math.floor(this.now() / 1e3)
|
|
2559
|
+
};
|
|
2560
|
+
this.state.channels.insert(created.id, created);
|
|
2561
|
+
return created;
|
|
2562
|
+
}
|
|
2563
|
+
messageBody(message) {
|
|
2564
|
+
const settings = this.settings();
|
|
2565
|
+
return {
|
|
2566
|
+
type: "message",
|
|
2567
|
+
...message.text !== null ? { text: message.text } : { text: "" },
|
|
2568
|
+
user: settings.botUserId,
|
|
2569
|
+
bot_id: settings.botId,
|
|
2570
|
+
app_id: settings.appId,
|
|
2571
|
+
team: settings.teamId,
|
|
2572
|
+
ts: message.ts,
|
|
2573
|
+
...message.thread_ts !== null ? { thread_ts: message.thread_ts } : {},
|
|
2574
|
+
...message.blocks !== null ? { blocks: message.blocks } : {},
|
|
2575
|
+
...message.edited !== null ? { edited: message.edited } : {},
|
|
2576
|
+
...message.reactions.length > 0 ? { reactions: message.reactions } : {}
|
|
2577
|
+
};
|
|
2578
|
+
}
|
|
2579
|
+
record(message) {
|
|
2580
|
+
const stored = {
|
|
2581
|
+
...message,
|
|
2582
|
+
id: `${message.channel}:${message.ts}`,
|
|
2583
|
+
createdAt: this.iso(),
|
|
2584
|
+
reactions: []
|
|
2585
|
+
};
|
|
2586
|
+
return this.state.outbox.record(stored);
|
|
2587
|
+
}
|
|
2588
|
+
incomingWebhook(context) {
|
|
2589
|
+
const path = `${context.params.team}/${context.params.bot}/${context.params.secret}`;
|
|
2590
|
+
const webhook = `/services/${path}`;
|
|
2591
|
+
const hooks = this.state.hooks.list();
|
|
2592
|
+
const hook = this.state.hooks.get(path);
|
|
2593
|
+
if (hooks.length > 0 && !hook) return text(404, "no_service");
|
|
2594
|
+
if (faultEffect(context.request, "no_service") !== void 0) return text(404, "no_service");
|
|
2595
|
+
if (faultEffect(context.request, "channel_not_found") !== void 0) {
|
|
2596
|
+
return text(404, "channel_not_found");
|
|
2597
|
+
}
|
|
2598
|
+
let payload;
|
|
2599
|
+
const body = context.body;
|
|
2600
|
+
if (body.kind === "json") payload = body.value;
|
|
2601
|
+
else if (body.kind === "form" && typeof body.value.payload === "string") {
|
|
2602
|
+
try {
|
|
2603
|
+
payload = JSON.parse(body.value.payload);
|
|
2604
|
+
} catch {
|
|
2605
|
+
return text(400, "invalid_payload");
|
|
2606
|
+
}
|
|
2607
|
+
} else return text(400, "invalid_payload");
|
|
2608
|
+
if (!isRecord5(payload)) return text(400, "invalid_payload");
|
|
2609
|
+
let blocks;
|
|
2610
|
+
try {
|
|
2611
|
+
blocks = checkBlocks(payload.blocks);
|
|
2612
|
+
} catch {
|
|
2613
|
+
return text(400, "invalid_blocks");
|
|
2614
|
+
}
|
|
2615
|
+
const attachments = Array.isArray(payload.attachments) ? payload.attachments : null;
|
|
2616
|
+
if (attachments && attachments.length > 100) return text(400, "too_many_attachments");
|
|
2617
|
+
const messageText = typeof payload.text === "string" ? payload.text : null;
|
|
2618
|
+
if (!messageText && !blocks && !attachments) return text(400, "no_text");
|
|
2619
|
+
const channel = hook ? this.state.findChannel(hook.channel) : void 0;
|
|
2620
|
+
if (channel?.is_archived) return text(410, "channel_is_archived");
|
|
2621
|
+
const ts = this.state.nextTs(this.now());
|
|
2622
|
+
const target = channel?.id ?? hook?.channel ?? webhook;
|
|
2623
|
+
const message = this.record({
|
|
2624
|
+
to: [webhook, ...channel ? [channel.id, `#${channel.name}`] : hook ? [hook.channel] : []],
|
|
2625
|
+
source: "webhook",
|
|
2626
|
+
method: "incoming-webhook",
|
|
2627
|
+
webhook,
|
|
2628
|
+
channel: target,
|
|
2629
|
+
text: messageText,
|
|
2630
|
+
blocks,
|
|
2631
|
+
attachments,
|
|
2632
|
+
thread_ts: str(payload.thread_ts) ?? null,
|
|
2633
|
+
ts,
|
|
2634
|
+
user: null,
|
|
2635
|
+
ephemeral: false,
|
|
2636
|
+
edited: null
|
|
2637
|
+
});
|
|
2638
|
+
return annotateResponse(text(200, "ok"), { ids: { ts: message.ts, webhook: path } });
|
|
2639
|
+
}
|
|
2640
|
+
postMessage(args, context) {
|
|
2641
|
+
const channel = this.channel(args.channel, context);
|
|
2642
|
+
if (channel.is_archived) throw new SlackError("is_archived");
|
|
2643
|
+
const blocks = checkBlocks(args.blocks);
|
|
2644
|
+
const attachments = Array.isArray(args.attachments) ? args.attachments : null;
|
|
2645
|
+
const messageText = typeof args.text === "string" ? args.text : null;
|
|
2646
|
+
if (!messageText && !blocks && !attachments) throw new SlackError("no_text");
|
|
2647
|
+
if (messageText && messageText.length > 4e4) throw new SlackError("msg_too_long");
|
|
2648
|
+
const message = this.record({
|
|
2649
|
+
to: [channel.id, `#${channel.name}`],
|
|
2650
|
+
source: "api",
|
|
2651
|
+
method: "chat.postMessage",
|
|
2652
|
+
webhook: null,
|
|
2653
|
+
channel: channel.id,
|
|
2654
|
+
text: messageText,
|
|
2655
|
+
blocks,
|
|
2656
|
+
attachments,
|
|
2657
|
+
thread_ts: str(args.thread_ts) ?? null,
|
|
2658
|
+
ts: this.state.nextTs(this.now()),
|
|
2659
|
+
user: this.settings().botUserId,
|
|
2660
|
+
ephemeral: false,
|
|
2661
|
+
edited: null
|
|
2662
|
+
});
|
|
2663
|
+
return reply(
|
|
2664
|
+
{
|
|
2665
|
+
ok: true,
|
|
2666
|
+
channel: channel.id,
|
|
2667
|
+
ts: message.ts,
|
|
2668
|
+
message: this.messageBody(message)
|
|
2669
|
+
},
|
|
2670
|
+
{ ids: { channel: channel.id, ts: message.ts } }
|
|
2671
|
+
);
|
|
2672
|
+
}
|
|
2673
|
+
update(args, context) {
|
|
2674
|
+
const channel = this.channel(args.channel, context);
|
|
2675
|
+
const ts = str(args.ts);
|
|
2676
|
+
const message = ts ? this.state.findMessage(channel.id, ts) : void 0;
|
|
2677
|
+
if (!message) throw new SlackError("message_not_found");
|
|
2678
|
+
if (message.source !== "api") throw new SlackError("cant_update_message");
|
|
2679
|
+
const blocks = checkBlocks(args.blocks);
|
|
2680
|
+
const messageText = typeof args.text === "string" ? args.text : null;
|
|
2681
|
+
if (!messageText && !blocks && args.blocks === void 0) throw new SlackError("no_text");
|
|
2682
|
+
const next = {
|
|
2683
|
+
...message,
|
|
2684
|
+
text: messageText ?? message.text,
|
|
2685
|
+
// Omitted blocks are retained, as Slack documents; `[]` clears them.
|
|
2686
|
+
blocks: Array.isArray(args.blocks) && args.blocks.length === 0 ? null : blocks ?? message.blocks,
|
|
2687
|
+
edited: { user: this.settings().botUserId, ts: this.state.nextTs(this.now()) }
|
|
2688
|
+
};
|
|
2689
|
+
this.state.outbox.update(message.id, next);
|
|
2690
|
+
return reply(
|
|
2691
|
+
{
|
|
2692
|
+
ok: true,
|
|
2693
|
+
channel: channel.id,
|
|
2694
|
+
ts: message.ts,
|
|
2695
|
+
text: next.text ?? "",
|
|
2696
|
+
message: this.messageBody(next)
|
|
2697
|
+
},
|
|
2698
|
+
{ ids: { channel: channel.id, ts: message.ts } }
|
|
2699
|
+
);
|
|
2700
|
+
}
|
|
2701
|
+
postEphemeral(args, context) {
|
|
2702
|
+
const channel = this.channel(args.channel, context);
|
|
2703
|
+
const userId = str(args.user);
|
|
2704
|
+
const user = userId ? this.state.users.get(userId) : void 0;
|
|
2705
|
+
if (!user) throw new SlackError("user_not_found");
|
|
2706
|
+
const blocks = checkBlocks(args.blocks);
|
|
2707
|
+
const messageText = typeof args.text === "string" ? args.text : null;
|
|
2708
|
+
if (!messageText && !blocks) throw new SlackError("no_text");
|
|
2709
|
+
const message = this.record({
|
|
2710
|
+
to: [channel.id, `#${channel.name}`, user.id],
|
|
2711
|
+
source: "api",
|
|
2712
|
+
method: "chat.postEphemeral",
|
|
2713
|
+
webhook: null,
|
|
2714
|
+
channel: channel.id,
|
|
2715
|
+
text: messageText,
|
|
2716
|
+
blocks,
|
|
2717
|
+
attachments: null,
|
|
2718
|
+
thread_ts: str(args.thread_ts) ?? null,
|
|
2719
|
+
ts: this.state.nextTs(this.now()),
|
|
2720
|
+
user: user.id,
|
|
2721
|
+
ephemeral: true,
|
|
2722
|
+
edited: null
|
|
2723
|
+
});
|
|
2724
|
+
return reply(
|
|
2725
|
+
{ ok: true, message_ts: message.ts },
|
|
2726
|
+
{
|
|
2727
|
+
ids: { channel: channel.id, ts: message.ts }
|
|
2728
|
+
}
|
|
2729
|
+
);
|
|
2730
|
+
}
|
|
2731
|
+
permalink(args, context) {
|
|
2732
|
+
const channel = this.channel(args.channel, context);
|
|
2733
|
+
const ts = str(args.message_ts);
|
|
2734
|
+
const message = ts ? this.state.findMessage(channel.id, ts) : void 0;
|
|
2735
|
+
if (!message) throw new SlackError("message_not_found");
|
|
2736
|
+
const base = `https://${this.settings().teamDomain}.slack.com/archives/${channel.id}/p${message.ts.replace(".", "")}`;
|
|
2737
|
+
const permalink = message.thread_ts ? `${base}?thread_ts=${message.thread_ts}&cid=${channel.id}` : base;
|
|
2738
|
+
return reply({ ok: true, channel: channel.id, permalink });
|
|
2739
|
+
}
|
|
2740
|
+
react(args, context, mode) {
|
|
2741
|
+
const name = str(args.name)?.replace(/:/g, "");
|
|
2742
|
+
if (!name) throw new SlackError("invalid_name");
|
|
2743
|
+
if (args.channel === void 0 && args.timestamp === void 0) {
|
|
2744
|
+
throw new SlackError("no_item_specified");
|
|
2745
|
+
}
|
|
2746
|
+
const channel = this.channel(args.channel, context);
|
|
2747
|
+
const ts = str(args.timestamp);
|
|
2748
|
+
const message = ts ? this.state.findMessage(channel.id, ts) : void 0;
|
|
2749
|
+
if (!message) throw new SlackError("message_not_found");
|
|
2750
|
+
const bot = this.settings().botUserId;
|
|
2751
|
+
const reactions = message.reactions.map((r) => ({ ...r, users: [...r.users] }));
|
|
2752
|
+
const existing = reactions.find((r) => r.name === name);
|
|
2753
|
+
if (mode === "add") {
|
|
2754
|
+
if (existing?.users.includes(bot)) throw new SlackError("already_reacted");
|
|
2755
|
+
if (existing) {
|
|
2756
|
+
existing.users.push(bot);
|
|
2757
|
+
existing.count = existing.users.length;
|
|
2758
|
+
} else reactions.push({ name, users: [bot], count: 1 });
|
|
2759
|
+
} else {
|
|
2760
|
+
if (!existing?.users.includes(bot)) throw new SlackError("no_reaction");
|
|
2761
|
+
existing.users = existing.users.filter((u) => u !== bot);
|
|
2762
|
+
existing.count = existing.users.length;
|
|
2763
|
+
}
|
|
2764
|
+
this.state.outbox.update(message.id, {
|
|
2765
|
+
...message,
|
|
2766
|
+
reactions: reactions.filter((r) => r.count > 0)
|
|
2767
|
+
});
|
|
2768
|
+
return reply({ ok: true });
|
|
2769
|
+
}
|
|
2770
|
+
reactions(args, context) {
|
|
2771
|
+
if (args.channel === void 0 && args.timestamp === void 0) {
|
|
2772
|
+
throw new SlackError("no_item_specified");
|
|
2773
|
+
}
|
|
2774
|
+
const channel = this.channel(args.channel, context);
|
|
2775
|
+
const ts = str(args.timestamp);
|
|
2776
|
+
const message = ts ? this.state.findMessage(channel.id, ts) : void 0;
|
|
2777
|
+
if (!message) throw new SlackError("message_not_found");
|
|
2778
|
+
return reply({
|
|
2779
|
+
ok: true,
|
|
2780
|
+
type: "message",
|
|
2781
|
+
channel: channel.id,
|
|
2782
|
+
message: this.messageBody(message)
|
|
2783
|
+
});
|
|
2784
|
+
}
|
|
2785
|
+
authTest() {
|
|
2786
|
+
const settings = this.settings();
|
|
2787
|
+
const bot = this.state.users.get(settings.botUserId);
|
|
2788
|
+
return reply({
|
|
2789
|
+
ok: true,
|
|
2790
|
+
url: `https://${settings.teamDomain}.slack.com/`,
|
|
2791
|
+
team: settings.teamName,
|
|
2792
|
+
user: bot?.name ?? "mockingbird",
|
|
2793
|
+
team_id: settings.teamId,
|
|
2794
|
+
user_id: settings.botUserId,
|
|
2795
|
+
bot_id: settings.botId,
|
|
2796
|
+
is_enterprise_install: false
|
|
2797
|
+
});
|
|
2798
|
+
}
|
|
2799
|
+
channelBody(channel) {
|
|
2800
|
+
return {
|
|
2801
|
+
id: channel.id,
|
|
2802
|
+
name: channel.name,
|
|
2803
|
+
is_channel: !channel.is_private,
|
|
2804
|
+
is_private: channel.is_private,
|
|
2805
|
+
is_archived: channel.is_archived,
|
|
2806
|
+
is_member: channel.is_member,
|
|
2807
|
+
created: channel.created
|
|
2808
|
+
};
|
|
2809
|
+
}
|
|
2810
|
+
join(args, context) {
|
|
2811
|
+
const channel = this.channel(args.channel, context);
|
|
2812
|
+
if (channel.is_archived) throw new SlackError("is_archived");
|
|
2813
|
+
if (channel.is_private) throw new SlackError("method_not_supported_for_channel_type");
|
|
2814
|
+
if (channel.is_member) {
|
|
2815
|
+
return reply({
|
|
2816
|
+
ok: true,
|
|
2817
|
+
channel: this.channelBody(channel),
|
|
2818
|
+
warning: "already_in_channel",
|
|
2819
|
+
response_metadata: { warnings: ["already_in_channel"] }
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
const joined = { ...channel, is_member: true };
|
|
2823
|
+
this.state.channels.update(channel.id, joined);
|
|
2824
|
+
return reply({ ok: true, channel: this.channelBody(joined) });
|
|
2825
|
+
}
|
|
2826
|
+
userBody(user) {
|
|
2827
|
+
return {
|
|
2828
|
+
id: user.id,
|
|
2829
|
+
team_id: this.settings().teamId,
|
|
2830
|
+
name: user.name,
|
|
2831
|
+
real_name: user.real_name,
|
|
2832
|
+
deleted: user.deleted,
|
|
2833
|
+
is_bot: user.is_bot,
|
|
2834
|
+
tz: user.tz,
|
|
2835
|
+
profile: {
|
|
2836
|
+
real_name: user.real_name,
|
|
2837
|
+
display_name: user.name,
|
|
2838
|
+
...user.email !== null ? { email: user.email } : {}
|
|
2839
|
+
}
|
|
2840
|
+
};
|
|
2841
|
+
}
|
|
2842
|
+
userInfo(args) {
|
|
2843
|
+
const id = str(args.user);
|
|
2844
|
+
const user = id ? this.state.users.get(id) : void 0;
|
|
2845
|
+
if (!user) throw new SlackError("user_not_found");
|
|
2846
|
+
return reply({ ok: true, user: this.userBody(user) });
|
|
2847
|
+
}
|
|
2848
|
+
lookupByEmail(args) {
|
|
2849
|
+
const email = str(args.email);
|
|
2850
|
+
if (!email) throw new SlackError("invalid_arguments");
|
|
2851
|
+
const user = this.state.findUserByEmail(email);
|
|
2852
|
+
if (!user) throw new SlackError("users_not_found");
|
|
2853
|
+
return reply({ ok: true, user: this.userBody(user) });
|
|
2854
|
+
}
|
|
2855
|
+
fileBody(file) {
|
|
2856
|
+
const settings = this.settings();
|
|
2857
|
+
const base = `https://files.slack.com/files-pri/${settings.teamId}-${file.id}`;
|
|
2858
|
+
return {
|
|
2859
|
+
...file,
|
|
2860
|
+
url_private: `${base}/${encodeURIComponent(file.name)}`,
|
|
2861
|
+
url_private_download: `${base}/download/${encodeURIComponent(file.name)}`,
|
|
2862
|
+
permalink: `https://${settings.teamDomain}.slack.com/files/${settings.botUserId}/${file.id}/${encodeURIComponent(file.name)}`
|
|
2863
|
+
};
|
|
2864
|
+
}
|
|
2865
|
+
fileInfo(args) {
|
|
2866
|
+
const id = str(args.file);
|
|
2867
|
+
const file = id ? this.state.files.get(id) : void 0;
|
|
2868
|
+
if (!file) throw new SlackError("file_not_found");
|
|
2869
|
+
return reply({ ok: true, file: this.fileBody(file) });
|
|
2870
|
+
}
|
|
2871
|
+
openView(args) {
|
|
2872
|
+
if (!str(args.trigger_id)) throw new SlackError("invalid_arguments");
|
|
2873
|
+
const view = args.view;
|
|
2874
|
+
if (!isRecord5(view) || view.type !== "modal" && view.type !== "home") {
|
|
2875
|
+
throw new SlackError("invalid_arguments", {
|
|
2876
|
+
response_metadata: { messages: ["[ERROR] view.type must be modal"] }
|
|
2877
|
+
});
|
|
2878
|
+
}
|
|
2879
|
+
const settings = this.settings();
|
|
2880
|
+
const seq = this.state.views.nextSequence();
|
|
2881
|
+
const id = `V${opaqueToken(`view:${seq}`, 10).toUpperCase()}`;
|
|
2882
|
+
const stored = {
|
|
2883
|
+
...view,
|
|
2884
|
+
id,
|
|
2885
|
+
team_id: settings.teamId,
|
|
2886
|
+
state: { values: {} },
|
|
2887
|
+
hash: `${Math.floor(this.now() / 1e3)}.${opaqueToken(`hash:${seq}`, 8)}`,
|
|
2888
|
+
app_id: settings.appId,
|
|
2889
|
+
bot_id: settings.botId,
|
|
2890
|
+
blocks: Array.isArray(view.blocks) ? view.blocks : []
|
|
2891
|
+
};
|
|
2892
|
+
this.state.views.insert(id, stored);
|
|
2893
|
+
return reply({ ok: true, view: stored }, { ids: { view: id } });
|
|
2894
|
+
}
|
|
2895
|
+
};
|
|
2896
|
+
|
|
2897
|
+
export {
|
|
2898
|
+
document,
|
|
2899
|
+
operationIds,
|
|
2900
|
+
supportedOperationIds,
|
|
2901
|
+
DEFAULT_SETTINGS,
|
|
2902
|
+
DEFAULT_CHANNELS,
|
|
2903
|
+
DEFAULT_USERS,
|
|
2904
|
+
DEFAULT_FILES,
|
|
2905
|
+
SLACK_PRESETS,
|
|
2906
|
+
createRuntime2 as createRuntime,
|
|
2907
|
+
SLACK_NAMESPACE,
|
|
2908
|
+
slackCredential,
|
|
2909
|
+
SlackAPI
|
|
2910
|
+
};
|
|
2911
|
+
//# sourceMappingURL=chunk-HYPQOQ27.js.map
|