diff --git a/CHANGELOG.md b/CHANGELOG.md index a6ab0e0..9b5c1df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [0.1.9](/github.com/xTCry/max-io/compare/v0.1.8...v0.1.9) (2026-10-28) + +### πŸš€ Features + +* **api:** support bot admin permissions updates ([612add3](/github.com/xTCry/max-io/commit/612add3dd2d746c97009846c5fa144ab6a38594f)) + +### πŸ› Bug Fixes + +* **core:** handle incomplete message updates ([4d4aefd](/github.com/xTCry/max-io/commit/4d4aefd1bb55aea20ecc2002dcf48cd582f0bf2f)) +* **middleware:** await downstream execution before saving sessions ([a58b27e](/github.com/xTCry/max-io/commit/a58b27eb215a5b2959f16f941ebb5b5acd3d7b31)) +* **upload:** enforce multipart upload timeout ([4eab412](/github.com/xTCry/max-io/commit/4eab412790008549232989de208b88fc1779e694)), closes [#2](/github.com/xTCry/max-io/issues/2) + +### πŸ“– Documentation + +* **api:** clarify chat and comment api contracts ([cbe4e3b](/github.com/xTCry/max-io/commit/cbe4e3b325316bef41ac913b3827924fa932c958)) + ## [0.1.8](/github.com/xTCry/max-io/compare/v0.1.7...v0.1.8) (2026-09-04) ### πŸš€ Features diff --git a/README.md b/README.md index 18b6c5b..cd07624 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ | Π’ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΡΡ‚ΡŒ | Π§Ρ‚ΠΎ Π΄Π°Ρ‘Ρ‚ | | ------------------ | ------------------------------------------------------------------------------------------------------- | | Middleware-runtime | `bot.use`, `bot.on`, `bot.command`, `bot.hears`, `bot.action` | -| Typed Context | `ctx.reply`, `ctx.message`, `ctx.args`, `ctx.payload`, `ctx.state`, `ctx.api` | +| Typed Context | `ctx.reply`, `ctx.message`, `ctx.args`, `ctx.payload`, `ctx.startPayload`, `ctx.state`, `ctx.api` | | Long polling | `bot.start()`, marker API, Ρ€Π΅ΠΆΠΈΠΌ для Ρ€Π°Π·Ρ€Π°Π±ΠΎΡ‚ΠΊΠΈ ΠΈ тСстирования | | Webhook | `bot.start({ webhook })`, `webhookCallback`, `createWebhook`, `deleteWebhook` | | Upload | image/video/audio/file, progress, timeout, `AbortSignal`, повторная ΠΎΡ‚ΠΏΡ€Π°Π²ΠΊΠ° ΠΏΡ€ΠΈ `attachment.not.ready` | @@ -108,7 +108,7 @@ await bot.start({ Если `path` Π½Π΅ ΡƒΠΊΠ°Π·Π°Π½, `max-io` создаёт бСзопасный ΡΡ‚Π°Π±ΠΈΠ»ΡŒΠ½Ρ‹ΠΉ path ΠΏΠΎ Ρ‚ΠΎΠΊΠ΅Π½Ρƒ. Callback ΠΏΡ€ΠΈΠ½ΠΈΠΌΠ°Π΅Ρ‚ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ `POST` с `content-type: application/json`; входящий JSON body ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ `5 MiB`, Π° Π»ΠΈΠΌΠΈΡ‚ ΠΌΠΎΠΆΠ½ΠΎ ΠΈΠ·ΠΌΠ΅Π½ΠΈΡ‚ΡŒ Ρ‡Π΅Ρ€Π΅Π· `webhook.maxBodySize` Π² Π±Π°ΠΉΡ‚Π°Ρ…. ΠŸΡ€ΠΈ запускС webhook ΠΏΠΎ ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ ΡƒΠ΄Π°Π»ΡΡŽΡ‚ΡΡ старыС подписки с Π΄Ρ€ΡƒΠ³ΠΈΠΌΠΈ URL; ΠΏΡ€ΠΈ запускС polling ΡƒΠ΄Π°Π»ΡΡŽΡ‚ΡΡ всС webhook-подписки. -ΠŸΠΎΠ΄Ρ€ΠΎΠ±Π½Π΅Π΅: [`docs/webhook.md`](./docs/webhook.md). +Π‘ΠΎΠ±Ρ‹Ρ‚ΠΈΠ΅ `bot_admin_permissions_changed` доступно Ρ‡Π΅Ρ€Π΅Π· webhook ΠΈ сообщаСт ΠΎΠ± ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΈ ΠΏΡ€Π°Π² Π±ΠΎΡ‚Π°-администратора. ΠŸΠΎΠ΄Ρ€ΠΎΠ±Π½Π΅Π΅: [`docs/webhook.md`](./docs/webhook.md). ## Polling marker diff --git a/contract-tests/public-entrypoints.ts b/contract-tests/public-entrypoints.ts index 917fdd1..1ef71bd 100644 --- a/contract-tests/public-entrypoints.ts +++ b/contract-tests/public-entrypoints.ts @@ -4,10 +4,13 @@ import { type Middleware, } from 'max-io'; import type { + BotAdminPermissionsChangedUpdate, BotInfo, + ChatAdminPermission, MessageCreatedUpdate, SendMessageExtra, Update, + UpdateType, } from 'max-io/types'; import { I18n, type I18nContext } from 'max-io/lib/i18n'; import { SceneManager, type IScene, type WithScene } from 'max-io/lib/scene'; @@ -67,13 +70,41 @@ const verifyUpdateNarrowing: Middleware = async (ctx, next) => { void update; } + if (ctx.has('bot_admin_permissions_changed')) { + const permissionsUpdate: BotAdminPermissionsChangedUpdate = ctx.update; + const chatId: number = ctx.chatId; + const permissions: ChatAdminPermission[] | null | undefined = + ctx.update.permissions; + void permissionsUpdate; + void chatId; + void permissions; + } + await next(); }; const update: Update | undefined = undefined; const botInfo: BotInfo | undefined = undefined; +const allowedUpdates: UpdateType[] = ['bot_admin_permissions_changed']; +const permissionsUpdate: BotAdminPermissionsChangedUpdate = { + update_type: 'bot_admin_permissions_changed', + timestamp: 1, + chat_id: 42, + user_id: 7, + bot_id: 100, + is_channel: true, + is_admin: true, + permissions: null, +}; + +bot.on('bot_admin_permissions_changed', (ctx) => { + const userId: number = ctx.update.user_id; + void userId; +}); void sceneMiddleware; void verifyUpdateNarrowing; void update; void botInfo; +void allowedUpdates; +void permissionsUpdate; diff --git a/docs/02-listen-and-respond.md b/docs/02-listen-and-respond.md index 4077d57..80a3df4 100644 --- a/docs/02-listen-and-respond.md +++ b/docs/02-listen-and-respond.md @@ -20,6 +20,26 @@ bot.on('message_callback', async (ctx) => { Π Π΅Π΄Π°ΠΊΡ‚ΠΎΡ€ подскаТСт доступныС `update_type`, ΠΏΠΎΡ‚ΠΎΠΌΡƒ Ρ‡Ρ‚ΠΎ Ρ‚ΠΈΠΏΡ‹ ΡΠΊΡΠΏΠΎΡ€Ρ‚ΠΈΡ€ΡƒΡŽΡ‚ΡΡ ΠΈΠ· `max-io` ΠΈ `max-io/types`. +На ΠΏΡ€Π°ΠΊΡ‚ΠΈΠΊΠ΅ Max ΠΈΠ½ΠΎΠ³Π΄Π° присылаСт `message_created` Π±Π΅Π· `message` (Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€, для голосовых сообщСний ΠΈ видСосообщСний), Π° Ρ‚Π΅Π»ΠΎ сообщСния Ρ‚ΠΎΠΆΠ΅ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΎΡ‚ΡΡƒΡ‚ΡΡ‚Π²ΠΎΠ²Π°Ρ‚ΡŒ. ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠΉΡ‚Π΅ `ctx.message?.body` ΠΏΠ΅Ρ€Π΅Π΄ ΠΎΠ±Ρ€Π°Ρ‰Π΅Π½ΠΈΠ΅ΠΌ ΠΊ Π΄Π°Π½Π½Ρ‹ΠΌ, Π΄Π°ΠΆΠ΅ Ссли Ρ‚ΠΈΠΏΡ‹ схСмы ΠΎΠΏΠΈΡΡ‹Π²Π°ΡŽΡ‚ эти поля ΠΊΠ°ΠΊ ΠΎΠ±ΡΠ·Π°Ρ‚Π΅Π»ΡŒΠ½Ρ‹Π΅. `command` ΠΈ `hears` ΠΏΡ€ΠΎΠΏΡƒΡΠΊΠ°ΡŽΡ‚ Ρ‚Π°ΠΊΠΈΠ΅ события ΠΈ сообщСния Π±Π΅Π· тСкста; ΠΎΡ‚ΡΡƒΡ‚ΡΡ‚Π²ΡƒΡŽΡ‰Π΅Π΅ содСрТимоС Π±ΠΈΠ±Π»ΠΈΠΎΡ‚Π΅ΠΊΠ° Π²ΠΎΡΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ‚. + +### Запуск Π±ΠΎΡ‚Π° ΠΏΠΎ ссылкС + +Π’ deep link Π±ΠΎΡ‚Π° ΠΌΠΎΠΆΠ½ΠΎ ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‚ΡŒ ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ `start`, Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€ +`https://max.ru/id123456_bot?start=campaign`. Π˜ΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠΉΡ‚Π΅ адрСс своСго Π±ΠΎΡ‚Π°; +ΠΏΡ€ΠΈ Ρ„ΠΎΡ€ΠΌΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠΈ ссылки ΠΊΠΎΠ΄ΠΈΡ€ΡƒΠΉΡ‚Π΅ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ Ρ‡Π΅Ρ€Π΅Π· `encodeURIComponent`. +ΠŸΡ€ΠΈ событии `bot_started` payload доступСн Ρ‡Π΅Ρ€Π΅Π· `ctx.startPayload`: + +```ts +bot.on('bot_started', async (ctx) => { + const payload = ctx.startPayload; + await ctx.reply(payload ? `Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ: ${payload}` : 'ΠŸΡ€ΠΈΠ²Π΅Ρ‚!'); +}); +``` + +По схСмС payload ΠΌΠΎΠΆΠ΅Ρ‚ ΠΎΡ‚ΡΡƒΡ‚ΡΡ‚Π²ΠΎΠ²Π°Ρ‚ΡŒ ΠΈΠ»ΠΈ Π±Ρ‹Ρ‚ΡŒ `null`, максимальная Π΄Π»ΠΈΠ½Π° β€” +512 символов. `ctx.startPayload` относится ΠΊ запуску ΠΏΠΎ ссылкС, Π° `ctx.payload` +содСрТит Π°Ρ€Π³ΡƒΠΌΠ΅Π½Ρ‚Ρ‹ ΠΊΠΎΠΌΠ°Π½Π΄Ρ‹. ΠŸΠΎΠ»Π½Ρ‹ΠΉ ΠΏΡ€ΠΈΠΌΠ΅Ρ€: [`examples/01-basic-minimum`](../examples/01-basic-minimum/README.md), Ρ„Π°ΠΉΠ» `src/start-payload-bot.ts`. + ### ΠšΠ°Π½Π°Π»Ρ‹ ΠΈ ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΈ `message_created` ΠΏΡ€ΠΈΡ…ΠΎΠ΄ΠΈΡ‚ Π½Π΅ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ для сообщСний ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ: Bot API Ρ‚Π°ΠΊΠΆΠ΅ @@ -139,6 +159,12 @@ await bot.api.deleteComment(postId, comment.body.mid); Π’ коммСнтариях Π½Π΅Ρ‚ Π²Π»ΠΎΠΆΠ΅Π½ΠΈΠΉ ΠΈ нСльзя ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ `forward`; для ΠΎΡ‚Π²Π΅Ρ‚Π° Π½Π° Π΄Ρ€ΡƒΠ³ΠΎΠΉ ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΉ ΠΏΠ΅Ρ€Π΅Π΄Π°ΠΉΡ‚Π΅ `link: { type: 'reply', mid: commentId }`. +По схСмС Ρ€Π΅Π΄Π°ΠΊΡ‚ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΉ ΠΌΠΎΠΆΠ½ΠΎ Π½Π΅ ΠΏΠΎΠ·Π΄Π½Π΅Π΅ 26 часов послС ΠΏΡƒΠ±Π»ΠΈΠΊΠ°Ρ†ΠΈΠΈ; +ΠΏΠΎΠ·ΠΆΠ΅ API Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ HTTP 422 с ΠΊΠΎΠ΄ΠΎΠΌ `comments.timeout_exceeded`. ΠžΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ΠΈΠ΅ +сохраняСтся ΠΏΡ€ΠΈ Π°Ρ€Ρ…ΠΈΠ²ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠΈ ΠΊΠ°Π½Π°Π»Π° ΠΈ ΠΎΡ‚ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠΈ ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠ΅Π². Π‘ΠΎΡ‚ Π±Π΅Π· ΠΏΡ€Π°Π²Π° +`edit` ΠΌΠΎΠΆΠ΅Ρ‚ Ρ€Π΅Π΄Π°ΠΊΡ‚ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ свои ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΈ, Π° с этим ΠΏΡ€Π°Π²ΠΎΠΌ β€” Ρ‚Π°ΠΊΠΆΠ΅ +ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΈ ΠΎΡ‚ ΠΈΠΌΠ΅Π½ΠΈ ΠΊΠ°Π½Π°Π»Π°. + ΠžΡ‚Π²Π΅Ρ‚ с reply-link: ```ts @@ -193,6 +219,8 @@ await bot.start({ marker: bot.polling.marker }); `ctx.state` β€” ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ Π½Π° врСмя ΠΎΠ΄Π½ΠΎΠ³ΠΎ update. Он ΡƒΠ΄ΠΎΠ±Π΅Π½ для ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‡ΠΈ Π΄Π°Π½Π½Ρ‹Ρ… ΠΌΠ΅ΠΆΠ΄Ρƒ middleware Π±Π΅Π· session. +Π’Ρ‹Π·Ρ‹Π²Π°ΠΉΡ‚Π΅ ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΉ middleware Ρ‡Π΅Ρ€Π΅Π· `await next()` ΠΈΠ»ΠΈ `return next()`: Ρ‚Π°ΠΊ явно ΡΠΎΡ…Ρ€Π°Π½ΡΡŽΡ‚ΡΡ порядок выполнСния ΠΈ Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΡΡ‚ΡŒ ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ ΠΎΡˆΠΈΠ±ΠΊΡƒ. Если Π²Ρ‹Π·Π²Π°Ρ‚ΡŒ `next()` Π±Π΅Π· оТидания Π²Π½ΡƒΡ‚Ρ€ΠΈ middleware, Ρ†Π΅ΠΏΠΎΡ‡ΠΊΠ° всё Ρ€Π°Π²Π½ΠΎ доТдётся Π·Π°ΠΏΡƒΡ‰Π΅Π½Π½ΠΎΠΉ ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΠΈ Π΄ΠΎ Π·Π°Π²Π΅Ρ€ΡˆΠ΅Π½ΠΈΡ update ΠΈ сохранСния сСссии. Π­Ρ‚ΠΎ Π½Π΅ относится ΠΊ Π²Ρ‹Π·ΠΎΠ²Ρƒ `next()` ΠΏΠΎΠ·ΠΆΠ΅ ΠΈΠ· Ρ„ΠΎΠ½ΠΎΠ²ΠΎΠ³ΠΎ Ρ‚Π°ΠΉΠΌΠ΅Ρ€Π° послС Π·Π°Π²Π΅Ρ€ΡˆΠ΅Π½ΠΈΡ middleware. + ```ts bot.use(async (ctx, next) => { ctx.state.startedAt = Date.now(); diff --git a/docs/webhook.md b/docs/webhook.md index c284c18..6af1bb0 100644 --- a/docs/webhook.md +++ b/docs/webhook.md @@ -11,6 +11,8 @@ Webhook URL Π΄ΠΎΠ»ΠΆΠ΅Π½ Π±Ρ‹Ρ‚ΡŒ ΠΏΡƒΠ±Π»ΠΈΡ‡Π½Ρ‹ΠΌ HTTPS endpoint. Для Π»ΠΎ ΠžΡ„ΠΈΡ†ΠΈΠ°Π»ΡŒΠ½Π°Ρ докумСнтация Max Π½Π°Π·Ρ‹Π²Π°Π΅Ρ‚ webhook основным ΠΌΠ΅Ρ…Π°Π½ΠΈΠ·ΠΌΠΎΠΌ доставки событий для ΠΏΡ€ΠΎΠ΄ΡƒΠΊΡ‚ΠΎΠ²Ρ‹Ρ… ΠΈΠ½Ρ‚Π΅Π³Ρ€Π°Ρ†ΠΈΠΉ. Long polling ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ ΠΏΠΎ скорости ΠΈ сроку хранСния событий, поэтому Π΅Π³ΠΎ Π»ΡƒΡ‡ΡˆΠ΅ ΠΎΡΡ‚Π°Π²Π»ΡΡ‚ΡŒ для Ρ€Π°Π·Ρ€Π°Π±ΠΎΡ‚ΠΊΠΈ ΠΈ Ρ€ΡƒΡ‡Π½ΠΎΠΉ ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ. +Π‘ΠΎΠ±Ρ‹Ρ‚ΠΈΠ΅ `bot_admin_permissions_changed` сообщаСт ΠΎΠ± ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΈ ΠΏΡ€Π°Π² Π±ΠΎΡ‚Π°-администратора Π³Ρ€ΡƒΠΏΠΏΠΎΠ²ΠΎΠ³ΠΎ Ρ‡Π°Ρ‚Π° ΠΈΠ»ΠΈ ΠΊΠ°Π½Π°Π»Π°. По Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ схСмС Max ΠΎΠ½ΠΎ доступно Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Ρ‡Π΅Ρ€Π΅Π· webhook, Π° Π½Π΅ long polling. ΠžΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ ΠΌΠΎΠΆΠ½ΠΎ Π·Π°Ρ€Π΅Π³ΠΈΡΡ‚Ρ€ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ Ρ‡Π΅Ρ€Π΅Π· `bot.on('bot_admin_permissions_changed', ...)`; Π² `ctx.update` доступны ID Ρ‡Π°Ρ‚Π°, Π±ΠΎΡ‚Π° ΠΈ ΠΈΠ½ΠΈΡ†ΠΈΠ°Ρ‚ΠΎΡ€Π° измСнСния, статус администратора ΠΈ, Ссли ΠΏΠ΅Ρ€Π΅Π΄Π°Π½Ρ‹, Π½ΠΎΠ²Ρ‹Π΅ ΠΏΡ€Π°Π²Π°. + ## ВстроСнный сСрвСр ```ts diff --git a/package.json b/package.json index 1dbabe9..59d5738 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "max-io", - "version": "0.1.8", + "version": "0.1.9", "description": "TypeScript framework for Max messenger bots", "keywords": [ "max", diff --git a/src/core/api.ts b/src/core/api.ts index 2b90d02..1663c7a 100755 --- a/src/core/api.ts +++ b/src/core/api.ts @@ -76,6 +76,10 @@ export class Api { return this.editMyCommands([]); }; + /** + * @deprecated `GET /chats` отсутствуСт Π² Π°ΠΊΡ‚ΡƒΠ°Π»ΡŒΠ½ΠΎΠΉ схСмС ΠΈ Π½Π΅ поддСрТиваСтся API. + * ΠœΠ΅Ρ‚ΠΎΠ΄ сохранён для совмСстимости; сохраняйтС `chat_id` ΠΈΠ· updates. + */ getAllChats = async (extra: GetAllChatsExtra = {}) => { return this.raw.chats.getAll(extra); }; @@ -238,6 +242,8 @@ export class Api { * Π Π΅Π΄Π°ΠΊΡ‚ΠΈΡ€ΡƒΠ΅Ρ‚ ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΉ Π±ΠΎΡ‚Π° ΠΊ посту Π² ΠΊΠ°Π½Π°Π»Π΅. * * @remarks Π‘ΠΎΡ‚ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΈΠ·ΠΌΠ΅Π½ΠΈΡ‚ΡŒ свой ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΉ, Π° ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΈ ΠΎΡ‚ ΠΈΠΌΠ΅Π½ΠΈ ΠΊΠ°Π½Π°Π»Π° β€” Ρ‚ΠΎΠ»ΡŒΠΊΠΎ с ΠΏΡ€Π°Π²ΠΎΠΌ `edit`. + * Π Π΅Π΄Π°ΠΊΡ‚ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ доступно Π² Ρ‚Π΅Ρ‡Π΅Π½ΠΈΠ΅ 26 часов послС ΠΏΡƒΠ±Π»ΠΈΠΊΠ°Ρ†ΠΈΠΈ; ΠΏΠΎΠ·Π΄Π½Π΅Π΅ API Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ + * HTTP 422 с ΠΊΠΎΠ΄ΠΎΠΌ `comments.timeout_exceeded`, Π΄Π°ΠΆΠ΅ Ссли ΠΊΠ°Π½Π°Π» Π°Ρ€Ρ…ΠΈΠ²ΠΈΡ€ΠΎΠ²Π°Π½ ΠΈΠ»ΠΈ ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΈ ΠΎΡ‚ΠΊΠ»ΡŽΡ‡Π΅Π½Ρ‹. */ editComment = async ( messageId: string, @@ -363,7 +369,11 @@ export class Api { /** * ДобавляСт ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ Π² Π³Ρ€ΡƒΠΏΠΏΠΎΠ²ΠΎΠΉ Ρ‡Π°Ρ‚. * - * @remarks По Π°ΠΊΡ‚ΡƒΠ°Π»ΡŒΠ½ΠΎΠΉ схСмС ΠΌΠ΅Ρ‚ΠΎΠ΄ Π½Π΅ добавляСт подписчиков Π² ΠΊΠ°Π½Π°Π»Ρ‹. + * @remarks Π‘ΠΎΡ‚ Π΄ΠΎΠ»ΠΆΠ΅Π½ Π±Ρ‹Ρ‚ΡŒ администратором с ΠΏΡ€Π°Π²ΠΎΠΌ `add_remove_members`. + * Π”ΠΎ 100 ΡƒΠ½ΠΈΠΊΠ°Π»ΡŒΠ½Ρ‹Ρ… ID Π·Π° запрос; подписчиков Π² ΠΊΠ°Π½Π°Π» Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ нСльзя. + * ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠΉΡ‚Π΅ `failed_user_ids` ΠΈ `failed_user_details` Π² ΠΎΡ‚Π²Π΅Ρ‚Π΅. + * Π’ ΡƒΠ²Π΅Π΄ΠΎΠΌΠ»Π΅Π½ΠΈΠΈ схСмы ΡƒΠΊΠ°Π·Π°Π½ΠΎ, Ρ‡Ρ‚ΠΎ с 9 сСнтября 2026 Π³ΠΎΠ΄Π° Ρ€Π°Π±ΠΎΡ‚Π° ΠΌΠ΅Ρ‚ΠΎΠ΄Π° ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½Π°; + * ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½Ρ‹Π΅ ограничСния Π² ΡƒΠ²Π΅Π΄ΠΎΠΌΠ»Π΅Π½ΠΈΠΈ Π½Π΅ раскрыты. */ addChatMembers = (chatId: number, userIds: number[]) => { return this.raw.chats.addChatMembers({ diff --git a/src/core/bot.test.ts b/src/core/bot.test.ts index 2a21736..ff61a1d 100644 --- a/src/core/bot.test.ts +++ b/src/core/bot.test.ts @@ -124,6 +124,71 @@ afterEach(() => { }); describe('Bot.webhookCallback', () => { + it('ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‘Ρ‚ Π½Π΅ΠΏΠΎΠ»Π½ΠΎΠ΅ message_created дальшС Π±Π΅Π· падСния тСкстовых Ρ„ΠΈΠ»ΡŒΡ‚Ρ€ΠΎΠ²', async () => { + const bot = new Bot('test-token'); + const command = vi.fn(); + const hears = vi.fn(); + const handler = vi.fn(); + bot.command('start', command); + bot.hears('hello', hears); + bot.on('message_created', (ctx) => { + handler({ user: ctx.user, messageId: ctx.messageId }); + }); + + const response = await sendRequest({ + listener: bot.webhookCallback('/updates'), + path: '/updates', + headers: { 'content-type': 'application/json' }, + bodyChunks: [ + JSON.stringify({ update_type: 'message_created', timestamp: 1 }), + ], + }); + + expect(response).toEqual({ status: 200, body: '{"ok":true}' }); + expect(command).not.toHaveBeenCalled(); + expect(hears).not.toHaveBeenCalled(); + expect(handler).toHaveBeenCalledWith({ + user: undefined, + messageId: undefined, + }); + }); + + it('ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‘Ρ‚ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠ΅ ΠΏΡ€Π°Π² Π±ΠΎΡ‚Π° Π² Ρ‚ΠΈΠΏΠΈΠ·ΠΈΡ€ΠΎΠ²Π°Π½Π½Ρ‹ΠΉ webhook-ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ', async () => { + const bot = new Bot('test-token'); + const handler = vi.fn(); + bot.on('bot_admin_permissions_changed', (ctx) => { + handler({ + update: ctx.update, + chatId: ctx.chatId, + user: ctx.user, + }); + }); + const update = { + update_type: 'bot_admin_permissions_changed', + timestamp: 1_700_000_000_000, + chat_id: 42, + user_id: 7, + bot_id: 100, + is_channel: true, + is_admin: true, + permissions: ['write', 'delete'], + }; + + const response = await sendRequest({ + listener: bot.webhookCallback('/updates'), + path: '/updates', + headers: { 'content-type': 'application/json' }, + bodyChunks: [JSON.stringify(update)], + }); + + expect(response).toEqual({ status: 200, body: '{"ok":true}' }); + expect(handler).toHaveBeenCalledWith({ + update, + chatId: 42, + user: undefined, + }); + }); + it('ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‘Ρ‚ ΠΊΠΎΡ€Ρ€Π΅ΠΊΡ‚Π½Ρ‹ΠΉ update Π² middleware', async () => { const bot = new Bot('test-token'); const handler = vi.fn(async () => undefined); diff --git a/src/core/composer.test.ts b/src/core/composer.test.ts index 36de460..e0ee424 100644 --- a/src/core/composer.test.ts +++ b/src/core/composer.test.ts @@ -83,6 +83,127 @@ const createContext = (update: U) => new Context(update, {} as Api, botInfo); describe('Composer', () => { + it('ΠΎΠΆΠΈΠ΄Π°Π΅Ρ‚ terminal next ΠΏΡ€ΠΈ Π²Ρ‹Π·ΠΎΠ²Π΅ Π±Π΅Π· await Π² послСднСм middleware', async () => { + let release: () => void = () => undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const completed = vi.fn(); + const composer = new Composer((_ctx, next) => { + expect(next()).toBeInstanceOf(Promise); + }); + const running = Promise.resolve( + composer.middleware()( + createContext(createBotStoppedUpdate()), + () => gate, + ), + ).then(completed); + await new Promise((resolve) => setTimeout(resolve, 0)); + const completedBeforeRelease = completed.mock.calls.length > 0; + release(); + await running; + expect(completedBeforeRelease).toBe(false); + }); + + it('ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‘Ρ‚ ΠΎΡˆΠΈΠ±ΠΊΡƒ downstream ΠΏΡ€ΠΈ Π²Ρ‹Π·ΠΎΠ²Π΅ next Π±Π΅Π· await', async () => { + const error = new Error('downstream error'); + const composer = new Composer( + (_ctx, next) => { + void next(); + }, + async () => { + await Promise.resolve(); + throw error; + }, + ); + + await expect( + composer.middleware()( + createContext(createBotStoppedUpdate()), + async () => undefined, + ), + ).rejects.toBe(error); + }); + + it('позволяСт middleware ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ ΠΎΡˆΠΈΠ±ΠΊΡƒ ΠΈΠ· await next', async () => { + const error = new Error('handled downstream error'); + const handler = vi.fn(); + const composer = new Composer( + async (_ctx, next) => { + try { + await next(); + } catch (caught) { + handler(caught); + } + }, + async () => { + throw error; + }, + ); + + await expect( + composer.middleware()( + createContext(createBotStoppedUpdate()), + async () => undefined, + ), + ).resolves.toBeUndefined(); + expect(handler).toHaveBeenCalledWith(error); + }); + + it('сохраняСт ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΡƒ ошибок Ρ‡Π΅Ρ€Π΅Π· return next().catch()', async () => { + const error = new Error('handled downstream error'); + const handler = vi.fn(); + const composer = new Composer( + (_ctx, next) => next().catch(handler), + async () => { + throw error; + }, + ); + + await expect( + composer.middleware()( + createContext(createBotStoppedUpdate()), + async () => undefined, + ), + ).resolves.toBeUndefined(); + expect(handler).toHaveBeenCalledWith(error); + }); + + it('пропускаСт Π½Π΅ΠΏΠΎΠ»Π½Ρ‹Π΅ сообщСния ΠΈ тСкст null Π² command ΠΈ hears', async () => { + const command = vi.fn(); + const hears = vi.fn(); + const terminal = vi.fn(async () => undefined); + const composer = new Composer(); + composer.command('start', command); + composer.hears(/hello/, hears); + + const base = createMessageCreatedUpdate('hello'); + const updates = [ + { update_type: 'message_created', timestamp: base.timestamp }, + { ...base, message: null }, + { ...base, message: { ...base.message, body: undefined } }, + { ...base, message: { ...base.message, body: null } }, + { + ...base, + message: { + ...base.message, + body: { ...base.message.body, text: null }, + }, + }, + ]; + + for (const update of updates) { + await composer.middleware()( + createContext(update as unknown as Update), + terminal, + ); + } + + expect(command).not.toHaveBeenCalled(); + expect(hears).not.toHaveBeenCalled(); + expect(terminal).toHaveBeenCalledTimes(updates.length); + }); + it('сохраняСт порядок middleware Π΄ΠΎ ΠΈ послС next()', async () => { const events: string[] = []; const composer = new Composer(); diff --git a/src/core/composer.ts b/src/core/composer.ts index 1a6b800..7827502 100644 --- a/src/core/composer.ts +++ b/src/core/composer.ts @@ -15,14 +15,34 @@ type TriggerFn = (value: string, ctx: C) => RegExpExecArray | null; type UpdateFilter = UpdateType | Guard; +/** ΠžΡ‚ΡΠ»Π΅ΠΆΠΈΠ²Π°Π΅Ρ‚, ΠΏΠ΅Ρ€Π΅Π΄Π°Π» Π»ΠΈ middleware ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΡƒ Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚Π° next() дальшС. */ +class NextPromise extends Promise { + observed = false; + + static get [Symbol.species]() { + return Promise; + } + + then( + onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null, + onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null, + ): Promise { + this.observed = true; + return super.then(onfulfilled, onrejected); + } +} + export class Composer implements MiddlewareObj { private handler: MiddlewareFn; + private middlewares: Array>; + private commandPrefix: CommandPrefix; constructor(...middlewares: Array>) { this.commandPrefix = true; - this.handler = Composer.compose(middlewares); + this.middlewares = middlewares.map(Composer.flatten); + this.handler = Composer.compose(this.middlewares); } middleware() { @@ -30,7 +50,8 @@ export class Composer implements MiddlewareObj { } use(...middlewares: Array>) { - this.handler = Composer.compose([this.handler, ...middlewares]); + this.middlewares.push(...middlewares.map(Composer.flatten)); + this.handler = Composer.compose(this.middlewares); return this; } @@ -56,7 +77,8 @@ export class Composer implements MiddlewareObj { return this.use( this.filter(filter, (ctx, next) => { - const text = extractTextFromMessage(ctx.message, ctx.myId)!; + const text = extractTextFromMessage(ctx.message, ctx.myId); + if (typeof text !== 'string') return next(); const parsedCommand = parseCommandText({ text, botUsername: ctx.botInfo?.username, @@ -93,7 +115,8 @@ export class Composer implements MiddlewareObj { return this.use( this.filter(filter, (ctx, next) => { - const text = extractTextFromMessage(ctx.message, ctx.myId)!; + const text = extractTextFromMessage(ctx.message, ctx.myId); + if (typeof text !== 'string') return next(); for (const trigger of normalizedTriggers) { const match = trigger(text, ctx); @@ -156,13 +179,35 @@ export class Composer implements MiddlewareObj { ): MiddlewareFn { return async (ctx, next) => { let nextCalled = false; - await first(ctx, async () => { + let nextPromise: NextPromise | undefined; + let downstreamResult: + Promise<{ error?: unknown; failed: boolean }> | undefined; + await first(ctx, () => { if (nextCalled) { - throw new Error('`next` already called before!'); + return Promise.reject(new Error('`next` already called before!')); } nextCalled = true; - await andThen(ctx, next); + nextPromise = new NextPromise((resolve, reject) => { + try { + Promise.resolve(andThen(ctx, next)).then(() => resolve(), reject); + } catch (error) { + reject(error); + } + }); + // Подписка Π±Π΅Π· Π²Ρ‹Π·ΠΎΠ²Π° ΠΏΠ΅Ρ€Π΅ΠΎΠΏΡ€Π΅Π΄Π΅Π»Ρ‘Π½Π½ΠΎΠ³ΠΎ then ΠΏΡ€Π΅Π΄ΠΎΡ‚Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ unhandled + // rejection, Π½Π΅ считая ΠΏΡ€ΠΎΠΈΠ³Π½ΠΎΡ€ΠΈΡ€ΠΎΠ²Π°Π½Π½Ρ‹ΠΉ next() ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Π°Π½Π½Ρ‹ΠΌ. + downstreamResult = Promise.prototype.then.call( + nextPromise, + () => ({ failed: false }), + (error: unknown) => ({ failed: true, error }), + ) as Promise<{ error?: unknown; failed: boolean }>; + return nextPromise; }); + + if (downstreamResult) { + const result = await downstreamResult; + if (result.failed && !nextPromise?.observed) throw result.error; + } }; } @@ -177,7 +222,12 @@ export class Composer implements MiddlewareObj { if (middlewares.length === 0) { return Composer.pass; } - return middlewares.map(Composer.flatten).reduce(Composer.concat); + return middlewares + .map(Composer.flatten) + .reduceRight>( + (andThen, first) => Composer.concat(first, andThen), + Composer.pass, + ); } } @@ -376,13 +426,14 @@ const parseCommandArgs = (payload: string) => { const extractTextFromMessage = (message: Message, myId?: number) => { const { text } = message.body; + if (typeof text !== 'string') return undefined; const mention = message.body.markup?.find((m) => { return m.type === 'user_mention'; }); if (mention && mention.from === 0 && mention.user_id === myId) { - return text?.slice(mention.length).trim(); + return text.slice(mention.length).trim(); } return text; diff --git a/src/core/context.test.ts b/src/core/context.test.ts index f45369c..0c7cacf 100644 --- a/src/core/context.test.ts +++ b/src/core/context.test.ts @@ -132,6 +132,28 @@ const createCommentRemovedUpdate = (): CommentRemovedUpdate => ({ }); describe('Context', () => { + it('бСзопасно ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅Ρ‚ Π΄Π°Π½Π½Ρ‹Π΅ ΠΈΠ· Π½Π΅ΠΏΠΎΠ»Π½Ρ‹Ρ… событий сообщСния', () => { + const base = createMessageCreatedUpdate(); + const updates = [ + { update_type: 'message_created', timestamp: base.timestamp }, + { ...base, message: null }, + { ...base, message: { ...base.message, body: undefined } }, + { ...base, message: { ...base.message, body: null, recipient: null } }, + ]; + + for (const update of updates) { + const context = new Context(update as unknown as Update, api); + expect(context.messageId).toBeUndefined(); + expect(context.contactInfo).toBeUndefined(); + expect(context.location).toBeUndefined(); + expect(context.sticker).toBeUndefined(); + expect(() => context.chatId).not.toThrow(); + expect(() => context.chatType).not.toThrow(); + expect(() => context.user).not.toThrow(); + expect(() => context.sender).not.toThrow(); + } + }); + it('прСдоставляСт Π΄Π°Π½Π½Ρ‹Π΅ сообщСния, отправитСля ΠΈ Π±ΠΎΡ‚Π°', () => { const update = createMessageCreatedUpdate(); const context = new Context(update, api, botInfo); diff --git a/src/core/context.ts b/src/core/context.ts index 095c67e..a627a2b 100644 --- a/src/core/context.ts +++ b/src/core/context.ts @@ -162,6 +162,7 @@ export class Context { return this.myId && this.sender?.user_id === this.myId; } + /** Payload deep link события `bot_started`; отличаСтся ΠΎΡ‚ `ctx.payload` ΠΊΠΎΠΌΠ°Π½Π΄Ρ‹. */ get startPayload() { return getStartPayload(this.update) as GetStartPayload; } @@ -226,6 +227,10 @@ export class Context { }); } + /** + * @deprecated `GET /chats` отсутствуСт Π² Π°ΠΊΡ‚ΡƒΠ°Π»ΡŒΠ½ΠΎΠΉ схСмС ΠΈ Π½Π΅ поддСрТиваСтся API. + * ΠœΠ΅Ρ‚ΠΎΠ΄ сохранён для совмСстимости; сохраняйтС `chat_id` ΠΈΠ· updates. + */ async getAllChats(extra?: GetAllChatsExtra) { return this.api.getAllChats(extra); } @@ -318,7 +323,11 @@ export class Context { /** * ДобавляСт ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ Π² Ρ‚Π΅ΠΊΡƒΡ‰ΠΈΠΉ Π³Ρ€ΡƒΠΏΠΏΠΎΠ²ΠΎΠΉ Ρ‡Π°Ρ‚. * - * @remarks По Π°ΠΊΡ‚ΡƒΠ°Π»ΡŒΠ½ΠΎΠΉ схСмС ΠΌΠ΅Ρ‚ΠΎΠ΄ Π½Π΅ добавляСт подписчиков Π² ΠΊΠ°Π½Π°Π»Ρ‹. + * @remarks Π‘ΠΎΡ‚Ρƒ Π½ΡƒΠΆΠ½ΠΎ ΠΏΡ€Π°Π²ΠΎ администратора `add_remove_members`. + * Π”ΠΎ 100 ΡƒΠ½ΠΈΠΊΠ°Π»ΡŒΠ½Ρ‹Ρ… ID Π·Π° запрос; подписчиков Π² ΠΊΠ°Π½Π°Π» Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ нСльзя. + * ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠΉΡ‚Π΅ `failed_user_ids` ΠΈ `failed_user_details` Π² ΠΎΡ‚Π²Π΅Ρ‚Π΅. + * Π’ ΡƒΠ²Π΅Π΄ΠΎΠΌΠ»Π΅Π½ΠΈΠΈ схСмы ΡƒΠΊΠ°Π·Π°Π½ΠΎ, Ρ‡Ρ‚ΠΎ с 9 сСнтября 2026 Π³ΠΎΠ΄Π° Ρ€Π°Π±ΠΎΡ‚Π° ΠΌΠ΅Ρ‚ΠΎΠ΄Π° ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½Π°; + * ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½Ρ‹Π΅ ограничСния Π² ΡƒΠ²Π΅Π΄ΠΎΠΌΠ»Π΅Π½ΠΈΠΈ Π½Π΅ раскрыты. */ async addChatMembers(userIds: number[]) { this.assert(this.chatId, 'addChatMembers'); @@ -361,7 +370,7 @@ const getChatId = (update: Update) => { return update.chat_id; } if ('message' in update && update.message && 'recipient' in update.message) { - return update.message.recipient.chat_id; + return update.message.recipient?.chat_id; } if ('chat' in update) { return update.chat.chat_id; @@ -378,7 +387,7 @@ const getChatType = (update: Update) => { return update.chat.type; } if ('message' in update && update.message && 'recipient' in update.message) { - return update.message.recipient.chat_type; + return update.message.recipient?.chat_type; } return undefined; }; @@ -404,7 +413,7 @@ const getMessageId = (update: Update) => { } if ('message' in update) { - return update.message?.body.mid; + return update.message?.body?.mid; } return undefined; @@ -420,7 +429,7 @@ const getCallback = (update: Update) => { const getContactInfo = (update: Update): ContactInfo | undefined => { const message = getMessage(update); if (!message) return undefined; - const contact = message.body.attachments?.find( + const contact = message.body?.attachments?.find( (attachment) => attachment.type === 'contact', ); if (!contact?.payload.vcf_info) return undefined; @@ -434,7 +443,7 @@ const getContactInfo = (update: Update): ContactInfo | undefined => { const getLocation = (update: Update): Location | undefined => { const message = getMessage(update); if (!message) return undefined; - const location = message.body.attachments?.find( + const location = message.body?.attachments?.find( (attachment) => attachment.type === 'location', ); if (!location) return undefined; @@ -447,7 +456,7 @@ const getLocation = (update: Update): Location | undefined => { const getSticker = (update: Update): Sticker | undefined => { const message = getMessage(update); if (!message) return undefined; - const sticker = message.body.attachments?.find( + const sticker = message.body?.attachments?.find( (attachment) => attachment.type === 'sticker', ); if (!sticker) return undefined; @@ -469,7 +478,7 @@ const getUser = (update: Update): User | undefined => { } if (update.update_type === 'message_created') { - return update.message.sender || undefined; + return update.message?.sender || undefined; } return undefined; diff --git a/src/core/filters.ts b/src/core/filters.ts index 25cbd93..a832c01 100644 --- a/src/core/filters.ts +++ b/src/core/filters.ts @@ -5,6 +5,9 @@ export const createdMessageBodyHas = >( ) => { return (update: Update): update is MessageCreatedUpdate => { if (update.update_type !== 'message_created') return false; + if (!update.message?.body || typeof update.message.body !== 'object') { + return false; + } for (const key of keys) { if (!(key in update.message.body)) return false; if (update.message.body[key] === undefined) return false; diff --git a/src/core/helpers/upload.test.ts b/src/core/helpers/upload.test.ts index ff003b1..cff5dc0 100644 --- a/src/core/helpers/upload.test.ts +++ b/src/core/helpers/upload.test.ts @@ -10,9 +10,113 @@ const createApi = () => new Api({ call: vi.fn() } as unknown as Client); afterEach(() => { vi.unstubAllGlobals(); + vi.useRealTimers(); }); describe('Upload', () => { + it.each(['image', 'file'] as const)( + 'ΠΏΡ€Π΅Ρ€Ρ‹Π²Π°Π΅Ρ‚ multipart-Π·Π°Π³Ρ€ΡƒΠ·ΠΊΡƒ %s ΠΏΠΎ timeout', + async (type) => { + vi.useFakeTimers(); + const api = createApi(); + const controller = new AbortController(); + vi.spyOn(api.raw.uploads, 'getUploadUrl').mockResolvedValue({ + url: 'https://upload.example.test/file', + }); + const fetchMock = vi.fn().mockImplementation( + (_url, init) => + new Promise((_resolve, reject) => { + const signal = init?.signal; + signal?.addEventListener('abort', () => reject(signal.reason), { + once: true, + }); + }), + ); + vi.stubGlobal('fetch', fetchMock); + + const options = { + source: Buffer.from('file'), + filename: 'file.png', + timeout: 100, + signal: controller.signal, + }; + const upload = + type === 'image' ? api.uploadImage(options) : api.uploadFile(options); + const result = upload.catch((error: unknown) => error); + await vi.advanceTimersByTimeAsync(0); + expect(fetchMock).toHaveBeenCalledOnce(); + await vi.advanceTimersByTimeAsync(100); + + const signal = fetchMock.mock.calls[0][1]?.signal; + const abortedByTimeout = signal?.aborted; + if (!abortedByTimeout) controller.abort(); + const error = await result; + expect(abortedByTimeout).toBe(true); + expect(error).toEqual(new Error('Upload timeout exceeded')); + }, + ); + + it('отмСняСт multipart-Π·Π°Π³Ρ€ΡƒΠ·ΠΊΡƒ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΡΠΊΠΈΠΌ signal ΠΈ ΠΎΡ‡ΠΈΡ‰Π°Π΅Ρ‚ Ρ‚Π°ΠΉΠΌΠ΅Ρ€', async () => { + vi.useFakeTimers(); + const api = createApi(); + const controller = new AbortController(); + const reason = new Error('Upload cancelled'); + vi.spyOn(api.raw.uploads, 'getUploadUrl').mockResolvedValue({ + url: 'https://upload.example.test/file', + }); + const fetchMock = vi.fn().mockImplementation( + (_url, init) => + new Promise((_resolve, reject) => { + const signal = init?.signal; + signal?.addEventListener('abort', () => reject(signal.reason), { + once: true, + }); + }), + ); + vi.stubGlobal('fetch', fetchMock); + + const result = api.uploadFile({ + source: Buffer.from('file'), + filename: 'file.txt', + timeout: 1000, + signal: controller.signal, + }); + const rejection = expect(result).rejects.toBe(reason); + await vi.advanceTimersByTimeAsync(0); + expect(fetchMock).toHaveBeenCalledOnce(); + controller.abort(reason); + await rejection; + expect(vi.getTimerCount()).toBe(0); + }); + + it.each([200, 500])( + 'ΠΎΡ‡ΠΈΡ‰Π°Π΅Ρ‚ Ρ‚Π°ΠΉΠΌΠ΅Ρ€ послС ΠΎΡ‚Π²Π΅Ρ‚Π° upload endpoint со статусом %s', + async (status) => { + vi.useFakeTimers(); + const api = createApi(); + vi.spyOn(api.raw.uploads, 'getUploadUrl').mockResolvedValue({ + url: 'https://upload.example.test/file', + }); + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + new Response(JSON.stringify({ token: 'token' }), { status }), + ), + ); + + const result = api.uploadFile({ + source: Buffer.from('file'), + filename: 'file.txt', + timeout: 1000, + }); + if (status === 200) await expect(result).resolves.toBeDefined(); + else await expect(result).rejects.toBeDefined(); + expect(vi.getTimerCount()).toBe(0); + }, + ); + it('Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ URL image Π±Π΅Π· Π²Ρ‹Π·ΠΎΠ²Π° upload endpoint', async () => { const api = createApi(); const getUploadUrl = vi.spyOn(api.raw.uploads, 'getUploadUrl'); diff --git a/src/core/helpers/upload.ts b/src/core/helpers/upload.ts index ea2594f..263e5ba 100644 --- a/src/core/helpers/upload.ts +++ b/src/core/helpers/upload.ts @@ -654,7 +654,7 @@ export class Upload { throw new Error('Multipart upload requires a Blob or Buffer source'); } - return uploadMultipart( + return await uploadMultipart( { file: toMultipartFile(file), uploadUrl, diff --git a/src/core/network/api/modules/chats/api.ts b/src/core/network/api/modules/chats/api.ts index 40f8d2c..3c5d0bb 100644 --- a/src/core/network/api/modules/chats/api.ts +++ b/src/core/network/api/modules/chats/api.ts @@ -128,7 +128,12 @@ export class ChatsApi extends BaseApi { }); } - /** ДобавляСт ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ Π² Π³Ρ€ΡƒΠΏΠΏΠΎΠ²ΠΎΠΉ Ρ‡Π°Ρ‚; подписчиков ΠΊΠ°Π½Π°Π»Π° Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ нСльзя. */ + /** + * ДобавляСт Π΄ΠΎ 100 ΡƒΠ½ΠΈΠΊΠ°Π»ΡŒΠ½Ρ‹Ρ… ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ Π² Π³Ρ€ΡƒΠΏΠΏΠΎΠ²ΠΎΠΉ Ρ‡Π°Ρ‚ ΠΏΡ€ΠΈ Π½Π°Π»ΠΈΡ‡ΠΈΠΈ ΠΏΡ€Π°Π²Π° `add_remove_members`. + * ΠŸΠΎΠ΄ΠΏΠΈΡΡ‡ΠΈΠΊΠΎΠ² ΠΊΠ°Π½Π°Π»Π° Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ нСльзя; провСряйтС `failed_user_ids` ΠΈ `failed_user_details` Π² ΠΎΡ‚Π²Π΅Ρ‚Π΅. + * Π£Π²Π΅Π΄ΠΎΠΌΠ»Π΅Π½ΠΈΠ΅ схСмы сообщаСт ΠΎΠ± ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ΠΈΠΈ Ρ€Π°Π±ΠΎΡ‚Ρ‹ ΠΌΠ΅Ρ‚ΠΎΠ΄Π° с 9 сСнтября 2026 Π³ΠΎΠ΄Π°, + * Π½Π΅ уточняя ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½Ρ‹Π΅ ограничСния. + */ async addChatMembers({ chat_id, ...body diff --git a/src/core/network/api/modules/chats/types.ts b/src/core/network/api/modules/chats/types.ts index 854f578..cfef548 100644 --- a/src/core/network/api/modules/chats/types.ts +++ b/src/core/network/api/modules/chats/types.ts @@ -235,7 +235,7 @@ export type GetChatMembersResponse = { export type AddChatMembersDTO = { path: DefaultPath; body: { - /** ID ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… Π½ΡƒΠΆΠ½ΠΎ Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ Π² Π³Ρ€ΡƒΠΏΠΏΠΎΠ²ΠΎΠΉ Ρ‡Π°Ρ‚. */ + /** Π”ΠΎ 100 ΡƒΠ½ΠΈΠΊΠ°Π»ΡŒΠ½Ρ‹Ρ… ID ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… Π½ΡƒΠΆΠ½ΠΎ Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ Π² Π³Ρ€ΡƒΠΏΠΏΠΎΠ²ΠΎΠΉ Ρ‡Π°Ρ‚. */ user_ids: number[]; }; }; diff --git a/src/core/network/api/modules/comments/api.ts b/src/core/network/api/modules/comments/api.ts index d94153a..ce395fb 100644 --- a/src/core/network/api/modules/comments/api.ts +++ b/src/core/network/api/modules/comments/api.ts @@ -54,7 +54,10 @@ export class CommentsApi extends BaseApi { }); } - /** Π Π΅Π΄Π°ΠΊΡ‚ΠΈΡ€ΡƒΠ΅Ρ‚ ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΉ ΠΊ посту. */ + /** + * Π Π΅Π΄Π°ΠΊΡ‚ΠΈΡ€ΡƒΠ΅Ρ‚ ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠΉ ΠΊ посту Π² Ρ‚Π΅Ρ‡Π΅Π½ΠΈΠ΅ 26 часов послС ΠΏΡƒΠ±Π»ΠΈΠΊΠ°Ρ†ΠΈΠΈ. + * ПослС этого API Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ HTTP 422 с ΠΊΠΎΠ΄ΠΎΠΌ `comments.timeout_exceeded`. + */ async edit({ message_id, comment_id, diff --git a/src/core/network/api/modules/comments/types.ts b/src/core/network/api/modules/comments/types.ts index 60b21df..3fddbb1 100644 --- a/src/core/network/api/modules/comments/types.ts +++ b/src/core/network/api/modules/comments/types.ts @@ -86,7 +86,7 @@ export type SendCommentResponse = { message: CommentMessage; }; -/** DTO рСдактирования коммСнтария ΠΊ посту. */ +/** DTO рСдактирования коммСнтария ΠΊ посту Π² Ρ‚Π΅Ρ‡Π΅Π½ΠΈΠ΅ 26 часов послС ΠΏΡƒΠ±Π»ΠΈΠΊΠ°Ρ†ΠΈΠΈ. */ export type EditCommentDTO = { path: CommentPath; query: { diff --git a/src/core/network/api/types/subcription.ts b/src/core/network/api/types/subcription.ts index ee6efce..e36e5ee 100644 --- a/src/core/network/api/types/subcription.ts +++ b/src/core/network/api/types/subcription.ts @@ -1,4 +1,4 @@ -import type { Chat } from './chat'; +import type { Chat, ChatAdminPermission } from './chat'; import type { ConstructedMessage, Message } from './message'; import type { User, UserLocale, UserWithPhoto } from './user'; @@ -99,6 +99,25 @@ export type CommentRemovedUpdate = MakeUpdate< } >; +/** ИзмСнСниС ΠΏΡ€Π°Π² Π±ΠΎΡ‚Π°-администратора; ΠΏΠΎ схСмС доступно Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Ρ‡Π΅Ρ€Π΅Π· webhook. */ +export type BotAdminPermissionsChangedUpdate = MakeUpdate< + 'bot_admin_permissions_changed', + { + /** ID Π³Ρ€ΡƒΠΏΠΏΠΎΠ²ΠΎΠ³ΠΎ Ρ‡Π°Ρ‚Π° ΠΈΠ»ΠΈ ΠΊΠ°Π½Π°Π»Π°. */ + chat_id: number; + /** ID ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ ΠΈΠ»ΠΈ Π±ΠΎΡ‚Π°, измСнившСго ΠΏΡ€Π°Π²Π°. */ + user_id: number; + /** ID Π±ΠΎΡ‚Π°, Ρ‡ΡŒΠΈ ΠΏΡ€Π°Π²Π° измСнились. */ + bot_id: number; + /** `true`, Ссли событиС ΠΏΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»ΠΎ Π² ΠΊΠ°Π½Π°Π»Π΅. */ + is_channel: boolean; + /** ЯвляСтся Π»ΠΈ Π±ΠΎΡ‚ администратором. */ + is_admin: boolean; + /** ΠžΠ±Π½ΠΎΠ²Π»Ρ‘Π½Π½Ρ‹Π΅ ΠΏΡ€Π°Π²Π° Π±ΠΎΡ‚Π°-администратора. */ + permissions?: ChatAdminPermission[] | null; + } +>; + /** Update добавлСния Π±ΠΎΡ‚Π° Π² Π³Ρ€ΡƒΠΏΠΏΠΎΠ²ΠΎΠΉ Ρ‡Π°Ρ‚ ΠΈΠ»ΠΈ ΠΊΠ°Π½Π°Π». */ export type BotAddedUpdate = MakeUpdate< 'bot_added', @@ -346,10 +365,13 @@ export type FilteredUpdate = ? MessageConstructedUpdate : Type extends 'message_chat_created' ? MessageChatCreatedUpdate - : never; + : Type extends 'bot_admin_permissions_changed' + ? BotAdminPermissionsChangedUpdate + : never; /** Update Bot API, Π²ΠΊΠ»ΡŽΡ‡Π°Ρ legacy-события для ΠΎΠ±Ρ€Π°Ρ‚Π½ΠΎΠΉ совмСстимости. */ export type Update = + | BotAdminPermissionsChangedUpdate | MessageCallbackUpdate | MessageCreatedUpdate | MessageRemovedUpdate diff --git a/src/session/session-manager.test.ts b/src/session/session-manager.test.ts index b98a0d1..87cf4aa 100644 --- a/src/session/session-manager.test.ts +++ b/src/session/session-manager.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; +import { Composer } from '../core/composer'; import { Context } from '../core/context'; import type { MiddlewareFn, NextFn } from '../core/middleware'; import type { BotStoppedUpdate } from '../core/network/api'; @@ -45,6 +46,41 @@ const runMiddleware = ( ) => (manager.middleware as MiddlewareFn)(context, next); describe('SessionManager', () => { + it('сохраняСт измСнСния послС ΠΎΡ‚Π»ΠΎΠΆΠ΅Π½Π½ΠΎΠ³ΠΎ middleware с Π²Ρ‹Π·ΠΎΠ²ΠΎΠΌ next Π±Π΅Π· await', async () => { + const storage = createStorage(); + const manager = new SessionManager({ storage }); + const context = createContext(); + let release: () => void = () => undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const started = vi.fn(); + const composer = new Composer(); + composer.use(manager.middleware); + composer.use((_ctx, next) => { + void next(); + }); + composer.use(async (ctx) => { + started(); + await gate; + ctx.session.visits = 2; + }); + + const completed = vi.fn(); + const running = Promise.resolve( + composer.middleware()(context, async () => undefined), + ).then(completed); + await vi.waitFor(() => expect(started).toHaveBeenCalledOnce()); + await new Promise((resolve) => setTimeout(resolve, 0)); + const completedBeforeRelease = completed.mock.calls.length > 0; + release(); + await running; + + expect(completedBeforeRelease).toBe(false); + expect(storage.set).toHaveBeenCalledWith('max-io:42:7', { visits: 2 }); + expect(storage.touch).not.toHaveBeenCalled(); + }); + it('Π·Π°Π³Ρ€ΡƒΠΆΠ°Π΅Ρ‚ сСссию, сохраняСт ΠΈΠ·ΠΌΠ΅Π½Ρ‘Π½Π½Ρ‹Π΅ поля ΠΈ Π½Π΅ сохраняСт слуТСбный ΠΌΠ΅Ρ‚ΠΎΠ΄', async () => { const storage = createStorage(); vi.mocked(storage.get).mockResolvedValue({ visits: 1 });