feat(client/codegen): slightly changed code generation to avoid creating redundant wrapper functions

This commit is contained in:
teidesu 2021-04-18 16:59:05 +03:00
parent 87481c9a32
commit 878c0e35e4
2 changed files with 239 additions and 353 deletions

View file

@ -198,6 +198,7 @@ async function addSingleMethod(state, fileName) {
func: stmt, func: stmt,
comment: getLeadingComments(stmt), comment: getLeadingComments(stmt),
aliases, aliases,
overload: !stmt.body,
}) })
const module = `./${relPath.replace(/\.ts$/, '')}` const module = `./${relPath.replace(/\.ts$/, '')}`
@ -282,25 +283,17 @@ async function main() {
output.write(`// from ${from}\n${code}\n`) output.write(`// from ${from}\n${code}\n`)
}) })
output.write('\nexport class TelegramClient extends BaseTelegramClient {') output.write(
'\nexport interface TelegramClient extends BaseTelegramClient {'
)
output.tab() output.tab()
state.fields.forEach(({ from, code }) => {
output.write(`// from ${from}\nprotected ${code}\n`)
})
output.write('constructor(opts: BaseTelegramClient.Options) {')
output.tab()
output.write('super(opts)')
state.init.forEach((code) => {
output.write(code)
})
output.untab()
output.write('}\n')
const printer = ts.createPrinter() const printer = ts.createPrinter()
const classContents = []
state.methods.list.forEach( state.methods.list.forEach(
({ name: origName, isPrivate, func, comment, aliases }) => { ({ name: origName, isPrivate, func, comment, aliases, overload }) => {
// create method that calls that function and passes `this` // create method that calls that function and passes `this`
// first let's determine the signature // first let's determine the signature
const returnType = func.type ? ': ' + func.type.getText() : '' const returnType = func.type ? ': ' + func.type.getText() : ''
@ -351,7 +344,8 @@ async function main() {
it.initializer = undefined it.initializer = undefined
const deleteParents = (obj) => { const deleteParents = (obj) => {
if (Array.isArray(obj)) return obj.forEach((it) => deleteParents(it)) if (Array.isArray(obj))
return obj.forEach((it) => deleteParents(it))
if (obj.parent) delete obj.parent if (obj.parent) delete obj.parent
@ -366,7 +360,7 @@ async function main() {
it.questionToken = { kind: ts.SyntaxKind.QuestionToken } it.questionToken = { kind: ts.SyntaxKind.QuestionToken }
return printer.printNode( return printer.printNode(
ts.EmitHint.Unspecified, ts.EmitHint.Unspecified,
it, it
// state.files[state.methods.used[origName]] // state.files[state.methods.used[origName]]
) )
} }
@ -396,27 +390,49 @@ async function main() {
) )
for (const name of [origName, ...aliases]) { for (const name of [origName, ...aliases]) {
if (!comment.match(/\/\*\*?\s*\*\//)) if (!isPrivate) {
// empty comment, no need to write it if (!comment.match(/\/\*\*?\s*\*\//))
output.write(comment) // empty comment, no need to write it
output.write(comment)
output.write(
`${name}${generics}(${parameters})${returnType}`
)
}
output.write( if (!overload) {
`${ classContents.push(
isPrivate ? 'protected ' : '' `${isPrivate ? 'protected ' : ''}${name} = ${origName}${
}${name}${generics}(${parameters})${returnType}${ // dirty hack required for overloads
func.body isPrivate ? '' : ` as TelegramClient['${name}']`
? `{ }`
return ${origName}.apply(this, arguments) )
}` }
: ''
}`
)
} }
} }
) )
output.untab() output.untab()
output.write('}') output.write('}')
output.write(
'/** @internal */\nexport class TelegramClient extends BaseTelegramClient {'
)
output.tab()
state.fields.forEach(({ code }) => output.write('protected ' + code))
output.write('constructor(opts: BaseTelegramClient.Options) {')
output.tab()
output.write('super(opts)')
state.init.forEach((code) => {
output.write(code)
})
output.untab()
output.write('}\n')
classContents.forEach((line) => output.write(line))
output.untab()
output.write('}')
// format the resulting file with prettier // format the resulting file with prettier
const targetFile = path.join(__dirname, '../src/client.ts') const targetFile = path.join(__dirname, '../src/client.ts')
const prettierConfig = await prettier.resolveConfig(targetFile) const prettierConfig = await prettier.resolveConfig(targetFile)

View file

@ -119,67 +119,13 @@ import {
import { MaybeArray, MaybeAsync, TelegramConnection } from '@mtcute/core' import { MaybeArray, MaybeAsync, TelegramConnection } from '@mtcute/core'
import { Lock } from './utils/lock' import { Lock } from './utils/lock'
export class TelegramClient extends BaseTelegramClient { export interface TelegramClient extends BaseTelegramClient {
// from methods/auth/_initialize.ts
protected _userId: number | null
// from methods/auth/_initialize.ts
protected _isBot: boolean
// from methods/files/_initialize.ts
protected _downloadConnections: Record<number, TelegramConnection>
// from methods/parse-modes/_initialize.ts
protected _parseModes: Record<string, IMessageEntityParser>
// from methods/parse-modes/_initialize.ts
protected _defaultParseMode: string | null
// from methods/updates/dispatcher.ts
protected _groups: Record<number, UpdateHandler[]>
// from methods/updates/dispatcher.ts
protected _groupsOrder: number[]
// from methods/updates/handle-update.ts
protected _updLock: Lock
// from methods/updates/handle-update.ts
protected _pts: number
// from methods/updates/handle-update.ts
protected _date: number
// from methods/updates/handle-update.ts
protected _cpts: Record<number, number>
constructor(opts: BaseTelegramClient.Options) {
super(opts)
this._userId = null
this._isBot = false
this._downloadConnections = {}
this._parseModes = {}
this._defaultParseMode = null
this._groups = {}
this._groupsOrder = []
this._updLock = new Lock()
// we dont need to initialize state fields since
// they are always loaded either from the server, or from storage.
// channel PTS are not loaded immediately, and instead are cached here
// after the first time they were retrieved from the storage.
// they are later pushed into the storage.
this._cpts = {}
}
/** /**
* Accept the given TOS * Accept the given TOS
* *
* @param tosId TOS id * @param tosId TOS id
*/ */
acceptTos(tosId: string): Promise<boolean> { acceptTos(tosId: string): Promise<boolean>
return acceptTos.apply(this, arguments)
}
/** /**
* Check your Two-Step verification password and log in * Check your Two-Step verification password and log in
* *
@ -187,17 +133,13 @@ export class TelegramClient extends BaseTelegramClient {
* @returns The authorized user * @returns The authorized user
* @throws BadRequestError In case the password is invalid * @throws BadRequestError In case the password is invalid
*/ */
checkPassword(password: string): Promise<User> { checkPassword(password: string): Promise<User>
return checkPassword.apply(this, arguments)
}
/** /**
* Get your Two-Step Verification password hint. * Get your Two-Step Verification password hint.
* *
* @returns The password hint as a string, if any * @returns The password hint as a string, if any
*/ */
getPasswordHint(): Promise<string | null> { getPasswordHint(): Promise<string | null>
return getPasswordHint.apply(this, arguments)
}
/** /**
* Log out from Telegram account and optionally reset the session storage. * Log out from Telegram account and optionally reset the session storage.
* *
@ -207,9 +149,7 @@ export class TelegramClient extends BaseTelegramClient {
* @param resetSession (default: `false`) Whether to reset the session * @param resetSession (default: `false`) Whether to reset the session
* @returns On success, `true` is returned * @returns On success, `true` is returned
*/ */
logOut(resetSession?: boolean): Promise<true> { logOut(resetSession?: boolean): Promise<true>
return logOut.apply(this, arguments)
}
/** /**
* Recover your password with a recovery code and log in. * Recover your password with a recovery code and log in.
* *
@ -217,9 +157,7 @@ export class TelegramClient extends BaseTelegramClient {
* @returns The authorized user * @returns The authorized user
* @throws BadRequestError In case the code is invalid * @throws BadRequestError In case the code is invalid
*/ */
recoverPassword(recoveryCode: string): Promise<User> { recoverPassword(recoveryCode: string): Promise<User>
return recoverPassword.apply(this, arguments)
}
/** /**
* Re-send the confirmation code using a different type. * Re-send the confirmation code using a different type.
* *
@ -229,26 +167,20 @@ export class TelegramClient extends BaseTelegramClient {
* @param phone Phone number in international format * @param phone Phone number in international format
* @param phoneCodeHash Confirmation code identifier from {@link SentCode} * @param phoneCodeHash Confirmation code identifier from {@link SentCode}
*/ */
resendCode(phone: string, phoneCodeHash: string): Promise<SentCode> { resendCode(phone: string, phoneCodeHash: string): Promise<SentCode>
return resendCode.apply(this, arguments)
}
/** /**
* Send the confirmation code to the given phone number * Send the confirmation code to the given phone number
* *
* @param phone Phone number in international format. * @param phone Phone number in international format.
* @returns An object containing information about the sent confirmation code * @returns An object containing information about the sent confirmation code
*/ */
sendCode(phone: string): Promise<SentCode> { sendCode(phone: string): Promise<SentCode>
return sendCode.apply(this, arguments)
}
/** /**
* Send a code to email needed to recover your password * Send a code to email needed to recover your password
* *
* @returns String containing email pattern to which the recovery code was sent * @returns String containing email pattern to which the recovery code was sent
*/ */
sendRecoveryCode(): Promise<string> { sendRecoveryCode(): Promise<string>
return sendRecoveryCode.apply(this, arguments)
}
/** /**
* Authorize a bot using its token issued by [@BotFather](//t.me/BotFather) * Authorize a bot using its token issued by [@BotFather](//t.me/BotFather)
* *
@ -256,9 +188,7 @@ export class TelegramClient extends BaseTelegramClient {
* @returns Bot's {@link User} object * @returns Bot's {@link User} object
* @throws BadRequestError In case the bot token is invalid * @throws BadRequestError In case the bot token is invalid
*/ */
signInBot(token: string): Promise<User> { signInBot(token: string): Promise<User>
return signInBot.apply(this, arguments)
}
/** /**
* Authorize a user in Telegram with a valid confirmation code. * Authorize a user in Telegram with a valid confirmation code.
* *
@ -277,9 +207,7 @@ export class TelegramClient extends BaseTelegramClient {
phone: string, phone: string,
phoneCodeHash: string, phoneCodeHash: string,
phoneCode: string phoneCode: string
): Promise<User | TermsOfService | false> { ): Promise<User | TermsOfService | false>
return signIn.apply(this, arguments)
}
/** /**
* Register a new user in Telegram. * Register a new user in Telegram.
* *
@ -293,9 +221,7 @@ export class TelegramClient extends BaseTelegramClient {
phoneCodeHash: string, phoneCodeHash: string,
firstName: string, firstName: string,
lastName?: string lastName?: string
): Promise<User> { ): Promise<User>
return signUp.apply(this, arguments)
}
/** /**
* Utility function to quickly authorize on test DC * Utility function to quickly authorize on test DC
* using a [Test phone number](https://core.telegram.org/api/auth#test-phone-numbers), * using a [Test phone number](https://core.telegram.org/api/auth#test-phone-numbers),
@ -344,9 +270,7 @@ export class TelegramClient extends BaseTelegramClient {
* If true, TOS will not be displayed and `tosCallback` will not be called. * If true, TOS will not be displayed and `tosCallback` will not be called.
*/ */
acceptTos?: boolean acceptTos?: boolean
}): Promise<User> { }): Promise<User>
return startTest.apply(this, arguments)
}
/** /**
* Start the client in an interactive and declarative manner, * Start the client in an interactive and declarative manner,
* by providing callbacks for authorization details. * by providing callbacks for authorization details.
@ -440,9 +364,7 @@ export class TelegramClient extends BaseTelegramClient {
* Defaults to true. * Defaults to true.
*/ */
catchUp?: boolean catchUp?: boolean
}): Promise<User> { }): Promise<User>
return start.apply(this, arguments)
}
/** /**
* Add new members to a group, supergroup or channel. * Add new members to a group, supergroup or channel.
* *
@ -457,17 +379,13 @@ export class TelegramClient extends BaseTelegramClient {
chatId: InputPeerLike, chatId: InputPeerLike,
users: MaybeArray<InputPeerLike>, users: MaybeArray<InputPeerLike>,
forwardCount?: number forwardCount?: number
): Promise<void> { ): Promise<void>
return addChatMembers.apply(this, arguments)
}
/** /**
* Archive one or more chats * Archive one or more chats
* *
* @param chats Chat ID(s), username(s), phone number(s), `"me"` or `"self"` * @param chats Chat ID(s), username(s), phone number(s), `"me"` or `"self"`
*/ */
archiveChats(chats: MaybeArray<InputPeerLike>): Promise<void> { archiveChats(chats: MaybeArray<InputPeerLike>): Promise<void>
return archiveChats.apply(this, arguments)
}
/** /**
* Create a new broadcast channel * Create a new broadcast channel
* *
@ -475,9 +393,7 @@ export class TelegramClient extends BaseTelegramClient {
* @param description (default: `''`) Channel description * @param description (default: `''`) Channel description
* @returns Newly created channel * @returns Newly created channel
*/ */
createChannel(title: string, description?: string): Promise<Chat> { createChannel(title: string, description?: string): Promise<Chat>
return createChannel.apply(this, arguments)
}
/** /**
* Create a legacy group chat * Create a legacy group chat
* *
@ -489,39 +405,28 @@ export class TelegramClient extends BaseTelegramClient {
* User(s) to be invited in the group (ID(s), username(s) or phone number(s)). * User(s) to be invited in the group (ID(s), username(s) or phone number(s)).
* Due to Telegram limitations, you can't create a legacy group with yourself. * Due to Telegram limitations, you can't create a legacy group with yourself.
*/ */
createGroup( createGroup(title: string, users: MaybeArray<InputPeerLike>): Promise<Chat>
title: string,
users: MaybeArray<InputPeerLike>
): Promise<Chat> {
return createGroup.apply(this, arguments)
}
/** /**
* Create a new supergroup * Create a new supergroup
* *
* @param title Title of the supergroup * @param title Title of the supergroup
* @param description (default: `''`) Description of the supergroup * @param description (default: `''`) Description of the supergroup
*/ */
createSupergroup(title: string, description?: string): Promise<Chat> { createSupergroup(title: string, description?: string): Promise<Chat>
return createSupergroup.apply(this, arguments)
}
/** /**
* Delete a channel or a supergroup * Delete a channel or a supergroup
* *
* @param chatId Chat ID or username * @param chatId Chat ID or username
*/ */
deleteChannel(chatId: InputPeerLike): Promise<void> { deleteChannel(chatId: InputPeerLike): Promise<void>
return deleteChannel.apply(this, arguments)
}
/** /**
* Delete a channel or a supergroup * Delete a channel or a supergroup
* *
* @param chatId Chat ID or username * @param chatId Chat ID or username
*/ */
deleteSupergroup(chatId: InputPeerLike): Promise<void> { deleteSupergroup(chatId: InputPeerLike): Promise<void>
return deleteChannel.apply(this, arguments)
}
/** /**
* Delete a chat photo * Delete a chat photo
* *
@ -529,17 +434,13 @@ export class TelegramClient extends BaseTelegramClient {
* *
* @param chatId Chat ID or username * @param chatId Chat ID or username
*/ */
deleteChatPhoto(chatId: InputPeerLike): Promise<void> { deleteChatPhoto(chatId: InputPeerLike): Promise<void>
return deleteChatPhoto.apply(this, arguments)
}
/** /**
* Delete a legacy group chat for all members * Delete a legacy group chat for all members
* *
* @param chatId Chat ID * @param chatId Chat ID
*/ */
deleteGroup(chatId: InputPeerLike): Promise<void> { deleteGroup(chatId: InputPeerLike): Promise<void>
return deleteGroup.apply(this, arguments)
}
/** /**
* Delete communication history (for private chats * Delete communication history (for private chats
* and legacy groups) * and legacy groups)
@ -559,9 +460,7 @@ export class TelegramClient extends BaseTelegramClient {
chat: InputPeerLike, chat: InputPeerLike,
mode?: 'delete' | 'clear' | 'revoke', mode?: 'delete' | 'clear' | 'revoke',
maxId?: number maxId?: number
): Promise<void> { ): Promise<void>
return deleteHistory.apply(this, arguments)
}
/** /**
* Get information about a single chat member * Get information about a single chat member
* *
@ -572,9 +471,7 @@ export class TelegramClient extends BaseTelegramClient {
getChatMember( getChatMember(
chatId: InputPeerLike, chatId: InputPeerLike,
userId: InputPeerLike userId: InputPeerLike
): Promise<ChatMember> { ): Promise<ChatMember>
return getChatMember.apply(this, arguments)
}
/** /**
* Get a chunk of members of some chat. * Get a chunk of members of some chat.
* *
@ -628,9 +525,7 @@ export class TelegramClient extends BaseTelegramClient {
| 'contacts' | 'contacts'
| 'mention' | 'mention'
} }
): Promise<ChatMember[]> { ): Promise<ChatMember[]>
return getChatMembers.apply(this, arguments)
}
/** /**
* Get preview information about a private chat. * Get preview information about a private chat.
* *
@ -640,9 +535,7 @@ export class TelegramClient extends BaseTelegramClient {
* In case you are trying to get info about private chat that you have already joined. * In case you are trying to get info about private chat that you have already joined.
* Use {@link getChat} or {@link getFullChat} instead. * Use {@link getChat} or {@link getFullChat} instead.
*/ */
getChatPreview(inviteLink: string): Promise<ChatPreview> { getChatPreview(inviteLink: string): Promise<ChatPreview>
return getChatPreview.apply(this, arguments)
}
/** /**
* Get basic information about a chat. * Get basic information about a chat.
* *
@ -651,9 +544,7 @@ export class TelegramClient extends BaseTelegramClient {
* In case you are trying to get info about private chat that you haven't joined. * In case you are trying to get info about private chat that you haven't joined.
* Use {@link getChatPreview} instead. * Use {@link getChatPreview} instead.
*/ */
getChat(chatId: InputPeerLike): Promise<Chat> { getChat(chatId: InputPeerLike): Promise<Chat>
return getChat.apply(this, arguments)
}
/** /**
* Get full information about a chat. * Get full information about a chat.
* *
@ -662,9 +553,7 @@ export class TelegramClient extends BaseTelegramClient {
* In case you are trying to get info about private chat that you haven't joined. * In case you are trying to get info about private chat that you haven't joined.
* Use {@link getChatPreview} instead. * Use {@link getChatPreview} instead.
*/ */
getFullChat(chatId: InputPeerLike): Promise<Chat> { getFullChat(chatId: InputPeerLike): Promise<Chat>
return getFullChat.apply(this, arguments)
}
/** /**
* Iterate through chat members * Iterate through chat members
* *
@ -686,9 +575,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
chunkSize?: number chunkSize?: number
} }
): AsyncIterableIterator<ChatMember> { ): AsyncIterableIterator<ChatMember>
return iterChatMembers.apply(this, arguments)
}
/** /**
* Join a channel or supergroup * Join a channel or supergroup
* *
@ -696,18 +583,14 @@ export class TelegramClient extends BaseTelegramClient {
* Chat identifier. Either an invite link (`t.me/joinchat/*`), a username (`@username`) * Chat identifier. Either an invite link (`t.me/joinchat/*`), a username (`@username`)
* or ID of the linked supergroup or channel. * or ID of the linked supergroup or channel.
*/ */
joinChat(chatId: InputPeerLike): Promise<Chat> { joinChat(chatId: InputPeerLike): Promise<Chat>
return joinChat.apply(this, arguments)
}
/** /**
* Leave a group chat, supergroup or channel * Leave a group chat, supergroup or channel
* *
* @param chatId Chat ID or username * @param chatId Chat ID or username
* @param clear (default: `false`) Whether to clear history after leaving (only for legacy group chats) * @param clear (default: `false`) Whether to clear history after leaving (only for legacy group chats)
*/ */
leaveChat(chatId: InputPeerLike, clear?: boolean): Promise<void> { leaveChat(chatId: InputPeerLike, clear?: boolean): Promise<void>
return leaveChat.apply(this, arguments)
}
/** /**
* Save or delete a draft message associated with some chat * Save or delete a draft message associated with some chat
* *
@ -717,9 +600,7 @@ export class TelegramClient extends BaseTelegramClient {
saveDraft( saveDraft(
chatId: InputPeerLike, chatId: InputPeerLike,
draft: null | Omit<tl.RawDraftMessage, '_' | 'date'> draft: null | Omit<tl.RawDraftMessage, '_' | 'date'>
): Promise<void> { ): Promise<void>
return saveDraft.apply(this, arguments)
}
/** /**
* Change default chat permissions for all members. * Change default chat permissions for all members.
* *
@ -744,9 +625,7 @@ export class TelegramClient extends BaseTelegramClient {
setChatDefaultPermissions( setChatDefaultPermissions(
chatId: InputPeerLike, chatId: InputPeerLike,
permissions: InputChatPermissions permissions: InputChatPermissions
): Promise<Chat> { ): Promise<Chat>
return setChatDefaultPermissions.apply(this, arguments)
}
/** /**
* Change chat description * Change chat description
* *
@ -758,9 +637,7 @@ export class TelegramClient extends BaseTelegramClient {
setChatDescription( setChatDescription(
chatId: InputPeerLike, chatId: InputPeerLike,
description: string description: string
): Promise<void> { ): Promise<void>
return setChatDescription.apply(this, arguments)
}
/** /**
* Set a new chat photo or video. * Set a new chat photo or video.
* *
@ -778,9 +655,7 @@ export class TelegramClient extends BaseTelegramClient {
type: 'photo' | 'video', type: 'photo' | 'video',
media: InputFileLike, media: InputFileLike,
previewSec?: number previewSec?: number
): Promise<void> { ): Promise<void>
return setChatPhoto.apply(this, arguments)
}
/** /**
* Change chat title * Change chat title
* *
@ -789,9 +664,7 @@ export class TelegramClient extends BaseTelegramClient {
* @param chatId Chat ID or username * @param chatId Chat ID or username
* @param title New chat title, 1-255 characters * @param title New chat title, 1-255 characters
*/ */
setChatTitle(chatId: InputPeerLike, title: string): Promise<void> { setChatTitle(chatId: InputPeerLike, title: string): Promise<void>
return setChatTitle.apply(this, arguments)
}
/** /**
* Change supergroup/channel username * Change supergroup/channel username
* *
@ -803,9 +676,7 @@ export class TelegramClient extends BaseTelegramClient {
setChatUsername( setChatUsername(
chatId: InputPeerLike, chatId: InputPeerLike,
username: string | null username: string | null
): Promise<void> { ): Promise<void>
return setChatUsername.apply(this, arguments)
}
/** /**
* Set supergroup's slow mode interval. * Set supergroup's slow mode interval.
* *
@ -816,17 +687,13 @@ export class TelegramClient extends BaseTelegramClient {
* Users will be able to send a message only once per this interval. * Users will be able to send a message only once per this interval.
* Valid values are: `0 (off), 10, 30, 60 (1m), 300 (5m), 900 (15m) or 3600 (1h)` * Valid values are: `0 (off), 10, 30, 60 (1m), 300 (5m), 900 (15m) or 3600 (1h)`
*/ */
setSlowMode(chatId: InputPeerLike, seconds?: number): Promise<void> { setSlowMode(chatId: InputPeerLike, seconds?: number): Promise<void>
return setSlowMode.apply(this, arguments)
}
/** /**
* Unarchive one or more chats * Unarchive one or more chats
* *
* @param chats Chat ID(s), username(s), phone number(s), `"me"` or `"self"` * @param chats Chat ID(s), username(s), phone number(s), `"me"` or `"self"`
*/ */
unarchiveChats(chats: MaybeArray<InputPeerLike>): Promise<void> { unarchiveChats(chats: MaybeArray<InputPeerLike>): Promise<void>
return unarchiveChats.apply(this, arguments)
}
/** /**
* Create a folder from given parameters * Create a folder from given parameters
* *
@ -838,17 +705,13 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
createFolder( createFolder(
folder: PartialExcept<tl.RawDialogFilter, 'title'> folder: PartialExcept<tl.RawDialogFilter, 'title'>
): Promise<tl.RawDialogFilter> { ): Promise<tl.RawDialogFilter>
return createFolder.apply(this, arguments)
}
/** /**
* Delete a folder by its ID * Delete a folder by its ID
* *
* @param id Folder ID or folder itself * @param id Folder ID or folder itself
*/ */
deleteFolder(id: number | tl.RawDialogFilter): Promise<void> { deleteFolder(id: number | tl.RawDialogFilter): Promise<void>
return deleteFolder.apply(this, arguments)
}
/** /**
* Edit a folder with given modification * Edit a folder with given modification
* *
@ -859,9 +722,7 @@ export class TelegramClient extends BaseTelegramClient {
editFolder( editFolder(
folder: tl.RawDialogFilter | number, folder: tl.RawDialogFilter | number,
modification: Partial<Omit<tl.RawDialogFilter, 'id' | '_'>> modification: Partial<Omit<tl.RawDialogFilter, 'id' | '_'>>
): Promise<tl.RawDialogFilter> { ): Promise<tl.RawDialogFilter>
return editFolder.apply(this, arguments)
}
/** /**
* Iterate over dialogs. * Iterate over dialogs.
* *
@ -958,15 +819,11 @@ export class TelegramClient extends BaseTelegramClient {
* By default fetches from "All" folder * By default fetches from "All" folder
*/ */
folder?: string | number | tl.RawDialogFilter folder?: string | number | tl.RawDialogFilter
}): AsyncIterableIterator<Dialog> { }): AsyncIterableIterator<Dialog>
return getDialogs.apply(this, arguments)
}
/** /**
* Get list of folders. * Get list of folders.
*/ */
getFolders(): Promise<tl.RawDialogFilter[]> { getFolders(): Promise<tl.RawDialogFilter[]>
return getFolders.apply(this, arguments)
}
/** /**
* Download a file and return its contents as a Buffer. * Download a file and return its contents as a Buffer.
* *
@ -975,9 +832,7 @@ export class TelegramClient extends BaseTelegramClient {
* *
* @param params File download parameters * @param params File download parameters
*/ */
downloadAsBuffer(params: FileDownloadParameters): Promise<Buffer> { downloadAsBuffer(params: FileDownloadParameters): Promise<Buffer>
return downloadAsBuffer.apply(this, arguments)
}
/** /**
* Download a remote file to a local file (only for NodeJS). * Download a remote file to a local file (only for NodeJS).
* Promise will resolve once the download is complete. * Promise will resolve once the download is complete.
@ -988,9 +843,7 @@ export class TelegramClient extends BaseTelegramClient {
downloadToFile( downloadToFile(
filename: string, filename: string,
params: FileDownloadParameters params: FileDownloadParameters
): Promise<void> { ): Promise<void>
return downloadToFile.apply(this, arguments)
}
/** /**
* Download a file and return it as an iterable, which yields file contents * Download a file and return it as an iterable, which yields file contents
* in chunks of a given size. Order of the chunks is guaranteed to be * in chunks of a given size. Order of the chunks is guaranteed to be
@ -1000,18 +853,14 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
downloadAsIterable( downloadAsIterable(
params: FileDownloadParameters params: FileDownloadParameters
): AsyncIterableIterator<Buffer> { ): AsyncIterableIterator<Buffer>
return downloadAsIterable.apply(this, arguments)
}
/** /**
* Download a file and return it as a Node readable stream, * Download a file and return it as a Node readable stream,
* streaming file contents. * streaming file contents.
* *
* @param params File download parameters * @param params File download parameters
*/ */
downloadAsStream(params: FileDownloadParameters): Readable { downloadAsStream(params: FileDownloadParameters): Readable
return downloadAsStream.apply(this, arguments)
}
/** /**
* Upload a file to Telegram servers, without actually * Upload a file to Telegram servers, without actually
* sending a message anywhere. Useful when an `InputFile` is required. * sending a message anywhere. Useful when an `InputFile` is required.
@ -1069,9 +918,7 @@ export class TelegramClient extends BaseTelegramClient {
* @param total Total file size * @param total Total file size
*/ */
progressCallback?: (uploaded: number, total: number) => void progressCallback?: (uploaded: number, total: number) => void
}): Promise<UploadedFile> { }): Promise<UploadedFile>
return uploadFile.apply(this, arguments)
}
/** /**
* Delete messages, including service messages. * Delete messages, including service messages.
* *
@ -1083,9 +930,7 @@ export class TelegramClient extends BaseTelegramClient {
chatId: InputPeerLike, chatId: InputPeerLike,
ids: MaybeArray<number>, ids: MaybeArray<number>,
revoke?: boolean revoke?: boolean
): Promise<boolean> { ): Promise<boolean>
return deleteMessages.apply(this, arguments)
}
/** /**
* Edit message text and/or reply markup. * Edit message text and/or reply markup.
* *
@ -1129,16 +974,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
replyMarkup?: ReplyMarkup replyMarkup?: ReplyMarkup
} }
): Promise<Message> { ): Promise<Message>
return editMessage.apply(this, arguments)
}
protected _findMessageInUpdate(
res: tl.TypeUpdates,
isEdit?: boolean
): Message {
return _findMessageInUpdate.apply(this, arguments)
}
/** /**
* Retrieve a chunk of the chat history. * Retrieve a chunk of the chat history.
* *
@ -1184,9 +1020,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
reverse?: boolean reverse?: boolean
} }
): Promise<Message[]> { ): Promise<Message[]>
return getHistory.apply(this, arguments)
}
/** /**
* Get a single message in chat by its ID * Get a single message in chat by its ID
* *
@ -1224,9 +1058,7 @@ export class TelegramClient extends BaseTelegramClient {
chatId: InputPeerLike, chatId: InputPeerLike,
messageIds: MaybeArray<number>, messageIds: MaybeArray<number>,
fromReply?: boolean fromReply?: boolean
): Promise<MaybeArray<Message>> { ): Promise<MaybeArray<Message>>
return getMessages.apply(this, arguments)
}
/** /**
* Iterate through a chat history sequentially. * Iterate through a chat history sequentially.
* *
@ -1281,17 +1113,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
chunkSize?: number chunkSize?: number
} }
): AsyncIterableIterator<Message> { ): AsyncIterableIterator<Message>
return iterHistory.apply(this, arguments)
}
protected _parseEntities(
text?: string,
mode?: string | null,
entities?: tl.TypeMessageEntity[]
): Promise<[string, tl.TypeMessageEntity[] | undefined]> {
return _parseEntities.apply(this, arguments)
}
/** /**
* Pin a message in a group, supergroup, channel or PM. * Pin a message in a group, supergroup, channel or PM.
* *
@ -1308,9 +1130,7 @@ export class TelegramClient extends BaseTelegramClient {
messageId: number, messageId: number,
notify?: boolean, notify?: boolean,
bothSides?: boolean bothSides?: boolean
): Promise<void> { ): Promise<void>
return pinMessage.apply(this, arguments)
}
/** /**
* Search for messages globally from all of your chats * Search for messages globally from all of your chats
* *
@ -1348,9 +1168,7 @@ export class TelegramClient extends BaseTelegramClient {
* Defaults to `100` * Defaults to `100`
*/ */
chunkSize?: number chunkSize?: number
}): AsyncIterableIterator<Message> { }): AsyncIterableIterator<Message>
return searchGlobal.apply(this, arguments)
}
/** /**
* Search for messages inside a specific chat * Search for messages inside a specific chat
* *
@ -1405,9 +1223,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
chunkSize?: number chunkSize?: number
} }
): AsyncIterableIterator<Message> { ): AsyncIterableIterator<Message>
return searchMessages.apply(this, arguments)
}
/** /**
* Send an animated dice with a random value. * Send an animated dice with a random value.
* *
@ -1448,9 +1264,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
replyMarkup?: ReplyMarkup replyMarkup?: ReplyMarkup
} }
): Promise<Message> { ): Promise<Message>
return sendDice.apply(this, arguments)
}
/** /**
* Send a static geo location. * Send a static geo location.
* *
@ -1486,9 +1300,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
replyMarkup?: ReplyMarkup replyMarkup?: ReplyMarkup
} }
): Promise<Message> { ): Promise<Message>
return sendLocation.apply(this, arguments)
}
/** /**
* Send a single media. * Send a single media.
* *
@ -1547,9 +1359,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
clearDraft?: boolean clearDraft?: boolean
} }
): Promise<Message> { ): Promise<Message>
return sendMedia.apply(this, arguments)
}
/** /**
* Send a single photo * Send a single photo
* *
@ -1627,9 +1437,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
clearDraft?: boolean clearDraft?: boolean
} }
): Promise<Message> { ): Promise<Message>
return sendPhoto.apply(this, arguments)
}
/** /**
* Send a text message * Send a text message
* *
@ -1691,9 +1499,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
clearDraft?: boolean clearDraft?: boolean
} }
): Promise<Message> { ): Promise<Message>
return sendText.apply(this, arguments)
}
/** /**
* Unpin a message in a group, supergroup, channel or PM. * Unpin a message in a group, supergroup, channel or PM.
* *
@ -1703,9 +1509,7 @@ export class TelegramClient extends BaseTelegramClient {
* @param chatId Chat ID, username, phone number, `"self"` or `"me"` * @param chatId Chat ID, username, phone number, `"self"` or `"me"`
* @param messageId Message ID * @param messageId Message ID
*/ */
unpinMessage(chatId: InputPeerLike, messageId: number): Promise<void> { unpinMessage(chatId: InputPeerLike, messageId: number): Promise<void>
return unpinMessage.apply(this, arguments)
}
/** /**
* Register a given {@link IMessageEntityParser} as a parse mode * Register a given {@link IMessageEntityParser} as a parse mode
* for messages. When this method is first called, given parse * for messages. When this method is first called, given parse
@ -1715,9 +1519,7 @@ export class TelegramClient extends BaseTelegramClient {
* @param name (default: `parseMode.name`) Parse mode name. By default is taken from the object. * @param name (default: `parseMode.name`) Parse mode name. By default is taken from the object.
* @throws MtCuteError When the parse mode with a given name is already registered. * @throws MtCuteError When the parse mode with a given name is already registered.
*/ */
registerParseMode(parseMode: IMessageEntityParser, name?: string): void { registerParseMode(parseMode: IMessageEntityParser, name?: string): void
return registerParseMode.apply(this, arguments)
}
/** /**
* Unregister a parse mode by its name. * Unregister a parse mode by its name.
* Will silently fail if given parse mode does not exist. * Will silently fail if given parse mode does not exist.
@ -1726,9 +1528,7 @@ export class TelegramClient extends BaseTelegramClient {
* *
* @param name Name of the parse mode to unregister * @param name Name of the parse mode to unregister
*/ */
unregisterParseMode(name: string): void { unregisterParseMode(name: string): void
return unregisterParseMode.apply(this, arguments)
}
/** /**
* Get a {@link IMessageEntityParser} registered under a given name (or a default one). * Get a {@link IMessageEntityParser} registered under a given name (or a default one).
* *
@ -1736,34 +1536,21 @@ export class TelegramClient extends BaseTelegramClient {
* @throws MtCuteError When the provided parse mode is not registered * @throws MtCuteError When the provided parse mode is not registered
* @throws MtCuteError When `name` is omitted and there is no default parse mode * @throws MtCuteError When `name` is omitted and there is no default parse mode
*/ */
getParseMode(name?: string | null): IMessageEntityParser { getParseMode(name?: string | null): IMessageEntityParser
return getParseMode.apply(this, arguments)
}
/** /**
* Set a given parse mode as a default one. * Set a given parse mode as a default one.
* *
* @param name Name of the parse mode * @param name Name of the parse mode
* @throws MtCuteError When given parse mode is not registered. * @throws MtCuteError When given parse mode is not registered.
*/ */
setDefaultParseMode(name: string): void { setDefaultParseMode(name: string): void
return setDefaultParseMode.apply(this, arguments)
}
protected _dispatchUpdate(
update: tl.TypeUpdate | tl.TypeMessage,
users: Record<number, tl.TypeUser>,
chats: Record<number, tl.TypeChat>
): void {
return _dispatchUpdate.apply(this, arguments)
}
/** /**
* Add an update handler to a given handlers group * Add an update handler to a given handlers group
* *
* @param handler Update handler * @param handler Update handler
* @param group (default: `0`) Handler group index * @param group (default: `0`) Handler group index
*/ */
addUpdateHandler(handler: UpdateHandler, group?: number): void { addUpdateHandler(handler: UpdateHandler, group?: number): void
return addUpdateHandler.apply(this, arguments)
}
/** /**
* Remove an update handler (or handlers) from a given * Remove an update handler (or handlers) from a given
* handler group. * handler group.
@ -1774,33 +1561,12 @@ export class TelegramClient extends BaseTelegramClient {
removeUpdateHandler( removeUpdateHandler(
handler: UpdateHandler | UpdateHandler['type'] | 'all', handler: UpdateHandler | UpdateHandler['type'] | 'all',
group?: number group?: number
): void { ): void
return removeUpdateHandler.apply(this, arguments)
}
/**
* Fetch updates state from the server.
* Meant to be used right after authorization,
* but before force-saving the session.
*/
protected _fetchUpdatesState(): Promise<void> {
return _fetchUpdatesState.apply(this, arguments)
}
protected _loadStorage(): Promise<void> {
return _loadStorage.apply(this, arguments)
}
protected _saveStorage(): Promise<void> {
return _saveStorage.apply(this, arguments)
}
protected _handleUpdate(update: tl.TypeUpdates): void {
return _handleUpdate.apply(this, arguments)
}
/** /**
* Catch up with the server by loading missed updates. * Catch up with the server by loading missed updates.
* *
*/ */
catchUp(): Promise<void> { catchUp(): Promise<void>
return catchUp.apply(this, arguments)
}
/** /**
* Register a message handler without any filters. * Register a message handler without any filters.
* *
@ -1829,34 +1595,26 @@ export class TelegramClient extends BaseTelegramClient {
handler?: ( handler?: (
msg: filters.Modify<Message, Mod> msg: filters.Modify<Message, Mod>
) => MaybeAsync<void | PropagationSymbol> ) => MaybeAsync<void | PropagationSymbol>
): void { ): void
return onNewMessage.apply(this, arguments)
}
/** /**
* Block a user * Block a user
* *
* @param id User ID, its username or phone number * @param id User ID, its username or phone number
* @returns Whether the action was successful * @returns Whether the action was successful
*/ */
blockUser(id: InputPeerLike): Promise<boolean> { blockUser(id: InputPeerLike): Promise<boolean>
return blockUser.apply(this, arguments)
}
/** /**
* Get a list of common chats you have with a given user * Get a list of common chats you have with a given user
* *
* @param userId User's ID, username or phone number * @param userId User's ID, username or phone number
* @throws MtCuteInvalidPeerTypeError * @throws MtCuteInvalidPeerTypeError
*/ */
getCommonChats(userId: InputPeerLike): Promise<Chat[]> { getCommonChats(userId: InputPeerLike): Promise<Chat[]>
return getCommonChats.apply(this, arguments)
}
/** /**
* Get currently authorized user's full information * Get currently authorized user's full information
* *
*/ */
getMe(): Promise<User> { getMe(): Promise<User>
return getMe.apply(this, arguments)
}
/** /**
* Get information about a single user. * Get information about a single user.
* *
@ -1871,9 +1629,7 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
getUsers(ids: InputPeerLike[]): Promise<User[]> getUsers(ids: InputPeerLike[]): Promise<User[]>
getUsers(ids: MaybeArray<InputPeerLike>): Promise<MaybeArray<User>> { getUsers(ids: MaybeArray<InputPeerLike>): Promise<MaybeArray<User>>
return getUsers.apply(this, arguments)
}
/** /**
* Get the `InputPeer` of a known peer id. * Get the `InputPeer` of a known peer id.
* Useful when an `InputPeer` is needed. * Useful when an `InputPeer` is needed.
@ -1882,7 +1638,121 @@ export class TelegramClient extends BaseTelegramClient {
*/ */
resolvePeer( resolvePeer(
peerId: InputPeerLike peerId: InputPeerLike
): Promise<tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel> { ): Promise<tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel>
return resolvePeer.apply(this, arguments) }
} /** @internal */
export class TelegramClient extends BaseTelegramClient {
protected _userId: number | null
protected _isBot: boolean
protected _downloadConnections: Record<number, TelegramConnection>
protected _parseModes: Record<string, IMessageEntityParser>
protected _defaultParseMode: string | null
protected _groups: Record<number, UpdateHandler[]>
protected _groupsOrder: number[]
protected _updLock: Lock
protected _pts: number
protected _date: number
protected _cpts: Record<number, number>
constructor(opts: BaseTelegramClient.Options) {
super(opts)
this._userId = null
this._isBot = false
this._downloadConnections = {}
this._parseModes = {}
this._defaultParseMode = null
this._groups = {}
this._groupsOrder = []
this._updLock = new Lock()
// we dont need to initialize state fields since
// they are always loaded either from the server, or from storage.
// channel PTS are not loaded immediately, and instead are cached here
// after the first time they were retrieved from the storage.
// they are later pushed into the storage.
this._cpts = {}
}
acceptTos = acceptTos as TelegramClient['acceptTos']
checkPassword = checkPassword as TelegramClient['checkPassword']
getPasswordHint = getPasswordHint as TelegramClient['getPasswordHint']
logOut = logOut as TelegramClient['logOut']
recoverPassword = recoverPassword as TelegramClient['recoverPassword']
resendCode = resendCode as TelegramClient['resendCode']
sendCode = sendCode as TelegramClient['sendCode']
sendRecoveryCode = sendRecoveryCode as TelegramClient['sendRecoveryCode']
signInBot = signInBot as TelegramClient['signInBot']
signIn = signIn as TelegramClient['signIn']
signUp = signUp as TelegramClient['signUp']
startTest = startTest as TelegramClient['startTest']
start = start as TelegramClient['start']
addChatMembers = addChatMembers as TelegramClient['addChatMembers']
archiveChats = archiveChats as TelegramClient['archiveChats']
createChannel = createChannel as TelegramClient['createChannel']
createGroup = createGroup as TelegramClient['createGroup']
createSupergroup = createSupergroup as TelegramClient['createSupergroup']
deleteChannel = deleteChannel as TelegramClient['deleteChannel']
deleteSupergroup = deleteChannel as TelegramClient['deleteSupergroup']
deleteChatPhoto = deleteChatPhoto as TelegramClient['deleteChatPhoto']
deleteGroup = deleteGroup as TelegramClient['deleteGroup']
deleteHistory = deleteHistory as TelegramClient['deleteHistory']
getChatMember = getChatMember as TelegramClient['getChatMember']
getChatMembers = getChatMembers as TelegramClient['getChatMembers']
getChatPreview = getChatPreview as TelegramClient['getChatPreview']
getChat = getChat as TelegramClient['getChat']
getFullChat = getFullChat as TelegramClient['getFullChat']
iterChatMembers = iterChatMembers as TelegramClient['iterChatMembers']
joinChat = joinChat as TelegramClient['joinChat']
leaveChat = leaveChat as TelegramClient['leaveChat']
saveDraft = saveDraft as TelegramClient['saveDraft']
setChatDefaultPermissions = setChatDefaultPermissions as TelegramClient['setChatDefaultPermissions']
setChatDescription = setChatDescription as TelegramClient['setChatDescription']
setChatPhoto = setChatPhoto as TelegramClient['setChatPhoto']
setChatTitle = setChatTitle as TelegramClient['setChatTitle']
setChatUsername = setChatUsername as TelegramClient['setChatUsername']
setSlowMode = setSlowMode as TelegramClient['setSlowMode']
unarchiveChats = unarchiveChats as TelegramClient['unarchiveChats']
createFolder = createFolder as TelegramClient['createFolder']
deleteFolder = deleteFolder as TelegramClient['deleteFolder']
editFolder = editFolder as TelegramClient['editFolder']
getDialogs = getDialogs as TelegramClient['getDialogs']
getFolders = getFolders as TelegramClient['getFolders']
downloadAsBuffer = downloadAsBuffer as TelegramClient['downloadAsBuffer']
downloadToFile = downloadToFile as TelegramClient['downloadToFile']
downloadAsIterable = downloadAsIterable as TelegramClient['downloadAsIterable']
downloadAsStream = downloadAsStream as TelegramClient['downloadAsStream']
uploadFile = uploadFile as TelegramClient['uploadFile']
deleteMessages = deleteMessages as TelegramClient['deleteMessages']
editMessage = editMessage as TelegramClient['editMessage']
protected _findMessageInUpdate = _findMessageInUpdate
getHistory = getHistory as TelegramClient['getHistory']
getMessages = getMessages as TelegramClient['getMessages']
iterHistory = iterHistory as TelegramClient['iterHistory']
protected _parseEntities = _parseEntities
pinMessage = pinMessage as TelegramClient['pinMessage']
searchGlobal = searchGlobal as TelegramClient['searchGlobal']
searchMessages = searchMessages as TelegramClient['searchMessages']
sendDice = sendDice as TelegramClient['sendDice']
sendLocation = sendLocation as TelegramClient['sendLocation']
sendMedia = sendMedia as TelegramClient['sendMedia']
sendPhoto = sendPhoto as TelegramClient['sendPhoto']
sendText = sendText as TelegramClient['sendText']
unpinMessage = unpinMessage as TelegramClient['unpinMessage']
registerParseMode = registerParseMode as TelegramClient['registerParseMode']
unregisterParseMode = unregisterParseMode as TelegramClient['unregisterParseMode']
getParseMode = getParseMode as TelegramClient['getParseMode']
setDefaultParseMode = setDefaultParseMode as TelegramClient['setDefaultParseMode']
protected _dispatchUpdate = _dispatchUpdate
addUpdateHandler = addUpdateHandler as TelegramClient['addUpdateHandler']
removeUpdateHandler = removeUpdateHandler as TelegramClient['removeUpdateHandler']
protected _fetchUpdatesState = _fetchUpdatesState
protected _loadStorage = _loadStorage
protected _saveStorage = _saveStorage
protected _handleUpdate = _handleUpdate
catchUp = catchUp as TelegramClient['catchUp']
onNewMessage = onNewMessage as TelegramClient['onNewMessage']
blockUser = blockUser as TelegramClient['blockUser']
getCommonChats = getCommonChats as TelegramClient['getCommonChats']
getMe = getMe as TelegramClient['getMe']
getUsers = getUsers as TelegramClient['getUsers']
resolvePeer = resolvePeer as TelegramClient['resolvePeer']
} }