diff --git a/.eslintignore b/.eslintignore index 8c40401b..a65ab06f 100644 --- a/.eslintignore +++ b/.eslintignore @@ -2,3 +2,11 @@ private/ docs/ dist/ scripts/ + +packages/tl/errors.js +packages/tl/errors.d.ts +packages/tl/index.js +packages/tl/index.d.ts +packages/tl/binary/reader.js +packages/tl/binary/writer.js +packages/tl/binary/rsa-keys.js diff --git a/package.json b/package.json index 0ad18861..8932bd1e 100644 --- a/package.json +++ b/package.json @@ -6,13 +6,10 @@ "license": "MIT", "author": "Alisa Sireneva ", "scripts": { - "test": "tsc && mocha dist/tests/**/*.spec.js", - "build": "tsc", + "test": "lerna run test", + "build": "lerna run build", "lint": "eslint packages/**/*.ts", - "generate-schema": "node scripts/generate-schema.js", - "generate-code": "node packages/client/scripts/generate-client.js && node scripts/generate-types.js && node scripts/generate-binary-reader.js && node scripts/generate-binary-writer.js && node scripts/post-build.js", - "generate-all": "npm run generate-schema && npm run generate-code", - "build:doc": "node packages/client/scripts/generate-client.js && typedoc" + "format": "prettier --write packages/**/*.ts" }, "dependencies": { "big-integer": "1.6.48", diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 9a2eb20d..56763ff9 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -164,7 +164,6 @@ import { Dialog, FileDownloadParameters, GameHighScore, - InputChatPermissions, InputFileLike, InputInlineResult, InputMediaLike, @@ -1444,6 +1443,7 @@ export interface TelegramClient extends BaseTelegramClient { * > into memory at once. This might cause an issue, so use wisely! * * @param params File download parameters + */ downloadAsBuffer(params: FileDownloadParameters): Promise /** @@ -1452,6 +1452,7 @@ export interface TelegramClient extends BaseTelegramClient { * * @param filename Local file name to which the remote file will be downloaded * @param params File download parameters + */ downloadToFile( filename: string, @@ -1463,6 +1464,7 @@ export interface TelegramClient extends BaseTelegramClient { * consecutive. * * @param params Download parameters + */ downloadAsIterable( params: FileDownloadParameters @@ -1472,6 +1474,7 @@ export interface TelegramClient extends BaseTelegramClient { * streaming file contents. * * @param params File download parameters + */ downloadAsStream(params: FileDownloadParameters): Readable /** diff --git a/packages/client/src/methods/.eslintrc.js b/packages/client/src/methods/.eslintrc.js new file mode 100644 index 00000000..dda846f8 --- /dev/null +++ b/packages/client/src/methods/.eslintrc.js @@ -0,0 +1,6 @@ +module.exports = { + rules: { + // common when using preprocessor directives + '@typescript-eslint/no-unused-vars': 'off', + } +} diff --git a/packages/client/src/methods/_imports.ts b/packages/client/src/methods/_imports.ts index 06eb168e..c47dfcaa 100644 --- a/packages/client/src/methods/_imports.ts +++ b/packages/client/src/methods/_imports.ts @@ -13,7 +13,6 @@ import { ChatPreview, ChatMember, Dialog, - InputChatPermissions, TermsOfService, SentCode, MaybeDynamic, diff --git a/packages/client/src/methods/bots/answer-callback-query.ts b/packages/client/src/methods/bots/answer-callback-query.ts index 57f4d5cd..2d760a78 100644 --- a/packages/client/src/methods/bots/answer-callback-query.ts +++ b/packages/client/src/methods/bots/answer-callback-query.ts @@ -55,6 +55,6 @@ export async function answerCallbackQuery( cacheTime: params.cacheTime ?? 0, alert: params.alert, message: params.text, - url: params.url + url: params.url, }) } diff --git a/packages/client/src/methods/bots/answer-inline-query.ts b/packages/client/src/methods/bots/answer-inline-query.ts index 2cc6da70..c7284804 100644 --- a/packages/client/src/methods/bots/answer-inline-query.ts +++ b/packages/client/src/methods/bots/answer-inline-query.ts @@ -93,7 +93,9 @@ export async function answerInlineQuery( ): Promise { if (!params) params = {} - const tlResults = await Promise.all(results.map(it => BotInline._convertToTl(this, it, params!.parseMode))) + const tlResults = await Promise.all( + results.map((it) => BotInline._convertToTl(this, it, params!.parseMode)) + ) await this.call({ _: 'messages.setInlineBotResults', @@ -103,10 +105,12 @@ export async function answerInlineQuery( gallery: params.gallery, private: params.private, nextOffset: params.nextOffset, - switchPm: params.switchPm ? { - _: 'inlineBotSwitchPM', - text: params.switchPm.text, - startParam: params.switchPm.parameter - } : undefined + switchPm: params.switchPm + ? { + _: 'inlineBotSwitchPM', + text: params.switchPm.text, + startParam: params.switchPm.parameter, + } + : undefined, }) } diff --git a/packages/client/src/methods/chats/add-chat-members.ts b/packages/client/src/methods/chats/add-chat-members.ts index 9ef9dae8..f82a817a 100644 --- a/packages/client/src/methods/chats/add-chat-members.ts +++ b/packages/client/src/methods/chats/add-chat-members.ts @@ -45,7 +45,7 @@ export async function addChatMembers( const updates = await this.call({ _: 'channels.inviteToChannel', channel: normalizeToInputChannel(chat), - users: await this.resolvePeerMany( + users: await this.resolvePeerMany( users as InputPeerLike[], normalizeToInputUser ), diff --git a/packages/client/src/methods/chats/archive-chats.ts b/packages/client/src/methods/chats/archive-chats.ts index 7247c168..b6746fb3 100644 --- a/packages/client/src/methods/chats/archive-chats.ts +++ b/packages/client/src/methods/chats/archive-chats.ts @@ -21,13 +21,13 @@ export async function archiveChats( folderPeers.push({ _: 'inputFolderPeer', peer: await this.resolvePeer(chat), - folderId: 1 + folderId: 1, }) } const updates = await this.call({ _: 'folders.editPeerFolders', - folderPeers + folderPeers, }) this._handleUpdate(updates) } diff --git a/packages/client/src/methods/chats/create-group.ts b/packages/client/src/methods/chats/create-group.ts index 287d51ae..73bdd7a7 100644 --- a/packages/client/src/methods/chats/create-group.ts +++ b/packages/client/src/methods/chats/create-group.ts @@ -24,7 +24,7 @@ export async function createGroup( ): Promise { if (!Array.isArray(users)) users = [users] - const peers = await this.resolvePeerMany( + const peers = await this.resolvePeerMany( users as InputPeerLike[], normalizeToInputUser ) @@ -32,7 +32,7 @@ export async function createGroup( const res = await this.call({ _: 'messages.createChat', title, - users: peers + users: peers, }) assertIsUpdatesGroup('messages.createChat', res) diff --git a/packages/client/src/methods/chats/create-supergroup.ts b/packages/client/src/methods/chats/create-supergroup.ts index 3ab88fa1..4aa9cdec 100644 --- a/packages/client/src/methods/chats/create-supergroup.ts +++ b/packages/client/src/methods/chats/create-supergroup.ts @@ -18,7 +18,7 @@ export async function createSupergroup( _: 'channels.createChannel', title, about: description, - megagroup: true + megagroup: true, }) assertIsUpdatesGroup('channels.createChannel', res) diff --git a/packages/client/src/methods/chats/delete-channel.ts b/packages/client/src/methods/chats/delete-channel.ts index 519ec5cd..2d8b34d7 100644 --- a/packages/client/src/methods/chats/delete-channel.ts +++ b/packages/client/src/methods/chats/delete-channel.ts @@ -9,13 +9,16 @@ import { normalizeToInputChannel } from '../../utils/peer-utils' * @param chatId Chat ID or username * @internal */ -export async function deleteChannel(this: TelegramClient, chatId: InputPeerLike): Promise { +export async function deleteChannel( + this: TelegramClient, + chatId: InputPeerLike +): Promise { const peer = normalizeToInputChannel(await this.resolvePeer(chatId)) if (!peer) throw new MtCuteInvalidPeerTypeError(chatId, 'channel') const res = await this.call({ _: 'channels.deleteChannel', - channel: peer + channel: peer, }) this._handleUpdate(res) } diff --git a/packages/client/src/methods/chats/delete-history.ts b/packages/client/src/methods/chats/delete-history.ts index b9a7abf8..5769f3f5 100644 --- a/packages/client/src/methods/chats/delete-history.ts +++ b/packages/client/src/methods/chats/delete-history.ts @@ -32,12 +32,18 @@ export async function deleteHistory( justClear: mode === 'clear', revoke: mode === 'revoke', peer, - maxId + maxId, }) const channel = normalizeToInputChannel(peer) if (channel) { - this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount, (channel as tl.RawInputChannel).channelId)) + this._handleUpdate( + createDummyUpdate( + res.pts, + res.ptsCount, + (channel as tl.RawInputChannel).channelId + ) + ) } else { this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount)) } diff --git a/packages/client/src/methods/chats/edit-admin-rights.ts b/packages/client/src/methods/chats/edit-admin-rights.ts index d2ef046f..a71553dc 100644 --- a/packages/client/src/methods/chats/edit-admin-rights.ts +++ b/packages/client/src/methods/chats/edit-admin-rights.ts @@ -1,7 +1,10 @@ import { TelegramClient } from '../../client' import { InputPeerLike, MtCuteInvalidPeerTypeError } from '../../types' import { tl } from '@mtcute/tl' -import { normalizeToInputChannel, normalizeToInputUser } from '../../utils/peer-utils' +import { + normalizeToInputChannel, + normalizeToInputUser, +} from '../../utils/peer-utils' /** * Edit supergroup/channel admin rights of a user. @@ -20,12 +23,10 @@ export async function editAdminRights( rank = '' ): Promise { const chat = normalizeToInputChannel(await this.resolvePeer(chatId)) - if (!chat) - throw new MtCuteInvalidPeerTypeError(chatId, 'channel') + if (!chat) throw new MtCuteInvalidPeerTypeError(chatId, 'channel') const user = normalizeToInputUser(await this.resolvePeer(userId)) - if (!user) - throw new MtCuteInvalidPeerTypeError(userId, 'user') + if (!user) throw new MtCuteInvalidPeerTypeError(userId, 'user') const res = await this.call({ _: 'channels.editAdmin', @@ -33,9 +34,9 @@ export async function editAdminRights( userId: user, adminRights: { _: 'chatAdminRights', - ...rights + ...rights, }, - rank + rank, }) this._handleUpdate(res) diff --git a/packages/client/src/methods/chats/get-chat-event-log.ts b/packages/client/src/methods/chats/get-chat-event-log.ts index 1fdedc5c..effda608 100644 --- a/packages/client/src/methods/chats/get-chat-event-log.ts +++ b/packages/client/src/methods/chats/get-chat-event-log.ts @@ -97,10 +97,7 @@ export async function* getChatEventLog( const chunkSize = Math.min(params.chunkSize ?? 100, total) const admins: tl.TypeInputUser[] | undefined = params.users - ? await this.resolvePeerMany( - params.users, - normalizeToInputUser - ) + ? await this.resolvePeerMany(params.users, normalizeToInputUser) : undefined let serverFilter: diff --git a/packages/client/src/methods/chats/get-chat-preview.ts b/packages/client/src/methods/chats/get-chat-preview.ts index 01b66997..0344abfb 100644 --- a/packages/client/src/methods/chats/get-chat-preview.ts +++ b/packages/client/src/methods/chats/get-chat-preview.ts @@ -26,9 +26,7 @@ export async function getChatPreview( }) if (res._ !== 'chatInvite') { - throw new MtCuteNotFoundError( - `You have already joined this chat!` - ) + throw new MtCuteNotFoundError(`You have already joined this chat!`) } return new ChatPreview(this, res, inviteLink) diff --git a/packages/client/src/methods/chats/get-nearby-chats.ts b/packages/client/src/methods/chats/get-nearby-chats.ts index 4255a640..0c849fc5 100644 --- a/packages/client/src/methods/chats/get-nearby-chats.ts +++ b/packages/client/src/methods/chats/get-nearby-chats.ts @@ -31,19 +31,23 @@ export async function getNearbyChats( if (!res.updates.length) return [] - assertTypeIs('contacts.getLocated (@ .updates[0])', res.updates[0], 'updatePeerLocated') + assertTypeIs( + 'contacts.getLocated (@ .updates[0])', + res.updates[0], + 'updatePeerLocated' + ) const chats = res.chats.map((it) => new Chat(this, it)) const index: Record = {} - chats.forEach((c) => index[c.id] = c) + chats.forEach((c) => (index[c.id] = c)) res.updates[0].peers.forEach((peer) => { if (peer._ === 'peerSelfLocated') return const id = getMarkedPeerId(peer.peer) if (index[id]) { - (index[id] as tl.Mutable).distance = peer.distance + ;(index[id] as tl.Mutable).distance = peer.distance } }) diff --git a/packages/client/src/methods/chats/iter-chat-members.ts b/packages/client/src/methods/chats/iter-chat-members.ts index a80783c2..2536939b 100644 --- a/packages/client/src/methods/chats/iter-chat-members.ts +++ b/packages/client/src/methods/chats/iter-chat-members.ts @@ -41,7 +41,7 @@ export async function* iterChatMembers( offset, limit, query: params.query, - type: params.type + type: params.type, }) if (!members.length) break diff --git a/packages/client/src/methods/chats/mark-chat-unread.ts b/packages/client/src/methods/chats/mark-chat-unread.ts index 6fd778a8..72431276 100644 --- a/packages/client/src/methods/chats/mark-chat-unread.ts +++ b/packages/client/src/methods/chats/mark-chat-unread.ts @@ -17,6 +17,6 @@ export async function markChatUnread( _: 'inputDialogPeer', peer: await this.resolvePeer(chatId), }, - unread: true + unread: true, }) } diff --git a/packages/client/src/methods/chats/save-draft.ts b/packages/client/src/methods/chats/save-draft.ts index e412be08..5c253775 100644 --- a/packages/client/src/methods/chats/save-draft.ts +++ b/packages/client/src/methods/chats/save-draft.ts @@ -20,13 +20,13 @@ export async function saveDraft( await this.call({ _: 'messages.saveDraft', peer, - ...draft + ...draft, }) } else { await this.call({ _: 'messages.saveDraft', peer, - message: '' + message: '', }) } } diff --git a/packages/client/src/methods/chats/set-chat-default-permissions.ts b/packages/client/src/methods/chats/set-chat-default-permissions.ts index 8e5a0b84..b69930a4 100644 --- a/packages/client/src/methods/chats/set-chat-default-permissions.ts +++ b/packages/client/src/methods/chats/set-chat-default-permissions.ts @@ -29,8 +29,8 @@ export async function setChatDefaultPermissions( bannedRights: { _: 'chatBannedRights', untilDate: 0, - ...restrictions - } + ...restrictions, + }, }) assertIsUpdatesGroup('messages.editChatDefaultBannedRights', res) diff --git a/packages/client/src/methods/chats/set-chat-title.ts b/packages/client/src/methods/chats/set-chat-title.ts index 4366fb23..084eb229 100644 --- a/packages/client/src/methods/chats/set-chat-title.ts +++ b/packages/client/src/methods/chats/set-chat-title.ts @@ -1,8 +1,5 @@ import { TelegramClient } from '../../client' -import { - InputPeerLike, - MtCuteInvalidPeerTypeError, -} from '../../types' +import { InputPeerLike, MtCuteInvalidPeerTypeError } from '../../types' import { isInputPeerChannel, isInputPeerChat, @@ -30,13 +27,13 @@ export async function setChatTitle( res = await this.call({ _: 'messages.editChatTitle', chatId: chat.chatId, - title + title, }) } else if (isInputPeerChannel(chat)) { res = await this.call({ _: 'channels.editTitle', channel: normalizeToInputChannel(chat), - title + title, }) } else throw new MtCuteInvalidPeerTypeError(chatId, 'chat or channel') diff --git a/packages/client/src/methods/chats/set-chat-username.ts b/packages/client/src/methods/chats/set-chat-username.ts index 36c7267e..b4f63095 100644 --- a/packages/client/src/methods/chats/set-chat-username.ts +++ b/packages/client/src/methods/chats/set-chat-username.ts @@ -1,8 +1,5 @@ import { TelegramClient } from '../../client' -import { - InputPeerLike, - MtCuteInvalidPeerTypeError, -} from '../../types' +import { InputPeerLike, MtCuteInvalidPeerTypeError } from '../../types' import { normalizeToInputChannel } from '../../utils/peer-utils' /** @@ -20,12 +17,11 @@ export async function setChatUsername( username: string | null ): Promise { const chat = normalizeToInputChannel(await this.resolvePeer(chatId)) - if (!chat) - throw new MtCuteInvalidPeerTypeError(chatId, 'channel') + if (!chat) throw new MtCuteInvalidPeerTypeError(chatId, 'channel') await this.call({ _: 'channels.updateUsername', channel: chat, - username: username || '' + username: username || '', }) } diff --git a/packages/client/src/methods/chats/set-slow-mode.ts b/packages/client/src/methods/chats/set-slow-mode.ts index 135d628c..7fcce869 100644 --- a/packages/client/src/methods/chats/set-slow-mode.ts +++ b/packages/client/src/methods/chats/set-slow-mode.ts @@ -23,7 +23,7 @@ export async function setSlowMode( const res = await this.call({ _: 'channels.toggleSlowMode', channel: chat, - seconds + seconds, }) this._handleUpdate(res) } diff --git a/packages/client/src/methods/chats/unarchive-chats.ts b/packages/client/src/methods/chats/unarchive-chats.ts index 62c95c84..051bc07c 100644 --- a/packages/client/src/methods/chats/unarchive-chats.ts +++ b/packages/client/src/methods/chats/unarchive-chats.ts @@ -21,13 +21,13 @@ export async function unarchiveChats( folderPeers.push({ _: 'inputFolderPeer', peer: await this.resolvePeer(chat), - folderId: 0 + folderId: 0, }) } const res = await this.call({ _: 'folders.editPeerFolders', - folderPeers + folderPeers, }) this._handleUpdate(res) } diff --git a/packages/client/src/methods/contacts/add-contact.ts b/packages/client/src/methods/contacts/add-contact.ts index ccc32b5f..d3003273 100644 --- a/packages/client/src/methods/contacts/add-contact.ts +++ b/packages/client/src/methods/contacts/add-contact.ts @@ -1,5 +1,10 @@ import { TelegramClient } from '../../client' -import { InputPeerLike, MtCuteInvalidPeerTypeError, MtCuteTypeAssertionError, User } from '../../types' +import { + InputPeerLike, + MtCuteInvalidPeerTypeError, + MtCuteTypeAssertionError, + User, +} from '../../types' import { normalizeToInputUser } from '../../utils/peer-utils' import { tl } from '@mtcute/tl' import { assertIsUpdatesGroup } from '../../utils/updates-utils' @@ -46,7 +51,7 @@ export async function addContact( firstName: params.firstName, lastName: params.lastName ?? '', phone: params.phone ?? '', - addPhonePrivacyException: !!params.sharePhone + addPhonePrivacyException: !!params.sharePhone, }) assertIsUpdatesGroup('contacts.addContact', res) diff --git a/packages/client/src/methods/contacts/delete-contacts.ts b/packages/client/src/methods/contacts/delete-contacts.ts index 67ecea16..b8c57d79 100644 --- a/packages/client/src/methods/contacts/delete-contacts.ts +++ b/packages/client/src/methods/contacts/delete-contacts.ts @@ -1,6 +1,11 @@ import { TelegramClient } from '../../client' import { MaybeArray } from '@mtcute/core' -import { InputPeerLike, MtCuteInvalidPeerTypeError, MtCuteTypeAssertionError, User } from '../../types' +import { + InputPeerLike, + MtCuteInvalidPeerTypeError, + MtCuteTypeAssertionError, + User, +} from '../../types' import { normalizeToInputUser } from '../../utils/peer-utils' import { tl } from '@mtcute/tl' import { assertIsUpdatesGroup } from '../../utils/updates-utils' @@ -41,7 +46,7 @@ export async function deleteContacts( const single = !Array.isArray(userIds) if (single) userIds = [userIds as InputPeerLike] - const inputPeers = await this.resolvePeerMany( + const inputPeers = await this.resolvePeerMany( userIds as InputPeerLike[], normalizeToInputUser ) @@ -54,7 +59,7 @@ export async function deleteContacts( const res = await this.call({ _: 'contacts.deleteContacts', - id: inputPeers + id: inputPeers, }) assertIsUpdatesGroup('contacts.deleteContacts', res) @@ -63,7 +68,7 @@ export async function deleteContacts( this._handleUpdate(res) - const users = res.users.map(user => new User(this, user)) + const users = res.users.map((user) => new User(this, user)) return single ? users[0] : users } diff --git a/packages/client/src/methods/contacts/get-contacts.ts b/packages/client/src/methods/contacts/get-contacts.ts index 6a632520..4dc2fde1 100644 --- a/packages/client/src/methods/contacts/get-contacts.ts +++ b/packages/client/src/methods/contacts/get-contacts.ts @@ -7,12 +7,10 @@ import { tl } from '@mtcute/tl' * Get list of contacts from your Telegram contacts list. * @internal */ -export async function getContacts( - this: TelegramClient -): Promise { +export async function getContacts(this: TelegramClient): Promise { const res = await this.call({ _: 'contacts.getContacts', - hash: 0 + hash: 0, }) assertTypeIs('getContacts', res, 'contacts.contacts') diff --git a/packages/client/src/methods/dialogs/create-folder.ts b/packages/client/src/methods/dialogs/create-folder.ts index 5edf48b7..c57fe7c1 100644 --- a/packages/client/src/methods/dialogs/create-folder.ts +++ b/packages/client/src/methods/dialogs/create-folder.ts @@ -36,13 +36,13 @@ export async function createFolder( includePeers: [], excludePeers: [], ...folder, - id + id, } await this.call({ _: 'messages.updateDialogFilter', id, - filter + filter, }) return filter diff --git a/packages/client/src/methods/dialogs/edit-folder.ts b/packages/client/src/methods/dialogs/edit-folder.ts index 6c175661..b6209eba 100644 --- a/packages/client/src/methods/dialogs/edit-folder.ts +++ b/packages/client/src/methods/dialogs/edit-folder.ts @@ -21,21 +21,22 @@ export async function editFolder( ): Promise { if (typeof folder === 'number' || typeof folder === 'string') { const old = await this.getFolders() - const found = old.find(it => it.id === folder || it.title === folder) - if (!found) throw new MtCuteArgumentError(`Could not find a folder ${folder}`) + const found = old.find((it) => it.id === folder || it.title === folder) + if (!found) + throw new MtCuteArgumentError(`Could not find a folder ${folder}`) folder = found } const filter: tl.RawDialogFilter = { ...folder, - ...modification + ...modification, } await this.call({ _: 'messages.updateDialogFilter', id: folder.id, - filter + filter, }) return filter diff --git a/packages/client/src/methods/dialogs/find-folder.ts b/packages/client/src/methods/dialogs/find-folder.ts index adc85b4b..51dec998 100644 --- a/packages/client/src/methods/dialogs/find-folder.ts +++ b/packages/client/src/methods/dialogs/find-folder.ts @@ -25,11 +25,13 @@ export async function findFolder( const folders = await this.getFolders() - return folders.find((it) => { - if (params.id && it.id !== params.id) return false - if (params.title && it.title !== params.title) return false - if (params.emoji && it.emoticon !== params.emoji) return false + return ( + folders.find((it) => { + if (params.id && it.id !== params.id) return false + if (params.title && it.title !== params.title) return false + if (params.emoji && it.emoticon !== params.emoji) return false - return true - }) ?? null + return true + }) ?? null + ) } diff --git a/packages/client/src/methods/dialogs/get-dialogs.ts b/packages/client/src/methods/dialogs/get-dialogs.ts index a1aef1f0..39d7a948 100644 --- a/packages/client/src/methods/dialogs/get-dialogs.ts +++ b/packages/client/src/methods/dialogs/get-dialogs.ts @@ -132,7 +132,9 @@ export async function* getDialogs( (it) => it.id === params!.folder || it.title === params!.folder ) if (!found) - throw new MtCuteArgumentError(`Could not find folder ${params.folder}`) + throw new MtCuteArgumentError( + `Could not find folder ${params.folder}` + ) filters = found } else { @@ -143,7 +145,7 @@ export async function* getDialogs( if (filters) { filters = { ...filters, - ...params.filter + ...params.filter, } } else { filters = { @@ -153,7 +155,7 @@ export async function* getDialogs( pinnedPeers: [], includePeers: [], excludePeers: [], - ...params.filter + ...params.filter, } } } @@ -164,11 +166,13 @@ export async function* getDialogs( _: 'messages.getPeerDialogs', peers: filters.pinnedPeers.map((peer) => ({ _: 'inputDialogPeer', - peer - })) + peer, + })), }) - res.dialogs.forEach((dialog: tl.Mutable) => dialog.pinned = true) + res.dialogs.forEach( + (dialog: tl.Mutable) => (dialog.pinned = true) + ) return res } @@ -243,11 +247,11 @@ export async function* getDialogs( } const filterFolder = filters - // if pinned is `only`, this wouldn't be reached - // if pinned is `exclude`, we want to exclude them - // if pinned is `include`, we already yielded them, so we also want to exclude them - // if pinned is `keep`, we want to keep them - ? Dialog.filterFolder(filters, pinned !== 'keep') + ? // if pinned is `only`, this wouldn't be reached + // if pinned is `exclude`, we want to exclude them + // if pinned is `include`, we already yielded them, so we also want to exclude them + // if pinned is `keep`, we want to keep them + Dialog.filterFolder(filters, pinned !== 'keep') : undefined const folderId = diff --git a/packages/client/src/methods/dialogs/get-folders.ts b/packages/client/src/methods/dialogs/get-folders.ts index 9054ee83..b2157aa3 100644 --- a/packages/client/src/methods/dialogs/get-folders.ts +++ b/packages/client/src/methods/dialogs/get-folders.ts @@ -5,8 +5,10 @@ import { tl } from '@mtcute/tl' * Get list of folders. * @internal */ -export async function getFolders(this: TelegramClient): Promise { +export async function getFolders( + this: TelegramClient +): Promise { return this.call({ - _: 'messages.getDialogFilters' + _: 'messages.getDialogFilters', }) } diff --git a/packages/client/src/methods/files/download-iterable.ts b/packages/client/src/methods/files/download-iterable.ts index e8fd288f..2aa7bf4d 100644 --- a/packages/client/src/methods/files/download-iterable.ts +++ b/packages/client/src/methods/files/download-iterable.ts @@ -8,7 +8,11 @@ import { FileDownloadParameters, FileLocation, } from '../../types' -import { fileIdToInputFileLocation, fileIdToInputWebFileLocation, parseFileId } from '@mtcute/file-id' +import { + fileIdToInputFileLocation, + fileIdToInputWebFileLocation, + parseFileId, +} from '@mtcute/file-id' /** * Download a file and return it as an iterable, which yields file contents @@ -84,14 +88,19 @@ export async function* downloadAsIterable( } const requestCurrent = async (): Promise => { - let result: tl.RpcCallReturn['upload.getFile'] | tl.RpcCallReturn['upload.getWebFile'] + let result: + | tl.RpcCallReturn['upload.getFile'] + | tl.RpcCallReturn['upload.getWebFile'] try { - result = await this.call({ - _: isWeb ? 'upload.getWebFile' : 'upload.getFile', - location: location as any, - offset, - limit: chunkSize - }, { connection }) + result = await this.call( + { + _: isWeb ? 'upload.getWebFile' : 'upload.getFile', + location: location as any, + offset, + limit: chunkSize, + }, + { connection } + ) } catch (e) { if (e.constructor === FileMigrateError) { connection = this._downloadConnections[e.newDc] @@ -116,7 +125,11 @@ export async function* downloadAsIterable( ) } - if (result._ === 'upload.webFile' && result.size && limit === Infinity) { + if ( + result._ === 'upload.webFile' && + result.size && + limit === Infinity + ) { limit = result.size } diff --git a/packages/client/src/methods/files/normalize-file-to-document.ts b/packages/client/src/methods/files/normalize-file-to-document.ts index 6260853e..44084941 100644 --- a/packages/client/src/methods/files/normalize-file-to-document.ts +++ b/packages/client/src/methods/files/normalize-file-to-document.ts @@ -11,16 +11,20 @@ export async function _normalizeFileToDocument( file: InputFileLike | tl.TypeInputDocument, params: { progressCallback?: (uploaded: number, total: number) => void - }, + } ): Promise { if (typeof file === 'object' && tl.isAnyInputDocument(file)) { return file } - const media = await this._normalizeInputMedia({ - type: 'document', - file, - }, params, true) + const media = await this._normalizeInputMedia( + { + type: 'document', + file, + }, + params, + true + ) assertTypeIs('createStickerSet', media, 'inputMediaDocument') assertTypeIs('createStickerSet', media.id, 'inputDocument') diff --git a/packages/client/src/methods/files/upload-file.ts b/packages/client/src/methods/files/upload-file.ts index cfe96eac..ffa2d795 100644 --- a/packages/client/src/methods/files/upload-file.ts +++ b/packages/client/src/methods/files/upload-file.ts @@ -24,7 +24,7 @@ const debug = require('debug')('mtcute:upload') const OVERRIDE_MIME: Record = { // tg doesn't interpret `audio/opus` files as voice messages for some reason - 'audio/opus': 'audio/ogg' + 'audio/opus': 'audio/ogg', } /** diff --git a/packages/client/src/methods/invite-links/create-invite-link.ts b/packages/client/src/methods/invite-links/create-invite-link.ts index c97e10f5..bf7fae14 100644 --- a/packages/client/src/methods/invite-links/create-invite-link.ts +++ b/packages/client/src/methods/invite-links/create-invite-link.ts @@ -36,7 +36,7 @@ export async function createInviteLink( _: 'messages.exportChatInvite', peer: await this.resolvePeer(chatId), expireDate: normalizeDate(params.expires), - usageLimit: params.usageLimit + usageLimit: params.usageLimit, }) return new ChatInviteLink(this, res) diff --git a/packages/client/src/methods/invite-links/edit-invite-link.ts b/packages/client/src/methods/invite-links/edit-invite-link.ts index f541004b..fc411a7d 100644 --- a/packages/client/src/methods/invite-links/edit-invite-link.ts +++ b/packages/client/src/methods/invite-links/edit-invite-link.ts @@ -40,7 +40,7 @@ export async function editInviteLink( peer: await this.resolvePeer(chatId), link, expireDate: normalizeDate(params.expires), - usageLimit: params.usageLimit + usageLimit: params.usageLimit, }) const { users } = createUsersChatsIndex(res) diff --git a/packages/client/src/methods/invite-links/export-invite-link.ts b/packages/client/src/methods/invite-links/export-invite-link.ts index 2599aec4..13fc5fe0 100644 --- a/packages/client/src/methods/invite-links/export-invite-link.ts +++ b/packages/client/src/methods/invite-links/export-invite-link.ts @@ -18,7 +18,7 @@ export async function exportInviteLink( const res = await this.call({ _: 'messages.exportChatInvite', peer: await this.resolvePeer(chatId), - legacyRevokePermanent: true + legacyRevokePermanent: true, }) return new ChatInviteLink(this, res) diff --git a/packages/client/src/methods/invite-links/get-invite-link-members.ts b/packages/client/src/methods/invite-links/get-invite-link-members.ts index 3c9707b9..dd9bac74 100644 --- a/packages/client/src/methods/invite-links/get-invite-link-members.ts +++ b/packages/client/src/methods/invite-links/get-invite-link-members.ts @@ -27,14 +27,16 @@ export async function* getInviteLinkMembers( for (;;) { // for some reason ts needs annotation, idk - const res: tl.RpcCallReturn['messages.getChatInviteImporters'] = await this.call({ - _: 'messages.getChatInviteImporters', - limit: Math.min(100, limit - current), - peer, - link, - offsetDate, - offsetUser, - }) + const res: tl.RpcCallReturn['messages.getChatInviteImporters'] = await this.call( + { + _: 'messages.getChatInviteImporters', + limit: Math.min(100, limit - current), + peer, + link, + offsetDate, + offsetUser, + } + ) if (!res.importers.length) break @@ -45,7 +47,7 @@ export async function* getInviteLinkMembers( offsetUser = { _: 'inputUser', userId: last.userId, - accessHash: (users[last.userId] as tl.RawUser).accessHash! + accessHash: (users[last.userId] as tl.RawUser).accessHash!, } for (const it of res.importers) { diff --git a/packages/client/src/methods/invite-links/get-invite-link.ts b/packages/client/src/methods/invite-links/get-invite-link.ts index 1004d7fa..4881af9a 100644 --- a/packages/client/src/methods/invite-links/get-invite-link.ts +++ b/packages/client/src/methods/invite-links/get-invite-link.ts @@ -17,7 +17,7 @@ export async function getInviteLink( const res = await this.call({ _: 'messages.getExportedChatInvite', peer: await this.resolvePeer(chatId), - link + link, }) const { users } = createUsersChatsIndex(res) diff --git a/packages/client/src/methods/invite-links/revoke-invite-link.ts b/packages/client/src/methods/invite-links/revoke-invite-link.ts index 347a1788..82422cec 100644 --- a/packages/client/src/methods/invite-links/revoke-invite-link.ts +++ b/packages/client/src/methods/invite-links/revoke-invite-link.ts @@ -22,12 +22,15 @@ export async function revokeInviteLink( _: 'messages.editExportedChatInvite', peer: await this.resolvePeer(chatId), link, - revoked: true + revoked: true, }) const { users } = createUsersChatsIndex(res) - const invite = res._ === 'messages.exportedChatInviteReplaced' ? res.newInvite : res.invite + const invite = + res._ === 'messages.exportedChatInviteReplaced' + ? res.newInvite + : res.invite return new ChatInviteLink(this, invite, users) } diff --git a/packages/client/src/methods/messages/find-in-update.ts b/packages/client/src/methods/messages/find-in-update.ts index 84bf389c..4a080f78 100644 --- a/packages/client/src/methods/messages/find-in-update.ts +++ b/packages/client/src/methods/messages/find-in-update.ts @@ -16,14 +16,13 @@ export function _findMessageInUpdate( for (const u of res.updates) { if ( - isEdit && ( - u._ === 'updateEditMessage' || - u._ === 'updateEditChannelMessage' - ) || !isEdit && ( - u._ === 'updateNewMessage' || - u._ === 'updateNewChannelMessage' || - u._ === 'updateNewScheduledMessage' - ) + (isEdit && + (u._ === 'updateEditMessage' || + u._ === 'updateEditChannelMessage')) || + (!isEdit && + (u._ === 'updateNewMessage' || + u._ === 'updateNewChannelMessage' || + u._ === 'updateNewScheduledMessage')) ) { const { users, chats } = createUsersChatsIndex(res) diff --git a/packages/client/src/methods/messages/forward-messages.ts b/packages/client/src/methods/messages/forward-messages.ts index e39e18ff..b9c795f8 100644 --- a/packages/client/src/methods/messages/forward-messages.ts +++ b/packages/client/src/methods/messages/forward-messages.ts @@ -8,9 +8,7 @@ import { } from '../../types' import { MaybeArray } from '@mtcute/core' import { tl } from '@mtcute/tl' -import { - createUsersChatsIndex, -} from '../../utils/peer-utils' +import { createUsersChatsIndex } from '../../utils/peer-utils' import { normalizeDate, randomUlong } from '../../utils/misc-utils' import { assertIsUpdatesGroup } from '../../utils/updates-utils' diff --git a/packages/client/src/methods/messages/get-discussion-message.ts b/packages/client/src/methods/messages/get-discussion-message.ts index 0bba7393..bb82ad12 100644 --- a/packages/client/src/methods/messages/get-discussion-message.ts +++ b/packages/client/src/methods/messages/get-discussion-message.ts @@ -29,8 +29,8 @@ export async function _getDiscussionMessage( { _: 'inputPeerChannel', channelId: chat.id, - accessHash: chat.accessHash! + accessHash: chat.accessHash!, }, - msg.id + msg.id, ] } diff --git a/packages/client/src/methods/messages/get-history.ts b/packages/client/src/methods/messages/get-history.ts index bfbb2096..234c2f45 100644 --- a/packages/client/src/methods/messages/get-history.ts +++ b/packages/client/src/methods/messages/get-history.ts @@ -1,6 +1,6 @@ import { TelegramClient } from '../../client' import { InputPeerLike, Message, MtCuteTypeAssertionError } from '../../types' -import { createUsersChatsIndex, } from '../../utils/peer-utils' +import { createUsersChatsIndex } from '../../utils/peer-utils' import { normalizeDate } from '../../utils/misc-utils' /** diff --git a/packages/client/src/methods/messages/get-message-group.ts b/packages/client/src/methods/messages/get-message-group.ts index a044f4b5..d2125555 100644 --- a/packages/client/src/methods/messages/get-message-group.ts +++ b/packages/client/src/methods/messages/get-message-group.ts @@ -24,8 +24,7 @@ export async function getMessageGroup( const messages = await this.getMessages(chatId, ids) const groupedId = messages.find((it) => it.id === message)!.groupedId - if (!groupedId) - throw new MtCuteArgumentError('This message is not grouped') + if (!groupedId) throw new MtCuteArgumentError('This message is not grouped') return messages.filter((it) => it.groupedId?.eq(groupedId)) } diff --git a/packages/client/src/methods/messages/normalize-inline.ts b/packages/client/src/methods/messages/normalize-inline.ts index b8a45d93..a1334e98 100644 --- a/packages/client/src/methods/messages/normalize-inline.ts +++ b/packages/client/src/methods/messages/normalize-inline.ts @@ -27,7 +27,7 @@ export async function _normalizeInline( if (!(id.dcId in this._connectionsForInline)) { this._connectionsForInline[ id.dcId - ] = await this.createAdditionalConnection(id.dcId) + ] = await this.createAdditionalConnection(id.dcId) } connection = this._connectionsForInline[id.dcId] } diff --git a/packages/client/src/methods/messages/parse-entities.ts b/packages/client/src/methods/messages/parse-entities.ts index caa3411a..29ea1e25 100644 --- a/packages/client/src/methods/messages/parse-entities.ts +++ b/packages/client/src/methods/messages/parse-entities.ts @@ -21,8 +21,7 @@ export async function _parseEntities( } // either explicitly disabled or no available parser if (!mode) return [text, []] - - ;([text, entities] = await this._parseModes[mode].parse(text)) + ;[text, entities] = await this._parseModes[mode].parse(text) } // replace mentionName entities with input ones diff --git a/packages/client/src/methods/messages/pin-message.ts b/packages/client/src/methods/messages/pin-message.ts index 3aced73e..9a82dbf9 100644 --- a/packages/client/src/methods/messages/pin-message.ts +++ b/packages/client/src/methods/messages/pin-message.ts @@ -25,7 +25,7 @@ export async function pinMessage( peer: await this.resolvePeer(chatId), id: messageId, silent: !notify, - pmOneside: !bothSides + pmOneside: !bothSides, }) this._handleUpdate(res) diff --git a/packages/client/src/methods/messages/send-media-group.ts b/packages/client/src/methods/messages/send-media-group.ts index 26dc1b8b..1b56ee4d 100644 --- a/packages/client/src/methods/messages/send-media-group.ts +++ b/packages/client/src/methods/messages/send-media-group.ts @@ -6,7 +6,11 @@ import { Message, ReplyMarkup, } from '../../types' -import { normalizeDate, normalizeMessageId, randomUlong } from '../../utils/misc-utils' +import { + normalizeDate, + normalizeMessageId, + randomUlong, +} from '../../utils/misc-utils' import { tl } from '@mtcute/tl' import { assertIsUpdatesGroup } from '../../utils/updates-utils' import { createUsersChatsIndex } from '../../utils/peer-utils' @@ -95,7 +99,10 @@ export async function sendMediaGroup( let replyTo = normalizeMessageId(params.replyTo) if (params.commentTo) { - ;[peer, replyTo] = await this._getDiscussionMessage(peer, normalizeMessageId(params.commentTo)!) + ;[peer, replyTo] = await this._getDiscussionMessage( + peer, + normalizeMessageId(params.commentTo)! + ) } const multiMedia: tl.RawInputSingleMedia[] = [] diff --git a/packages/client/src/methods/messages/send-media.ts b/packages/client/src/methods/messages/send-media.ts index 3595ac6a..36261b1e 100644 --- a/packages/client/src/methods/messages/send-media.ts +++ b/packages/client/src/methods/messages/send-media.ts @@ -6,7 +6,11 @@ import { Message, ReplyMarkup, } from '../../types' -import { normalizeDate, normalizeMessageId, randomUlong } from '../../utils/misc-utils' +import { + normalizeDate, + normalizeMessageId, + randomUlong, +} from '../../utils/misc-utils' /** * Send a single media (a photo or a document-based media) @@ -108,7 +112,10 @@ export async function sendMedia( let replyTo = normalizeMessageId(params.replyTo) if (params.commentTo) { - ;[peer, replyTo] = await this._getDiscussionMessage(peer, normalizeMessageId(params.commentTo)!) + ;[peer, replyTo] = await this._getDiscussionMessage( + peer, + normalizeMessageId(params.commentTo)! + ) } const res = await this.call({ diff --git a/packages/client/src/methods/messages/send-text.ts b/packages/client/src/methods/messages/send-text.ts index 4d1fbe63..174f6748 100644 --- a/packages/client/src/methods/messages/send-text.ts +++ b/packages/client/src/methods/messages/send-text.ts @@ -1,7 +1,11 @@ import { TelegramClient } from '../../client' import { tl } from '@mtcute/tl' import { inputPeerToPeer } from '../../utils/peer-utils' -import { normalizeDate, normalizeMessageId, randomUlong } from '../../utils/misc-utils' +import { + normalizeDate, + normalizeMessageId, + randomUlong, +} from '../../utils/misc-utils' import { InputPeerLike, Message, BotKeyboard, ReplyMarkup } from '../../types' /** @@ -91,7 +95,10 @@ export async function sendText( let replyTo = normalizeMessageId(params.replyTo) if (params.commentTo) { - ;[peer, replyTo] = await this._getDiscussionMessage(peer, normalizeMessageId(params.commentTo)!) + ;[peer, replyTo] = await this._getDiscussionMessage( + peer, + normalizeMessageId(params.commentTo)! + ) } const res = await this.call({ diff --git a/packages/client/src/methods/messages/send-typing.ts b/packages/client/src/methods/messages/send-typing.ts index ee717481..c23c3610 100644 --- a/packages/client/src/methods/messages/send-typing.ts +++ b/packages/client/src/methods/messages/send-typing.ts @@ -36,49 +36,49 @@ export async function sendTyping( switch (status) { case 'typing': status = { _: 'sendMessageTypingAction' } - break; + break case 'cancel': status = { _: 'sendMessageCancelAction' } - break; + break case 'record_video': status = { _: 'sendMessageRecordVideoAction' } - break; + break case 'upload_video': status = { _: 'sendMessageUploadVideoAction', progress } - break; + break case 'record_voice': status = { _: 'sendMessageRecordAudioAction' } - break; + break case 'upload_voice': status = { _: 'sendMessageUploadAudioAction', progress } - break; + break case 'upload_photo': status = { _: 'sendMessageUploadPhotoAction', progress } - break; + break case 'upload_document': status = { _: 'sendMessageUploadDocumentAction', progress } - break; + break case 'geo': status = { _: 'sendMessageGeoLocationAction' } - break; + break case 'contact': status = { _: 'sendMessageChooseContactAction' } - break; + break case 'game': status = { _: 'sendMessageGamePlayAction' } - break; + break case 'record_round': status = { _: 'sendMessageRecordRoundAction' } - break; + break case 'upload_round': status = { _: 'sendMessageUploadRoundAction', progress } - break; + break case 'speak_call': status = { _: 'speakingInGroupCallAction' } - break; + break case 'history_import': status = { _: 'sendMessageHistoryImportAction', progress } - break; + break } } @@ -86,6 +86,6 @@ export async function sendTyping( _: 'messages.setTyping', peer: await this.resolvePeer(chatId), action: status, - topMsgId: params?.threadId + topMsgId: params?.threadId, }) } diff --git a/packages/client/src/methods/messages/unpin-all-messages.ts b/packages/client/src/methods/messages/unpin-all-messages.ts index 3ae7b98f..ac7a7737 100644 --- a/packages/client/src/methods/messages/unpin-all-messages.ts +++ b/packages/client/src/methods/messages/unpin-all-messages.ts @@ -17,11 +17,13 @@ export async function unpinAllMessages( const res = await this.call({ _: 'messages.unpinAllMessages', - peer + peer, }) if (isInputPeerChannel(peer)) { - this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount, peer.channelId)) + this._handleUpdate( + createDummyUpdate(res.pts, res.ptsCount, peer.channelId) + ) } else { this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount)) } diff --git a/packages/client/src/methods/messages/unpin-message.ts b/packages/client/src/methods/messages/unpin-message.ts index aede0a4d..315f8a85 100644 --- a/packages/client/src/methods/messages/unpin-message.ts +++ b/packages/client/src/methods/messages/unpin-message.ts @@ -14,13 +14,13 @@ import { InputPeerLike } from '../../types' export async function unpinMessage( this: TelegramClient, chatId: InputPeerLike, - messageId: number, + messageId: number ): Promise { const res = await this.call({ _: 'messages.updatePinnedMessage', peer: await this.resolvePeer(chatId), id: messageId, - unpin: true + unpin: true, }) this._handleUpdate(res) diff --git a/packages/client/src/methods/misc/init-takeout-session.ts b/packages/client/src/methods/misc/init-takeout-session.ts index 1491ff1a..2ac926ab 100644 --- a/packages/client/src/methods/misc/init-takeout-session.ts +++ b/packages/client/src/methods/misc/init-takeout-session.ts @@ -12,8 +12,11 @@ export async function initTakeoutSession( this: TelegramClient, params: Omit ): Promise { - return new TakeoutSession(this, await this.call({ - _: 'account.initTakeoutSession', - ...params - })) + return new TakeoutSession( + this, + await this.call({ + _: 'account.initTakeoutSession', + ...params, + }) + ) } diff --git a/packages/client/src/methods/pasword/change-cloud-password.ts b/packages/client/src/methods/pasword/change-cloud-password.ts index e89b8943..0a1bad39 100644 --- a/packages/client/src/methods/pasword/change-cloud-password.ts +++ b/packages/client/src/methods/pasword/change-cloud-password.ts @@ -29,7 +29,11 @@ export async function changeCloudPassword( ) const oldSrp = await computeSrpParams(this._crypto, pwd, currentPassword) - const newHash = await computeNewPasswordHash(this._crypto, algo, newPassword) + const newHash = await computeNewPasswordHash( + this._crypto, + algo, + newPassword + ) await this.call({ _: 'account.updatePasswordSettings', @@ -38,7 +42,7 @@ export async function changeCloudPassword( _: 'account.passwordInputSettings', newAlgo: algo, newPasswordHash: newHash, - hint - } + hint, + }, }) } diff --git a/packages/client/src/methods/pasword/enable-cloud-password.ts b/packages/client/src/methods/pasword/enable-cloud-password.ts index 452d3442..f69dcdab 100644 --- a/packages/client/src/methods/pasword/enable-cloud-password.ts +++ b/packages/client/src/methods/pasword/enable-cloud-password.ts @@ -43,7 +43,7 @@ export async function enableCloudPassword( newAlgo: algo, newPasswordHash: newHash, hint, - email - } + email, + }, }) } diff --git a/packages/client/src/methods/pasword/password-email.ts b/packages/client/src/methods/pasword/password-email.ts index 78e50901..f56b0f0d 100644 --- a/packages/client/src/methods/pasword/password-email.ts +++ b/packages/client/src/methods/pasword/password-email.ts @@ -12,7 +12,7 @@ export async function verifyPasswordEmail( ): Promise { await this.call({ _: 'account.confirmPasswordEmail', - code + code, }) } @@ -23,7 +23,7 @@ export async function verifyPasswordEmail( */ export async function resendPasswordEmail(this: TelegramClient): Promise { await this.call({ - _: 'account.resendPasswordEmail' + _: 'account.resendPasswordEmail', }) } @@ -34,6 +34,6 @@ export async function resendPasswordEmail(this: TelegramClient): Promise { */ export async function cancelPasswordEmail(this: TelegramClient): Promise { await this.call({ - _: 'account.cancelPasswordEmail' + _: 'account.cancelPasswordEmail', }) } diff --git a/packages/client/src/methods/pasword/remove-cloud-password.ts b/packages/client/src/methods/pasword/remove-cloud-password.ts index 0ebbb1d6..d431f8e0 100644 --- a/packages/client/src/methods/pasword/remove-cloud-password.ts +++ b/packages/client/src/methods/pasword/remove-cloud-password.ts @@ -10,7 +10,7 @@ import { computeSrpParams } from '@mtcute/core' */ export async function removeCloudPassword( this: TelegramClient, - password: string, + password: string ): Promise { const pwd = await this.call({ _: 'account.getPassword' }) if (!pwd.hasPassword) @@ -25,7 +25,7 @@ export async function removeCloudPassword( _: 'account.passwordInputSettings', newAlgo: { _: 'passwordKdfAlgoUnknown' }, newPasswordHash: Buffer.alloc(0), - hint: '' - } + hint: '', + }, }) } diff --git a/packages/client/src/methods/stickers/add-sticker-to-set.ts b/packages/client/src/methods/stickers/add-sticker-to-set.ts index 45928f56..c6511c16 100644 --- a/packages/client/src/methods/stickers/add-sticker-to-set.ts +++ b/packages/client/src/methods/stickers/add-sticker-to-set.ts @@ -33,12 +33,12 @@ export async function addStickerToSet( * @param total Total file size */ progressCallback?: (uploaded: number, total: number) => void - }, + } ): Promise { if (typeof id === 'string') { id = { _: 'inputStickerSetShortName', - shortName: id + shortName: id, } } @@ -47,18 +47,21 @@ export async function addStickerToSet( stickerset: id, sticker: { _: 'inputStickerSetItem', - document: await this._normalizeFileToDocument(sticker.file, params ?? {}), + document: await this._normalizeFileToDocument( + sticker.file, + params ?? {} + ), emoji: sticker.emojis, maskCoords: sticker.maskPosition ? { - _: 'maskCoords', - n: MASK_POS[sticker.maskPosition.point], - x: sticker.maskPosition.x, - y: sticker.maskPosition.y, - zoom: sticker.maskPosition.scale, - } + _: 'maskCoords', + n: MASK_POS[sticker.maskPosition.point], + x: sticker.maskPosition.x, + y: sticker.maskPosition.y, + zoom: sticker.maskPosition.scale, + } : undefined, - } + }, }) return new StickerSet(this, res) diff --git a/packages/client/src/methods/stickers/delete-sticker-from-set.ts b/packages/client/src/methods/stickers/delete-sticker-from-set.ts index a70eb757..e78addea 100644 --- a/packages/client/src/methods/stickers/delete-sticker-from-set.ts +++ b/packages/client/src/methods/stickers/delete-sticker-from-set.ts @@ -25,7 +25,7 @@ export async function deleteStickerFromSet( const res = await this.call({ _: 'stickers.removeStickerFromSet', - sticker + sticker, }) return new StickerSet(this, res) diff --git a/packages/client/src/methods/stickers/get-installed-stickers.ts b/packages/client/src/methods/stickers/get-installed-stickers.ts index 81a2fdec..5daebdb0 100644 --- a/packages/client/src/methods/stickers/get-installed-stickers.ts +++ b/packages/client/src/methods/stickers/get-installed-stickers.ts @@ -17,7 +17,7 @@ export async function getInstalledStickers( ): Promise { const res = await this.call({ _: 'messages.getAllStickers', - hash: 0 + hash: 0, }) assertTypeIs('getInstalledStickers', res, 'messages.allStickers') diff --git a/packages/client/src/methods/stickers/get-sticker-set.ts b/packages/client/src/methods/stickers/get-sticker-set.ts index 951bfa42..e40f8786 100644 --- a/packages/client/src/methods/stickers/get-sticker-set.ts +++ b/packages/client/src/methods/stickers/get-sticker-set.ts @@ -14,16 +14,19 @@ export async function getStickerSet( ): Promise { let input: tl.TypeInputStickerSet if (typeof id === 'string') { - input = id === 'emoji' ? { - _: 'inputStickerSetAnimatedEmoji' - } : { - _: 'inputStickerSetShortName', - shortName: id - } + input = + id === 'emoji' + ? { + _: 'inputStickerSetAnimatedEmoji', + } + : { + _: 'inputStickerSetShortName', + shortName: id, + } } else if ('dice' in id) { input = { _: 'inputStickerSetDice', - emoticon: id.dice + emoticon: id.dice, } } else { input = id @@ -31,7 +34,7 @@ export async function getStickerSet( const res = await this.call({ _: 'messages.getStickerSet', - stickerset: input + stickerset: input, }) return new StickerSet(this, res) diff --git a/packages/client/src/methods/stickers/move-sticker-in-set.ts b/packages/client/src/methods/stickers/move-sticker-in-set.ts index b583e724..1a731929 100644 --- a/packages/client/src/methods/stickers/move-sticker-in-set.ts +++ b/packages/client/src/methods/stickers/move-sticker-in-set.ts @@ -30,7 +30,7 @@ export async function moveStickerInSet( const res = await this.call({ _: 'stickers.changeStickerPosition', sticker, - position + position, }) return new StickerSet(this, res) diff --git a/packages/client/src/methods/stickers/set-sticker-set-thumb.ts b/packages/client/src/methods/stickers/set-sticker-set-thumb.ts index e2736456..1dc8cd6b 100644 --- a/packages/client/src/methods/stickers/set-sticker-set-thumb.ts +++ b/packages/client/src/methods/stickers/set-sticker-set-thumb.ts @@ -23,19 +23,19 @@ export async function setStickerSetThumb( * @param total Total file size */ progressCallback?: (uploaded: number, total: number) => void - }, + } ): Promise { if (typeof id === 'string') { id = { _: 'inputStickerSetShortName', - shortName: id + shortName: id, } } const res = await this.call({ _: 'stickers.setStickerSetThumb', stickerset: id, - thumb: await this._normalizeFileToDocument(thumb, params ?? {}) + thumb: await this._normalizeFileToDocument(thumb, params ?? {}), }) return new StickerSet(this, res) diff --git a/packages/client/src/methods/updates.ts b/packages/client/src/methods/updates.ts index 575f29ac..b040a8e8 100644 --- a/packages/client/src/methods/updates.ts +++ b/packages/client/src/methods/updates.ts @@ -106,7 +106,10 @@ export async function _loadStorage(this: TelegramClient): Promise { /** * @internal */ -export async function _saveStorage(this: TelegramClient, afterImport = false): Promise { +export async function _saveStorage( + this: TelegramClient, + afterImport = false +): Promise { // save updates state to the session if (afterImport) { @@ -312,7 +315,10 @@ async function _fetchPeersForShort( case 'updateNewChannelMessage': case 'updateEditMessage': case 'updateEditChannelMessage': { - const msg = upd._ === 'message' || upd._ === 'messageService' ? upd : upd.message + const msg = + upd._ === 'message' || upd._ === 'messageService' + ? upd + : upd.message if (msg._ === 'messageEmpty') return null // ref: https://github.com/tdlib/td/blob/e1ebf743988edfcf4400cd5d33a664ff941dc13e/td/telegram/UpdatesManager.cpp#L412 @@ -357,13 +363,19 @@ async function _fetchPeersForShort( } break case 'messageActionChatJoinedByLink': - if (!(await fetchPeer(msg.action.inviterId))) return null + if (!(await fetchPeer(msg.action.inviterId))) + return null break case 'messageActionChatDeleteUser': if (!(await fetchPeer(msg.action.userId))) return null break case 'messageActionChatMigrateTo': - if (!(await fetchPeer(MAX_CHANNEL_ID - msg.action.channelId))) return null + if ( + !(await fetchPeer( + MAX_CHANNEL_ID - msg.action.channelId + )) + ) + return null break case 'messageActionChannelMigrateFrom': if (!(await fetchPeer(-msg.action.chatId))) return null @@ -465,7 +477,12 @@ async function _loadDifference( if (nextLocalPts) { if (nextLocalPts > pts) continue if (nextLocalPts < pts) { - await _loadChannelDifference.call(this, cid, noDispatch, pts) + await _loadChannelDifference.call( + this, + cid, + noDispatch, + pts + ) continue } } @@ -735,7 +752,10 @@ export function _handleUpdate( this._config = await this.call({ _: 'help.getConfig' }) } else { if (!noDispatch) { - const peers = await _fetchPeersForShort.call(this, upd) + const peers = await _fetchPeersForShort.call( + this, + upd + ) if (!peers) { // some peer is not cached. // need to re-fetch the thing, and cache them on the way diff --git a/packages/client/src/methods/users/delete-profile-photos.ts b/packages/client/src/methods/users/delete-profile-photos.ts index b7a7f3cf..ccc95df8 100644 --- a/packages/client/src/methods/users/delete-profile-photos.ts +++ b/packages/client/src/methods/users/delete-profile-photos.ts @@ -25,6 +25,6 @@ export async function deleteProfilePhotos( await this.call({ _: 'photos.deletePhotos', - id: photos + id: photos, }) } diff --git a/packages/client/src/methods/users/get-profile-photos.ts b/packages/client/src/methods/users/get-profile-photos.ts index d3f31c97..99415b50 100644 --- a/packages/client/src/methods/users/get-profile-photos.ts +++ b/packages/client/src/methods/users/get-profile-photos.ts @@ -40,7 +40,7 @@ export async function getProfilePhotos( userId: peer, offset: params.offset ?? 0, limit: params.limit ?? 100, - maxId: bigInt.zero + maxId: bigInt.zero, }) return res.photos.map((it) => new Photo(this, it as tl.RawPhoto)) diff --git a/packages/client/src/methods/users/iter-profile-photos.ts b/packages/client/src/methods/users/iter-profile-photos.ts index d022fb17..8091cfcb 100644 --- a/packages/client/src/methods/users/iter-profile-photos.ts +++ b/packages/client/src/methods/users/iter-profile-photos.ts @@ -62,7 +62,7 @@ export async function* iterProfilePhotos( userId: peer, limit: Math.min(limit, total - current), offset, - maxId + maxId, }) if (!res.photos.length) break diff --git a/packages/client/src/methods/users/resolve-peer-many.ts b/packages/client/src/methods/users/resolve-peer-many.ts index cf2b201c..aa484ad9 100644 --- a/packages/client/src/methods/users/resolve-peer-many.ts +++ b/packages/client/src/methods/users/resolve-peer-many.ts @@ -19,9 +19,7 @@ export async function resolvePeerMany< >( this: TelegramClient, peerIds: InputPeerLike[], - normalizer: ( - obj: tl.TypeInputPeer - ) => T | null + normalizer: (obj: tl.TypeInputPeer) => T | null ): Promise /** diff --git a/packages/client/src/methods/users/resolve-peer.ts b/packages/client/src/methods/users/resolve-peer.ts index 713e8e4c..b8f39550 100644 --- a/packages/client/src/methods/users/resolve-peer.ts +++ b/packages/client/src/methods/users/resolve-peer.ts @@ -75,7 +75,10 @@ export async function resolvePeer( accessHash: found.accessHash!, } } else { - const id = res.peer._ === 'peerChannel' ? res.peer.channelId : res.peer.chatId + const id = + res.peer._ === 'peerChannel' + ? res.peer.channelId + : res.peer.chatId const found = res.chats.find((it) => it.id === id) if (found) @@ -85,13 +88,13 @@ export async function resolvePeer( return { _: 'inputPeerChannel', channelId: found.id, - accessHash: found.accessHash! + accessHash: found.accessHash!, } case 'chat': case 'chatForbidden': return { _: 'inputPeerChat', - chatId: found.id + chatId: found.id, } } } @@ -145,7 +148,7 @@ export async function resolvePeer( return { _: 'inputPeerChat', - chatId: -peerId + chatId: -peerId, } // break } @@ -163,7 +166,10 @@ export async function resolvePeer( }) const found = res.chats.find((it) => it.id === id) - if (found && (found._ === 'channel' || found._ === 'channelForbidden')) + if ( + found && + (found._ === 'channel' || found._ === 'channelForbidden') + ) return { _: 'inputPeerChannel', channelId: found.id, diff --git a/packages/client/src/methods/users/set-offline.ts b/packages/client/src/methods/users/set-offline.ts index 47a0c937..c07cb20a 100644 --- a/packages/client/src/methods/users/set-offline.ts +++ b/packages/client/src/methods/users/set-offline.ts @@ -12,6 +12,6 @@ export async function setOffline( ): Promise { await this.call({ _: 'account.updateStatus', - offline + offline, }) } diff --git a/packages/client/src/methods/users/set-profile-photo.ts b/packages/client/src/methods/users/set-profile-photo.ts index c55db7e6..e9a1cf0b 100644 --- a/packages/client/src/methods/users/set-profile-photo.ts +++ b/packages/client/src/methods/users/set-profile-photo.ts @@ -20,8 +20,11 @@ export async function setProfilePhoto( ): Promise { const res = await this.call({ _: 'photos.uploadProfilePhoto', - [type === 'photo' ? 'file' : 'video']: await this._normalizeInputFile(media, {}), - videoStartTs: previewSec + [type === 'photo' ? 'file' : 'video']: await this._normalizeInputFile( + media, + {} + ), + videoStartTs: previewSec, }) return new Photo(this, res.photo as tl.RawPhoto) diff --git a/packages/client/src/methods/users/update-profile.ts b/packages/client/src/methods/users/update-profile.ts index 539efe38..8de32039 100644 --- a/packages/client/src/methods/users/update-profile.ts +++ b/packages/client/src/methods/users/update-profile.ts @@ -32,7 +32,7 @@ export async function updateProfile( _: 'account.updateProfile', firstName: params.firstName, lastName: params.lastName, - about: params.bio + about: params.bio, }) return new User(this, res) diff --git a/packages/client/src/methods/users/update-username.ts b/packages/client/src/methods/users/update-username.ts index f43730e2..e347aa89 100644 --- a/packages/client/src/methods/users/update-username.ts +++ b/packages/client/src/methods/users/update-username.ts @@ -18,7 +18,7 @@ export async function updateUsername( const res = await this.call({ _: 'account.updateUsername', - username + username, }) return new User(this, res) diff --git a/packages/client/src/types/bots/game-high-score.ts b/packages/client/src/types/bots/game-high-score.ts index 2dc6d7bb..e66236d6 100644 --- a/packages/client/src/types/bots/game-high-score.ts +++ b/packages/client/src/types/bots/game-high-score.ts @@ -12,7 +12,11 @@ export class GameHighScore { readonly _users: UsersIndex - constructor (client: TelegramClient, raw: tl.RawHighScore, users: UsersIndex) { + constructor( + client: TelegramClient, + raw: tl.RawHighScore, + users: UsersIndex + ) { this.client = client this.raw = raw this._users = users diff --git a/packages/client/src/types/bots/input/input-inline-message.ts b/packages/client/src/types/bots/input/input-inline-message.ts index 1871fd2e..d148e695 100644 --- a/packages/client/src/types/bots/input/input-inline-message.ts +++ b/packages/client/src/types/bots/input/input-inline-message.ts @@ -160,7 +160,10 @@ export namespace BotInlineMessage { export function geo( latitude: number, longitude: number, - params: Omit = {} + params: Omit< + InputInlineMessageGeo, + 'type' | 'latitude' | 'longitude' + > = {} ): InputInlineMessageGeo { const ret = params as tl.Mutable ret.type = 'geo' diff --git a/packages/client/src/types/bots/input/input-inline-result.ts b/packages/client/src/types/bots/input/input-inline-result.ts index 10229fb0..71e10e9a 100644 --- a/packages/client/src/types/bots/input/input-inline-result.ts +++ b/packages/client/src/types/bots/input/input-inline-result.ts @@ -1,5 +1,5 @@ import { tl } from '@mtcute/tl' -import { BotInlineMessage, InputInlineMessage, InputInlineMessageGame } from './input-inline-message' +import { BotInlineMessage, InputInlineMessage } from './input-inline-message' import { TelegramClient } from '../../../client' import { fileIdToInputDocument, fileIdToInputPhoto } from '@mtcute/file-id' import { extractFileName } from '../../../utils/file-utils' @@ -711,7 +711,12 @@ export namespace BotInline { obj: InputInlineResult, fallback?: string ): tl.RawInputWebDocument | undefined => { - if (obj.type !== 'voice' && obj.type !== 'audio' && obj.type !== 'sticker' && obj.type !== 'game') { + if ( + obj.type !== 'voice' && + obj.type !== 'audio' && + obj.type !== 'sticker' && + obj.type !== 'game' + ) { if (!obj.thumb || typeof obj.thumb === 'string') { if (!obj.thumb && !fallback) { return undefined @@ -805,11 +810,13 @@ export namespace BotInline { parseMode ) if (sendMessage._ !== 'inputBotInlineMessageGame') { - throw new MtCuteArgumentError('game inline result must contain a game inline message') + throw new MtCuteArgumentError( + 'game inline result must contain a game inline message' + ) } } else { sendMessage = { - _: 'inputBotInlineMessageGame' + _: 'inputBotInlineMessageGame', } } @@ -817,7 +824,7 @@ export namespace BotInline { _: 'inputBotInlineResultGame', id: obj.id, shortName: obj.shortName, - sendMessage + sendMessage, } } @@ -830,7 +837,9 @@ export namespace BotInline { ) } else { if (obj.type === 'venue') - throw new MtCuteArgumentError('message bust be supplied for venue inline result') + throw new MtCuteArgumentError( + 'message bust be supplied for venue inline result' + ) if ( obj.type === 'video' && @@ -856,8 +865,7 @@ export namespace BotInline { phoneNumber: obj.phone, firstName: obj.firstName, lastName: obj.lastName ?? '', - vcard: '' - + vcard: '', } } else { sendMessage = { @@ -872,12 +880,18 @@ export namespace BotInline { | tl.TypeInputDocument | tl.TypeInputPhoto | undefined = undefined - if (obj.type !== 'geo' && obj.type !== 'venue' && obj.type !== 'contact') { + if ( + obj.type !== 'geo' && + obj.type !== 'venue' && + obj.type !== 'contact' + ) { if (typeof obj.media === 'string') { // file id or url if (obj.media.match(/^https?:\/\//)) { if (obj.type === 'sticker') - throw new MtCuteArgumentError('sticker inline result cannot contain a URL') + throw new MtCuteArgumentError( + 'sticker inline result cannot contain a URL' + ) let mime: string if (obj.type === 'video') mime = 'video/mp4' @@ -959,7 +973,9 @@ export namespace BotInline { // but whatever. // ref: https://github.com/tdlib/td/blob/master/td/telegram/InlineQueriesManager.cpp if (obj.type === 'contact') { - title = obj.lastName?.length ? `${obj.firstName} ${obj.lastName}` : obj.firstName + title = obj.lastName?.length + ? `${obj.firstName} ${obj.lastName}` + : obj.firstName } else if (obj.type !== 'sticker') { title = obj.title } @@ -972,7 +988,11 @@ export namespace BotInline { description = obj.address } else if (obj.type === 'contact') { description = obj.phone - } else if (obj.type !== 'gif' && obj.type !== 'voice' && obj.type !== 'sticker') { + } else if ( + obj.type !== 'gif' && + obj.type !== 'voice' && + obj.type !== 'sticker' + ) { description = obj.description } diff --git a/packages/client/src/types/bots/keyboards.ts b/packages/client/src/types/bots/keyboards.ts index b9ffa61e..3d7fd0a7 100644 --- a/packages/client/src/types/bots/keyboards.ts +++ b/packages/client/src/types/bots/keyboards.ts @@ -302,10 +302,10 @@ export namespace BotKeyboard { text, url, bot: params.bot ?? { - _: 'inputUserSelf' + _: 'inputUserSelf', }, fwdText: params.fwdText, - requestWriteAccess: params.requestWriteAccess + requestWriteAccess: params.requestWriteAccess, } } diff --git a/packages/client/src/types/files/file-location.ts b/packages/client/src/types/files/file-location.ts index 7af15427..b7934e40 100644 --- a/packages/client/src/types/files/file-location.ts +++ b/packages/client/src/types/files/file-location.ts @@ -29,7 +29,10 @@ export class FileLocation { | tl.TypeInputFileLocation | tl.TypeInputWebFileLocation | Buffer - | (() => tl.TypeInputFileLocation | tl.TypeInputWebFileLocation | Buffer) + | (() => + | tl.TypeInputFileLocation + | tl.TypeInputWebFileLocation + | Buffer) /** * File size in bytes, when available @@ -47,7 +50,10 @@ export class FileLocation { | tl.TypeInputFileLocation | tl.TypeInputWebFileLocation | Buffer - | (() => tl.TypeInputFileLocation | tl.TypeInputWebFileLocation | Buffer), + | (() => + | tl.TypeInputFileLocation + | tl.TypeInputWebFileLocation + | Buffer), fileSize?: number, dcId?: number ) { diff --git a/packages/client/src/types/files/uploaded-file.ts b/packages/client/src/types/files/uploaded-file.ts index f94cc6d8..5977510b 100644 --- a/packages/client/src/types/files/uploaded-file.ts +++ b/packages/client/src/types/files/uploaded-file.ts @@ -25,7 +25,7 @@ export interface UploadedFile { } /** @internal */ -export function isUploadedFile(obj: any): obj is UploadedFile { +export function isUploadedFile(obj: object): obj is UploadedFile { return ( obj && typeof obj === 'object' && diff --git a/packages/client/src/types/files/utils.ts b/packages/client/src/types/files/utils.ts index c216120d..7d66680f 100644 --- a/packages/client/src/types/files/utils.ts +++ b/packages/client/src/types/files/utils.ts @@ -52,7 +52,11 @@ export interface FileDownloadParameters { * File location which should be downloaded. * You can also provide TDLib and Bot API compatible File ID */ - location: tl.TypeInputFileLocation | tl.TypeInputWebFileLocation | FileLocation | string + location: + | tl.TypeInputFileLocation + | tl.TypeInputWebFileLocation + | FileLocation + | string /** * Total file size, if known. diff --git a/packages/client/src/types/media/dice.ts b/packages/client/src/types/media/dice.ts index 05ac6707..0315c39d 100644 --- a/packages/client/src/types/media/dice.ts +++ b/packages/client/src/types/media/dice.ts @@ -171,7 +171,7 @@ export class Dice { get inputMedia(): tl.TypeInputMedia { return { _: 'inputMediaDice', - emoticon: this.obj.emoticon + emoticon: this.obj.emoticon, } } } diff --git a/packages/client/src/types/media/document.ts b/packages/client/src/types/media/document.ts index 7305286e..35ac91a6 100644 --- a/packages/client/src/types/media/document.ts +++ b/packages/client/src/types/media/document.ts @@ -3,7 +3,6 @@ import { tl } from '@mtcute/tl' import { Thumbnail } from './thumbnail' import { TelegramClient } from '../../client' import { makeInspectable } from '../utils' -import { InputMediaLike } from './input-media' import { tdFileId as td, toFileId, toUniqueFileId } from '@mtcute/file-id' /** @@ -105,7 +104,7 @@ export class RawDocument extends FileLocation { _: 'inputDocument', id: this.doc.id, accessHash: this.doc.accessHash, - fileReference: this.doc.fileReference + fileReference: this.doc.fileReference, } } @@ -117,7 +116,7 @@ export class RawDocument extends FileLocation { get inputMedia(): tl.TypeInputMedia { return { _: 'inputMediaDocument', - id: this.inputDocument + id: this.inputDocument, } } diff --git a/packages/client/src/types/media/game.ts b/packages/client/src/types/media/game.ts index d9ecd6cb..c74361a0 100644 --- a/packages/client/src/types/media/game.ts +++ b/packages/client/src/types/media/game.ts @@ -91,8 +91,8 @@ export class Game { id: { _: 'inputGameID', id: this.game.id, - accessHash: this.game.accessHash - } + accessHash: this.game.accessHash, + }, } } } diff --git a/packages/client/src/types/media/input-media.ts b/packages/client/src/types/media/input-media.ts index 4003dd4b..28069632 100644 --- a/packages/client/src/types/media/input-media.ts +++ b/packages/client/src/types/media/input-media.ts @@ -2,7 +2,6 @@ import { InputFileLike } from '../files' import { tl } from '@mtcute/tl' import { Venue } from './venue' import { MaybeArray } from '@mtcute/core' -import { InputInlineResultGame } from '../bots' interface BaseInputMedia { /** @@ -728,7 +727,10 @@ export namespace InputMedia { export function geoLive( latitude: number, longitude: number, - params: OmitTypeAndFile = {} + params: OmitTypeAndFile< + InputMediaGeoLive, + 'latitude' | 'longitude' + > = {} ): InputMediaGeoLive { const ret = params as tl.Mutable ret.type = 'geo_live' diff --git a/packages/client/src/types/media/invoice.ts b/packages/client/src/types/media/invoice.ts index 9915c508..e66b10ec 100644 --- a/packages/client/src/types/media/invoice.ts +++ b/packages/client/src/types/media/invoice.ts @@ -11,7 +11,7 @@ export class Invoice { readonly client: TelegramClient readonly raw: tl.RawMessageMediaInvoice - constructor (client: TelegramClient, raw: tl.RawMessageMediaInvoice) { + constructor(client: TelegramClient, raw: tl.RawMessageMediaInvoice) { this.client = client this.raw = raw } diff --git a/packages/client/src/types/media/location.ts b/packages/client/src/types/media/location.ts index c71fb77f..c0e3e923 100644 --- a/packages/client/src/types/media/location.ts +++ b/packages/client/src/types/media/location.ts @@ -40,42 +40,44 @@ export class Location { * Create {@link FileLocation} containing * server-generated image with the map preview */ - preview(params: { - /** - * Map width in pixels before applying scale (16-1024) - * - * Defaults to `128` - */ - width?: number + preview( + params: { + /** + * Map width in pixels before applying scale (16-1024) + * + * Defaults to `128` + */ + width?: number - /** - * Map height in pixels before applying scale (16-1024) - * - * Defaults to `128` - */ - height?: number + /** + * Map height in pixels before applying scale (16-1024) + * + * Defaults to `128` + */ + height?: number - /** - * Map zoom level (13-20) - * - * Defaults to `15` - */ - zoom?: number + /** + * Map zoom level (13-20) + * + * Defaults to `15` + */ + zoom?: number - /** - * Map scale (1-3) - * - * Defaults to `1` - */ - scale?: number - } = {}): FileLocation { + /** + * Map scale (1-3) + * + * Defaults to `1` + */ + scale?: number + } = {} + ): FileLocation { return new FileLocation(this.client, { _: 'inputWebFileGeoPointLocation', geoPoint: { _: 'inputGeoPoint', lat: this.geo.lat, long: this.geo.long, - accuracyRadius: this.geo.accuracyRadius + accuracyRadius: this.geo.accuracyRadius, }, accessHash: this.geo.accessHash, w: params.width ?? 128, @@ -97,8 +99,8 @@ export class Location { _: 'inputGeoPoint', lat: this.geo.lat, long: this.geo.long, - accuracyRadius: this.geo.accuracyRadius - } + accuracyRadius: this.geo.accuracyRadius, + }, } } } @@ -141,11 +143,11 @@ export class LiveLocation extends Location { _: 'inputGeoPoint', lat: this.geo.lat, long: this.geo.long, - accuracyRadius: this.geo.accuracyRadius + accuracyRadius: this.geo.accuracyRadius, }, heading: this.live.heading, period: this.live.period, - proximityNotificationRadius: this.live.proximityNotificationRadius + proximityNotificationRadius: this.live.proximityNotificationRadius, } } diff --git a/packages/client/src/types/media/photo.ts b/packages/client/src/types/media/photo.ts index f77e004d..73494fb4 100644 --- a/packages/client/src/types/media/photo.ts +++ b/packages/client/src/types/media/photo.ts @@ -4,7 +4,6 @@ import { TelegramClient } from '../../client' import { MtCuteArgumentError } from '../errors' import { Thumbnail } from './thumbnail' import { makeInspectable } from '../utils' -import { InputMediaLike } from './input-media' /** * A photo diff --git a/packages/client/src/types/media/poll.ts b/packages/client/src/types/media/poll.ts index 364924ba..b49197f3 100644 --- a/packages/client/src/types/media/poll.ts +++ b/packages/client/src/types/media/poll.ts @@ -86,7 +86,7 @@ export class Poll { data: ans.option, voters: res.voters, chosen: !!res.chosen, - correct: !!res.correct + correct: !!res.correct, } } else { return { @@ -94,7 +94,7 @@ export class Poll { data: ans.option, voters: 0, chosen: false, - correct: false + correct: false, } } }) @@ -210,7 +210,7 @@ export class Poll { question: this.raw.question, answers: this.raw.answers, closePeriod: this.raw.closePeriod, - closeDate: this.raw.closeDate + closeDate: this.raw.closeDate, }, } } diff --git a/packages/client/src/types/media/sticker.ts b/packages/client/src/types/media/sticker.ts index 18480d83..2de4e4c6 100644 --- a/packages/client/src/types/media/sticker.ts +++ b/packages/client/src/types/media/sticker.ts @@ -125,7 +125,7 @@ export class Sticker extends RawDocument { point: MASK_POS[raw.n], x: raw.x, y: raw.y, - scale: raw.zoom + scale: raw.zoom, } } diff --git a/packages/client/src/types/media/venue.ts b/packages/client/src/types/media/venue.ts index b9e1dda1..ef5f11fb 100644 --- a/packages/client/src/types/media/venue.ts +++ b/packages/client/src/types/media/venue.ts @@ -3,7 +3,6 @@ import { Location } from './location' import { assertTypeIs } from '../../utils/type-assertion' import { makeInspectable } from '../utils' import { TelegramClient } from '../../client' -import bigInt from 'big-integer' export namespace Venue { export interface VenueSource { @@ -33,7 +32,7 @@ export class Venue { readonly client: TelegramClient readonly raw: tl.RawMessageMediaVenue - constructor (client: TelegramClient, raw: tl.RawMessageMediaVenue) { + constructor(client: TelegramClient, raw: tl.RawMessageMediaVenue) { this.client = client this.raw = raw } @@ -106,7 +105,7 @@ export class Venue { address: this.raw.address, provider: this.raw.provider, venueId: this.raw.venueId, - venueType: this.raw.venueType + venueType: this.raw.venueType, } } } diff --git a/packages/client/src/types/messages/message-action.ts b/packages/client/src/types/messages/message-action.ts index f7828e23..a5374c51 100644 --- a/packages/client/src/types/messages/message-action.ts +++ b/packages/client/src/types/messages/message-action.ts @@ -1,6 +1,9 @@ import { tl } from '@mtcute/tl' import { Photo } from '../media' -import { _callDiscardReasonFromTl, CallDiscardReason } from '../calls/discard-reason' +import { + _callDiscardReasonFromTl, + CallDiscardReason, +} from '../calls/discard-reason' import { Message } from './message' export namespace MessageAction { @@ -279,7 +282,10 @@ export type MessageAction = | null /** @internal */ -export function _messageActionFromTl(this: Message, act: tl.TypeMessageAction): MessageAction { +export function _messageActionFromTl( + this: Message, + act: tl.TypeMessageAction +): MessageAction { switch (act._) { case 'messageActionChatCreate': return { @@ -329,10 +335,7 @@ export function _messageActionFromTl(this: Message, act: tl.TypeMessageAction): case 'messageActionChatEditPhoto': return { type: 'photo_changed', - photo: new Photo( - this.client, - act.photo as tl.RawPhoto - ), + photo: new Photo(this.client, act.photo as tl.RawPhoto), } case 'messageActionChatDeletePhoto': return { @@ -390,12 +393,12 @@ export function _messageActionFromTl(this: Message, act: tl.TypeMessageAction): } case 'messageActionScreenshotTaken': return { - type: 'screenshot_taken' + type: 'screenshot_taken', } case 'messageActionBotAllowed': return { type: 'bot_allowed', - domain: act.domain + domain: act.domain, } case 'messageActionGeoProximityReached': if (act.fromId._ !== 'peerUser' || act.toId._ !== 'peerUser') { @@ -405,7 +408,7 @@ export function _messageActionFromTl(this: Message, act: tl.TypeMessageAction): type: 'geo_proximity', targetId: act.toId.userId, userId: act.fromId.userId, - distance: act.distance + distance: act.distance, } } case 'messageActionGroupCall': @@ -413,24 +416,24 @@ export function _messageActionFromTl(this: Message, act: tl.TypeMessageAction): return { type: 'group_call_ended', call: act.call, - duration: act.duration + duration: act.duration, } } else { return { type: 'group_call_started', - call: act.call + call: act.call, } } case 'messageActionInviteToGroupCall': return { type: 'group_call_invite', call: act.call, - userIds: act.users + userIds: act.users, } case 'messageActionSetMessagesTTL': return { type: 'set_ttl', - period: act.period + period: act.period, } default: return null diff --git a/packages/client/src/types/messages/message-entity.ts b/packages/client/src/types/messages/message-entity.ts index 969c2536..4fa7a14d 100644 --- a/packages/client/src/types/messages/message-entity.ts +++ b/packages/client/src/types/messages/message-entity.ts @@ -1,5 +1,4 @@ import { tl } from '@mtcute/tl' -import { User } from '../peers/user' import { makeInspectable } from '../utils' const entityToType: Partial< diff --git a/packages/client/src/types/messages/message-media.ts b/packages/client/src/types/messages/message-media.ts index b65625cb..b5d664a9 100644 --- a/packages/client/src/types/messages/message-media.ts +++ b/packages/client/src/types/messages/message-media.ts @@ -40,7 +40,10 @@ export type MessageMedia = // todo: successful_payment, connected_website /** @internal */ -export function _messageMediaFromTl(this: Message, m: tl.TypeMessageMedia): MessageMedia { +export function _messageMediaFromTl( + this: Message, + m: tl.TypeMessageMedia +): MessageMedia { switch (m._) { case 'messageMediaPhoto': if (!(m.photo?._ === 'photo')) return null diff --git a/packages/client/src/types/messages/search-filters.ts b/packages/client/src/types/messages/search-filters.ts index 84d46c1f..23cc1478 100644 --- a/packages/client/src/types/messages/search-filters.ts +++ b/packages/client/src/types/messages/search-filters.ts @@ -33,16 +33,22 @@ export const SearchFilters = { Empty: { _: 'inputMessagesFilterEmpty' } as tl.TypeMessagesFilter, Photo: { _: 'inputMessagesFilterPhotos' } as tl.TypeMessagesFilter, Video: { _: 'inputMessagesFilterVideo' } as tl.TypeMessagesFilter, - PhotoAndVideo: { _: 'inputMessagesFilterPhotoVideo' } as tl.TypeMessagesFilter, + PhotoAndVideo: { + _: 'inputMessagesFilterPhotoVideo', + } as tl.TypeMessagesFilter, Document: { _: 'inputMessagesFilterDocument' } as tl.TypeMessagesFilter, Url: { _: 'inputMessagesFilterUrl' } as tl.TypeMessagesFilter, Gif: { _: 'inputMessagesFilterGif' } as tl.TypeMessagesFilter, Voice: { _: 'inputMessagesFilterVoice' } as tl.TypeMessagesFilter, Audio: { _: 'inputMessagesFilterMusic' } as tl.TypeMessagesFilter, - ChatPhotoChange: { _: 'inputMessagesFilterChatPhotos' } as tl.TypeMessagesFilter, + ChatPhotoChange: { + _: 'inputMessagesFilterChatPhotos', + } as tl.TypeMessagesFilter, Call: { _: 'inputMessagesFilterPhoneCalls' } as tl.TypeMessagesFilter, Round: { _: 'inputMessagesFilterRoundVideo' } as tl.TypeMessagesFilter, - RoundAndVoice: { _: 'inputMessagesFilterRoundVoice' } as tl.TypeMessagesFilter, + RoundAndVoice: { + _: 'inputMessagesFilterRoundVoice', + } as tl.TypeMessagesFilter, MyMention: { _: 'inputMessagesFilterMyMentions' } as tl.TypeMessagesFilter, Location: { _: 'inputMessagesFilterGeo' } as tl.TypeMessagesFilter, Contact: { _: 'inputMessagesFilterContacts' } as tl.TypeMessagesFilter, diff --git a/packages/client/src/types/misc/sticker-set.ts b/packages/client/src/types/misc/sticker-set.ts index 04f15715..8cec7fb7 100644 --- a/packages/client/src/types/misc/sticker-set.ts +++ b/packages/client/src/types/misc/sticker-set.ts @@ -107,7 +107,7 @@ export class StickerSet { return { _: 'inputStickerSetID', id: this.brief.id, - accessHash: this.brief.accessHash + accessHash: this.brief.accessHash, } } @@ -156,7 +156,7 @@ export class StickerSet { const info: tl.Mutable = { alt: sticker.emoji, emoji: '', // populated later - sticker + sticker, } this._stickers!.push(info) index[doc.id.toString()] = info @@ -183,7 +183,9 @@ export class StickerSet { * In case this object does not contain info about stickers (i.e. {@link isFull} = false) */ getStickersByEmoji(emoji: string): StickerSet.StickerInfo[] { - return this.stickers.filter(it => it.alt === emoji || it.emoji.indexOf(emoji) != -1) + return this.stickers.filter( + (it) => it.alt === emoji || it.emoji.indexOf(emoji) != -1 + ) } /** @@ -217,13 +219,14 @@ export class StickerSet { if (idx < 0) idx = this.full!.documents.length + idx const doc = this.full!.documents[idx] as tl.RawDocument - if (!doc) throw new RangeError(`Sticker set does not have sticker ${idx}`) + if (!doc) + throw new RangeError(`Sticker set does not have sticker ${idx}`) return { _: 'inputDocument', id: doc.id, accessHash: doc.accessHash, - fileReference: doc.fileReference + fileReference: doc.fileReference, } } @@ -240,7 +243,9 @@ export class StickerSet { * Sticker File ID. In case this is a full sticker set object, * you can also pass index (even negative), and that sticker will be removed */ - async deleteSticker(sticker: number | Parameters[0]): Promise { + async deleteSticker( + sticker: number | Parameters[0] + ): Promise { if (typeof sticker === 'number') { sticker = this._getInputDocument(sticker) } @@ -262,7 +267,10 @@ export class StickerSet { * you can also pass index (even negative), and that sticker will be removed * @param position New sticker position */ - async moveSticker(sticker: number | Parameters[0], position: number): Promise { + async moveSticker( + sticker: number | Parameters[0], + position: number + ): Promise { if (typeof sticker === 'number') { sticker = this._getInputDocument(sticker) } @@ -284,7 +292,9 @@ export class StickerSet { * you can also pass index (even negative), and that sticker * will be used as a thumb */ - async setThumb(thumb: number | Parameters[1]): Promise { + async setThumb( + thumb: number | Parameters[1] + ): Promise { if (typeof thumb === 'number') { thumb = this._getInputDocument(thumb) } diff --git a/packages/client/src/types/peers/chat-event.ts b/packages/client/src/types/peers/chat-event.ts index 96b526d6..b077f13e 100644 --- a/packages/client/src/types/peers/chat-event.ts +++ b/packages/client/src/types/peers/chat-event.ts @@ -351,35 +351,55 @@ function _actionFromTl( return { type: 'photo_changed', old: new Photo(this.client, e.prevPhoto as tl.RawPhoto), - new: new Photo(this.client, e.newPhoto as tl.RawPhoto) + new: new Photo(this.client, e.newPhoto as tl.RawPhoto), } case 'channelAdminLogEventActionToggleInvites': return { type: 'invites_toggled', old: !e.newValue, - new: e.newValue + new: e.newValue, } case 'channelAdminLogEventActionToggleSignatures': return { type: 'signatures_toggled', old: !e.newValue, - new: e.newValue + new: e.newValue, } case 'channelAdminLogEventActionUpdatePinned': return { type: 'msg_pinned', - message: new Message(this.client, e.message, this._users, this._chats) + message: new Message( + this.client, + e.message, + this._users, + this._chats + ), } case 'channelAdminLogEventActionEditMessage': return { type: 'msg_edited', - old: new Message(this.client, e.prevMessage, this._users, this._chats), - new: new Message(this.client, e.newMessage, this._users, this._chats) + old: new Message( + this.client, + e.prevMessage, + this._users, + this._chats + ), + new: new Message( + this.client, + e.newMessage, + this._users, + this._chats + ), } case 'channelAdminLogEventActionDeleteMessage': return { type: 'msg_deleted', - message: new Message(this.client, e.message, this._users, this._chats) + message: new Message( + this.client, + e.message, + this._users, + this._chats + ), } case 'channelAdminLogEventActionParticipantLeave': return { type: 'user_left' } @@ -391,65 +411,84 @@ function _actionFromTl( case 'channelAdminLogEventActionParticipantToggleBan': return { type: 'user_perms_changed', - old: new ChatMember(this.client, e.prevParticipant, this._users), - new: new ChatMember(this.client, e.newParticipant, this._users) + old: new ChatMember( + this.client, + e.prevParticipant, + this._users + ), + new: new ChatMember(this.client, e.newParticipant, this._users), } case 'channelAdminLogEventActionParticipantToggleAdmin': return { type: 'user_admin_perms_changed', - old: new ChatMember(this.client, e.prevParticipant, this._users), - new: new ChatMember(this.client, e.newParticipant, this._users) + old: new ChatMember( + this.client, + e.prevParticipant, + this._users + ), + new: new ChatMember(this.client, e.newParticipant, this._users), } case 'channelAdminLogEventActionChangeStickerSet': return { type: 'stickerset_changed', old: e.prevStickerset, - new: e.newStickerset + new: e.newStickerset, } case 'channelAdminLogEventActionTogglePreHistoryHidden': return { type: 'history_toggled', old: !e.newValue, - new: e.newValue + new: e.newValue, } case 'channelAdminLogEventActionDefaultBannedRights': return { type: 'def_perms_changed', old: new ChatPermissions(e.prevBannedRights), - new: new ChatPermissions(e.newBannedRights) + new: new ChatPermissions(e.newBannedRights), } case 'channelAdminLogEventActionStopPoll': return { type: 'poll_stopped', - message: new Message(this.client, e.message, this._users, this._chats) + message: new Message( + this.client, + e.message, + this._users, + this._chats + ), } case 'channelAdminLogEventActionChangeLinkedChat': return { type: 'linked_chat_changed', old: e.prevValue, - new: e.newValue + new: e.newValue, } case 'channelAdminLogEventActionChangeLocation': return { type: 'location_changed', - old: e.prevValue._ === 'channelLocationEmpty' ? null : new ChatLocation(this.client, e.prevValue), - new: e.newValue._ === 'channelLocationEmpty' ? null : new ChatLocation(this.client, e.newValue), + old: + e.prevValue._ === 'channelLocationEmpty' + ? null + : new ChatLocation(this.client, e.prevValue), + new: + e.newValue._ === 'channelLocationEmpty' + ? null + : new ChatLocation(this.client, e.newValue), } case 'channelAdminLogEventActionToggleSlowMode': return { type: 'slow_mode_changed', old: e.prevValue, - new: e.newValue + new: e.newValue, } case 'channelAdminLogEventActionStartGroupCall': return { type: 'call_started', - call: e.call + call: e.call, } case 'channelAdminLogEventActionDiscardGroupCall': return { type: 'call_ended', - call: e.call + call: e.call, } case 'channelAdminLogEventActionParticipantMute': case 'channelAdminLogEventActionParticipantUnmute': @@ -459,34 +498,34 @@ function _actionFromTl( case 'channelAdminLogEventActionToggleGroupCallSetting': return { type: 'call_setting_changed', - joinMuted: e.joinMuted + joinMuted: e.joinMuted, } case 'channelAdminLogEventActionParticipantJoinByInvite': return { type: 'user_joined_invite', - link: new ChatInviteLink(this.client, e.invite, this._users) + link: new ChatInviteLink(this.client, e.invite, this._users), } case 'channelAdminLogEventActionExportedInviteDelete': return { type: 'invite_deleted', - link: new ChatInviteLink(this.client, e.invite, this._users) + link: new ChatInviteLink(this.client, e.invite, this._users), } case 'channelAdminLogEventActionExportedInviteRevoke': return { type: 'invite_revoked', - link: new ChatInviteLink(this.client, e.invite, this._users) + link: new ChatInviteLink(this.client, e.invite, this._users), } case 'channelAdminLogEventActionExportedInviteEdit': return { type: 'invite_edited', old: new ChatInviteLink(this.client, e.prevInvite, this._users), - new: new ChatInviteLink(this.client, e.newInvite, this._users) + new: new ChatInviteLink(this.client, e.newInvite, this._users), } case 'channelAdminLogEventActionChangeHistoryTTL': return { type: 'ttl_changed', old: e.prevValue, - new: e.newValue + new: e.newValue, } default: return null diff --git a/packages/client/src/types/peers/chat-invite-link.ts b/packages/client/src/types/peers/chat-invite-link.ts index 391c9413..8be19053 100644 --- a/packages/client/src/types/peers/chat-invite-link.ts +++ b/packages/client/src/types/peers/chat-invite-link.ts @@ -20,7 +20,11 @@ export class ChatInviteLink { readonly _users?: UsersIndex - constructor (client: TelegramClient, raw: tl.RawChatInviteExported, users?: UsersIndex) { + constructor( + client: TelegramClient, + raw: tl.RawChatInviteExported, + users?: UsersIndex + ) { this.client = client this.raw = raw this._users = users diff --git a/packages/client/src/types/peers/chat-location.ts b/packages/client/src/types/peers/chat-location.ts index 78aa1e3a..576c8dac 100644 --- a/packages/client/src/types/peers/chat-location.ts +++ b/packages/client/src/types/peers/chat-location.ts @@ -10,7 +10,7 @@ export class ChatLocation { readonly client: TelegramClient readonly raw: tl.RawChannelLocation - constructor (client: TelegramClient, raw: tl.RawChannelLocation) { + constructor(client: TelegramClient, raw: tl.RawChannelLocation) { this.client = client this.raw = raw } @@ -21,7 +21,10 @@ export class ChatLocation { */ get location(): Location { if (!this._location) { - this._location = new Location(this.client, this.raw.geoPoint as tl.RawGeoPoint) + this._location = new Location( + this.client, + this.raw.geoPoint as tl.RawGeoPoint + ) } return this._location diff --git a/packages/client/src/types/peers/chat-photo.ts b/packages/client/src/types/peers/chat-photo.ts index 621894e9..92eafcfd 100644 --- a/packages/client/src/types/peers/chat-photo.ts +++ b/packages/client/src/types/peers/chat-photo.ts @@ -16,18 +16,23 @@ export class ChatPhotoSize extends FileLocation { readonly peer: tl.TypeInputPeer readonly big: boolean - constructor ( + constructor( client: TelegramClient, peer: tl.TypeInputPeer, obj: tl.RawUserProfilePhoto | tl.RawChatPhoto, - big: boolean, + big: boolean ) { - super(client, { - _: 'inputPeerPhotoFileLocation', - peer, - photoId: obj.photoId, - big, - }, undefined, obj.dcId) + super( + client, + { + _: 'inputPeerPhotoFileLocation', + peer, + photoId: obj.photoId, + big, + }, + undefined, + obj.dcId + ) this.peer = peer this.obj = obj @@ -39,7 +44,7 @@ export class ChatPhotoSize extends FileLocation { /** * TDLib and Bot API compatible File ID representing this size */ - get fileId (): string { + get fileId(): string { if (!this._fileId) { const peer = this.peer @@ -77,7 +82,7 @@ export class ChatPhotoSize extends FileLocation { _: 'dialogPhoto', big: this.big, id: bigInt(id), - accessHash: hash + accessHash: hash, }, }, }) @@ -93,10 +98,13 @@ export class ChatPhotoSize extends FileLocation { get uniqueFileId(): string { if (!this._uniqueFileId) { // todo: check how tdlib handles big/small photos here - this._uniqueFileId = toUniqueFileId(tdFileId.FileType.ProfilePhoto, { - _: 'common', - id: this.obj.photoId - }) + this._uniqueFileId = toUniqueFileId( + tdFileId.FileType.ProfilePhoto, + { + _: 'common', + id: this.obj.photoId, + } + ) } return this._uniqueFileId @@ -113,10 +121,10 @@ export class ChatPhoto { readonly obj: tl.RawUserProfilePhoto | tl.RawChatPhoto readonly peer: tl.TypeInputPeer - constructor ( + constructor( client: TelegramClient, peer: tl.TypeInputPeer, - obj: tl.RawUserProfilePhoto | tl.RawChatPhoto, + obj: tl.RawUserProfilePhoto | tl.RawChatPhoto ) { this.client = client this.peer = peer @@ -126,7 +134,7 @@ export class ChatPhoto { private _smallFile?: ChatPhotoSize /** Chat photo file location in small resolution (160x160) */ - get small (): ChatPhotoSize { + get small(): ChatPhotoSize { if (!this._smallFile) { this._smallFile = new ChatPhotoSize( this.client, @@ -141,9 +149,9 @@ export class ChatPhoto { private _bigFile: ChatPhotoSize /** Chat photo file location in big resolution (640x640) */ - get big (): ChatPhotoSize { + get big(): ChatPhotoSize { if (!this._bigFile) { - this._bigFile = new ChatPhotoSize( + this._bigFile = new ChatPhotoSize( this.client, this.peer, this.obj, @@ -159,7 +167,7 @@ export class ChatPhoto { /** * Chat photo preview in *very* small resolution, if available */ - get thumb (): Buffer | null { + get thumb(): Buffer | null { if (!this.obj.strippedThumb) return null if (!this._thumb) { diff --git a/packages/client/src/types/peers/chat.ts b/packages/client/src/types/peers/chat.ts index 15bb2e72..7280295c 100644 --- a/packages/client/src/types/peers/chat.ts +++ b/packages/client/src/types/peers/chat.ts @@ -416,11 +416,18 @@ export class Chat { * Returned only in {@link TelegramClient.getFullChat} */ get location(): ChatLocation | null { - if (!this.fullPeer || this.fullPeer._ !== 'channelFull' || this.fullPeer.location?._ !== 'channelLocation') + if ( + !this.fullPeer || + this.fullPeer._ !== 'channelFull' || + this.fullPeer.location?._ !== 'channelLocation' + ) return null if (!this._location) { - this._location = new ChatLocation(this.client, this.fullPeer.location) + this._location = new ChatLocation( + this.client, + this.fullPeer.location + ) } return this._location diff --git a/packages/client/src/types/peers/user.ts b/packages/client/src/types/peers/user.ts index e7b601bf..9a491dfd 100644 --- a/packages/client/src/types/peers/user.ts +++ b/packages/client/src/types/peers/user.ts @@ -117,7 +117,10 @@ export class User { return this._user.lastName ?? null } - static parseStatus(status: tl.TypeUserStatus, bot = false): User.ParsedStatus { + static parseStatus( + status: tl.TypeUserStatus, + bot = false + ): User.ParsedStatus { let ret: User.Status let date: Date @@ -159,7 +162,10 @@ export class User { private _parsedStatus?: User.ParsedStatus private _parseStatus() { - this._parsedStatus = User.parseStatus(this._user.status!, this._user.bot) + this._parsedStatus = User.parseStatus( + this._user.status!, + this._user.bot + ) } /** User's Last Seen & Online status */ diff --git a/packages/client/src/utils/peer-utils.ts b/packages/client/src/utils/peer-utils.ts index 0d06218b..0ff2bf9e 100644 --- a/packages/client/src/utils/peer-utils.ts +++ b/packages/client/src/utils/peer-utils.ts @@ -47,7 +47,11 @@ export function normalizeToInputPeer( } export function normalizeToInputUser( - res: tl.TypeInputUser | tl.RawInputPeerUser | tl.RawInputPeerUserFromMessage | tl.RawInputPeerSelf + res: + | tl.TypeInputUser + | tl.RawInputPeerUser + | tl.RawInputPeerUserFromMessage + | tl.RawInputPeerSelf ): tl.TypeInputUser export function normalizeToInputUser( res: tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel @@ -77,7 +81,10 @@ export function normalizeToInputUser( } export function normalizeToInputChannel( - res: tl.TypeInputChannel | tl.RawInputPeerChannel | tl.RawInputPeerChannelFromMessage + res: + | tl.TypeInputChannel + | tl.RawInputPeerChannel + | tl.RawInputPeerChannelFromMessage ): tl.TypeInputChannel export function normalizeToInputChannel( res: tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel diff --git a/packages/client/src/utils/updates-utils.ts b/packages/client/src/utils/updates-utils.ts index 4a1c664a..c1727c4d 100644 --- a/packages/client/src/utils/updates-utils.ts +++ b/packages/client/src/utils/updates-utils.ts @@ -5,7 +5,11 @@ import { MtCuteTypeAssertionError } from '../types' // that is not an update, but it carries info about pts, and we need to handle it /** @internal */ -export function createDummyUpdate(pts: number, ptsCount: number, channelId = 0): tl.TypeUpdates { +export function createDummyUpdate( + pts: number, + ptsCount: number, + channelId = 0 +): tl.TypeUpdates { return { _: 'updates', seq: 0, @@ -20,24 +24,35 @@ export function createDummyUpdate(pts: number, ptsCount: number, channelId = 0): ptsCount, // since message id cant be negative, using negative 42 // here makes it distinctive from real updates - messages: [-42] - } - ] + messages: [-42], + }, + ], } } /** @internal */ export function isDummyUpdate(upd: tl.TypeUpdate): boolean { - return upd._ === 'updatePinnedChannelMessages' && upd.messages.length === 1 && upd.messages[0] === -42 + return ( + upd._ === 'updatePinnedChannelMessages' && + upd.messages.length === 1 && + upd.messages[0] === -42 + ) } /** @internal */ export function isDummyUpdates(upd: tl.TypeUpdates): boolean { - return upd._ === 'updates' && upd.updates.length === 1 && isDummyUpdate(upd.updates[0]) + return ( + upd._ === 'updates' && + upd.updates.length === 1 && + isDummyUpdate(upd.updates[0]) + ) } /** @internal */ -export function assertIsUpdatesGroup(ctx: string, upd: tl.TypeUpdates): asserts upd is tl.RawUpdates | tl.RawUpdatesCombined { +export function assertIsUpdatesGroup( + ctx: string, + upd: tl.TypeUpdates +): asserts upd is tl.RawUpdates | tl.RawUpdatesCombined { switch (upd._) { case 'updates': case 'updatesCombined': diff --git a/packages/core/src/base-client.ts b/packages/core/src/base-client.ts index 5ff656bf..c863d814 100644 --- a/packages/core/src/base-client.ts +++ b/packages/core/src/base-client.ts @@ -288,6 +288,7 @@ export class BaseTelegramClient { await this.storage.load?.() } + // eslint-disable-next-line @typescript-eslint/no-unused-vars protected async _saveStorage(afterImport = false): Promise { await this.storage.save?.() } @@ -370,7 +371,8 @@ export class BaseTelegramClient { if (!this.primaryConnection.authKey && this._importFrom) { const buf = parseUrlSafeBase64(this._importFrom) - if (buf[0] !== 1) throw new Error(`Invalid session string (version = ${buf[0]})`) + if (buf[0] !== 1) + throw new Error(`Invalid session string (version = ${buf[0]})`) const reader = new BinaryReader(buf, 1) @@ -379,7 +381,9 @@ export class BaseTelegramClient { const primaryDc = reader.object() if (primaryDc._ !== 'dcOption') { - throw new Error(`Invalid session string (dc._ = ${primaryDc._})`) + throw new Error( + `Invalid session string (dc._ = ${primaryDc._})` + ) } this._primaryDc = this.primaryConnection.params.dc = primaryDc @@ -725,7 +729,7 @@ export class BaseTelegramClient { * * @returns `true` if there were any `min` peers */ - protected async _cachePeersFrom(obj: any): Promise { + protected async _cachePeersFrom(obj: object): Promise { const parsedPeers: ITelegramStorage.PeerInfo[] = [] let hadMin = false diff --git a/packages/core/src/network/mtproto-session.ts b/packages/core/src/network/mtproto-session.ts index 60ee9aa6..3d0b0e14 100644 --- a/packages/core/src/network/mtproto-session.ts +++ b/packages/core/src/network/mtproto-session.ts @@ -69,10 +69,9 @@ export class MtprotoSession { ): Promise { if (!this._authKey) throw new Error('Keys are not set up!') - const length = - Buffer.isBuffer(message) - ? message.length - : SerializationCounter.countNeededBytes(message) + const length = Buffer.isBuffer(message) + ? message.length + : SerializationCounter.countNeededBytes(message) let padding = (32 /* header size */ + length + 12) /* min padding */ % 16 padding = 12 + (padding ? 16 - padding : 0) diff --git a/packages/core/src/network/telegram-connection.ts b/packages/core/src/network/telegram-connection.ts index 59aeccfe..c1867ac6 100644 --- a/packages/core/src/network/telegram-connection.ts +++ b/packages/core/src/network/telegram-connection.ts @@ -16,15 +16,18 @@ import { import { debounce } from '../utils/function-utils' import { bufferToBigInt, ulongToLong } from '../utils/bigint-utils' import { randomBytes } from '../utils/buffer-utils' -import { BadRequestError, createRpcErrorFromTl, RpcError, RpcTimeoutError, TimeoutError } from '@mtcute/tl/errors' +import { + BadRequestError, + createRpcErrorFromTl, + RpcError, + RpcTimeoutError, +} from '@mtcute/tl/errors' import { LruStringSet } from '../utils/lru-string-set' function makeNiceStack(error: RpcError, stack: string, method?: string) { - error.stack = `${error.constructor.name} (${error.code} ${ - error.text - }): ${error.message}\n at ${ - method - }\n${stack.split('\n').slice(2).join('\n')}` + error.stack = `${error.constructor.name} (${error.code} ${error.text}): ${ + error.message + }\n at ${method}\n${stack.split('\n').slice(2).join('\n')}` } const _debug = require('debug') @@ -187,7 +190,9 @@ export class TelegramConnection extends PersistentConnection { this._sendOnceUsable = [] sendOnceUsable.forEach((it) => this._resend(it)) - Object.entries(this._pendingRpcCalls).forEach(([id, it]) => this._resend(it, id)) + Object.entries(this._pendingRpcCalls).forEach(([id, it]) => + this._resend(it, id) + ) this._pingInterval = setInterval(() => { if (this._pendingPing === null) { @@ -562,15 +567,19 @@ export class TelegramConnection extends PersistentConnection { method: string, message: Buffer, stack?: string, - timeout?: number, + timeout?: number ): Promise async _sendBufferForResult( method: string | PendingMessage, message?: Buffer, stack?: string, - timeout?: number, + timeout?: number ): Promise { - if (typeof method === 'string' && this.params.niceStacks !== false && !stack) { + if ( + typeof method === 'string' && + this.params.niceStacks !== false && + !stack + ) { stack = new Error().stack } @@ -580,7 +589,9 @@ export class TelegramConnection extends PersistentConnection { // and since we resend them, it will get resent after reconnection and // that will be an endless loop of reconnections. we don't want that, // and payloads this large are usually a sign of an error in the code. - const err = new Error(`Payload is too big (${content.length} > 1044404)`) + const err = new Error( + `Payload is too big (${content.length} > 1044404)` + ) if (typeof method === 'string') { throw err } else { @@ -645,7 +656,7 @@ export class TelegramConnection extends PersistentConnection { async sendForResult( message: T, stack?: string, - timeout?: number, + timeout?: number ): Promise { if (this._usable && this.params.inactivityTimeout) this._rescheduleInactivity() diff --git a/packages/core/src/network/transports/obfuscated.ts b/packages/core/src/network/transports/obfuscated.ts index 6524812c..3387c947 100644 --- a/packages/core/src/network/transports/obfuscated.ts +++ b/packages/core/src/network/transports/obfuscated.ts @@ -1,6 +1,5 @@ import { PacketCodec } from './abstract' -import { ICryptoProvider, IEncryptionScheme } from '../../utils/crypto' -import { EventEmitter } from 'events' +import { IEncryptionScheme } from '../../utils/crypto' import { buffersEqual, randomBytes } from '../../utils/buffer-utils' import { WrappedCodec } from './wrapped' diff --git a/packages/core/src/network/transports/websocket.ts b/packages/core/src/network/transports/websocket.ts index e94cedc9..8e157d31 100644 --- a/packages/core/src/network/transports/websocket.ts +++ b/packages/core/src/network/transports/websocket.ts @@ -10,10 +10,7 @@ import { ObfuscatedPacketCodec } from './obfuscated' const debug = require('debug')('mtcute:ws') let ws: { - new ( - address: string, - options?: string - ): WebSocket + new (address: string, options?: string): WebSocket } | null if (typeof window === 'undefined' || typeof window.WebSocket === 'undefined') { try { @@ -104,7 +101,8 @@ export abstract class WebSocketTransport this._socket = new ws!( `wss://${this._subdomains[dc.id]}.${this._baseDomain}/apiws${ this._isTest ? '_test' : '' - }`, 'binary' + }`, + 'binary' ) this._socket.addEventListener('message', (evt) => diff --git a/packages/core/src/network/transports/wrapped.ts b/packages/core/src/network/transports/wrapped.ts index 42ab6356..236922b0 100644 --- a/packages/core/src/network/transports/wrapped.ts +++ b/packages/core/src/network/transports/wrapped.ts @@ -6,7 +6,7 @@ export abstract class WrappedCodec extends EventEmitter { protected _crypto: ICryptoProvider protected _inner: PacketCodec - constructor (inner: PacketCodec) { + constructor(inner: PacketCodec) { super() this._inner = inner this._inner.on('error', (err) => this.emit('error', err)) diff --git a/packages/core/src/storage/memory.ts b/packages/core/src/storage/memory.ts index 80676cf1..577f27a3 100644 --- a/packages/core/src/storage/memory.ts +++ b/packages/core/src/storage/memory.ts @@ -28,7 +28,7 @@ interface MemorySessionState { pts: Record // state for fsm (v = value, e = expires) - fsm: Record + fsm: Record self: ITelegramStorage.SelfInfo | null } @@ -79,7 +79,7 @@ export class MemoryStorage implements ITelegramStorage /*, IStateStorage */ { * Note that this object will be used as-is, so if * you plan on using it somewhere else, be sure to copy it beforehand. */ - protected _setStateFrom(obj: any): void { + protected _setStateFrom(obj: MemorySessionState): void { if (obj.$version !== CURRENT_VERSION) return // populate indexes if needed @@ -94,10 +94,12 @@ export class MemoryStorage implements ITelegramStorage /*, IStateStorage */ { } if (populate) { - obj.entities.forEach((ent: ITelegramStorage.PeerInfo) => { - if (ent.phone) obj.phoneIndex[ent.phone] = ent.id - if (ent.username) obj.usernameIndex[ent.username] = ent.id - }) + Object.values(obj.entities).forEach( + (ent: ITelegramStorage.PeerInfo) => { + if (ent.phone) obj.phoneIndex[ent.phone] = ent.id + if (ent.username) obj.usernameIndex[ent.username] = ent.id + } + ) } this._state = obj @@ -252,8 +254,12 @@ export class MemoryStorage implements ITelegramStorage /*, IStateStorage */ { return val.v } + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types setState(key: string, state: any, ttl?: number): void { - this._state.fsm[key] = { v: state, e: ttl ? Date.now() + (ttl * 1000) : undefined } + this._state.fsm[key] = { + v: state, + e: ttl ? Date.now() + ttl * 1000 : undefined, + } } deleteState(key: string): void { diff --git a/packages/core/src/utils/binary/binary-reader.ts b/packages/core/src/utils/binary/binary-reader.ts index dbdb9d9b..a106e21f 100644 --- a/packages/core/src/utils/binary/binary-reader.ts +++ b/packages/core/src/utils/binary/binary-reader.ts @@ -5,7 +5,8 @@ import readerMap, { ITlBinaryReader } from '@mtcute/tl/binary/reader' import { bufferToBigInt, longToUlong, ulongToLong } from '../bigint-utils' import { tl } from '@mtcute/tl' -const isNativeBigIntAvailable = typeof BigInt !== 'undefined' && 'readBigInt64LE' in Buffer.prototype +const isNativeBigIntAvailable = + typeof BigInt !== 'undefined' && 'readBigInt64LE' in Buffer.prototype export class BinaryReader implements ITlBinaryReader { data: Buffer diff --git a/packages/core/src/utils/binary/binary-writer.ts b/packages/core/src/utils/binary/binary-writer.ts index 6c5be1f5..d6b9881a 100644 --- a/packages/core/src/utils/binary/binary-writer.ts +++ b/packages/core/src/utils/binary/binary-writer.ts @@ -11,9 +11,10 @@ type SerializableObject = { [key: string]: any } -const isNativeBigIntAvailable = typeof BigInt !== 'undefined' && 'writeBigInt64LE' in Buffer.prototype +const isNativeBigIntAvailable = + typeof BigInt !== 'undefined' && 'writeBigInt64LE' in Buffer.prototype -function utf8ByteLength (string: string): number { +function utf8ByteLength(string: string): number { let codePoint const length = string.length let leadSurrogate = null @@ -23,11 +24,11 @@ function utf8ByteLength (string: string): number { codePoint = string.charCodeAt(i) // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { + if (codePoint > 0xd7ff && codePoint < 0xe000) { // last char was a lead if (!leadSurrogate) { // no lead yet - if (codePoint > 0xDBFF) { + if (codePoint > 0xdbff) { // unexpected trail bytes += 3 continue @@ -44,14 +45,16 @@ function utf8ByteLength (string: string): number { } // 2 leads in a row - if (codePoint < 0xDC00) { + if (codePoint < 0xdc00) { bytes += 3 leadSurrogate = codePoint continue } // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + codePoint = + (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead bytes += 3 @@ -79,7 +82,9 @@ function utf8ByteLength (string: string): number { // buffer package for the web detects size by writing the string to an array and checking size // that is slow. // see https://github.com/feross/buffer/blob/795bbb5bda1b39f1370ebd784bea6107b087e3a7/index.js#L527 -const utfLength = (Buffer.prototype as any)._isBuffer ? utf8ByteLength : Buffer.byteLength +const utfLength = (Buffer.prototype as any)._isBuffer + ? utf8ByteLength + : Buffer.byteLength export class SerializationCounter implements ITlBinaryWriter { count = 0 @@ -95,39 +100,39 @@ export class SerializationCounter implements ITlBinaryWriter { return cnt.count } - boolean(val: boolean): void { + boolean(): void { this.count += 4 } - double(val: number): void { + double(): void { this.count += 8 } - float(val: number): void { + float(): void { this.count += 4 } - int128(val: Buffer): void { + int128(): void { this.count += 16 } - int256(val: Buffer): void { + int256(): void { this.count += 32 } - int32(val: number): void { + int32(): void { this.count += 4 } - uint32(val: number): void { + uint32(): void { this.count += 4 } - long(val: BigInteger): void { + long(): void { this.count += 8 } - rawLong(val: Buffer): void { + rawLong(): void { this.count += 8 } @@ -192,7 +197,7 @@ export class BinaryWriter implements ITlBinaryWriter { static serializeObject( obj: SerializableObject, knownSize = -1, - objectMap?: any + objectMap?: TlWriterMap ): Buffer { if (knownSize === -1) knownSize = SerializationCounter.countNeededBytes(obj) diff --git a/packages/core/src/utils/crypto/abstract.ts b/packages/core/src/utils/crypto/abstract.ts index 860044f2..f53788c4 100644 --- a/packages/core/src/utils/crypto/abstract.ts +++ b/packages/core/src/utils/crypto/abstract.ts @@ -66,7 +66,11 @@ export abstract class BaseCryptoProvider implements ICryptoProvider { return bigIntToBuffer(encryptedBigInt) } - abstract createAesCtr(key: Buffer, iv: Buffer, encrypt: boolean): IEncryptionScheme + abstract createAesCtr( + key: Buffer, + iv: Buffer, + encrypt: boolean + ): IEncryptionScheme abstract createAesEcb(key: Buffer): IEncryptionScheme diff --git a/packages/core/src/utils/crypto/factorization.ts b/packages/core/src/utils/crypto/factorization.ts index a4b8b5fd..f4aa2287 100644 --- a/packages/core/src/utils/crypto/factorization.ts +++ b/packages/core/src/utils/crypto/factorization.ts @@ -58,6 +58,8 @@ function leemonPqFactorizationSync(what: leemonBigint): [Buffer, Buffer] { lim = 1 << (i + 18) for (j = 1; j < lim; j++) { + // idk why is this needed, but i'd rather not touch :shrug: + // eslint-disable-next-line @typescript-eslint/no-unused-vars ++it copy_(a, x) copy_(b, x) diff --git a/packages/core/src/utils/crypto/forge-crypto.ts b/packages/core/src/utils/crypto/forge-crypto.ts index ea918fa6..39fa8da0 100644 --- a/packages/core/src/utils/crypto/forge-crypto.ts +++ b/packages/core/src/utils/crypto/forge-crypto.ts @@ -104,9 +104,6 @@ export class ForgeCryptoProvider extends BaseCryptoProvider { const hmac = forge.hmac.create() hmac.start('sha256', key.toString('binary')) hmac.update(data.toString('binary')) - return Buffer.from( - hmac.digest().data, - 'binary' - ) + return Buffer.from(hmac.digest().data, 'binary') } } diff --git a/packages/core/src/utils/crypto/keys.ts b/packages/core/src/utils/crypto/keys.ts index 80367019..c7ed8a0e 100644 --- a/packages/core/src/utils/crypto/keys.ts +++ b/packages/core/src/utils/crypto/keys.ts @@ -35,7 +35,7 @@ export async function addPublicKey( crypto: ICryptoProvider, key: string, old = false -) { +): Promise { const parsed = await parsePublicKey(crypto, key, old) keysIndex[parsed.fingerprint] = parsed } diff --git a/packages/core/src/utils/crypto/password.ts b/packages/core/src/utils/crypto/password.ts index 32fab2b5..79b4ca36 100644 --- a/packages/core/src/utils/crypto/password.ts +++ b/packages/core/src/utils/crypto/password.ts @@ -29,7 +29,10 @@ export async function computeNewPasswordHash( algo: tl.RawPasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow, password: string ): Promise { - (algo as tl.Mutable).salt1 = Buffer.concat([algo.salt1, randomBytes(32)]) + ;(algo as tl.Mutable).salt1 = Buffer.concat([ + algo.salt1, + randomBytes(32), + ]) const _x = await computePasswordHash( crypto, diff --git a/packages/core/src/utils/function-utils.ts b/packages/core/src/utils/function-utils.ts index 7889b5fa..382e8da2 100644 --- a/packages/core/src/utils/function-utils.ts +++ b/packages/core/src/utils/function-utils.ts @@ -40,7 +40,7 @@ export function debounce( * @param func Function to throttle * @param delay Throttle delay */ -export function throttle (func: T, delay: number): T { +export function throttle(func: T, delay: number): T { let timeout: NodeJS.Timeout | null return function (this: any) { diff --git a/packages/core/src/utils/lru-map.ts b/packages/core/src/utils/lru-map.ts index 34d4b5ec..165e746d 100644 --- a/packages/core/src/utils/lru-map.ts +++ b/packages/core/src/utils/lru-map.ts @@ -29,7 +29,7 @@ export class LruMap { if (typeof Map === 'undefined' || useObject) { const obj = {} as any - this._set = (k, v) => obj[k] = v + this._set = (k, v) => (obj[k] = v) this._has = (k) => k in obj this._get = (k) => obj[k] this._del = (k) => delete obj[k] @@ -95,7 +95,7 @@ export class LruMap { item = { k: key, - v: value + v: value, } this._set(key, item as any) diff --git a/packages/core/src/utils/peer-utils.ts b/packages/core/src/utils/peer-utils.ts index 4a9b84eb..b1977ad7 100644 --- a/packages/core/src/utils/peer-utils.ts +++ b/packages/core/src/utils/peer-utils.ts @@ -28,10 +28,7 @@ export function getBarePeerId(peer: tl.TypePeer): number { * - ID is negated for chats * - ID is negated and `1e12` is subtracted for channels */ -export function getMarkedPeerId( - peerId: number, - peerType: BasicPeerType -): number +export function getMarkedPeerId(peerId: number, peerType: BasicPeerType): number export function getMarkedPeerId(peer: tl.TypePeer | tl.TypeInputPeer): number export function getMarkedPeerId( peer: tl.TypePeer | tl.TypeInputPeer | number, @@ -108,10 +105,9 @@ export function markedPeerIdToBare(peerId: number): number { * Only checks `.user`, `.chat`, `.channel`, `.users` and `.chats` properties */ export function* getAllPeersFrom( + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types obj: any -): Iterable< - (tl.TypeUser | tl.TypeChat) -> { +): Iterable { if (typeof obj !== 'object') return switch (obj._) { diff --git a/packages/core/src/utils/tl-json.ts b/packages/core/src/utils/tl-json.ts index 0ccb333d..127fb470 100644 --- a/packages/core/src/utils/tl-json.ts +++ b/packages/core/src/utils/tl-json.ts @@ -5,6 +5,7 @@ import { tl } from '@mtcute/tl' * * @param obj Object to be converted */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export function jsonToTlJson(obj: any): tl.TypeJSONValue { if (obj === null || obj === undefined) return { _: 'jsonNull' } if (typeof obj === 'boolean') return { _: 'jsonBool', value: obj } diff --git a/packages/dispatcher/src/builders.ts b/packages/dispatcher/src/builders.ts index 9bc0f871..c6cfc4d2 100644 --- a/packages/dispatcher/src/builders.ts +++ b/packages/dispatcher/src/builders.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ // begin-codegen-imports import { UpdateHandler, diff --git a/packages/dispatcher/src/dispatcher.ts b/packages/dispatcher/src/dispatcher.ts index ed26b6d4..f8927f65 100644 --- a/packages/dispatcher/src/dispatcher.ts +++ b/packages/dispatcher/src/dispatcher.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import { CallbackQuery, ChatsIndex, @@ -196,9 +197,8 @@ export class Dispatcher { this.bindToClient(client) if (storage) { this._storage = storage as any - this._stateKeyDelegate = ( - key ?? defaultStateKeyDelegate - ) as any + this._stateKeyDelegate = (key ?? + defaultStateKeyDelegate) as any } } else if (typeof client === 'function') { // is StateKeyDelegate @@ -367,7 +367,10 @@ export class Dispatcher { const key = await this._stateKeyDelegate!(parsed) if (key) { let customKey - if (!this._customStateKeyDelegate || (customKey = await this._customStateKeyDelegate(parsed))) { + if ( + !this._customStateKeyDelegate || + (customKey = await this._customStateKeyDelegate(parsed)) + ) { parsedState = new UpdateState( this._storage!, key, @@ -454,7 +457,7 @@ export class Dispatcher { users, chats, parsed, - parsedType, + parsedType ) } } @@ -636,9 +639,7 @@ export class Dispatcher { } if (uid[0] === '$') { - throw new MtCuteArgumentError( - `Scene UID cannot start with $` - ) + throw new MtCuteArgumentError(`Scene UID cannot start with $`) } if (scene._scene) { @@ -668,7 +669,6 @@ export class Dispatcher { const idx = this._children.indexOf(child) if (idx > -1) { child._parent = child._client = undefined - ;(child as any)._stateKeyDelegate = undefined ;(child as any)._storage = undefined this._children.splice(idx, 1) @@ -770,44 +770,42 @@ export class Dispatcher { ) } - return Promise.resolve(this._stateKeyDelegate!(object)).then( - (key) => { - if (!key) { - throw new MtCuteArgumentError( - 'Cannot derive key from given object' - ) - } + return Promise.resolve(this._stateKeyDelegate!(object)).then((key) => { + if (!key) { + throw new MtCuteArgumentError( + 'Cannot derive key from given object' + ) + } + + if (!this._customStateKeyDelegate) { + return new UpdateState( + this._storage!, + key, + this._scene ?? null, + this._sceneScoped, + this._customStorage + ) + } + + return Promise.resolve(this._customStateKeyDelegate(object)).then( + (customKey) => { + if (!customKey) { + throw new MtCuteArgumentError( + 'Cannot derive custom key from given object' + ) + } - if (!this._customStateKeyDelegate) { return new UpdateState( this._storage!, key, this._scene ?? null, this._sceneScoped, - this._customStorage + this._customStorage, + customKey ) } - - return Promise.resolve(this._customStateKeyDelegate(object)).then( - (customKey) => { - if (!customKey) { - throw new MtCuteArgumentError( - 'Cannot derive custom key from given object' - ) - } - - return new UpdateState( - this._storage!, - key, - this._scene ?? null, - this._sceneScoped, - this._customStorage, - customKey - ) - } - ) - } - ) + ) + }) } // addUpdateHandler convenience wrappers // diff --git a/packages/dispatcher/src/filters.ts b/packages/dispatcher/src/filters.ts index c0c7e9dc..06784582 100644 --- a/packages/dispatcher/src/filters.ts +++ b/packages/dispatcher/src/filters.ts @@ -13,7 +13,6 @@ import { Photo, RawDocument, Sticker, - TelegramClient, User, Venue, Video, @@ -309,16 +308,18 @@ export namespace filters { * * Messages sent to yourself (i.e. Saved Messages) are also "incoming" */ - export const incoming: UpdateFilter = (msg) => - !msg.isOutgoing + export const incoming: UpdateFilter = ( + msg + ) => !msg.isOutgoing /** * Filter outgoing messages. * * Messages sent to yourself (i.e. Saved Messages) are **not** "outgoing" */ - export const outgoing: UpdateFilter = (msg) => - msg.isOutgoing + export const outgoing: UpdateFilter = ( + msg + ) => msg.isOutgoing /** * Filter messages that are replies to some other message @@ -692,7 +693,9 @@ export namespace filters { * * @param predicate State predicate */ - export const state = (predicate: (state: T) => MaybeAsync): UpdateFilter => { + export const state = ( + predicate: (state: T) => MaybeAsync + ): UpdateFilter => { return async (upd, state) => { if (!state) return false const data = await state.get() diff --git a/packages/dispatcher/src/state/key.ts b/packages/dispatcher/src/state/key.ts index 3d5aec34..397faef7 100644 --- a/packages/dispatcher/src/state/key.ts +++ b/packages/dispatcher/src/state/key.ts @@ -14,7 +14,9 @@ import { MaybeAsync } from '@mtcute/core' * @param msg Message or callback from which to derive the key * @param scene Current scene UID, or `null` if none */ -export type StateKeyDelegate = (upd: Message | CallbackQuery) => MaybeAsync +export type StateKeyDelegate = ( + upd: Message | CallbackQuery +) => MaybeAsync /** * Default state key delegate. @@ -27,7 +29,9 @@ export type StateKeyDelegate = (upd: Message | CallbackQuery) => MaybeAsync { +export const defaultStateKeyDelegate: StateKeyDelegate = ( + upd +): string | null => { if (upd.constructor === Message) { switch (upd.chat.type) { case 'private': diff --git a/packages/dispatcher/src/state/update-state.ts b/packages/dispatcher/src/state/update-state.ts index 354d36f3..39406487 100644 --- a/packages/dispatcher/src/state/update-state.ts +++ b/packages/dispatcher/src/state/update-state.ts @@ -44,7 +44,10 @@ export class UpdateState { private _updateLocalKey(): void { if (!this._scoped) this._localKey = this._localKeyBase - else this._localKey = this._scene ? this._scene + '_' + this._localKeyBase : this._localKeyBase + else + this._localKey = this._scene + ? this._scene + '_' + this._localKeyBase + : this._localKeyBase } /** diff --git a/packages/dispatcher/src/updates/chosen-inline-result.ts b/packages/dispatcher/src/updates/chosen-inline-result.ts index d1c83953..a55250a4 100644 --- a/packages/dispatcher/src/updates/chosen-inline-result.ts +++ b/packages/dispatcher/src/updates/chosen-inline-result.ts @@ -4,7 +4,8 @@ import { TelegramClient, User, Location, - MtCuteArgumentError, UsersIndex, + MtCuteArgumentError, + UsersIndex, } from '@mtcute/client' import { encodeInlineMessageId } from '@mtcute/client/src/utils/inline-utils' diff --git a/packages/dispatcher/src/updates/user-status-update.ts b/packages/dispatcher/src/updates/user-status-update.ts index b53a9d71..c6a48657 100644 --- a/packages/dispatcher/src/updates/user-status-update.ts +++ b/packages/dispatcher/src/updates/user-status-update.ts @@ -9,10 +9,7 @@ export class UserStatusUpdate { readonly client: TelegramClient readonly raw: tl.RawUpdateUserStatus - constructor( - client: TelegramClient, - raw: tl.RawUpdateUserStatus - ) { + constructor(client: TelegramClient, raw: tl.RawUpdateUserStatus) { this.client = client this.raw = raw } diff --git a/packages/file-id/src/convert.ts b/packages/file-id/src/convert.ts index 0b9c6150..b03518c1 100644 --- a/packages/file-id/src/convert.ts +++ b/packages/file-id/src/convert.ts @@ -124,7 +124,7 @@ export function fileIdToInputFileLocation( id: loc.source.id, accessHash: loc.source.accessHash, }, - thumbVersion: 0 // todo: check how tdlib stores this + thumbVersion: 0, // todo: check how tdlib stores this } } diff --git a/packages/file-id/src/types.ts b/packages/file-id/src/types.ts index 3ef00ac4..819d1652 100644 --- a/packages/file-id/src/types.ts +++ b/packages/file-id/src/types.ts @@ -192,6 +192,7 @@ export namespace tdFileId { } export function isFileIdLike( + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types obj: any ): obj is string | RawFullRemoteFileLocation { return ( diff --git a/packages/file-id/tests/serialize-unique.spec.ts b/packages/file-id/tests/serialize-unique.spec.ts index 2b9272c1..e76ec902 100644 --- a/packages/file-id/tests/serialize-unique.spec.ts +++ b/packages/file-id/tests/serialize-unique.spec.ts @@ -35,8 +35,14 @@ describe('serializing unique file ids', () => { it('serializes unique ids for profile pictures', () => { // big - test('AQADAgATySHBDgAEAwAD0npI3Bb___-wfxjpg7QCPf8pBQABHwQ', 'AQADySHBDgAE_ykFAAE') + test( + 'AQADAgATySHBDgAEAwAD0npI3Bb___-wfxjpg7QCPf8pBQABHwQ', + 'AQADySHBDgAE_ykFAAE' + ) // small - test('AQADAgATySHBDgAEAgAD0npI3Bb___-wfxjpg7QCPf0pBQABHwQ', 'AQADySHBDgAE_SkFAAE') + test( + 'AQADAgATySHBDgAEAgAD0npI3Bb___-wfxjpg7QCPf0pBQABHwQ', + 'AQADySHBDgAE_SkFAAE' + ) }) }) diff --git a/packages/file-id/tests/serialize.spec.ts b/packages/file-id/tests/serialize.spec.ts index 0124a2f8..5032da5d 100644 --- a/packages/file-id/tests/serialize.spec.ts +++ b/packages/file-id/tests/serialize.spec.ts @@ -8,9 +8,15 @@ describe('serializing to file ids', () => { expect(toFileId(parseFileId(fileId))).eq(fileId) } - test('CAACAgIAAxkBAAEJny9gituz1_V_uSKBUuG_nhtzEtFOeQACXFoAAuCjggfYjw_KAAGSnkgfBA') - test('BQACAgIAAxkBAAEJnzNgit00IDsKd07OdSeanwz8osecYAACdAwAAueoWEicaPvNdOYEwB8E') - test('AAMCAgADGQEAAQmfL2CK27PX9X-5IoFS4b-eG3MS0U55AAJcWgAC4KOCB9iPD8oAAZKeSK1c8w4ABAEAB20AA1kCAAIfBA') + test( + 'CAACAgIAAxkBAAEJny9gituz1_V_uSKBUuG_nhtzEtFOeQACXFoAAuCjggfYjw_KAAGSnkgfBA' + ) + test( + 'BQACAgIAAxkBAAEJnzNgit00IDsKd07OdSeanwz8osecYAACdAwAAueoWEicaPvNdOYEwB8E' + ) + test( + 'AAMCAgADGQEAAQmfL2CK27PX9X-5IoFS4b-eG3MS0U55AAJcWgAC4KOCB9iPD8oAAZKeSK1c8w4ABAEAB20AA1kCAAIfBA' + ) test('AQADAgATqfDdly4AAwMAA4siCOX_____AAhKowIAAR8E') test('AQADAgATqfDdly4AAwIAA4siCOX_____AAhIowIAAR8E') test('AQADAgATySHBDgAEAwAD0npI3Bb___-wfxjpg7QCPf8pBQABHwQ') diff --git a/packages/file-id/tests/utils.spec.ts b/packages/file-id/tests/utils.spec.ts index 79c2a2ea..c5e7d25a 100644 --- a/packages/file-id/tests/utils.spec.ts +++ b/packages/file-id/tests/utils.spec.ts @@ -1,9 +1,6 @@ import { describe, it } from 'mocha' import { expect } from 'chai' -import { - telegramRleDecode, - telegramRleEncode, -} from '../src/utils' +import { telegramRleDecode, telegramRleEncode } from '../src/utils' describe('telegramRleEncode', () => { it('should not modify input if there are no \\x00', () => { diff --git a/packages/html-parser/src/index.ts b/packages/html-parser/src/index.ts index 0a7b5613..c9240cd7 100644 --- a/packages/html-parser/src/index.ts +++ b/packages/html-parser/src/index.ts @@ -115,7 +115,7 @@ export class HtmlMessageEntityParser implements IMessageEntityParser { language: attribs.language ?? '', } break - case 'a': + case 'a': { const url = attribs.href if (!url) return @@ -150,6 +150,7 @@ export class HtmlMessageEntityParser implements IMessageEntityParser { } } break + } default: return } diff --git a/packages/http-proxy/index.ts b/packages/http-proxy/index.ts index cc15b3c1..efe50f51 100644 --- a/packages/http-proxy/index.ts +++ b/packages/http-proxy/index.ts @@ -15,8 +15,10 @@ const debug = require('debug')('mtcute:http-proxy') export class HttpProxyConnectionError extends Error { readonly proxy: HttpProxySettings - constructor (proxy: HttpProxySettings, message: string) { - super(`Error while connecting to ${proxy.host}:${proxy.port}: ${message}`) + constructor(proxy: HttpProxySettings, message: string) { + super( + `Error while connecting to ${proxy.host}:${proxy.port}: ${message}` + ) this.proxy = proxy } } diff --git a/packages/mtproxy/fake-tls.ts b/packages/mtproxy/fake-tls.ts index 42e9dce2..a8a33966 100644 --- a/packages/mtproxy/fake-tls.ts +++ b/packages/mtproxy/fake-tls.ts @@ -4,7 +4,7 @@ import { ICryptoProvider, PacketCodec, WrappedCodec, - randomBytes + randomBytes, } from '@mtcute/core' import bigInt, { BigInteger } from 'big-integer' @@ -17,9 +17,15 @@ const KEY_MOD = bigInt( 16 ) // 2^255 - 19 -const QUAD_RES_MOD = bigInt('7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed', 16) +const QUAD_RES_MOD = bigInt( + '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed', + 16 +) // (mod - 1) / 2 = 2^254 - 10 -const QUAD_RES_POW = bigInt('3ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6', 16) +const QUAD_RES_POW = bigInt( + '3ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6', + 16 +) function _getY2(x: BigInteger, mod: BigInteger): BigInteger { // returns y = x^3 + x^2 * 486662 + x @@ -261,7 +267,11 @@ class TlsHelloWriter implements TlsOperationHandler { } /** @internal */ -export async function generateFakeTlsHeader(domain: string, secret: Buffer, crypto: ICryptoProvider): Promise { +export async function generateFakeTlsHeader( + domain: string, + secret: Buffer, + crypto: ICryptoProvider +): Promise { const domainBuf = Buffer.from(domain) const writer = new TlsHelloWriter(517, domainBuf) @@ -309,7 +319,10 @@ export class FakeTlsPacketCodec extends WrappedCodec implements PacketCodec { if (packet.length + this._header.length > MAX_TLS_PACKET_LENGTH) { const ret: Buffer[] = [] while (packet.length) { - const buf = packet.slice(0, MAX_TLS_PACKET_LENGTH - this._header.length) + const buf = packet.slice( + 0, + MAX_TLS_PACKET_LENGTH - this._header.length + ) packet = packet.slice(buf.length) ret.push(this._encodeTls(buf)) } diff --git a/packages/mtproxy/index.ts b/packages/mtproxy/index.ts index cfd1de07..a4611153 100644 --- a/packages/mtproxy/index.ts +++ b/packages/mtproxy/index.ts @@ -155,7 +155,11 @@ export class MtProxyTcpTransport extends TcpTransport { private async _handleConnectFakeTls(): Promise { try { - const hello = await generateFakeTlsHeader(this._fakeTlsDomain!, this._rawSecret, this._crypto) + const hello = await generateFakeTlsHeader( + this._fakeTlsDomain!, + this._rawSecret, + this._crypto + ) const helloRand = hello.slice(11, 11 + 32) const checkHelloResponse = async (buf: Buffer): Promise => { @@ -166,7 +170,9 @@ export class MtProxyTcpTransport extends TcpTransport { } if (first.compare(first, 0, first.length) !== 0) { - throw new Error('First part of hello response is invalid') + throw new Error( + 'First part of hello response is invalid' + ) } buf = buf.slice(first.length) @@ -180,12 +186,15 @@ export class MtProxyTcpTransport extends TcpTransport { } const respRand = resp.slice(11, 11 + 32) - const hash = await this._crypto.hmacSha256(Buffer.concat([ - helloRand, - resp.slice(0, 11), - Buffer.alloc(32, 0), - resp.slice(11 + 32) - ]), this._rawSecret) + const hash = await this._crypto.hmacSha256( + Buffer.concat([ + helloRand, + resp.slice(0, 11), + Buffer.alloc(32, 0), + resp.slice(11 + 32), + ]), + this._rawSecret + ) if (hash.compare(respRand) !== 0) { throw new Error('Response hash is invalid') @@ -196,7 +205,9 @@ export class MtProxyTcpTransport extends TcpTransport { try { await checkHelloResponse(buf) - this._socket!.on('data', (data) => this._packetCodec.feed(data)) + this._socket!.on('data', (data) => + this._packetCodec.feed(data) + ) this._socket!.off('data', packetHandler) this.handleConnect() } catch (e) { diff --git a/packages/node/index.ts b/packages/node/index.ts index 7bb21112..7103fabc 100644 --- a/packages/node/index.ts +++ b/packages/node/index.ts @@ -8,7 +8,8 @@ import { SqliteStorage } from '@mtcute/sqlite' export * from '@mtcute/dispatcher' export namespace NodeTelegramClient { - export interface Options extends Omit { + export interface Options + extends Omit { /** * Default parse mode to use. * diff --git a/packages/socks-proxy/index.ts b/packages/socks-proxy/index.ts index 0c22f6f2..cebccb00 100644 --- a/packages/socks-proxy/index.ts +++ b/packages/socks-proxy/index.ts @@ -9,7 +9,6 @@ import { connect } from 'net' // @ts-ignore import { normalize } from 'ip6' - const debug = require('debug')('mtcute:socks-proxy') /** @@ -284,7 +283,7 @@ export abstract class SocksProxiedTcpTransport extends TcpTransport { debug( '[%s:%d] sending CONNECT', this._proxy.host, - this._proxy.port, + this._proxy.port ) try { diff --git a/packages/sqlite/index.ts b/packages/sqlite/index.ts index 9237067b..5b5e50ba 100644 --- a/packages/sqlite/index.ts +++ b/packages/sqlite/index.ts @@ -310,6 +310,7 @@ export class SqliteStorage implements ITelegramStorage /*, IStateStorage */ { private _runMany: (stmts: [sqlite3.Statement, any[]][]) => void private _updateManyPeers: (updates: any[]) => void + // eslint-disable-next-line @typescript-eslint/no-unused-vars private _upgradeDatabase(from: number): void { // not needed (yet) since no versions except 1 // } @@ -591,6 +592,7 @@ export class SqliteStorage implements ITelegramStorage /*, IStateStorage */ { return val.value } + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types setState(key: string, state: any, ttl?: number, parse = true): void { const item: FsmItem = { value: state, diff --git a/packages/tl/.eslintignore b/packages/tl/.eslintignore deleted file mode 100644 index fe1198f3..00000000 --- a/packages/tl/.eslintignore +++ /dev/null @@ -1,7 +0,0 @@ -errors.js -errors.d.ts -index.js -index.d.ts -binary/reader.js -binary/writer.js -binary/rsa-keys.js diff --git a/packages/tl/tests/types.ts b/packages/tl/tests/types.ts index d74dba5b..8e569b81 100644 --- a/packages/tl/tests/types.ts +++ b/packages/tl/tests/types.ts @@ -1,3 +1,4 @@ +/* eslint-disable */ // This is a test for TypeScript typings // This file is never executed, only compiled