@capybara-hq/testing 0.1.0-rc.4 → 0.1.0-rc.41
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/dist/containers.d.ts +7 -2
- package/dist/containers.js +7 -3
- package/dist/device-service-conformance.d.ts +38 -0
- package/dist/device-service-conformance.js +142 -0
- package/dist/dual-replica.d.ts +23 -1
- package/dist/dual-replica.js +53 -0
- package/dist/fake-channel.d.ts +44 -5
- package/dist/fake-channel.js +63 -2
- package/dist/fake-dial-in-machine.d.ts +173 -0
- package/dist/fake-dial-in-machine.js +429 -0
- package/dist/fake-e2b.d.ts +34 -0
- package/dist/fake-e2b.js +95 -1
- package/dist/fake-git-server.d.ts +32 -4
- package/dist/fake-git-server.js +87 -19
- package/dist/fake-lark.d.ts +12 -1
- package/dist/fake-lark.js +63 -10
- package/dist/fake-oauth-server.d.ts +62 -2
- package/dist/fake-oauth-server.js +86 -5
- package/dist/fake-slack.d.ts +17 -1
- package/dist/fake-slack.js +98 -0
- package/dist/fake-telegram.d.ts +173 -0
- package/dist/fake-telegram.js +632 -0
- package/dist/fixtures.d.ts +24 -8
- package/dist/fixtures.js +31 -8
- package/dist/index.d.ts +15 -9
- package/dist/index.js +10 -4
- package/dist/kernel-helpers.d.ts +16 -4
- package/dist/kernel-helpers.js +39 -4
- package/dist/media-samples.d.ts +2 -0
- package/dist/media-samples.js +2 -0
- package/dist/model-conformance.d.ts +15 -10
- package/dist/model-conformance.js +87 -14
- package/dist/push-conformance.d.ts +31 -0
- package/dist/push-conformance.js +160 -0
- package/dist/replica-runner.js +2 -0
- package/dist/sandbox-native-conformance.d.ts +31 -0
- package/dist/sandbox-native-conformance.js +153 -0
- package/dist/sandbox-permission-conformance.d.ts +310 -0
- package/dist/sandbox-permission-conformance.js +1491 -0
- package/fixtures/extensions/fake-bootstrap-a/src/index.ts +8 -4
- package/fixtures/extensions/fake-bootstrap-b/src/index.ts +8 -4
- package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
- package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
- package/fixtures/extensions/fake-client/package.json +12 -0
- package/fixtures/extensions/fake-client/src/client.tsx +51 -0
- package/fixtures/extensions/fake-client/src/index.ts +43 -0
- package/fixtures/extensions/fake-client/themes/fake.json +11 -0
- package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-client-broken/package.json +12 -0
- package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
- package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
- package/fixtures/extensions/fake-config-form/src/index.ts +52 -46
- package/fixtures/extensions/fake-connector/src/index.ts +64 -34
- package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-context/package.json +12 -0
- package/fixtures/extensions/fake-context/src/index.ts +78 -0
- package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
- package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
- package/fixtures/extensions/fake-embed/src/index.ts +26 -26
- package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
- package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
- package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
- package/fixtures/extensions/fake-im/src/channel.ts +22 -1
- package/fixtures/extensions/fake-im/src/checks.ts +94 -0
- package/fixtures/extensions/fake-im/src/directory.ts +44 -20
- package/fixtures/extensions/fake-im/src/index.ts +59 -11
- package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
- package/fixtures/extensions/fake-lifecycle/package.json +12 -0
- package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
- package/fixtures/extensions/fake-object-store/src/index.ts +12 -8
- package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
- package/fixtures/extensions/fake-push/.capybara-plugin/plugin.json +13 -0
- package/fixtures/extensions/fake-push/guides/fake-push-key.md +6 -0
- package/fixtures/extensions/fake-push/guides/fake-push-key.zh.md +6 -0
- package/fixtures/extensions/fake-push/migrations/0001_sends.sql +9 -0
- package/fixtures/extensions/fake-push/package.json +12 -0
- package/fixtures/extensions/fake-push/src/check.ts +40 -0
- package/fixtures/extensions/fake-push/src/index.ts +56 -0
- package/fixtures/extensions/fake-push/src/push.ts +103 -0
- package/fixtures/extensions/fake-tools-ui/src/index.ts +61 -2
- package/fixtures/extensions/fake-web/src/index.ts +5 -4
- package/fixtures/extensions/fake-web/src/web.ts +11 -7
- package/fixtures/extensions/fake-web-2/src/index.ts +2 -2
- package/fixtures/extensions/fake-web-2/src/web.ts +11 -7
- package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
- package/fixtures/plugins/fake-theme/brand/app-512.png +0 -0
- package/fixtures/plugins/fake-theme/brand/app-mask-512.png +0 -0
- package/fixtures/plugins/fake-theme/brand/avatars/bot.svg +1 -0
- package/fixtures/plugins/fake-theme/brand/avatars/cat.png +0 -0
- package/fixtures/plugins/fake-theme/brand/illustration.svg +1 -0
- package/fixtures/plugins/fake-theme/brand/unnamed.svg +1 -0
- package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
- package/fixtures/plugins/fake-theme/logo.svg +1 -0
- package/fixtures/plugins/fake-theme/package.json +8 -0
- package/fixtures/plugins/fake-theme/themes/brand-kit.json +24 -0
- package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
- package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
- package/package.json +6 -5
|
@@ -0,0 +1,632 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
const MAX_TEXT = 4096;
|
|
3
|
+
const MAX_CAPTION = 1024;
|
|
4
|
+
const ENTITIES = { lt: "<", gt: ">", amp: "&", quot: '"' };
|
|
5
|
+
/**
|
|
6
|
+
* The text length Telegram limits: UTF-16 code units after entity parsing. With `parse_mode`
|
|
7
|
+
* HTML, tags (including `<a href>`) are removed and character references decoded.
|
|
8
|
+
*/
|
|
9
|
+
function telegramTextLength(text, parseMode) {
|
|
10
|
+
if (parseMode?.toUpperCase() !== "HTML")
|
|
11
|
+
return text.length;
|
|
12
|
+
return text
|
|
13
|
+
.replace(/<[^>]*>/g, "")
|
|
14
|
+
.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|amp|quot);/g, (_, ref) => {
|
|
15
|
+
if (ref.startsWith("#x"))
|
|
16
|
+
return String.fromCodePoint(Number.parseInt(ref.slice(2), 16));
|
|
17
|
+
if (ref.startsWith("#"))
|
|
18
|
+
return String.fromCodePoint(Number.parseInt(ref.slice(1), 10));
|
|
19
|
+
return ENTITIES[ref] ?? "";
|
|
20
|
+
}).length;
|
|
21
|
+
}
|
|
22
|
+
const JSON_PARAMS = new Set(["reply_markup", "reply_parameters", "allowed_updates", "entities"]);
|
|
23
|
+
const DEFAULT_BOT = {
|
|
24
|
+
token: "123456:fake-telegram-token",
|
|
25
|
+
id: 123456,
|
|
26
|
+
username: "capybara_bot",
|
|
27
|
+
firstName: "Capybara",
|
|
28
|
+
};
|
|
29
|
+
class TelegramError extends Error {
|
|
30
|
+
code;
|
|
31
|
+
constructor(code, description) {
|
|
32
|
+
super(description);
|
|
33
|
+
this.code = code;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const readBody = (req) => new Promise((resolve, reject) => {
|
|
37
|
+
const chunks = [];
|
|
38
|
+
req.on("data", (c) => chunks.push(c));
|
|
39
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
40
|
+
req.on("error", reject);
|
|
41
|
+
});
|
|
42
|
+
async function parseParams(url, rawBytes, contentType, uploads) {
|
|
43
|
+
const raw = contentType?.includes("multipart/form-data") ? "" : rawBytes.toString();
|
|
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 (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
|
+
}
|
|
87
|
+
if (raw === "")
|
|
88
|
+
return out;
|
|
89
|
+
if (contentType?.includes("application/json")) {
|
|
90
|
+
let body;
|
|
91
|
+
try {
|
|
92
|
+
body = JSON.parse(raw);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
throw new TelegramError(400, "Bad Request: invalid JSON");
|
|
96
|
+
}
|
|
97
|
+
if (body !== null && typeof body === "object")
|
|
98
|
+
Object.assign(out, body);
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
fromForm(new URLSearchParams(raw));
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
const num = (v) => {
|
|
106
|
+
if (typeof v === "number")
|
|
107
|
+
return v;
|
|
108
|
+
if (typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)))
|
|
109
|
+
return Number(v);
|
|
110
|
+
return undefined;
|
|
111
|
+
};
|
|
112
|
+
const str = (v) => (typeof v === "string" ? v : undefined);
|
|
113
|
+
const nowSec = () => Math.floor(Date.now() / 1000);
|
|
114
|
+
/** The update's type: its one field besides `update_id`. */
|
|
115
|
+
const updateType = (u) => Object.keys(u).find((k) => k !== "update_id");
|
|
116
|
+
/** Starts the fake Telegram Bot API (listens on a random 127.0.0.1 port). */
|
|
117
|
+
export async function startFakeTelegram(opts = {}) {
|
|
118
|
+
const bots = opts.bots && opts.bots.length > 0 ? opts.bots : [DEFAULT_BOT];
|
|
119
|
+
const states = new Map();
|
|
120
|
+
for (const [i, bot] of bots.entries()) {
|
|
121
|
+
if (states.has(bot.token))
|
|
122
|
+
throw new Error(`fake telegram: duplicate bot token ${bot.token}`);
|
|
123
|
+
states.set(bot.token, {
|
|
124
|
+
bot,
|
|
125
|
+
queue: [],
|
|
126
|
+
nextUpdateId: 100_000_001 + i * 10_000_000,
|
|
127
|
+
confirmed: 0,
|
|
128
|
+
webhook: "",
|
|
129
|
+
allowed: undefined,
|
|
130
|
+
pollers: [],
|
|
131
|
+
peakPollers: 0,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
const first = bots[0];
|
|
135
|
+
const messages = [];
|
|
136
|
+
const edits = [];
|
|
137
|
+
const calls = [];
|
|
138
|
+
const callbackAnswers = [];
|
|
139
|
+
const failures = [];
|
|
140
|
+
const delays = new Map();
|
|
141
|
+
/** Per bot and chat: the last message id sent. */
|
|
142
|
+
const lastMessageId = new Map();
|
|
143
|
+
/** Per bot, chat and message: the current text and markup (for "message is not modified"). */
|
|
144
|
+
const current = new Map();
|
|
145
|
+
/** Pending `delay` waits, cleared (and released) on close. */
|
|
146
|
+
const delayTimers = new Map();
|
|
147
|
+
let closed = false;
|
|
148
|
+
const stateOf = (token) => {
|
|
149
|
+
const s = states.get(token ?? first.token);
|
|
150
|
+
if (!s)
|
|
151
|
+
throw new Error(`fake telegram: unknown bot token ${token}`);
|
|
152
|
+
return s;
|
|
153
|
+
};
|
|
154
|
+
const reply = (res, status, body) => {
|
|
155
|
+
if (res.headersSent || res.destroyed)
|
|
156
|
+
return;
|
|
157
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
158
|
+
res.end(JSON.stringify(body));
|
|
159
|
+
};
|
|
160
|
+
const ok = (res, result) => reply(res, 200, { ok: true, result });
|
|
161
|
+
const fail = (res, code, description) => reply(res, code, { ok: false, error_code: code, description });
|
|
162
|
+
const botUser = (bot) => ({
|
|
163
|
+
id: bot.id,
|
|
164
|
+
is_bot: true,
|
|
165
|
+
first_name: bot.firstName ?? bot.username,
|
|
166
|
+
username: bot.username,
|
|
167
|
+
});
|
|
168
|
+
/** Drops updates of types not allowed, then returns up to `limit` of the queue. */
|
|
169
|
+
const collect = (s, limit) => {
|
|
170
|
+
if (s.allowed) {
|
|
171
|
+
const allowed = s.allowed;
|
|
172
|
+
s.queue = s.queue.filter((u) => allowed.has(updateType(u) ?? ""));
|
|
173
|
+
}
|
|
174
|
+
return s.queue.slice(0, limit);
|
|
175
|
+
};
|
|
176
|
+
const removePoller = (s, p) => {
|
|
177
|
+
clearTimeout(p.timer);
|
|
178
|
+
const i = s.pollers.indexOf(p);
|
|
179
|
+
if (i >= 0)
|
|
180
|
+
s.pollers.splice(i, 1);
|
|
181
|
+
};
|
|
182
|
+
const getUpdates = (s, params, req) => {
|
|
183
|
+
if (s.webhook !== "") {
|
|
184
|
+
throw new TelegramError(409, "Conflict: can't use getUpdates method while webhook is active; use deleteWebhook to delete the webhook first");
|
|
185
|
+
}
|
|
186
|
+
const offset = num(params.offset);
|
|
187
|
+
if (offset !== undefined && offset > 0) {
|
|
188
|
+
s.queue = s.queue.filter((u) => u.update_id >= offset);
|
|
189
|
+
s.confirmed = Math.max(s.confirmed, offset);
|
|
190
|
+
}
|
|
191
|
+
else if (offset !== undefined && offset < 0) {
|
|
192
|
+
s.queue = s.queue.slice(offset);
|
|
193
|
+
}
|
|
194
|
+
const allowed = params.allowed_updates;
|
|
195
|
+
if (Array.isArray(allowed)) {
|
|
196
|
+
s.allowed = allowed.length > 0 ? new Set(allowed.map(String)) : undefined;
|
|
197
|
+
}
|
|
198
|
+
// An overlapping request counts as concurrent even though Telegram ends the earlier one.
|
|
199
|
+
s.peakPollers = Math.max(s.peakPollers, s.pollers.length + 1);
|
|
200
|
+
for (const earlier of [...s.pollers]) {
|
|
201
|
+
removePoller(s, earlier);
|
|
202
|
+
fail(earlier.res, 409, "Conflict: terminated by other getUpdates request");
|
|
203
|
+
}
|
|
204
|
+
const limit = Math.min(Math.max(num(params.limit) ?? 100, 1), 100);
|
|
205
|
+
const timeout = Math.max(num(params.timeout) ?? 0, 0);
|
|
206
|
+
return { limit, timeout, ready: collect(s, limit), port: req.socket.remotePort };
|
|
207
|
+
};
|
|
208
|
+
/** `upload` set: a sendPhoto / sendDocument, whose text is the caption (up to 1024). */
|
|
209
|
+
const sendMessage = (s, params, upload) => {
|
|
210
|
+
const chatId = num(params.chat_id);
|
|
211
|
+
if (chatId === undefined)
|
|
212
|
+
throw new TelegramError(400, "Bad Request: chat not found");
|
|
213
|
+
const text = (upload ? str(params.caption) : str(params.text)) ?? "";
|
|
214
|
+
if (!upload && text === "")
|
|
215
|
+
throw new TelegramError(400, "Bad Request: message text is empty");
|
|
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");
|
|
221
|
+
}
|
|
222
|
+
const chatKey = `${s.bot.token}|${chatId}`;
|
|
223
|
+
const messageId = (lastMessageId.get(chatKey) ?? 0) + 1;
|
|
224
|
+
lastMessageId.set(chatKey, messageId);
|
|
225
|
+
const threadId = num(params.message_thread_id);
|
|
226
|
+
const replyParams = params.reply_parameters;
|
|
227
|
+
const replyTo = num(replyParams?.message_id) ?? num(params.reply_to_message_id);
|
|
228
|
+
const parseMode = str(params.parse_mode);
|
|
229
|
+
const m = {
|
|
230
|
+
chatId,
|
|
231
|
+
messageId,
|
|
232
|
+
text,
|
|
233
|
+
...(parseMode !== undefined && { parseMode }),
|
|
234
|
+
...(params.reply_markup !== undefined && { replyMarkup: params.reply_markup }),
|
|
235
|
+
...(threadId !== undefined && { messageThreadId: threadId }),
|
|
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
|
+
}),
|
|
245
|
+
at: Date.now(),
|
|
246
|
+
};
|
|
247
|
+
messages.push(m);
|
|
248
|
+
current.set(`${chatKey}|${messageId}`, m);
|
|
249
|
+
return messageResult(s, m);
|
|
250
|
+
};
|
|
251
|
+
const editMessageText = (s, params) => {
|
|
252
|
+
const chatId = num(params.chat_id);
|
|
253
|
+
const messageId = num(params.message_id);
|
|
254
|
+
const key = `${s.bot.token}|${chatId}|${messageId}`;
|
|
255
|
+
const before = current.get(key);
|
|
256
|
+
if (chatId === undefined || messageId === undefined || !before) {
|
|
257
|
+
throw new TelegramError(400, "Bad Request: message to edit not found");
|
|
258
|
+
}
|
|
259
|
+
const text = str(params.text) ?? "";
|
|
260
|
+
if (text === "")
|
|
261
|
+
throw new TelegramError(400, "Bad Request: message text is empty");
|
|
262
|
+
if (telegramTextLength(text, str(params.parse_mode)) > MAX_TEXT) {
|
|
263
|
+
throw new TelegramError(400, "Bad Request: message is too long");
|
|
264
|
+
}
|
|
265
|
+
const markup = params.reply_markup;
|
|
266
|
+
if (text === before.text && JSON.stringify(markup) === JSON.stringify(before.replyMarkup)) {
|
|
267
|
+
throw new TelegramError(400, "Bad Request: message is not modified");
|
|
268
|
+
}
|
|
269
|
+
const parseMode = str(params.parse_mode);
|
|
270
|
+
const m = {
|
|
271
|
+
chatId,
|
|
272
|
+
messageId,
|
|
273
|
+
text,
|
|
274
|
+
...(parseMode !== undefined && { parseMode }),
|
|
275
|
+
...(markup !== undefined && { replyMarkup: markup }),
|
|
276
|
+
...(before.messageThreadId !== undefined && { messageThreadId: before.messageThreadId }),
|
|
277
|
+
...(before.replyToMessageId !== undefined && { replyToMessageId: before.replyToMessageId }),
|
|
278
|
+
at: Date.now(),
|
|
279
|
+
};
|
|
280
|
+
edits.push(m);
|
|
281
|
+
current.set(key, m);
|
|
282
|
+
return { ...messageResult(s, m), edit_date: nowSec() };
|
|
283
|
+
};
|
|
284
|
+
const messageResult = (s, m) => ({
|
|
285
|
+
message_id: m.messageId,
|
|
286
|
+
from: botUser(s.bot),
|
|
287
|
+
chat: { id: m.chatId, type: m.chatId > 0 ? "private" : "supergroup" },
|
|
288
|
+
date: Math.floor(m.at / 1000),
|
|
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 }),
|
|
304
|
+
...(m.messageThreadId !== undefined && { message_thread_id: m.messageThreadId }),
|
|
305
|
+
...(m.replyMarkup !== undefined && { reply_markup: m.replyMarkup }),
|
|
306
|
+
});
|
|
307
|
+
const handle = async (req, res, token, name) => {
|
|
308
|
+
const url = new URL(req.url ?? "/", "http://x");
|
|
309
|
+
let params;
|
|
310
|
+
const uploads = [];
|
|
311
|
+
try {
|
|
312
|
+
params = await parseParams(url, await readBody(req), req.headers["content-type"], uploads);
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
if (e instanceof TelegramError)
|
|
316
|
+
return fail(res, e.code, e.message);
|
|
317
|
+
throw e;
|
|
318
|
+
}
|
|
319
|
+
const s = states.get(token);
|
|
320
|
+
if (!s)
|
|
321
|
+
return fail(res, 401, "Unauthorized");
|
|
322
|
+
calls.push({ method: name, token, params, at: Date.now() });
|
|
323
|
+
const method = name.toLowerCase();
|
|
324
|
+
const wait = delays.get(method) ?? 0;
|
|
325
|
+
if (wait > 0) {
|
|
326
|
+
await new Promise((resolve) => {
|
|
327
|
+
const timer = setTimeout(() => {
|
|
328
|
+
delayTimers.delete(timer);
|
|
329
|
+
resolve();
|
|
330
|
+
}, wait);
|
|
331
|
+
delayTimers.set(timer, resolve);
|
|
332
|
+
});
|
|
333
|
+
if (closed)
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const f = failures.find((x) => x.method === method && x.left > 0);
|
|
337
|
+
if (f) {
|
|
338
|
+
f.left--;
|
|
339
|
+
const { status, errorCode, description, retryAfter, migrateToChatId } = f.failure;
|
|
340
|
+
const parameters = {
|
|
341
|
+
...(retryAfter !== undefined && { retry_after: retryAfter }),
|
|
342
|
+
...(migrateToChatId !== undefined && { migrate_to_chat_id: migrateToChatId }),
|
|
343
|
+
};
|
|
344
|
+
return reply(res, status, {
|
|
345
|
+
ok: false,
|
|
346
|
+
error_code: errorCode ?? status,
|
|
347
|
+
description,
|
|
348
|
+
...(Object.keys(parameters).length > 0 && { parameters }),
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
try {
|
|
352
|
+
switch (method) {
|
|
353
|
+
case "getme":
|
|
354
|
+
return ok(res, {
|
|
355
|
+
...botUser(s.bot),
|
|
356
|
+
can_join_groups: true,
|
|
357
|
+
can_read_all_group_messages: s.bot.canReadAllGroupMessages ?? false,
|
|
358
|
+
supports_inline_queries: false,
|
|
359
|
+
has_topics_enabled: s.bot.hasTopicsEnabled ?? false,
|
|
360
|
+
});
|
|
361
|
+
case "getwebhookinfo":
|
|
362
|
+
return ok(res, {
|
|
363
|
+
url: s.webhook,
|
|
364
|
+
has_custom_certificate: false,
|
|
365
|
+
pending_update_count: s.queue.length,
|
|
366
|
+
});
|
|
367
|
+
case "getupdates": {
|
|
368
|
+
const { limit, timeout, ready, port } = getUpdates(s, params, req);
|
|
369
|
+
if (ready.length > 0 || timeout === 0 || closed)
|
|
370
|
+
return ok(res, ready);
|
|
371
|
+
const p = {
|
|
372
|
+
res,
|
|
373
|
+
port,
|
|
374
|
+
limit,
|
|
375
|
+
timer: setTimeout(() => {
|
|
376
|
+
removePoller(s, p);
|
|
377
|
+
ok(res, collect(s, limit));
|
|
378
|
+
}, timeout * 1000),
|
|
379
|
+
};
|
|
380
|
+
s.pollers.push(p);
|
|
381
|
+
res.on("close", () => removePoller(s, p));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
case "sendmessage":
|
|
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
|
+
}
|
|
395
|
+
case "editmessagetext":
|
|
396
|
+
return ok(res, editMessageText(s, params));
|
|
397
|
+
case "answercallbackquery":
|
|
398
|
+
callbackAnswers.push(str(params.callback_query_id) ?? "");
|
|
399
|
+
return ok(res, true);
|
|
400
|
+
default:
|
|
401
|
+
return fail(res, 404, "Not Found");
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
catch (e) {
|
|
405
|
+
if (e instanceof TelegramError)
|
|
406
|
+
return fail(res, e.code, e.message);
|
|
407
|
+
throw e;
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
const server = createServer((req, res) => {
|
|
411
|
+
void (async () => {
|
|
412
|
+
const path = new URL(req.url ?? "/", "http://x").pathname;
|
|
413
|
+
const m = /^\/bot([^/]+)\/([A-Za-z]+)$/.exec(path);
|
|
414
|
+
if (!m || (req.method !== "GET" && req.method !== "POST")) {
|
|
415
|
+
return fail(res, 404, "Not Found");
|
|
416
|
+
}
|
|
417
|
+
return handle(req, res, decodeURIComponent(m[1]), m[2]);
|
|
418
|
+
})().catch(() => {
|
|
419
|
+
if (!res.headersSent)
|
|
420
|
+
res.writeHead(500);
|
|
421
|
+
res.end();
|
|
422
|
+
});
|
|
423
|
+
});
|
|
424
|
+
await new Promise((r) => server.listen(0, "127.0.0.1", r));
|
|
425
|
+
const url = `http://127.0.0.1:${server.address().port}`;
|
|
426
|
+
return {
|
|
427
|
+
url,
|
|
428
|
+
apiUrl: url,
|
|
429
|
+
bot: first,
|
|
430
|
+
bots,
|
|
431
|
+
messages,
|
|
432
|
+
edits,
|
|
433
|
+
calls,
|
|
434
|
+
callbackAnswers,
|
|
435
|
+
push(update, token) {
|
|
436
|
+
const s = stateOf(token);
|
|
437
|
+
const id = s.nextUpdateId++;
|
|
438
|
+
s.queue.push({ update_id: id, ...update });
|
|
439
|
+
for (const p of [...s.pollers]) {
|
|
440
|
+
const ready = collect(s, p.limit);
|
|
441
|
+
if (ready.length === 0)
|
|
442
|
+
continue;
|
|
443
|
+
removePoller(s, p);
|
|
444
|
+
ok(p.res, ready);
|
|
445
|
+
}
|
|
446
|
+
return id;
|
|
447
|
+
},
|
|
448
|
+
confirmedOffset: (token) => stateOf(token).confirmed,
|
|
449
|
+
pending: (token) => stateOf(token).queue.length,
|
|
450
|
+
activePollers: (token) => stateOf(token).pollers.length,
|
|
451
|
+
maxConcurrentPollers: (token) => stateOf(token).peakPollers,
|
|
452
|
+
pollerPeerPorts: (token) => stateOf(token).pollers.flatMap((p) => (p.port === undefined ? [] : [p.port])),
|
|
453
|
+
setWebhook(webhookUrl, token) {
|
|
454
|
+
stateOf(token).webhook = webhookUrl ?? "";
|
|
455
|
+
},
|
|
456
|
+
failNext(method, failure, count = 1) {
|
|
457
|
+
failures.push({ method: method.toLowerCase(), failure, left: count });
|
|
458
|
+
},
|
|
459
|
+
delay(method, ms) {
|
|
460
|
+
delays.set(method.toLowerCase(), ms);
|
|
461
|
+
},
|
|
462
|
+
async close() {
|
|
463
|
+
closed = true;
|
|
464
|
+
for (const [timer, release] of delayTimers) {
|
|
465
|
+
clearTimeout(timer);
|
|
466
|
+
release();
|
|
467
|
+
}
|
|
468
|
+
delayTimers.clear();
|
|
469
|
+
for (const s of states.values())
|
|
470
|
+
for (const p of [...s.pollers])
|
|
471
|
+
removePoller(s, p);
|
|
472
|
+
server.closeAllConnections();
|
|
473
|
+
await new Promise((r) => server.close(() => r()));
|
|
474
|
+
},
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
let seq = 0;
|
|
478
|
+
const nextMessageId = () => 1000 + ++seq;
|
|
479
|
+
const userOf = (u) => ({
|
|
480
|
+
id: u.id,
|
|
481
|
+
is_bot: u.is_bot ?? false,
|
|
482
|
+
first_name: u.first_name,
|
|
483
|
+
...(u.last_name !== undefined && { last_name: u.last_name }),
|
|
484
|
+
...(u.username !== undefined && { username: u.username }),
|
|
485
|
+
});
|
|
486
|
+
/** A `bot_command` entity when the text starts with `/command`. */
|
|
487
|
+
const commandEntities = (text) => {
|
|
488
|
+
const m = /^\/[A-Za-z0-9_]+(@[A-Za-z0-9_]+)?/.exec(text);
|
|
489
|
+
return m ? [{ type: "bot_command", offset: 0, length: m[0].length }] : [];
|
|
490
|
+
};
|
|
491
|
+
/** An update with a private (direct) message from `from`. */
|
|
492
|
+
export function telegramPrivateMessage(from, text, o = {}) {
|
|
493
|
+
const entities = commandEntities(text);
|
|
494
|
+
return {
|
|
495
|
+
message: {
|
|
496
|
+
message_id: o.messageId ?? nextMessageId(),
|
|
497
|
+
date: o.date ?? nowSec(),
|
|
498
|
+
chat: {
|
|
499
|
+
id: from.id,
|
|
500
|
+
type: "private",
|
|
501
|
+
first_name: from.first_name,
|
|
502
|
+
...(from.last_name !== undefined && { last_name: from.last_name }),
|
|
503
|
+
...(from.username !== undefined && { username: from.username }),
|
|
504
|
+
},
|
|
505
|
+
from: userOf(from),
|
|
506
|
+
text,
|
|
507
|
+
...(entities.length > 0 && { entities }),
|
|
508
|
+
},
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* An update with a group message. `mention` (with or without `@`) adds a `mention` entity at its
|
|
513
|
+
* UTF-16 offset, prefixing `@<mention> ` when the text lacks it; `replyTo` sets `reply_to_message`
|
|
514
|
+
* (from the bot when `fromBot` is given); `messageThreadId` sets the thread, with
|
|
515
|
+
* `is_topic_message` defaulting to the chat's `is_forum`; `caption` turns the message into a photo
|
|
516
|
+
* whose caption carries the text and entities.
|
|
517
|
+
*/
|
|
518
|
+
export function telegramGroupMessage(chat, from, text, o = {}) {
|
|
519
|
+
let body = text;
|
|
520
|
+
const entities = commandEntities(text);
|
|
521
|
+
if (o.mention !== undefined) {
|
|
522
|
+
const handle = o.mention.startsWith("@") ? o.mention : `@${o.mention}`;
|
|
523
|
+
if (!body.includes(handle))
|
|
524
|
+
body = `${handle} ${body}`;
|
|
525
|
+
entities.splice(0, entities.length, ...commandEntities(body));
|
|
526
|
+
entities.push({ type: "mention", offset: body.indexOf(handle), length: handle.length });
|
|
527
|
+
}
|
|
528
|
+
const date = nowSec();
|
|
529
|
+
const isTopic = o.isTopicMessage ?? (chat.is_forum === true ? true : undefined);
|
|
530
|
+
const r = o.replyTo;
|
|
531
|
+
const replyFrom = r?.fromBot
|
|
532
|
+
? {
|
|
533
|
+
id: r.fromBot.id,
|
|
534
|
+
is_bot: true,
|
|
535
|
+
first_name: r.fromBot.firstName ?? r.fromBot.username,
|
|
536
|
+
username: r.fromBot.username,
|
|
537
|
+
}
|
|
538
|
+
: userOf(from);
|
|
539
|
+
return {
|
|
540
|
+
message: {
|
|
541
|
+
message_id: o.messageId ?? nextMessageId(),
|
|
542
|
+
date,
|
|
543
|
+
chat,
|
|
544
|
+
from: userOf(from),
|
|
545
|
+
...(o.messageThreadId !== undefined && { message_thread_id: o.messageThreadId }),
|
|
546
|
+
...(o.messageThreadId !== undefined &&
|
|
547
|
+
isTopic !== undefined && { is_topic_message: isTopic }),
|
|
548
|
+
...(r && {
|
|
549
|
+
reply_to_message: {
|
|
550
|
+
message_id: r.messageId,
|
|
551
|
+
date: date - 60,
|
|
552
|
+
chat,
|
|
553
|
+
from: replyFrom,
|
|
554
|
+
text: r.text ?? "",
|
|
555
|
+
...(o.messageThreadId !== undefined && { message_thread_id: o.messageThreadId }),
|
|
556
|
+
},
|
|
557
|
+
}),
|
|
558
|
+
...(o.caption
|
|
559
|
+
? {
|
|
560
|
+
photo: [
|
|
561
|
+
{
|
|
562
|
+
file_id: "fake-photo-small",
|
|
563
|
+
file_unique_id: "fps",
|
|
564
|
+
width: 90,
|
|
565
|
+
height: 90,
|
|
566
|
+
file_size: 1200,
|
|
567
|
+
},
|
|
568
|
+
{
|
|
569
|
+
file_id: "fake-photo-large",
|
|
570
|
+
file_unique_id: "fpl",
|
|
571
|
+
width: 800,
|
|
572
|
+
height: 800,
|
|
573
|
+
file_size: 64000,
|
|
574
|
+
},
|
|
575
|
+
],
|
|
576
|
+
caption: body,
|
|
577
|
+
...(entities.length > 0 && { caption_entities: entities }),
|
|
578
|
+
}
|
|
579
|
+
: { text: body, ...(entities.length > 0 && { entities }) }),
|
|
580
|
+
},
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
/** An update with a callback query: `from` pressed an inline button with `data` on a bot message. */
|
|
584
|
+
export function telegramCallback(from, message, data, o = {}) {
|
|
585
|
+
return {
|
|
586
|
+
callback_query: {
|
|
587
|
+
id: o.id ?? `cbq-${++seq}`,
|
|
588
|
+
from: userOf(from),
|
|
589
|
+
chat_instance: `ci${Math.abs(message.chatId)}`,
|
|
590
|
+
data,
|
|
591
|
+
message: {
|
|
592
|
+
message_id: message.messageId,
|
|
593
|
+
date: nowSec(),
|
|
594
|
+
chat: {
|
|
595
|
+
id: message.chatId,
|
|
596
|
+
type: message.chatType ?? (message.chatId > 0 ? "private" : "supergroup"),
|
|
597
|
+
},
|
|
598
|
+
...(message.messageThreadId !== undefined && {
|
|
599
|
+
message_thread_id: message.messageThreadId,
|
|
600
|
+
}),
|
|
601
|
+
},
|
|
602
|
+
},
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
/** Finds an inline keyboard button in a `reply_markup` (object or JSON string). */
|
|
606
|
+
export function findTelegramButton(replyMarkup, pred) {
|
|
607
|
+
let markup = replyMarkup;
|
|
608
|
+
if (typeof markup === "string") {
|
|
609
|
+
try {
|
|
610
|
+
markup = JSON.parse(markup);
|
|
611
|
+
}
|
|
612
|
+
catch {
|
|
613
|
+
return undefined;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
const rows = markup?.inline_keyboard;
|
|
617
|
+
if (!Array.isArray(rows))
|
|
618
|
+
return undefined;
|
|
619
|
+
for (const row of rows) {
|
|
620
|
+
if (!Array.isArray(row))
|
|
621
|
+
continue;
|
|
622
|
+
for (const b of row) {
|
|
623
|
+
if (pred(b))
|
|
624
|
+
return b;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return undefined;
|
|
628
|
+
}
|
|
629
|
+
/** The headers Telegram sends to a webhook set with `secret_token`. */
|
|
630
|
+
export function telegramWebhookHeaders(secret) {
|
|
631
|
+
return { "content-type": "application/json", "x-telegram-bot-api-secret-token": secret };
|
|
632
|
+
}
|