@capybara-hq/testing 0.1.0-rc.0 → 0.1.0-rc.10
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/README.md +7 -1
- package/dist/dual-replica.d.ts +35 -10
- package/dist/dual-replica.js +37 -12
- package/dist/fake-channel.d.ts +15 -2
- package/dist/fake-channel.js +11 -2
- package/dist/fake-e2b.d.ts +36 -1
- package/dist/fake-e2b.js +95 -1
- package/dist/fake-git-server.js +3 -1
- package/dist/fake-oauth-server.d.ts +16 -2
- package/dist/fake-oauth-server.js +21 -1
- package/dist/fake-telegram.d.ts +165 -0
- package/dist/fake-telegram.js +569 -0
- package/dist/fixtures.d.ts +8 -4
- package/dist/fixtures.js +10 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/kernel-helpers.d.ts +38 -16
- package/dist/kernel-helpers.js +42 -13
- package/dist/model-conformance.d.ts +5 -0
- package/dist/model-conformance.js +33 -1
- package/dist/replica-runner.js +17 -9
- package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
- package/fixtures/extensions/fake-config-form/package.json +12 -0
- package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
- package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +33 -1
- package/fixtures/extensions/fake-im/guides/app.long-connection.yaml.tmpl +5 -0
- package/fixtures/extensions/fake-im/guides/app.webhook.json.tmpl +8 -0
- package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
- package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
- package/fixtures/extensions/fake-tools-ui/src/index.ts +1 -1
- package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-web/package.json +12 -0
- package/fixtures/extensions/fake-web/src/index.ts +22 -0
- package/fixtures/extensions/fake-web/src/web.ts +183 -0
- package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-web-2/package.json +12 -0
- package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
- package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
- package/package.json +6 -5
|
@@ -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/fixtures.d.ts
CHANGED
|
@@ -17,17 +17,21 @@
|
|
|
17
17
|
* | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
|
|
18
18
|
* | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
|
|
19
19
|
* | `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-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`) |
|
|
21
|
+
* | `fake-config-form` | display name 表单样例 / Form sample; no extension point: an openai-compatible-shaped deployment config (endpoints with a preset menu, an API key per endpoint in the secret record `apiKeys`, model rows, advanced fields, localized custom issues) carrying the config form hints of the extension config forms spec §6, for the web form e2e |
|
|
20
22
|
*/
|
|
21
|
-
export declare const FAKE_EXTENSIONS: readonly ["fake-connector", "fake-openapi", "fake-object-store", "fake-tools-ui", "fake-storage-user", "fake-embed", "fake-bootstrap-a", "fake-bootstrap-b", "fake-dep-provider", "fake-dep-requirer", "fake-im"];
|
|
23
|
+
export declare const FAKE_EXTENSIONS: readonly ["fake-connector", "fake-openapi", "fake-object-store", "fake-tools-ui", "fake-storage-user", "fake-embed", "fake-bootstrap-a", "fake-bootstrap-b", "fake-dep-provider", "fake-dep-requirer", "fake-im", "fake-web", "fake-web-2", "fake-config-form"];
|
|
22
24
|
/** The name of a fake extension (also its plugin and extension name). */
|
|
23
25
|
export type FakeExtensionName = (typeof FAKE_EXTENSIONS)[number];
|
|
24
26
|
/** The plugin directory of a fake (pack layout), for `packFixture` or a packer of your own. */
|
|
25
27
|
export declare function fakeExtensionDir(name: FakeExtensionName): string;
|
|
26
28
|
/**
|
|
27
29
|
* The extension entry `src/index.ts` of a fake, for kernel configs that load extensions by path
|
|
28
|
-
* (`extensions: [fakeExtensionEntry("fake-connector")]`).
|
|
29
|
-
*
|
|
30
|
-
*
|
|
30
|
+
* (`extensions: [fakeExtensionEntry("fake-connector")]`). `createDualReplicaHarness` loads it in
|
|
31
|
+
* its replicas wherever this package is installed (they run under tsx for TypeScript entries). An
|
|
32
|
+
* in-process kernel under vitest loads it when vitest transforms the kernel (in this repository, or
|
|
33
|
+
* with the core packages inlined: `server.deps.inline`); elsewhere, pack the fake with
|
|
34
|
+
* {@link packFixture} (Node does not strip types under node_modules).
|
|
31
35
|
*/
|
|
32
36
|
export declare function fakeExtensionEntry(name: FakeExtensionName): string;
|
|
33
37
|
/** The result of {@link packFixture}. */
|
package/dist/fixtures.js
CHANGED
|
@@ -20,6 +20,8 @@ import { fileURLToPath } from "node:url";
|
|
|
20
20
|
* | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
|
|
21
21
|
* | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
|
|
22
22
|
* | `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-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`) |
|
|
24
|
+
* | `fake-config-form` | display name 表单样例 / Form sample; no extension point: an openai-compatible-shaped deployment config (endpoints with a preset menu, an API key per endpoint in the secret record `apiKeys`, model rows, advanced fields, localized custom issues) carrying the config form hints of the extension config forms spec §6, for the web form e2e |
|
|
23
25
|
*/
|
|
24
26
|
export const FAKE_EXTENSIONS = [
|
|
25
27
|
"fake-connector",
|
|
@@ -33,6 +35,9 @@ export const FAKE_EXTENSIONS = [
|
|
|
33
35
|
"fake-dep-provider",
|
|
34
36
|
"fake-dep-requirer",
|
|
35
37
|
"fake-im",
|
|
38
|
+
"fake-web",
|
|
39
|
+
"fake-web-2",
|
|
40
|
+
"fake-config-form",
|
|
36
41
|
];
|
|
37
42
|
/** `fixtures/extensions/` of this package (same path from `src/` and from `dist/`). */
|
|
38
43
|
const FIXTURES_DIR = fileURLToPath(new URL("../fixtures/extensions/", import.meta.url));
|
|
@@ -42,9 +47,11 @@ export function fakeExtensionDir(name) {
|
|
|
42
47
|
}
|
|
43
48
|
/**
|
|
44
49
|
* The extension entry `src/index.ts` of a fake, for kernel configs that load extensions by path
|
|
45
|
-
* (`extensions: [fakeExtensionEntry("fake-connector")]`).
|
|
46
|
-
*
|
|
47
|
-
*
|
|
50
|
+
* (`extensions: [fakeExtensionEntry("fake-connector")]`). `createDualReplicaHarness` loads it in
|
|
51
|
+
* its replicas wherever this package is installed (they run under tsx for TypeScript entries). An
|
|
52
|
+
* in-process kernel under vitest loads it when vitest transforms the kernel (in this repository, or
|
|
53
|
+
* with the core packages inlined: `server.deps.inline`); elsewhere, pack the fake with
|
|
54
|
+
* {@link packFixture} (Node does not strip types under node_modules).
|
|
48
55
|
*/
|
|
49
56
|
export function fakeExtensionEntry(name) {
|
|
50
57
|
return join(FIXTURES_DIR, name, "src/index.ts");
|
package/dist/index.d.ts
CHANGED
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
* package and the SDK: the database helpers and types, and model-visible texts, queue names and
|
|
4
4
|
* keys the kernel owns (assert on them instead of copying their values).
|
|
5
5
|
*/
|
|
6
|
-
export { type ConversationEvent, createDb, gatewayReplicasKey, type
|
|
6
|
+
export { type ConversationEvent, createDb, gatewayReplicasKey, type KernelConfig, type KernelSchemaDb, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RESTARTED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
|
|
7
7
|
export { createFreshDatabase, startTestPostgres, startTestRedis, startTestS3, 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 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 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";
|
|
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, startFakeGitServer, } from "./fake-git-server.js";
|
|
13
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";
|
|
@@ -18,8 +18,9 @@ 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
|
-
export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, eventsOf, joinOrg, type KernelRequest, type KernelRequestOptions, type KernelResponse, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
|
|
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";
|
|
24
25
|
export { type ConformanceTarget, checkDeclaredParameters, describeModelProviderConformance, MEDIA_SAMPLES, thinkingReplayParams, } from "./model-conformance.js";
|
|
25
26
|
export { openSse, type SseClient, type SseMessage } from "./sse.js";
|