@capybara-hq/testing 0.1.0-rc.26 → 0.1.0-rc.27

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.
@@ -108,6 +108,14 @@ export interface Harness {
108
108
  * 另一个副本照常工作。已退出时是空操作。
109
109
  */
110
110
  kill(index: number): Promise<void>;
111
+ /**
112
+ * Stops replica `index` gracefully, through the kernel's own shutdown (as `stop()` does for all of
113
+ * them), and waits for it to exit; the other replicas keep working. A stop stuck for 10 s ends
114
+ * with the replica's own forced exit (code 1), and the harness SIGKILLs it after 15 s. Like after
115
+ * `kill`, `request()` keeps rotating to the stopped replica and requests to it throw. A no-op
116
+ * when it already exited.
117
+ */
118
+ stopReplica(index: number): Promise<void>;
111
119
  /**
112
120
  * 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。Before the replicas stop it asserts
113
121
  * that they left no queued run without its job (neither in the outbox nor in BullMQ: the "queue
@@ -276,6 +276,7 @@ export async function createDualReplicaHarness(opts) {
276
276
  redisUrl,
277
277
  stop,
278
278
  kill,
279
+ stopReplica: (index) => stopRunner(runnerAt(index).runner),
279
280
  startExtraReplica(extraRoles) {
280
281
  // Extra starts run one at a time: the index is the next free slot when the start begins,
281
282
  // and a failed start appends nothing, so there are never holes in the replica indexes
@@ -47,6 +47,21 @@ export interface FakeChannelSent {
47
47
  locale?: "zh" | "en";
48
48
  at: number;
49
49
  }
50
+ /** A file the bot uploaded (`POST /send-file`). */
51
+ export interface FakeChannelSentFile {
52
+ appId: string;
53
+ target: ChannelTarget;
54
+ name: string;
55
+ contentType: string;
56
+ kind: "image" | "file";
57
+ data: Buffer;
58
+ sha256: string;
59
+ messageId: string;
60
+ pid: number;
61
+ idempotencyKey?: string;
62
+ locale?: "zh" | "en";
63
+ at: number;
64
+ }
50
65
  /** 平台上的一个用户(OAuth 登录时可用 `as=<externalId>` 选中)。 */
51
66
  export interface FakeChannelUser {
52
67
  externalId: string;
@@ -74,10 +89,10 @@ export interface FakeDirectoryBook {
74
89
  /** 整轮同步开始的次数(不带游标的请求数)。 */
75
90
  starts(): number;
76
91
  }
77
- /** Which `/send` or `/update` requests a {@link FakeChannelServer.failNext} failure applies to. */
92
+ /** Which `/send`, `/update` or `/send-file` requests a {@link FakeChannelServer.failNext} failure applies to. */
78
93
  export interface FakeChannelFailMatch {
79
94
  chatId?: string;
80
- /** The message's text contains it. */
95
+ /** The message's text (for `/send-file`: the file name) contains it. */
81
96
  textIncludes?: string;
82
97
  }
83
98
  /** A `fake-im` setup check's call of `POST /checks`. */
@@ -111,6 +126,10 @@ export interface FakeChannelServer {
111
126
  updated: FakeChannelSent[];
112
127
  /** 命中幂等键、被平台去重的发送请求(没有产生新消息)。 */
113
128
  duplicateSends: FakeChannelSent[];
129
+ /** Files the bot uploaded (`/send-file`), after dedupe. */
130
+ sentFiles: FakeChannelSentFile[];
131
+ /** `/send-file` requests that hit an idempotency key already seen (no new message). */
132
+ duplicateFiles: FakeChannelSentFile[];
114
133
  /** 插件工具发的公告。 */
115
134
  posts: FakeChannelPost[];
116
135
  /** Calls of `fake-im` setup checks (`POST /checks`). */
@@ -127,14 +146,14 @@ export interface FakeChannelServer {
127
146
  * text (`textIncludes`: the message's text contains it). Without it the next requests to any chat
128
147
  * fail, so a late delivery from an earlier test can take the failure meant for the request under test.
129
148
  */
130
- failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
149
+ failNext(path: "/send" | "/update" | "/send-file", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
131
150
  /**
132
151
  * Delay the response of the next `count` successful `/send` (or `/update`) requests by `delayMs`.
133
152
  * The message is recorded (visible in `sent` / `updated`) as soon as the request arrives; only the
134
153
  * response carrying its `messageId` is late (a slow platform API, or a sender that dies mid-call).
135
154
  * `onlyCards`: count and delay only requests whose message carries cards.
136
155
  */
137
- delayNext(path: "/send" | "/update", delayMs: number, opts?: {
156
+ delayNext(path: "/send" | "/update" | "/send-file", delayMs: number, opts?: {
138
157
  count?: number;
139
158
  onlyCards?: boolean;
140
159
  }): void;
@@ -20,6 +20,8 @@ export async function startFakeChannelServer(opts = {}) {
20
20
  const sent = [];
21
21
  const updated = [];
22
22
  const duplicateSends = [];
23
+ const sentFiles = [];
24
+ const duplicateFiles = [];
23
25
  const posts = [];
24
26
  const checks = [];
25
27
  let checkHold = null;
@@ -27,6 +29,7 @@ export async function startFakeChannelServer(opts = {}) {
27
29
  const books = new Map();
28
30
  const codes = new Map();
29
31
  const byKey = new Map();
32
+ const fileByKey = new Map();
30
33
  const failures = [];
31
34
  const delays = [];
32
35
  const live = new Map();
@@ -66,7 +69,8 @@ export async function startFakeChannelServer(opts = {}) {
66
69
  const parsed = JSON.parse(body);
67
70
  const matches = (m) => m === undefined ||
68
71
  ((m.chatId === undefined || m.chatId === parsed.target?.chatId) &&
69
- (m.textIncludes === undefined || (parsed.message?.text ?? "").includes(m.textIncludes)));
72
+ (m.textIncludes === undefined ||
73
+ (parsed.message?.text ?? parsed.file?.name ?? "").includes(m.textIncludes)));
70
74
  const f = failures.find((x) => x.path === path && x.left > 0 && matches(x.match));
71
75
  if (f) {
72
76
  f.left--;
@@ -75,6 +79,41 @@ export async function startFakeChannelServer(opts = {}) {
75
79
  json(res, f.status, { retryAfterMs: f.retryAfterMs ?? null, reason: f.reason ?? null });
76
80
  return;
77
81
  }
82
+ if (path === "/send-file") {
83
+ const fb = JSON.parse(body);
84
+ const data = Buffer.from(fb.file.data, "base64");
85
+ const fkey = fb.idempotencyKey ? `${fb.appId}\u0000${fb.idempotencyKey}` : undefined;
86
+ const fseen = fkey !== undefined ? fileByKey.get(fkey) : undefined;
87
+ const fid = fseen ?? `of_${++seq}`;
88
+ const frec = {
89
+ appId: fb.appId,
90
+ target: fb.target,
91
+ name: fb.file.name,
92
+ contentType: fb.file.contentType,
93
+ kind: fb.file.kind,
94
+ data,
95
+ sha256: createHash("sha256").update(data).digest("hex"),
96
+ messageId: fid,
97
+ pid: pidOf(req),
98
+ ...(fb.idempotencyKey !== undefined && { idempotencyKey: fb.idempotencyKey }),
99
+ ...(fb.locale !== undefined && { locale: fb.locale }),
100
+ at: Date.now(),
101
+ };
102
+ if (fseen !== undefined && dedupe)
103
+ duplicateFiles.push(frec);
104
+ else {
105
+ sentFiles.push(frec);
106
+ if (fkey !== undefined && fseen === undefined)
107
+ fileByKey.set(fkey, fid);
108
+ }
109
+ const fd = delays.find((x) => x.path === path && x.left > 0);
110
+ if (fd) {
111
+ fd.left--;
112
+ await new Promise((r) => setTimeout(r, fd.delayMs));
113
+ }
114
+ json(res, 200, { messageId: fid });
115
+ return;
116
+ }
78
117
  const b = JSON.parse(body);
79
118
  const key = b.idempotencyKey ? `${b.appId}\u0000${b.idempotencyKey}` : undefined;
80
119
  const seen = path === "/send" && key !== undefined ? byKey.get(key) : undefined;
@@ -165,7 +204,7 @@ export async function startFakeChannelServer(opts = {}) {
165
204
  const route = `${req.method} ${u.pathname}`;
166
205
  if (route === "GET /connect")
167
206
  return connect(req, res, u);
168
- if (route === "POST /send" || route === "POST /update") {
207
+ if (route === "POST /send" || route === "POST /update" || route === "POST /send-file") {
169
208
  return sendOrUpdate(req, res, u.pathname);
170
209
  }
171
210
  if (route === "POST /bot/verify") {
@@ -219,6 +258,8 @@ export async function startFakeChannelServer(opts = {}) {
219
258
  sent,
220
259
  updated,
221
260
  duplicateSends,
261
+ sentFiles,
262
+ duplicateFiles,
222
263
  posts,
223
264
  checks,
224
265
  holdChecks(hold) {
@@ -56,6 +56,15 @@ export interface FakeLarkDepartment {
56
56
  /** 上级部门(根部门为 `"0"`)。 */
57
57
  parent: string;
58
58
  }
59
+ /** An image or file the bot uploaded (`im/v1/images`, `im/v1/files`); `key` is what a message names. */
60
+ export interface FakeLarkUpload {
61
+ kind: "image" | "file";
62
+ key: string;
63
+ fileType?: string;
64
+ fileName?: string;
65
+ data: Buffer;
66
+ at: number;
67
+ }
59
68
  /** 机器人发出(或更新后)的一条消息。 */
60
69
  export interface FakeLarkMessage {
61
70
  messageId: string;
@@ -110,7 +119,7 @@ export interface FakeLarkOptions {
110
119
  * 接口名:`token`、`bot`、`tenant`、`create`、`reply`、`patch`、`user`、`endpoint`、`oauth_token`、`user_info`、
111
120
  * `departments`、`find_by_department`。
112
121
  */
113
- export type FakeLarkApi = "token" | "bot" | "tenant" | "create" | "reply" | "patch" | "user" | "endpoint" | "oauth_token" | "user_info" | "departments" | "find_by_department";
122
+ export type FakeLarkApi = "token" | "bot" | "tenant" | "create" | "reply" | "patch" | "user" | "endpoint" | "oauth_token" | "user_info" | "departments" | "find_by_department" | "image_upload" | "file_upload";
114
123
  export interface FakeLarkServer {
115
124
  /** 开放平台根地址(插件的 `apiUrl` / SDK 的 `domain`)。 */
116
125
  url: string;
@@ -121,6 +130,8 @@ export interface FakeLarkServer {
121
130
  botName: string;
122
131
  messages: FakeLarkMessage[];
123
132
  updates: FakeLarkMessage[];
133
+ /** Successful image and file uploads, in order. */
134
+ uploads: FakeLarkUpload[];
124
135
  calls: FakeLarkCall[];
125
136
  acks: FakeLarkAck[];
126
137
  users: Map<string, FakeLarkUser>;
package/dist/fake-lark.js CHANGED
@@ -34,11 +34,9 @@ const Frame = root.lookupType("pbbp2.Frame");
34
34
  const encodeFrame = (f) => Buffer.from(Frame.encode(Frame.fromObject(f)).finish());
35
35
  const decodeFrame = (b) => Frame.toObject(Frame.decode(b), { longs: Number, bytes: Buffer });
36
36
  const readBody = (req) => new Promise((resolve) => {
37
- let body = "";
38
- req.on("data", (c) => {
39
- body += c.toString();
40
- });
41
- req.on("end", () => resolve(body));
37
+ const chunks = [];
38
+ req.on("data", (c) => chunks.push(c));
39
+ req.on("end", () => resolve(Buffer.concat(chunks)));
42
40
  });
43
41
  const obj = (v) => typeof v === "object" && v !== null && !Array.isArray(v)
44
42
  ? v
@@ -72,6 +70,7 @@ export async function startFakeLark(opts = {}) {
72
70
  const botName = opts.botName ?? "Capybara";
73
71
  const messages = [];
74
72
  const updates = [];
73
+ const uploads = [];
75
74
  const calls = [];
76
75
  const acks = [];
77
76
  const users = new Map();
@@ -116,6 +115,14 @@ export async function startFakeLark(opts = {}) {
116
115
  fail(res, 230001, "invalid content");
117
116
  return undefined;
118
117
  }
118
+ if (msgType === "image" || msgType === "file") {
119
+ const kind = msgType === "image" ? "image" : "file";
120
+ const key = str(obj(card)?.[`${kind}_key`]);
121
+ if (key === undefined || !uploads.some((x) => x.kind === kind && x.key === key)) {
122
+ fail(res, 230001, `invalid ${kind}_key`);
123
+ return undefined;
124
+ }
125
+ }
119
126
  if (msgType === "interactive") {
120
127
  const c = obj(card);
121
128
  if (c?.schema !== "2.0" || obj(c.config)?.update_multi === false || !obj(c.body)) {
@@ -126,13 +133,34 @@ export async function startFakeLark(opts = {}) {
126
133
  return { msgType, card };
127
134
  };
128
135
  const api = async (req, res, u) => {
129
- const raw = await readBody(req);
136
+ const rawBytes = await readBody(req);
137
+ const raw = rawBytes.toString();
138
+ const contentType = req.headers["content-type"] ?? "";
130
139
  let body = {};
131
- try {
132
- body = raw === "" ? {} : JSON.parse(raw);
140
+ let blob;
141
+ if (contentType.includes("multipart/form-data")) {
142
+ try {
143
+ const form = await new Response(new Uint8Array(rawBytes), {
144
+ headers: { "content-type": contentType },
145
+ }).formData();
146
+ for (const [k, v] of form) {
147
+ if (typeof v === "string")
148
+ body[k] = v;
149
+ else
150
+ blob = { data: Buffer.from(await v.arrayBuffer()), field: k };
151
+ }
152
+ }
153
+ catch {
154
+ return fail(res, 9499, "bad request");
155
+ }
133
156
  }
134
- catch {
135
- return fail(res, 9499, "bad request");
157
+ else {
158
+ try {
159
+ body = raw === "" ? {} : JSON.parse(raw);
160
+ }
161
+ catch {
162
+ return fail(res, 9499, "bad request");
163
+ }
136
164
  }
137
165
  const path = u.pathname;
138
166
  const method = req.method ?? "GET";
@@ -151,6 +179,10 @@ export async function startFakeLark(opts = {}) {
151
179
  name = "tenant";
152
180
  else if (path === "/open-apis/im/v1/messages" && method === "POST")
153
181
  name = "create";
182
+ else if (path === "/open-apis/im/v1/images" && method === "POST")
183
+ name = "image_upload";
184
+ else if (path === "/open-apis/im/v1/files" && method === "POST")
185
+ name = "file_upload";
154
186
  else if (reply$ && method === "POST")
155
187
  name = "reply";
156
188
  else if (msg$ && method === "PATCH")
@@ -290,6 +322,26 @@ export async function startFakeLark(opts = {}) {
290
322
  },
291
323
  });
292
324
  }
325
+ case "image_upload": {
326
+ if (str(body.image_type) !== "message" || blob?.field !== "image" || blob.data.length === 0)
327
+ return fail(res, 234001, "Invalid request param.");
328
+ const key = `img_v3_${hex(10)}`;
329
+ uploads.push({ kind: "image", key, data: blob.data, at: Date.now() });
330
+ return reply(res, { code: 0, msg: "success", data: { image_key: key } });
331
+ }
332
+ case "file_upload": {
333
+ const fileType = str(body.file_type);
334
+ const fileName = str(body.file_name);
335
+ if (!fileType ||
336
+ !["opus", "mp4", "pdf", "doc", "xls", "ppt", "stream"].includes(fileType) ||
337
+ !fileName ||
338
+ blob?.field !== "file" ||
339
+ blob.data.length === 0)
340
+ return fail(res, 234001, "Invalid request param.");
341
+ const key = `file_v3_${hex(10)}`;
342
+ uploads.push({ kind: "file", key, fileType, fileName, data: blob.data, at: Date.now() });
343
+ return reply(res, { code: 0, msg: "success", data: { file_key: key } });
344
+ }
293
345
  case "create":
294
346
  case "reply": {
295
347
  const uuid = str(body.uuid);
@@ -645,6 +697,7 @@ export async function startFakeLark(opts = {}) {
645
697
  botName,
646
698
  messages,
647
699
  updates,
700
+ uploads,
648
701
  calls,
649
702
  acks,
650
703
  users,
@@ -60,6 +60,16 @@ export interface FakeSlackCall {
60
60
  token: string;
61
61
  body: Record<string, unknown>;
62
62
  }
63
+ /** A file the bot uploaded through the external upload flow and completed into a channel. */
64
+ export interface FakeSlackFile {
65
+ id: string;
66
+ filename: string;
67
+ title?: string;
68
+ channel: string;
69
+ threadTs?: string;
70
+ data: Buffer;
71
+ at: number;
72
+ }
63
73
  /** 客户端对信封的确认。 */
64
74
  export interface FakeSlackAck {
65
75
  envelopeId: string;
@@ -128,6 +138,8 @@ export interface FakeSlackServer {
128
138
  clientSecret: string;
129
139
  messages: FakeSlackMessage[];
130
140
  updates: FakeSlackMessage[];
141
+ /** Completed external uploads (`files.completeUploadExternal`), in order. */
142
+ files: FakeSlackFile[];
131
143
  calls: FakeSlackCall[];
132
144
  acks: FakeSlackAck[];
133
145
  users: Map<string, FakeSlackUser>;
@@ -148,8 +160,12 @@ export interface FakeSlackServer {
148
160
  * closed unacked is dropped from this count.
149
161
  */
150
162
  pendingEnvelopes(appToken?: string): number;
163
+ /**
164
+ * The next `count` calls of `method` fail. The pseudo-method `"upload"` is the `POST /upload/<id>`
165
+ * step of the external upload flow: it answers `failure.status` (default 500) with a plain-text body.
166
+ */
151
167
  failNext(method: string, failure: FakeSlackFailure, count?: number): void;
152
- /** 之后该方法的每次调用先等 `ms` 毫秒再响应(0 取消)。 */
168
+ /** Every later call of the method waits `ms` milliseconds before answering (0 cancels); `"upload"` holds the upload POST. */
153
169
  delay(method: string, ms: number): void;
154
170
  /** 接下来 `count` 条 Socket Mode 连接在发出 hello 后立即被关闭(不发 disconnect 消息)。 */
155
171
  dropNextConnections(count: number): void;
@@ -8,6 +8,12 @@ const readBody = (req) => new Promise((resolve) => {
8
8
  });
9
9
  req.on("end", () => resolve(body));
10
10
  });
11
+ const readRaw = (req) => new Promise((resolve, reject) => {
12
+ const chunks = [];
13
+ req.on("data", (c) => chunks.push(c));
14
+ req.on("end", () => resolve(Buffer.concat(chunks)));
15
+ req.on("error", reject);
16
+ });
11
17
  const JSON_FIELDS = new Set(["blocks", "attachments", "metadata"]);
12
18
  function parseBody(raw, contentType) {
13
19
  if (raw === "")
@@ -49,6 +55,9 @@ export async function startFakeSlack(opts = {}) {
49
55
  let tamper;
50
56
  const messages = [];
51
57
  const updates = [];
58
+ const files = [];
59
+ /** External uploads by file id: announced by getUploadURLExternal, `data` set once uploaded. */
60
+ const uploads = new Map();
52
61
  const calls = [];
53
62
  const acks = [];
54
63
  const users = new Map();
@@ -207,6 +216,54 @@ export async function startFakeSlack(opts = {}) {
207
216
  });
208
217
  return reply(res, { ok: true, channel, ts, text });
209
218
  }
219
+ case "files.getUploadURLExternal": {
220
+ const filename = str(body.filename);
221
+ const length = Number(body.length);
222
+ if (!filename || !Number.isInteger(length) || length < 0) {
223
+ return reply(res, { ok: false, error: "invalid_arguments" });
224
+ }
225
+ const id = `F${String(++seq).padStart(8, "0")}`;
226
+ uploads.set(id, { filename, length });
227
+ return reply(res, { ok: true, upload_url: `${base}/upload/${id}`, file_id: id });
228
+ }
229
+ case "files.completeUploadExternal": {
230
+ const channel = str(body.channel_id);
231
+ const threadTs = str(body.thread_ts);
232
+ let list = body.files;
233
+ if (typeof list === "string") {
234
+ try {
235
+ list = JSON.parse(list);
236
+ }
237
+ catch {
238
+ return reply(res, { ok: false, error: "invalid_arguments" });
239
+ }
240
+ }
241
+ if (!Array.isArray(list) || list.length === 0 || !channel) {
242
+ return reply(res, { ok: false, error: "invalid_arguments" });
243
+ }
244
+ const items = list;
245
+ for (const it of items) {
246
+ const u = typeof it.id === "string" ? uploads.get(it.id) : undefined;
247
+ if (!u?.data)
248
+ return reply(res, { ok: false, error: "invalid_arguments" });
249
+ }
250
+ const done = items.map((it) => {
251
+ const id = it.id;
252
+ const u = uploads.get(id);
253
+ const title = str(it.title);
254
+ files.push({
255
+ id,
256
+ filename: u.filename,
257
+ ...(title !== undefined && { title }),
258
+ channel,
259
+ ...(threadTs !== undefined && { threadTs }),
260
+ data: u.data,
261
+ at: Date.now(),
262
+ });
263
+ return { id, title: title ?? u.filename };
264
+ });
265
+ return reply(res, { ok: true, files: done });
266
+ }
210
267
  case "users.list": {
211
268
  const limit = Math.max(1, Math.min(1000, Number(body.limit ?? 100) || 100));
212
269
  const offset = str(body.cursor)
@@ -327,12 +384,52 @@ export async function startFakeSlack(opts = {}) {
327
384
  }
328
385
  res.writeHead(302, { location: back.toString() }).end();
329
386
  };
387
+ /** `POST /upload/<id>`: the raw bytes or one multipart file part; the length must match. */
388
+ const upload = async (req, res, id) => {
389
+ const raw = await readRaw(req);
390
+ const wait = delays.get("upload") ?? 0;
391
+ if (wait > 0)
392
+ await new Promise((r) => setTimeout(r, wait));
393
+ const f = failures.find((x) => x.method === "upload" && x.left > 0);
394
+ if (f) {
395
+ f.left--;
396
+ const { status, retryAfter } = f.failure;
397
+ const headers = { "content-type": "text/plain" };
398
+ if (retryAfter !== undefined)
399
+ headers["retry-after"] = String(retryAfter);
400
+ res.writeHead(status ?? 500, headers).end("upload failed");
401
+ return;
402
+ }
403
+ const u = uploads.get(id);
404
+ if (!u)
405
+ return reply(res, { ok: false, error: "invalid_arguments" }, 404);
406
+ const type = req.headers["content-type"];
407
+ let data = raw;
408
+ if (type?.includes("multipart/form-data")) {
409
+ const form = await new Response(new Uint8Array(raw), {
410
+ headers: { "content-type": type },
411
+ }).formData();
412
+ const part = [...form.values()].find((v) => typeof v !== "string");
413
+ if (!part)
414
+ return reply(res, { ok: false, error: "invalid_arguments" }, 400);
415
+ data = Buffer.from(await part.arrayBuffer());
416
+ }
417
+ if (data.length !== u.length) {
418
+ res.writeHead(400, { "content-type": "text/plain" }).end("length mismatch");
419
+ return;
420
+ }
421
+ u.data = data;
422
+ res.writeHead(200, { "content-type": "text/plain" }).end(`OK - ${data.length}`);
423
+ };
330
424
  const server = createServer((req, res) => {
331
425
  void (async () => {
332
426
  const u = new URL(req.url ?? "/", "http://x");
333
427
  const m = /^\/api\/([A-Za-z.]+)$/.exec(u.pathname);
334
428
  if (m && req.method === "POST")
335
429
  return api(req, res, m[1]);
430
+ const up = /^\/upload\/([A-Za-z0-9]+)$/.exec(u.pathname);
431
+ if (up && req.method === "POST")
432
+ return upload(req, res, up[1]);
336
433
  if (u.pathname === "/openid/connect/authorize" && req.method === "GET")
337
434
  return authorize(res, u);
338
435
  if (u.pathname === "/openid/connect/keys" && req.method === "GET") {
@@ -463,6 +560,7 @@ export async function startFakeSlack(opts = {}) {
463
560
  clientSecret,
464
561
  messages,
465
562
  updates,
563
+ files,
466
564
  calls,
467
565
  acks,
468
566
  users,
@@ -7,7 +7,8 @@
7
7
  * An unknown token → 401 `Unauthorized`; an unknown method → 404 `Not Found`. Point a client at
8
8
  * `apiUrl` (it appends `/bot<token>/<method>`).
9
9
  * - **Methods**: `getMe`, `getWebhookInfo` (the url given to {@link FakeTelegramServer.setWebhook}),
10
- * `getUpdates`, `sendMessage`, `editMessageText`, `answerCallbackQuery`.
10
+ * `getUpdates`, `sendMessage`, `editMessageText`, `answerCallbackQuery`, and the multipart uploads
11
+ * `sendPhoto` / `sendDocument` (recorded in `messages` with `file`).
11
12
  * - **Long polling**: {@link FakeTelegramServer.push} queues an update per bot and assigns its
12
13
  * `update_id`. `getUpdates` with `offset` confirms (drops) the lower ids; with `timeout` it waits
13
14
  * until a push or the timeout; `allowed_updates` is remembered per bot like Telegram and updates of
@@ -49,6 +50,13 @@ export interface FakeTelegramMessage {
49
50
  replyMarkup?: unknown;
50
51
  messageThreadId?: number;
51
52
  replyToMessageId?: number;
53
+ /** The uploaded file of a `sendPhoto` / `sendDocument` (the text is its caption). */
54
+ file?: {
55
+ kind: "photo" | "document";
56
+ name: string;
57
+ contentType: string;
58
+ data: Buffer;
59
+ };
52
60
  at: number;
53
61
  }
54
62
  /** An injected error answer: `status` is the HTTP status, `errorCode` defaults to it. */
@@ -1,5 +1,6 @@
1
1
  import { createServer } from "node:http";
2
2
  const MAX_TEXT = 4096;
3
+ const MAX_CAPTION = 1024;
3
4
  const ENTITIES = { lt: "<", gt: ">", amp: "&", quot: '"' };
4
5
  /**
5
6
  * The text length Telegram limits: UTF-16 code units after entity parsing. With `parse_mode`
@@ -33,14 +34,13 @@ class TelegramError extends Error {
33
34
  }
34
35
  }
35
36
  const readBody = (req) => new Promise((resolve, reject) => {
36
- let body = "";
37
- req.on("data", (c) => {
38
- body += c.toString();
39
- });
40
- req.on("end", () => resolve(body));
37
+ const chunks = [];
38
+ req.on("data", (c) => chunks.push(c));
39
+ req.on("end", () => resolve(Buffer.concat(chunks)));
41
40
  req.on("error", reject);
42
41
  });
43
- function parseParams(url, raw, contentType) {
42
+ async function parseParams(url, rawBytes, contentType, uploads) {
43
+ const raw = contentType?.includes("multipart/form-data") ? "" : rawBytes.toString();
44
44
  const out = {};
45
45
  const fromForm = (form) => {
46
46
  for (const [k, v] of form) {
@@ -57,6 +57,33 @@ function parseParams(url, raw, contentType) {
57
57
  }
58
58
  };
59
59
  fromForm(url.searchParams);
60
+ if (contentType?.includes("multipart/form-data")) {
61
+ let form;
62
+ try {
63
+ form = await new Response(new Uint8Array(rawBytes), {
64
+ headers: { "content-type": contentType },
65
+ }).formData();
66
+ }
67
+ catch {
68
+ throw new TelegramError(400, "Bad Request: invalid multipart body");
69
+ }
70
+ for (const [k, v] of form) {
71
+ if (typeof v === "string") {
72
+ const one = new URLSearchParams();
73
+ one.set(k, v);
74
+ fromForm(one);
75
+ }
76
+ else {
77
+ uploads.push({
78
+ field: k,
79
+ name: v.name,
80
+ contentType: v.type,
81
+ data: Buffer.from(await v.arrayBuffer()),
82
+ });
83
+ }
84
+ }
85
+ return out;
86
+ }
60
87
  if (raw === "")
61
88
  return out;
62
89
  if (contentType?.includes("application/json")) {
@@ -178,15 +205,19 @@ export async function startFakeTelegram(opts = {}) {
178
205
  const timeout = Math.max(num(params.timeout) ?? 0, 0);
179
206
  return { limit, timeout, ready: collect(s, limit), port: req.socket.remotePort };
180
207
  };
181
- const sendMessage = (s, params) => {
208
+ /** `upload` set: a sendPhoto / sendDocument, whose text is the caption (up to 1024). */
209
+ const sendMessage = (s, params, upload) => {
182
210
  const chatId = num(params.chat_id);
183
211
  if (chatId === undefined)
184
212
  throw new TelegramError(400, "Bad Request: chat not found");
185
- const text = str(params.text) ?? "";
186
- if (text === "")
213
+ const text = (upload ? str(params.caption) : str(params.text)) ?? "";
214
+ if (!upload && text === "")
187
215
  throw new TelegramError(400, "Bad Request: message text is empty");
188
- if (telegramTextLength(text, str(params.parse_mode)) > MAX_TEXT) {
189
- throw new TelegramError(400, "Bad Request: message is too long");
216
+ if (upload && upload.part.data.length === 0) {
217
+ throw new TelegramError(400, "Bad Request: file must be non-empty");
218
+ }
219
+ if (telegramTextLength(text, str(params.parse_mode)) > (upload ? MAX_CAPTION : MAX_TEXT)) {
220
+ throw new TelegramError(400, upload ? "Bad Request: message caption is too long" : "Bad Request: message is too long");
190
221
  }
191
222
  const chatKey = `${s.bot.token}|${chatId}`;
192
223
  const messageId = (lastMessageId.get(chatKey) ?? 0) + 1;
@@ -203,6 +234,14 @@ export async function startFakeTelegram(opts = {}) {
203
234
  ...(params.reply_markup !== undefined && { replyMarkup: params.reply_markup }),
204
235
  ...(threadId !== undefined && { messageThreadId: threadId }),
205
236
  ...(replyTo !== undefined && { replyToMessageId: replyTo }),
237
+ ...(upload && {
238
+ file: {
239
+ kind: upload.kind,
240
+ name: upload.part.name,
241
+ contentType: upload.part.contentType,
242
+ data: upload.part.data,
243
+ },
244
+ }),
206
245
  at: Date.now(),
207
246
  };
208
247
  messages.push(m);
@@ -247,15 +286,30 @@ export async function startFakeTelegram(opts = {}) {
247
286
  from: botUser(s.bot),
248
287
  chat: { id: m.chatId, type: m.chatId > 0 ? "private" : "supergroup" },
249
288
  date: Math.floor(m.at / 1000),
250
- text: m.text,
289
+ ...(m.file
290
+ ? {
291
+ ...(m.text !== "" && { caption: m.text }),
292
+ ...(m.file.kind === "photo"
293
+ ? { photo: [{ file_id: "fake-photo", file_unique_id: "fp", width: 800, height: 800 }] }
294
+ : {
295
+ document: {
296
+ file_id: "fake-document",
297
+ file_unique_id: "fd",
298
+ file_name: m.file.name,
299
+ mime_type: m.file.contentType,
300
+ },
301
+ }),
302
+ }
303
+ : { text: m.text }),
251
304
  ...(m.messageThreadId !== undefined && { message_thread_id: m.messageThreadId }),
252
305
  ...(m.replyMarkup !== undefined && { reply_markup: m.replyMarkup }),
253
306
  });
254
307
  const handle = async (req, res, token, name) => {
255
308
  const url = new URL(req.url ?? "/", "http://x");
256
309
  let params;
310
+ const uploads = [];
257
311
  try {
258
- params = parseParams(url, await readBody(req), req.headers["content-type"]);
312
+ params = await parseParams(url, await readBody(req), req.headers["content-type"], uploads);
259
313
  }
260
314
  catch (e) {
261
315
  if (e instanceof TelegramError)
@@ -329,6 +383,15 @@ export async function startFakeTelegram(opts = {}) {
329
383
  }
330
384
  case "sendmessage":
331
385
  return ok(res, sendMessage(s, params));
386
+ case "sendphoto":
387
+ case "senddocument": {
388
+ const kind = method === "sendphoto" ? "photo" : "document";
389
+ const part = uploads.find((u) => u.field === kind);
390
+ if (!part) {
391
+ throw new TelegramError(400, `Bad Request: there is no ${kind} in the request`);
392
+ }
393
+ return ok(res, sendMessage(s, params, { kind, part }));
394
+ }
332
395
  case "editmessagetext":
333
396
  return ok(res, editMessageText(s, params));
334
397
  case "answercallbackquery":
@@ -17,7 +17,7 @@
17
17
  * | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
18
18
  * | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
19
19
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
20
- * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
20
+ * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, files via `sendFile`, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
21
21
  * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
22
22
  * | `fake-context` | `context@1` scripted by its deployment config (`text`, default "fake context"; `mode` `ok` / `null` / `throw` / `hang`); calls recorded on `globalThis.__fakeContext` (`fakeContextProbe`); tool `note` (`sources` web and channel_dm) |
23
23
  * | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
package/dist/fixtures.js CHANGED
@@ -20,7 +20,7 @@ import { fileURLToPath } from "node:url";
20
20
  * | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
21
21
  * | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
22
22
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
23
- * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
23
+ * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, files via `sendFile`, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
24
24
  * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
25
25
  * | `fake-context` | `context@1` scripted by its deployment config (`text`, default "fake context"; `mode` `ok` / `null` / `throw` / `hang`); calls recorded on `globalThis.__fakeContext` (`fakeContextProbe`); tool `note` (`sources` web and channel_dm) |
26
26
  * | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
package/dist/index.d.ts CHANGED
@@ -7,17 +7,17 @@ export { type ConversationEvent, createDb, gatewayReplicasKey, type KernelConfig
7
7
  export { createFreshDatabase, startPostgresContainer, startTestPostgres, startTestRedis, startTestS3, TEST_PG_IMAGE, TEST_S3_IMAGE, type TestContainer, type TestS3, } from "./containers.js";
8
8
  export { createDualReplicaHarness, type DualReplicaOptions, type ExtraReplicaHandle, type Harness, REPLICA_HEADER, type ReplicaHandle, type ReplicaResponse, replicaOf, } from "./dual-replica.js";
9
9
  export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
10
- export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
10
+ export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelSentFile, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
11
11
  export { type FakeE2BCall, type FakeE2BMatch, type FakeE2BOptions, type FakeE2BSandbox, type FakeE2BServer, startFakeE2B, } from "./fake-e2b.js";
12
12
  export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, type FakeGitServerOptions, startFakeGitServer, } from "./fake-git-server.js";
13
- export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
13
+ export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUpload, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
14
14
  export { type FakeMarketplace, type FakeMarketplaceRequest, startFakeMarketplace, } from "./fake-marketplace.js";
15
15
  export { type FakeMcpCallInfo, type FakeMcpHandlerContext, type FakeMcpPrompt, type FakeMcpRequest, type FakeMcpResource, FakeMcpRpcError, type FakeMcpServer, type FakeMcpServerOptions, type FakeMcpTool, startFakeMcpServer, } from "./fake-mcp-server.js";
16
16
  export { type FakeModelServer, type FakeRequest, type FakeResponse, startFakeModelServer, } from "./fake-model-server.js";
17
17
  export { type FakeNpmPackage, type FakeNpmRegistry, npmProvenanceAttestations, startFakeNpmRegistry, } from "./fake-npm-registry.js";
18
18
  export { type FakeOAuthClient, type FakeOAuthServer, type FakeOAuthServerOptions, type FakeTokenRequest, startFakeOAuthServer, } from "./fake-oauth-server.js";
19
19
  export { defaultFakeOpenApiSpec, type FakeOpenApiRequest, type FakeOpenApiServer, type FakeOpenApiServerOptions, type FakePet, startFakeOpenApiServer, } from "./fake-openapi-server.js";
20
- export { type FakeSlackAck, type FakeSlackCall, type FakeSlackFailure, type FakeSlackMessage, type FakeSlackOptions, type FakeSlackServer, type FakeSlackUser, findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
20
+ export { type FakeSlackAck, type FakeSlackCall, type FakeSlackFailure, type FakeSlackFile, type FakeSlackMessage, type FakeSlackOptions, type FakeSlackServer, type FakeSlackUser, findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
21
21
  export { type FakeTelegramBot, type FakeTelegramCall, type FakeTelegramFailure, type FakeTelegramMessage, type FakeTelegramOptions, type FakeTelegramServer, findTelegramButton, startFakeTelegram, type TgChat, type TgUser, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
22
22
  export { FAKE_EXTENSIONS, type FakeExtensionName, fakeExtensionDir, fakeExtensionEntry, type PackedFixture, packFixture, } from "./fixtures.js";
23
23
  export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, enableModelProviders, eventsOf, joinOrg, type KernelApp, type KernelRequest, type KernelRequestOptions, type KernelResponse, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, type TestKernel, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
@@ -223,4 +223,23 @@ export const makeFakeImChannel = (
223
223
  const res = await post(c, "/update", body, signal);
224
224
  await res.body?.cancel();
225
225
  },
226
+ ...(features.files !== undefined && {
227
+ async sendFile({ config, target, file, signal, idempotencyKey, locale }) {
228
+ const c = config as ConnConfig;
229
+ const body = {
230
+ appId: c.appId,
231
+ target,
232
+ file: {
233
+ name: file.name,
234
+ contentType: file.contentType,
235
+ kind: file.kind,
236
+ data: Buffer.from(file.data).toString("base64"),
237
+ },
238
+ idempotencyKey,
239
+ locale,
240
+ };
241
+ const res = await post(c, "/send-file", body, signal);
242
+ return (await res.json()) as { messageId: string };
243
+ },
244
+ }),
226
245
  });
@@ -107,7 +107,15 @@ export default defineExtension({
107
107
  const config = () => Deployment.parse(ctx.config);
108
108
  ctx.provide(
109
109
  "channel@1",
110
- makeFakeImChannel({ cards: true, edit: true, threads: true }, { webhook: true }),
110
+ makeFakeImChannel(
111
+ {
112
+ cards: true,
113
+ edit: true,
114
+ threads: true,
115
+ files: { maxBytes: 20_971_520, imageMaxBytes: 10_485_760 },
116
+ },
117
+ { webhook: true },
118
+ ),
111
119
  );
112
120
  ctx.provide("identity-source@1", fakeImIdentitySource);
113
121
  ctx.provide("directory@1", fakeImDirectory);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.26",
3
+ "version": "0.1.0-rc.27",
4
4
  "description": "Test helpers for Capybara: test containers, dual-replica harness and fake third-party servers",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -47,18 +47,18 @@
47
47
  "tsx": "^4.23.15",
48
48
  "ws": "^8.22.0",
49
49
  "zod": "^4.6.7",
50
- "@capybara-hq/kernel": "^0.1.0-rc.44"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.48"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
- "@capybara-hq/plugin-client": "^0.1.0-rc.5",
56
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.32"
55
+ "@capybara-hq/plugin-client": "^0.1.0-rc.6",
56
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.34"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": "^5.0.5",
60
- "@capybara-hq/plugin-tools": "^0.1.0-rc.17",
61
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.32"
60
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.34",
61
+ "@capybara-hq/plugin-tools": "^0.1.0-rc.17"
62
62
  },
63
63
  "peerDependenciesMeta": {
64
64
  "@capybara-hq/plugin-tools": {