@capybara-hq/testing 0.1.0-rc.7 → 0.1.0-rc.9

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.
@@ -0,0 +1,165 @@
1
+ /**
2
+ * A programmable fake Telegram Bot API (for the Telegram channel plugin's tests).
3
+ *
4
+ * - **Routing**: `GET|POST /bot<token>/<method>` (method names are case-insensitive, like Telegram);
5
+ * parameters come from the query string and a JSON or form-urlencoded body. Every answer is the
6
+ * Bot API envelope: `{ ok: true, result }` or `{ ok: false, error_code, description, parameters? }`.
7
+ * An unknown token → 401 `Unauthorized`; an unknown method → 404 `Not Found`. Point a client at
8
+ * `apiUrl` (it appends `/bot<token>/<method>`).
9
+ * - **Methods**: `getMe`, `getWebhookInfo` (the url given to {@link FakeTelegramServer.setWebhook}),
10
+ * `getUpdates`, `sendMessage`, `editMessageText`, `answerCallbackQuery`.
11
+ * - **Long polling**: {@link FakeTelegramServer.push} queues an update per bot and assigns its
12
+ * `update_id`. `getUpdates` with `offset` confirms (drops) the lower ids; with `timeout` it waits
13
+ * until a push or the timeout; `allowed_updates` is remembered per bot like Telegram and updates of
14
+ * other types are dropped. While a webhook is set `getUpdates` answers 409; a second concurrent
15
+ * `getUpdates` for the same token ends the earlier one with 409 "Conflict: terminated by other
16
+ * getUpdates request", as Telegram does.
17
+ * - **Several bots**: {@link FakeTelegramOptions.bots}; each token has its own queue, offset, webhook
18
+ * and pollers.
19
+ * - **Failures**: {@link FakeTelegramServer.failNext} answers a method with an error envelope
20
+ * (`parameters.retry_after` / `migrate_to_chat_id`), {@link FakeTelegramServer.delay} holds it.
21
+ *
22
+ * Records: `messages` (sendMessage), `edits` (successful editMessageText), `calls` (every call with
23
+ * a known token), `callbackAnswers` (answerCallbackQuery ids).
24
+ */
25
+ export interface FakeTelegramBot {
26
+ /** `<id>:<secret>`, as BotFather issues it. */
27
+ token: string;
28
+ id: number;
29
+ username: string;
30
+ firstName?: string;
31
+ /** getMe `can_read_all_group_messages` (privacy mode off); default false. */
32
+ canReadAllGroupMessages?: boolean;
33
+ /** getMe `has_topics_enabled` (forum topics in private chats); default false. */
34
+ hasTopicsEnabled?: boolean;
35
+ }
36
+ /** One Bot API call with a known token (parameters merged from query string and body). */
37
+ export interface FakeTelegramCall {
38
+ method: string;
39
+ token: string;
40
+ params: Record<string, unknown>;
41
+ at: number;
42
+ }
43
+ /** A message the bot sent (`sendMessage`) or an edit of one (`editMessageText`). */
44
+ export interface FakeTelegramMessage {
45
+ chatId: number;
46
+ messageId: number;
47
+ text: string;
48
+ parseMode?: string;
49
+ replyMarkup?: unknown;
50
+ messageThreadId?: number;
51
+ replyToMessageId?: number;
52
+ at: number;
53
+ }
54
+ /** An injected error answer: `status` is the HTTP status, `errorCode` defaults to it. */
55
+ export interface FakeTelegramFailure {
56
+ status: number;
57
+ errorCode?: number;
58
+ description: string;
59
+ retryAfter?: number;
60
+ migrateToChatId?: number;
61
+ }
62
+ export interface FakeTelegramOptions {
63
+ /** The bots this fake serves; default one bot (`123456:fake-telegram-token`, `capybara_bot`). */
64
+ bots?: FakeTelegramBot[];
65
+ }
66
+ export interface FakeTelegramServer {
67
+ url: string;
68
+ /** Same as `url`: the client appends `/bot<token>/<method>`. */
69
+ apiUrl: string;
70
+ /** The first bot (the default for every `token?` argument). */
71
+ bot: FakeTelegramBot;
72
+ bots: FakeTelegramBot[];
73
+ /** sendMessage results, in order. */
74
+ messages: FakeTelegramMessage[];
75
+ /** Successful editMessageText calls, in order (markup-only edits are recorded too). */
76
+ edits: FakeTelegramMessage[];
77
+ calls: FakeTelegramCall[];
78
+ /** answerCallbackQuery `callback_query_id`s, in order. */
79
+ callbackAnswers: string[];
80
+ /** Queues an update for the bot, assigns its `update_id` and returns it; wakes a long poll. */
81
+ push(update: Record<string, unknown>, token?: string): number;
82
+ /** The highest offset passed to getUpdates (0 before any). */
83
+ confirmedOffset(token?: string): number;
84
+ /** Updates pushed and not yet confirmed. */
85
+ pending(token?: string): number;
86
+ /** In-flight getUpdates requests. */
87
+ activePollers(token?: string): number;
88
+ /**
89
+ * The peak number of overlapping getUpdates requests: a request that arrives while another is in
90
+ * flight counts as concurrent with it, although it ends the earlier one with 409.
91
+ */
92
+ maxConcurrentPollers(token?: string): number;
93
+ /**
94
+ * The client TCP ports of the in-flight getUpdates requests; dual-replica tests map them to the
95
+ * replica process holding the poll.
96
+ */
97
+ pollerPeerPorts(token?: string): number[];
98
+ /** Sets (or clears with null) the webhook getWebhookInfo reports; while set, getUpdates is 409. */
99
+ setWebhook(url: string | null, token?: string): void;
100
+ /** The next `count` (default 1) calls of `method` answer with `failure`. */
101
+ failNext(method: string, failure: FakeTelegramFailure, count?: number): void;
102
+ /** Every later call of `method` waits `ms` before answering (0 cancels). */
103
+ delay(method: string, ms: number): void;
104
+ close(): Promise<void>;
105
+ }
106
+ export type TgUser = {
107
+ id: number;
108
+ first_name: string;
109
+ last_name?: string;
110
+ username?: string;
111
+ is_bot?: boolean;
112
+ };
113
+ export type TgChat = {
114
+ id: number;
115
+ type: "private" | "group" | "supergroup";
116
+ title?: string;
117
+ is_forum?: boolean;
118
+ };
119
+ /** Starts the fake Telegram Bot API (listens on a random 127.0.0.1 port). */
120
+ export declare function startFakeTelegram(opts?: FakeTelegramOptions): Promise<FakeTelegramServer>;
121
+ /** An update with a private (direct) message from `from`. */
122
+ export declare function telegramPrivateMessage(from: TgUser, text: string, o?: {
123
+ messageId?: number;
124
+ date?: number;
125
+ }): Record<string, unknown>;
126
+ /**
127
+ * An update with a group message. `mention` (with or without `@`) adds a `mention` entity at its
128
+ * UTF-16 offset, prefixing `@<mention> ` when the text lacks it; `replyTo` sets `reply_to_message`
129
+ * (from the bot when `fromBot` is given); `messageThreadId` sets the thread, with
130
+ * `is_topic_message` defaulting to the chat's `is_forum`; `caption` turns the message into a photo
131
+ * whose caption carries the text and entities.
132
+ */
133
+ export declare function telegramGroupMessage(chat: TgChat, from: TgUser, text: string, o?: {
134
+ messageId?: number;
135
+ mention?: string;
136
+ replyTo?: {
137
+ messageId: number;
138
+ fromBot?: FakeTelegramBot;
139
+ text?: string;
140
+ };
141
+ messageThreadId?: number;
142
+ isTopicMessage?: boolean;
143
+ caption?: boolean;
144
+ }): Record<string, unknown>;
145
+ /** An update with a callback query: `from` pressed an inline button with `data` on a bot message. */
146
+ export declare function telegramCallback(from: TgUser, message: {
147
+ chatId: number;
148
+ messageId: number;
149
+ chatType?: string;
150
+ messageThreadId?: number;
151
+ }, data: string, o?: {
152
+ id?: string;
153
+ }): Record<string, unknown>;
154
+ /** Finds an inline keyboard button in a `reply_markup` (object or JSON string). */
155
+ export declare function findTelegramButton(replyMarkup: unknown, pred: (b: {
156
+ text: string;
157
+ callback_data?: string;
158
+ url?: string;
159
+ }) => boolean): {
160
+ text: string;
161
+ callback_data?: string;
162
+ url?: string;
163
+ } | undefined;
164
+ /** The headers Telegram sends to a webhook set with `secret_token`. */
165
+ export declare function telegramWebhookHeaders(secret: string): Record<string, string>;
@@ -0,0 +1,569 @@
1
+ import { createServer } from "node:http";
2
+ const MAX_TEXT = 4096;
3
+ const ENTITIES = { lt: "<", gt: ">", amp: "&", quot: '"' };
4
+ /**
5
+ * The text length Telegram limits: UTF-16 code units after entity parsing. With `parse_mode`
6
+ * HTML, tags (including `<a href>`) are removed and character references decoded.
7
+ */
8
+ function telegramTextLength(text, parseMode) {
9
+ if (parseMode?.toUpperCase() !== "HTML")
10
+ return text.length;
11
+ return text
12
+ .replace(/<[^>]*>/g, "")
13
+ .replace(/&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|amp|quot);/g, (_, ref) => {
14
+ if (ref.startsWith("#x"))
15
+ return String.fromCodePoint(Number.parseInt(ref.slice(2), 16));
16
+ if (ref.startsWith("#"))
17
+ return String.fromCodePoint(Number.parseInt(ref.slice(1), 10));
18
+ return ENTITIES[ref] ?? "";
19
+ }).length;
20
+ }
21
+ const JSON_PARAMS = new Set(["reply_markup", "reply_parameters", "allowed_updates", "entities"]);
22
+ const DEFAULT_BOT = {
23
+ token: "123456:fake-telegram-token",
24
+ id: 123456,
25
+ username: "capybara_bot",
26
+ firstName: "Capybara",
27
+ };
28
+ class TelegramError extends Error {
29
+ code;
30
+ constructor(code, description) {
31
+ super(description);
32
+ this.code = code;
33
+ }
34
+ }
35
+ 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));
41
+ req.on("error", reject);
42
+ });
43
+ function parseParams(url, raw, contentType) {
44
+ const out = {};
45
+ const fromForm = (form) => {
46
+ for (const [k, v] of form) {
47
+ if (JSON_PARAMS.has(k)) {
48
+ try {
49
+ out[k] = JSON.parse(v);
50
+ continue;
51
+ }
52
+ catch {
53
+ // keep the raw string
54
+ }
55
+ }
56
+ out[k] = v;
57
+ }
58
+ };
59
+ fromForm(url.searchParams);
60
+ if (raw === "")
61
+ return out;
62
+ if (contentType?.includes("application/json")) {
63
+ let body;
64
+ try {
65
+ body = JSON.parse(raw);
66
+ }
67
+ catch {
68
+ throw new TelegramError(400, "Bad Request: invalid JSON");
69
+ }
70
+ if (body !== null && typeof body === "object")
71
+ Object.assign(out, body);
72
+ }
73
+ else {
74
+ fromForm(new URLSearchParams(raw));
75
+ }
76
+ return out;
77
+ }
78
+ const num = (v) => {
79
+ if (typeof v === "number")
80
+ return v;
81
+ if (typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)))
82
+ return Number(v);
83
+ return undefined;
84
+ };
85
+ const str = (v) => (typeof v === "string" ? v : undefined);
86
+ const nowSec = () => Math.floor(Date.now() / 1000);
87
+ /** The update's type: its one field besides `update_id`. */
88
+ const updateType = (u) => Object.keys(u).find((k) => k !== "update_id");
89
+ /** Starts the fake Telegram Bot API (listens on a random 127.0.0.1 port). */
90
+ export async function startFakeTelegram(opts = {}) {
91
+ const bots = opts.bots && opts.bots.length > 0 ? opts.bots : [DEFAULT_BOT];
92
+ const states = new Map();
93
+ for (const [i, bot] of bots.entries()) {
94
+ if (states.has(bot.token))
95
+ throw new Error(`fake telegram: duplicate bot token ${bot.token}`);
96
+ states.set(bot.token, {
97
+ bot,
98
+ queue: [],
99
+ nextUpdateId: 100_000_001 + i * 10_000_000,
100
+ confirmed: 0,
101
+ webhook: "",
102
+ allowed: undefined,
103
+ pollers: [],
104
+ peakPollers: 0,
105
+ });
106
+ }
107
+ const first = bots[0];
108
+ const messages = [];
109
+ const edits = [];
110
+ const calls = [];
111
+ const callbackAnswers = [];
112
+ const failures = [];
113
+ const delays = new Map();
114
+ /** Per bot and chat: the last message id sent. */
115
+ const lastMessageId = new Map();
116
+ /** Per bot, chat and message: the current text and markup (for "message is not modified"). */
117
+ const current = new Map();
118
+ /** Pending `delay` waits, cleared (and released) on close. */
119
+ const delayTimers = new Map();
120
+ let closed = false;
121
+ const stateOf = (token) => {
122
+ const s = states.get(token ?? first.token);
123
+ if (!s)
124
+ throw new Error(`fake telegram: unknown bot token ${token}`);
125
+ return s;
126
+ };
127
+ const reply = (res, status, body) => {
128
+ if (res.headersSent || res.destroyed)
129
+ return;
130
+ res.writeHead(status, { "content-type": "application/json" });
131
+ res.end(JSON.stringify(body));
132
+ };
133
+ const ok = (res, result) => reply(res, 200, { ok: true, result });
134
+ const fail = (res, code, description) => reply(res, code, { ok: false, error_code: code, description });
135
+ const botUser = (bot) => ({
136
+ id: bot.id,
137
+ is_bot: true,
138
+ first_name: bot.firstName ?? bot.username,
139
+ username: bot.username,
140
+ });
141
+ /** Drops updates of types not allowed, then returns up to `limit` of the queue. */
142
+ const collect = (s, limit) => {
143
+ if (s.allowed) {
144
+ const allowed = s.allowed;
145
+ s.queue = s.queue.filter((u) => allowed.has(updateType(u) ?? ""));
146
+ }
147
+ return s.queue.slice(0, limit);
148
+ };
149
+ const removePoller = (s, p) => {
150
+ clearTimeout(p.timer);
151
+ const i = s.pollers.indexOf(p);
152
+ if (i >= 0)
153
+ s.pollers.splice(i, 1);
154
+ };
155
+ const getUpdates = (s, params, req) => {
156
+ if (s.webhook !== "") {
157
+ throw new TelegramError(409, "Conflict: can't use getUpdates method while webhook is active; use deleteWebhook to delete the webhook first");
158
+ }
159
+ const offset = num(params.offset);
160
+ if (offset !== undefined && offset > 0) {
161
+ s.queue = s.queue.filter((u) => u.update_id >= offset);
162
+ s.confirmed = Math.max(s.confirmed, offset);
163
+ }
164
+ else if (offset !== undefined && offset < 0) {
165
+ s.queue = s.queue.slice(offset);
166
+ }
167
+ const allowed = params.allowed_updates;
168
+ if (Array.isArray(allowed)) {
169
+ s.allowed = allowed.length > 0 ? new Set(allowed.map(String)) : undefined;
170
+ }
171
+ // An overlapping request counts as concurrent even though Telegram ends the earlier one.
172
+ s.peakPollers = Math.max(s.peakPollers, s.pollers.length + 1);
173
+ for (const earlier of [...s.pollers]) {
174
+ removePoller(s, earlier);
175
+ fail(earlier.res, 409, "Conflict: terminated by other getUpdates request");
176
+ }
177
+ const limit = Math.min(Math.max(num(params.limit) ?? 100, 1), 100);
178
+ const timeout = Math.max(num(params.timeout) ?? 0, 0);
179
+ return { limit, timeout, ready: collect(s, limit), port: req.socket.remotePort };
180
+ };
181
+ const sendMessage = (s, params) => {
182
+ const chatId = num(params.chat_id);
183
+ if (chatId === undefined)
184
+ throw new TelegramError(400, "Bad Request: chat not found");
185
+ const text = str(params.text) ?? "";
186
+ if (text === "")
187
+ 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");
190
+ }
191
+ const chatKey = `${s.bot.token}|${chatId}`;
192
+ const messageId = (lastMessageId.get(chatKey) ?? 0) + 1;
193
+ lastMessageId.set(chatKey, messageId);
194
+ const threadId = num(params.message_thread_id);
195
+ const replyParams = params.reply_parameters;
196
+ const replyTo = num(replyParams?.message_id) ?? num(params.reply_to_message_id);
197
+ const parseMode = str(params.parse_mode);
198
+ const m = {
199
+ chatId,
200
+ messageId,
201
+ text,
202
+ ...(parseMode !== undefined && { parseMode }),
203
+ ...(params.reply_markup !== undefined && { replyMarkup: params.reply_markup }),
204
+ ...(threadId !== undefined && { messageThreadId: threadId }),
205
+ ...(replyTo !== undefined && { replyToMessageId: replyTo }),
206
+ at: Date.now(),
207
+ };
208
+ messages.push(m);
209
+ current.set(`${chatKey}|${messageId}`, m);
210
+ return messageResult(s, m);
211
+ };
212
+ const editMessageText = (s, params) => {
213
+ const chatId = num(params.chat_id);
214
+ const messageId = num(params.message_id);
215
+ const key = `${s.bot.token}|${chatId}|${messageId}`;
216
+ const before = current.get(key);
217
+ if (chatId === undefined || messageId === undefined || !before) {
218
+ throw new TelegramError(400, "Bad Request: message to edit not found");
219
+ }
220
+ const text = str(params.text) ?? "";
221
+ if (text === "")
222
+ throw new TelegramError(400, "Bad Request: message text is empty");
223
+ if (telegramTextLength(text, str(params.parse_mode)) > MAX_TEXT) {
224
+ throw new TelegramError(400, "Bad Request: message is too long");
225
+ }
226
+ const markup = params.reply_markup;
227
+ if (text === before.text && JSON.stringify(markup) === JSON.stringify(before.replyMarkup)) {
228
+ throw new TelegramError(400, "Bad Request: message is not modified");
229
+ }
230
+ const parseMode = str(params.parse_mode);
231
+ const m = {
232
+ chatId,
233
+ messageId,
234
+ text,
235
+ ...(parseMode !== undefined && { parseMode }),
236
+ ...(markup !== undefined && { replyMarkup: markup }),
237
+ ...(before.messageThreadId !== undefined && { messageThreadId: before.messageThreadId }),
238
+ ...(before.replyToMessageId !== undefined && { replyToMessageId: before.replyToMessageId }),
239
+ at: Date.now(),
240
+ };
241
+ edits.push(m);
242
+ current.set(key, m);
243
+ return { ...messageResult(s, m), edit_date: nowSec() };
244
+ };
245
+ const messageResult = (s, m) => ({
246
+ message_id: m.messageId,
247
+ from: botUser(s.bot),
248
+ chat: { id: m.chatId, type: m.chatId > 0 ? "private" : "supergroup" },
249
+ date: Math.floor(m.at / 1000),
250
+ text: m.text,
251
+ ...(m.messageThreadId !== undefined && { message_thread_id: m.messageThreadId }),
252
+ ...(m.replyMarkup !== undefined && { reply_markup: m.replyMarkup }),
253
+ });
254
+ const handle = async (req, res, token, name) => {
255
+ const url = new URL(req.url ?? "/", "http://x");
256
+ let params;
257
+ try {
258
+ params = parseParams(url, await readBody(req), req.headers["content-type"]);
259
+ }
260
+ catch (e) {
261
+ if (e instanceof TelegramError)
262
+ return fail(res, e.code, e.message);
263
+ throw e;
264
+ }
265
+ const s = states.get(token);
266
+ if (!s)
267
+ return fail(res, 401, "Unauthorized");
268
+ calls.push({ method: name, token, params, at: Date.now() });
269
+ const method = name.toLowerCase();
270
+ const wait = delays.get(method) ?? 0;
271
+ if (wait > 0) {
272
+ await new Promise((resolve) => {
273
+ const timer = setTimeout(() => {
274
+ delayTimers.delete(timer);
275
+ resolve();
276
+ }, wait);
277
+ delayTimers.set(timer, resolve);
278
+ });
279
+ if (closed)
280
+ return;
281
+ }
282
+ const f = failures.find((x) => x.method === method && x.left > 0);
283
+ if (f) {
284
+ f.left--;
285
+ const { status, errorCode, description, retryAfter, migrateToChatId } = f.failure;
286
+ const parameters = {
287
+ ...(retryAfter !== undefined && { retry_after: retryAfter }),
288
+ ...(migrateToChatId !== undefined && { migrate_to_chat_id: migrateToChatId }),
289
+ };
290
+ return reply(res, status, {
291
+ ok: false,
292
+ error_code: errorCode ?? status,
293
+ description,
294
+ ...(Object.keys(parameters).length > 0 && { parameters }),
295
+ });
296
+ }
297
+ try {
298
+ switch (method) {
299
+ case "getme":
300
+ return ok(res, {
301
+ ...botUser(s.bot),
302
+ can_join_groups: true,
303
+ can_read_all_group_messages: s.bot.canReadAllGroupMessages ?? false,
304
+ supports_inline_queries: false,
305
+ has_topics_enabled: s.bot.hasTopicsEnabled ?? false,
306
+ });
307
+ case "getwebhookinfo":
308
+ return ok(res, {
309
+ url: s.webhook,
310
+ has_custom_certificate: false,
311
+ pending_update_count: s.queue.length,
312
+ });
313
+ case "getupdates": {
314
+ const { limit, timeout, ready, port } = getUpdates(s, params, req);
315
+ if (ready.length > 0 || timeout === 0 || closed)
316
+ return ok(res, ready);
317
+ const p = {
318
+ res,
319
+ port,
320
+ limit,
321
+ timer: setTimeout(() => {
322
+ removePoller(s, p);
323
+ ok(res, collect(s, limit));
324
+ }, timeout * 1000),
325
+ };
326
+ s.pollers.push(p);
327
+ res.on("close", () => removePoller(s, p));
328
+ return;
329
+ }
330
+ case "sendmessage":
331
+ return ok(res, sendMessage(s, params));
332
+ case "editmessagetext":
333
+ return ok(res, editMessageText(s, params));
334
+ case "answercallbackquery":
335
+ callbackAnswers.push(str(params.callback_query_id) ?? "");
336
+ return ok(res, true);
337
+ default:
338
+ return fail(res, 404, "Not Found");
339
+ }
340
+ }
341
+ catch (e) {
342
+ if (e instanceof TelegramError)
343
+ return fail(res, e.code, e.message);
344
+ throw e;
345
+ }
346
+ };
347
+ const server = createServer((req, res) => {
348
+ void (async () => {
349
+ const path = new URL(req.url ?? "/", "http://x").pathname;
350
+ const m = /^\/bot([^/]+)\/([A-Za-z]+)$/.exec(path);
351
+ if (!m || (req.method !== "GET" && req.method !== "POST")) {
352
+ return fail(res, 404, "Not Found");
353
+ }
354
+ return handle(req, res, decodeURIComponent(m[1]), m[2]);
355
+ })().catch(() => {
356
+ if (!res.headersSent)
357
+ res.writeHead(500);
358
+ res.end();
359
+ });
360
+ });
361
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
362
+ const url = `http://127.0.0.1:${server.address().port}`;
363
+ return {
364
+ url,
365
+ apiUrl: url,
366
+ bot: first,
367
+ bots,
368
+ messages,
369
+ edits,
370
+ calls,
371
+ callbackAnswers,
372
+ push(update, token) {
373
+ const s = stateOf(token);
374
+ const id = s.nextUpdateId++;
375
+ s.queue.push({ update_id: id, ...update });
376
+ for (const p of [...s.pollers]) {
377
+ const ready = collect(s, p.limit);
378
+ if (ready.length === 0)
379
+ continue;
380
+ removePoller(s, p);
381
+ ok(p.res, ready);
382
+ }
383
+ return id;
384
+ },
385
+ confirmedOffset: (token) => stateOf(token).confirmed,
386
+ pending: (token) => stateOf(token).queue.length,
387
+ activePollers: (token) => stateOf(token).pollers.length,
388
+ maxConcurrentPollers: (token) => stateOf(token).peakPollers,
389
+ pollerPeerPorts: (token) => stateOf(token).pollers.flatMap((p) => (p.port === undefined ? [] : [p.port])),
390
+ setWebhook(webhookUrl, token) {
391
+ stateOf(token).webhook = webhookUrl ?? "";
392
+ },
393
+ failNext(method, failure, count = 1) {
394
+ failures.push({ method: method.toLowerCase(), failure, left: count });
395
+ },
396
+ delay(method, ms) {
397
+ delays.set(method.toLowerCase(), ms);
398
+ },
399
+ async close() {
400
+ closed = true;
401
+ for (const [timer, release] of delayTimers) {
402
+ clearTimeout(timer);
403
+ release();
404
+ }
405
+ delayTimers.clear();
406
+ for (const s of states.values())
407
+ for (const p of [...s.pollers])
408
+ removePoller(s, p);
409
+ server.closeAllConnections();
410
+ await new Promise((r) => server.close(() => r()));
411
+ },
412
+ };
413
+ }
414
+ let seq = 0;
415
+ const nextMessageId = () => 1000 + ++seq;
416
+ const userOf = (u) => ({
417
+ id: u.id,
418
+ is_bot: u.is_bot ?? false,
419
+ first_name: u.first_name,
420
+ ...(u.last_name !== undefined && { last_name: u.last_name }),
421
+ ...(u.username !== undefined && { username: u.username }),
422
+ });
423
+ /** A `bot_command` entity when the text starts with `/command`. */
424
+ const commandEntities = (text) => {
425
+ const m = /^\/[A-Za-z0-9_]+(@[A-Za-z0-9_]+)?/.exec(text);
426
+ return m ? [{ type: "bot_command", offset: 0, length: m[0].length }] : [];
427
+ };
428
+ /** An update with a private (direct) message from `from`. */
429
+ export function telegramPrivateMessage(from, text, o = {}) {
430
+ const entities = commandEntities(text);
431
+ return {
432
+ message: {
433
+ message_id: o.messageId ?? nextMessageId(),
434
+ date: o.date ?? nowSec(),
435
+ chat: {
436
+ id: from.id,
437
+ type: "private",
438
+ first_name: from.first_name,
439
+ ...(from.last_name !== undefined && { last_name: from.last_name }),
440
+ ...(from.username !== undefined && { username: from.username }),
441
+ },
442
+ from: userOf(from),
443
+ text,
444
+ ...(entities.length > 0 && { entities }),
445
+ },
446
+ };
447
+ }
448
+ /**
449
+ * An update with a group message. `mention` (with or without `@`) adds a `mention` entity at its
450
+ * UTF-16 offset, prefixing `@<mention> ` when the text lacks it; `replyTo` sets `reply_to_message`
451
+ * (from the bot when `fromBot` is given); `messageThreadId` sets the thread, with
452
+ * `is_topic_message` defaulting to the chat's `is_forum`; `caption` turns the message into a photo
453
+ * whose caption carries the text and entities.
454
+ */
455
+ export function telegramGroupMessage(chat, from, text, o = {}) {
456
+ let body = text;
457
+ const entities = commandEntities(text);
458
+ if (o.mention !== undefined) {
459
+ const handle = o.mention.startsWith("@") ? o.mention : `@${o.mention}`;
460
+ if (!body.includes(handle))
461
+ body = `${handle} ${body}`;
462
+ entities.splice(0, entities.length, ...commandEntities(body));
463
+ entities.push({ type: "mention", offset: body.indexOf(handle), length: handle.length });
464
+ }
465
+ const date = nowSec();
466
+ const isTopic = o.isTopicMessage ?? (chat.is_forum === true ? true : undefined);
467
+ const r = o.replyTo;
468
+ const replyFrom = r?.fromBot
469
+ ? {
470
+ id: r.fromBot.id,
471
+ is_bot: true,
472
+ first_name: r.fromBot.firstName ?? r.fromBot.username,
473
+ username: r.fromBot.username,
474
+ }
475
+ : userOf(from);
476
+ return {
477
+ message: {
478
+ message_id: o.messageId ?? nextMessageId(),
479
+ date,
480
+ chat,
481
+ from: userOf(from),
482
+ ...(o.messageThreadId !== undefined && { message_thread_id: o.messageThreadId }),
483
+ ...(o.messageThreadId !== undefined &&
484
+ isTopic !== undefined && { is_topic_message: isTopic }),
485
+ ...(r && {
486
+ reply_to_message: {
487
+ message_id: r.messageId,
488
+ date: date - 60,
489
+ chat,
490
+ from: replyFrom,
491
+ text: r.text ?? "",
492
+ ...(o.messageThreadId !== undefined && { message_thread_id: o.messageThreadId }),
493
+ },
494
+ }),
495
+ ...(o.caption
496
+ ? {
497
+ photo: [
498
+ {
499
+ file_id: "fake-photo-small",
500
+ file_unique_id: "fps",
501
+ width: 90,
502
+ height: 90,
503
+ file_size: 1200,
504
+ },
505
+ {
506
+ file_id: "fake-photo-large",
507
+ file_unique_id: "fpl",
508
+ width: 800,
509
+ height: 800,
510
+ file_size: 64000,
511
+ },
512
+ ],
513
+ caption: body,
514
+ ...(entities.length > 0 && { caption_entities: entities }),
515
+ }
516
+ : { text: body, ...(entities.length > 0 && { entities }) }),
517
+ },
518
+ };
519
+ }
520
+ /** An update with a callback query: `from` pressed an inline button with `data` on a bot message. */
521
+ export function telegramCallback(from, message, data, o = {}) {
522
+ return {
523
+ callback_query: {
524
+ id: o.id ?? `cbq-${++seq}`,
525
+ from: userOf(from),
526
+ chat_instance: `ci${Math.abs(message.chatId)}`,
527
+ data,
528
+ message: {
529
+ message_id: message.messageId,
530
+ date: nowSec(),
531
+ chat: {
532
+ id: message.chatId,
533
+ type: message.chatType ?? (message.chatId > 0 ? "private" : "supergroup"),
534
+ },
535
+ ...(message.messageThreadId !== undefined && {
536
+ message_thread_id: message.messageThreadId,
537
+ }),
538
+ },
539
+ },
540
+ };
541
+ }
542
+ /** Finds an inline keyboard button in a `reply_markup` (object or JSON string). */
543
+ export function findTelegramButton(replyMarkup, pred) {
544
+ let markup = replyMarkup;
545
+ if (typeof markup === "string") {
546
+ try {
547
+ markup = JSON.parse(markup);
548
+ }
549
+ catch {
550
+ return undefined;
551
+ }
552
+ }
553
+ const rows = markup?.inline_keyboard;
554
+ if (!Array.isArray(rows))
555
+ return undefined;
556
+ for (const row of rows) {
557
+ if (!Array.isArray(row))
558
+ continue;
559
+ for (const b of row) {
560
+ if (pred(b))
561
+ return b;
562
+ }
563
+ }
564
+ return undefined;
565
+ }
566
+ /** The headers Telegram sends to a webhook set with `secret_token`. */
567
+ export function telegramWebhookHeaders(secret) {
568
+ return { "content-type": "application/json", "x-telegram-bot-api-secret-token": secret };
569
+ }
package/dist/index.d.ts CHANGED
@@ -18,6 +18,7 @@ export { type FakeNpmPackage, type FakeNpmRegistry, npmProvenanceAttestations, s
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
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";
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";
21
22
  export { FAKE_EXTENSIONS, type FakeExtensionName, fakeExtensionDir, fakeExtensionEntry, type PackedFixture, packFixture, } from "./fixtures.js";
22
23
  export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, 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";
23
24
  export { isPngBase64, pdfBase64, pdfSampleWord, redPngBase64, solidPngBase64, } from "./media-samples.js";
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ export { npmProvenanceAttestations, startFakeNpmRegistry, } from "./fake-npm-reg
18
18
  export { startFakeOAuthServer, } from "./fake-oauth-server.js";
19
19
  export { defaultFakeOpenApiSpec, startFakeOpenApiServer, } from "./fake-openapi-server.js";
20
20
  export { findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
21
+ export { findTelegramButton, startFakeTelegram, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
21
22
  export { FAKE_EXTENSIONS, fakeExtensionDir, fakeExtensionEntry, packFixture, } from "./fixtures.js";
22
23
  export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, eventsOf, joinOrg, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
23
24
  export { isPngBase64, pdfBase64, pdfSampleWord, redPngBase64, solidPngBase64, } from "./media-samples.js";
@@ -96,15 +96,16 @@ export declare function joinOrg(k: Pick<TestKernel, "http">, owner: KernelReques
96
96
  req: KernelRequest;
97
97
  }>;
98
98
  /**
99
- * Creates an org-visible agent; returns its id. Without `tools` the agent has none (model-fake then
100
- * answers ordinary messages instead of calling the first tool).
99
+ * Creates an org-visible agent; returns its id. An agent has every tool the org offers unless
100
+ * `disabledTools` turns it off (tools default-on spec); with several tools model-fake answers
101
+ * ordinary messages instead of calling one.
101
102
  */
102
103
  export declare function createAgent(req: KernelRequest, orgId: string, opts?: {
103
104
  model?: {
104
105
  provider: string;
105
106
  model: string;
106
107
  };
107
- tools?: unknown[];
108
+ disabledTools?: unknown[];
108
109
  }): Promise<string>;
109
110
  /** Creates a conversation with the agent; returns its id. */
110
111
  export declare function createConversation(req: KernelRequest, orgId: string, agentId: string): Promise<string>;
@@ -178,8 +178,9 @@ export async function joinOrg(k, owner, orgId, name, role = "member") {
178
178
  return { accountId: accepted.json().account.id, req };
179
179
  }
180
180
  /**
181
- * Creates an org-visible agent; returns its id. Without `tools` the agent has none (model-fake then
182
- * answers ordinary messages instead of calling the first tool).
181
+ * Creates an org-visible agent; returns its id. An agent has every tool the org offers unless
182
+ * `disabledTools` turns it off (tools default-on spec); with several tools model-fake answers
183
+ * ordinary messages instead of calling one.
183
184
  */
184
185
  export async function createAgent(req, orgId, opts = {}) {
185
186
  const res = await req({
@@ -190,7 +191,7 @@ export async function createAgent(req, orgId, opts = {}) {
190
191
  name: "Helper",
191
192
  instructions: "Be helpful.",
192
193
  model: opts.model ?? { provider: "model-fake", model: "fake-1" },
193
- tools: opts.tools ?? [],
194
+ disabledTools: opts.disabledTools ?? [],
194
195
  },
195
196
  visibility: "org",
196
197
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.7",
3
+ "version": "0.1.0-rc.9",
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,16 +47,16 @@
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.6"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.8"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.4"
55
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.5"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "vitest": "^5.0.5",
59
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.4",
59
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.5",
60
60
  "@capybara-hq/plugin-tools": "^0.1.0-rc.6"
61
61
  },
62
62
  "peerDependenciesMeta": {