Pārlūkot izejas kodu

Get rid of ts mixer hack

painor 3 gadi atpakaļ
vecāks
revīzija
a8154081ba

+ 7 - 7
gramjs/Utils.ts

@@ -161,7 +161,7 @@ export function getInputPeer(
     _raiseCastFail(entity, "InputPeer");
 }
 
-export function _photoSizeByteCount(size: FileLike) {
+export function _photoSizeByteCount(size: Api.TypePhotoSize) {
     if (size instanceof Api.PhotoSize) {
         return size.size;
     } else if (size instanceof Api.PhotoStrippedSize) {
@@ -250,7 +250,7 @@ export function getInputChannel(entity: EntityLike) {
 }
 
 /**
- Similar to :meth:`get_input_peer`, but for :tl:`InputUser`'s alone.
+ Similar to :meth:`getInputPeer`, but for :tl:`InputUser`'s alone.
 
  .. important::
 
@@ -260,7 +260,7 @@ export function getInputChannel(entity: EntityLike) {
 
  * @param entity
  */
-export function getInputUser(entity: EntityLike): Api.InputPeerSelf {
+export function getInputUser(entity: EntityLike): Api.TypeInputUser {
     if (typeof entity === "string" || typeof entity == "number") {
         _raiseCastFail(entity, "InputUser");
     }
@@ -275,7 +275,7 @@ export function getInputUser(entity: EntityLike): Api.InputPeerSelf {
 
     if (entity instanceof Api.User) {
         if (entity.self) {
-            return new Api.InputPeerSelf();
+            return new Api.InputUserSelf();
         } else {
             return new Api.InputUser({
                 userId: entity.id,
@@ -284,7 +284,7 @@ export function getInputUser(entity: EntityLike): Api.InputPeerSelf {
         }
     }
     if (entity instanceof Api.InputPeerSelf) {
-        return new Api.InputPeerSelf();
+        return new Api.InputUserSelf();
     }
     if (
         entity instanceof Api.UserEmpty ||
@@ -457,7 +457,7 @@ function getInputLocation(location) {
 /**
  *  Similar to :meth:`get_input_peer`, but for photos
  */
-export function getInputPhoto(photo: any): Api.TypePhoto | Api.InputPhotoEmpty {
+export function getInputPhoto(photo: any): Api.TypeInputPhoto {
     if (photo.SUBCLASS_OF_ID === undefined) {
         _raiseCastFail(photo, "InputPhoto");
     }
@@ -985,7 +985,7 @@ export function getAppropriatedPartSize(fileSize: number) {
     throw new Error("File size too large");
 }
 
-export function getPeer(peer: EntityLike) {
+export function getPeer(peer: EntityLike | any) {
     if (!peer) {
         _raiseCastFail(peer, "undefined");
     }

+ 1 - 1
gramjs/Version.ts

@@ -1 +1 @@
-export const version = "1.9.6";
+export const version = "1.10.0";

+ 2 - 3
gramjs/client/TelegramClient.ts

@@ -21,7 +21,6 @@ import { MTProtoSender, UpdateConnectionState } from "../network";
 import { LAYER } from "../tl/AllTLObjects";
 import { betterConsoleLog, IS_NODE } from "../Helpers";
 import { DownloadMediaInterface } from "./downloads";
-import type { Message } from "../tl/patched";
 import { NewMessage, NewMessageEvent } from "../events";
 import { _handleUpdate, _updateLoop } from "./updates";
 import { Session } from "../sessions";
@@ -337,7 +336,7 @@ export class TelegramClient extends TelegramBaseClient {
         query: string,
         entity?: Api.InputPeerSelf,
         offset?: string,
-        geoPoint?: Api.GeoPoint
+        geoPoint?: Api.TypeInputGeoPoint
     ) {
         return botMethods.inlineQuery(
             this,
@@ -476,7 +475,7 @@ export class TelegramClient extends TelegramBaseClient {
      * ```
      */
     downloadMedia(
-        messageOrMedia: Api.Message | Api.TypeMessageMedia | Message,
+        messageOrMedia: Api.Message | Api.TypeMessageMedia,
         downloadParams: DownloadMediaInterface
     ) {
         return downloadMethods.downloadMedia(

+ 0 - 1
gramjs/client/auth.ts

@@ -3,7 +3,6 @@ import * as utils from "../Utils";
 import { sleep } from "../Helpers";
 import { computeCheck as computePasswordSrpCheck } from "../Password";
 import type { TelegramClient } from "./TelegramClient";
-import { RPCError } from "../errors";
 
 /**
  * For when you want to login as a {@link Api.User}<br/>

+ 2 - 2
gramjs/client/bots.ts

@@ -12,10 +12,10 @@ export async function inlineQuery(
     query: string,
     entity?: Api.InputPeerSelf,
     offset?: string,
-    geoPoint?: Api.GeoPoint
+    geoPoint?: Api.TypeInputGeoPoint
 ): Promise<InlineResults> {
     bot = await client.getInputEntity(bot);
-    let peer = new Api.InputPeerSelf();
+    let peer: Api.TypeInputPeer = new Api.InputPeerSelf();
     if (entity) {
         peer = await client.getInputEntity(entity);
     }

+ 0 - 1
gramjs/client/buttons.ts

@@ -24,7 +24,6 @@ export function buildReplyMarkup(
         }
     }
     if (!isArrayLike(buttons)) {
-        // @ts-ignore
         buttons = [[buttons]];
     } else if (!buttons || !isArrayLike(buttons[0])) {
         // @ts-ignore

+ 2 - 3
gramjs/client/dialogs.ts

@@ -1,7 +1,6 @@
 import { Api } from "../tl";
 import { RequestIter } from "../requestIter";
 import { TelegramClient, utils } from "../index";
-import { Message } from "../tl/custom/message";
 import { Dialog } from "../tl/custom/dialog";
 import { DateLike, EntityLike } from "../define";
 import { TotalList } from "../Helpers";
@@ -93,7 +92,7 @@ export class _DialogsIter extends RequestIter {
             this.total = r.dialogs.length;
         }
         const entities = new Map<number, Api.TypeUser | Api.TypeChat>();
-        const messages = new Map<string, Message>();
+        const messages = new Map<string, Api.Message>();
 
         for (const entity of [...r.users, ...r.chats]) {
             if (
@@ -105,7 +104,7 @@ export class _DialogsIter extends RequestIter {
             entities.set(utils.getPeerId(entity), entity);
         }
         for (const m of r.messages) {
-            let message = m as unknown as Message;
+            let message = m as unknown as Api.Message;
             try {
                 // todo make sure this never fails
                 message._finishInit(this.client, entities, undefined);

+ 3 - 7
gramjs/client/downloads.ts

@@ -2,7 +2,6 @@ import { Api } from "../tl";
 import type { TelegramClient } from "./TelegramClient";
 import { getAppropriatedPartSize, strippedPhotoToJpg } from "../Utils";
 import { sleep } from "../Helpers";
-import { Message } from "../tl/patched";
 import { EntityLike } from "../define";
 import { errors, utils } from "../";
 
@@ -249,16 +248,13 @@ export interface DownloadMediaInterface {
 /** @hidden */
 export async function downloadMedia(
     client: TelegramClient,
-    messageOrMedia: Api.Message | Api.TypeMessageMedia | Message,
+    messageOrMedia: Api.Message | Api.TypeMessageMedia,
     downloadParams: DownloadMediaInterface
 ): Promise<Buffer> {
     let date;
     let media;
 
-    if (
-        messageOrMedia instanceof Message ||
-        messageOrMedia instanceof Api.Message
-    ) {
+    if (messageOrMedia instanceof Api.Message) {
         media = messageOrMedia.media;
     } else {
         media = messageOrMedia;
@@ -293,7 +289,7 @@ export async function downloadMedia(
 /** @hidden */
 export async function _downloadDocument(
     client: TelegramClient,
-    doc: Api.MessageMediaDocument | Api.Document,
+    doc: Api.MessageMediaDocument | Api.TypeDocument,
     args: DownloadMediaInterface
 ): Promise<Buffer> {
     if (doc instanceof Api.MessageMediaDocument) {

+ 17 - 16
gramjs/client/messageParse.ts

@@ -4,7 +4,6 @@ import type { EntityLike } from "../define";
 import type { TelegramClient } from "./TelegramClient";
 import { utils } from "../index";
 import { _EntityType, _entityType, isArrayLike } from "../Helpers";
-import { Message } from "../tl/custom/message";
 import bigInt from "big-integer";
 
 export type messageEntities =
@@ -39,7 +38,9 @@ export async function _replaceWithMention(
         entities[i] = new Api.InputMessageEntityMentionName({
             offset: entities[i].offset,
             length: entities[i].length,
-            userId: await client.getInputEntity(user),
+            userId: (await client.getInputEntity(
+                user
+            )) as unknown as Api.TypeInputUser,
         });
         return true;
     } catch (e) {
@@ -110,8 +111,8 @@ export function _getResponseMessage(
         return;
     }
     const randomToId = new Map<string, number>();
-    const idToMessage = new Map<number, Message>();
-    const schedToMessage = new Map<number, Message>();
+    const idToMessage = new Map<number, Api.Message>();
+    const schedToMessage = new Map<number, Api.Message>();
     for (const update of updates) {
         if (update instanceof Api.UpdateMessageID) {
             randomToId.set(update.randomId.toString(), update.id);
@@ -119,7 +120,7 @@ export function _getResponseMessage(
             update instanceof Api.UpdateNewChannelMessage ||
             update instanceof Api.UpdateNewMessage
         ) {
-            (update.message as unknown as Message)._finishInit(
+            (update.message as unknown as Api.Message)._finishInit(
                 client,
                 entities,
                 inputChat
@@ -127,17 +128,17 @@ export function _getResponseMessage(
             if ("randomId" in request || isArrayLike(request)) {
                 idToMessage.set(
                     update.message.id,
-                    update.message as unknown as Message
+                    update.message as unknown as Api.Message
                 );
             } else {
-                return update.message as unknown as Message;
+                return update.message as unknown as Api.Message;
             }
         } else if (
             update instanceof Api.UpdateEditMessage &&
             "peer" in request &&
             _entityType(request.peer) != _EntityType.CHANNEL
         ) {
-            (update.message as unknown as Message)._finishInit(
+            (update.message as unknown as Api.Message)._finishInit(
                 client,
                 entities,
                 inputChat
@@ -145,7 +146,7 @@ export function _getResponseMessage(
             if ("randomId" in request) {
                 idToMessage.set(
                     update.message.id,
-                    update.message as unknown as Message
+                    update.message as unknown as Api.Message
                 );
             } else if ("id" in request && request.id === update.message.id) {
                 return update.message;
@@ -154,10 +155,10 @@ export function _getResponseMessage(
             update instanceof Api.UpdateEditChannelMessage &&
             "peer" in request &&
             getPeerId(request.peer) ==
-                getPeerId((update.message as unknown as Message).peerId!)
+                getPeerId((update.message as unknown as Api.Message).peerId!)
         ) {
             if (request.id == update.message.id) {
-                (update.message as unknown as Message)._finishInit(
+                (update.message as unknown as Api.Message)._finishInit(
                     client,
                     entities,
                     inputChat
@@ -165,18 +166,18 @@ export function _getResponseMessage(
                 return update.message;
             }
         } else if (update instanceof Api.UpdateNewScheduledMessage) {
-            (update.message as unknown as Message)._finishInit(
+            (update.message as unknown as Api.Message)._finishInit(
                 client,
                 entities,
                 inputChat
             );
             schedToMessage.set(
                 update.message.id,
-                update.message as unknown as Message
+                update.message as unknown as Api.Message
             );
         } else if (update instanceof Api.UpdateMessagePoll) {
             if (request.media.poll.id == update.pollId) {
-                const m = new Message({
+                const m = new Api.Message({
                     id: request.id,
                     peerId: utils.getPeerId(request.peer),
                     media: new Api.MessageMediaPoll({
@@ -194,8 +195,8 @@ export function _getResponseMessage(
     if (request == undefined) {
         return idToMessage;
     }
-    let mapping: Map<number, Message>;
-    let opposite = new Map<number, Message>();
+    let mapping: Map<number, Api.Message>;
+    let opposite = new Map<number, Api.Message>();
     if ("scheduleDate" in request && request.scheduleDate != undefined) {
         mapping = schedToMessage;
         opposite = idToMessage;

+ 18 - 19
gramjs/client/messages.ts

@@ -1,5 +1,4 @@
 import { Api } from "../tl";
-import { Message } from "../tl/custom/message";
 import type {
     DateLike,
     EntityLike,
@@ -235,9 +234,9 @@ export class _MessagesIter extends RequestIter {
         for (const x of [...r.users, ...r.chats]) {
             entities.set(getPeerId(x), x);
         }
-        const messages: Message[] = this.reverse
-            ? (r.messages.reverse() as unknown as Message[])
-            : (r.messages as unknown as Message[]);
+        const messages: Api.Message[] = this.reverse
+            ? (r.messages.reverse() as unknown as Api.Message[])
+            : (r.messages as unknown as Api.Message[]);
         for (const message of messages) {
             if (this.fromId && message.senderId != this.fromId) {
                 continue;
@@ -264,7 +263,7 @@ export class _MessagesIter extends RequestIter {
         }
     }
 
-    _messageInRange(message: Message) {
+    _messageInRange(message: Api.Message) {
         if (this.entity) {
             if (this.reverse) {
                 if (message.id <= this.lastId! || message.id >= this.maxId!) {
@@ -279,11 +278,11 @@ export class _MessagesIter extends RequestIter {
         return true;
     }
 
-    [Symbol.asyncIterator](): AsyncIterator<Message, any, undefined> {
+    [Symbol.asyncIterator](): AsyncIterator<Api.Message, any, undefined> {
         return super[Symbol.asyncIterator]();
     }
 
-    _updateOffset(lastMessage: Message, response: any) {
+    _updateOffset(lastMessage: Api.Message, response: any) {
         if (!this.request) {
             throw new Error("Request not set yet");
         }
@@ -334,7 +333,7 @@ export class _IDsIter extends RequestIter {
         }
     }
 
-    [Symbol.asyncIterator](): AsyncIterator<Message, any, undefined> {
+    [Symbol.asyncIterator](): AsyncIterator<Api.Message, any, undefined> {
         return super[Symbol.asyncIterator]();
     }
 
@@ -393,7 +392,7 @@ export class _IDsIter extends RequestIter {
             ) {
                 this.buffer?.push(undefined);
             } else {
-                const temp: Message = message as unknown as Message;
+                const temp: Api.Message = message as unknown as Api.Message;
                 temp._finishInit(this.client, entities, this._entity);
                 temp._entities = entities;
                 this.buffer?.push(temp);
@@ -614,7 +613,7 @@ export async function getMessages(
     client: TelegramClient,
     entity: EntityLike | undefined,
     params: IterMessagesParams
-): Promise<TotalList<Message>> {
+): Promise<TotalList<Api.Message>> {
     if (Object.keys(params).length == 1 && params.limit === undefined) {
         if (params.minId === undefined && params.maxId === undefined) {
             params.limit = undefined;
@@ -631,7 +630,7 @@ export async function getMessages(
         }
         return [];
     }
-    return (await it.collect()) as TotalList<Message>;
+    return (await it.collect()) as TotalList<Api.Message>;
 }
 
 // region Message
@@ -744,7 +743,7 @@ export async function sendMessage(
     }
     const result = await client.invoke(request);
     if (result instanceof Api.UpdateShortSentMessage) {
-        const msg = new Message({
+        const msg = new Api.Message({
             id: result.id,
             peerId: await _getPeer(client, entity),
             message: message,
@@ -758,7 +757,7 @@ export async function sendMessage(
         msg._finishInit(client, new Map(), entity);
         return msg;
     }
-    return client._getResponseMessage(request, result, entity) as Message;
+    return client._getResponseMessage(request, result, entity) as Api.Message;
 }
 
 /** @hidden */
@@ -773,7 +772,7 @@ export async function forwardMessages(
         fromPeer = await client.getInputEntity(fromPeer);
         fromPeerId = await client.getPeerId(fromPeer);
     }
-    const getKey = (m: number | Message) => {
+    const getKey = (m: number | Api.Message) => {
         if (typeof m == "number") {
             if (fromPeerId !== undefined) {
                 return fromPeerId;
@@ -785,10 +784,10 @@ export async function forwardMessages(
             throw new Error(`Cannot forward ${m}`);
         }
     };
-    const sent: Message[] = [];
+    const sent: Api.Message[] = [];
     for (let [chatId, chunk] of groupBy(messages, getKey) as Map<
         number,
-        Message[] | number[]
+        Api.Message[] | number[]
     >) {
         let chat;
         let numbers: number[] = [];
@@ -797,7 +796,7 @@ export async function forwardMessages(
             numbers = chunk as number[];
         } else {
             chat = await chunk[0].getInputChat();
-            numbers = (chunk as Message[]).map((m: Message) => m.id);
+            numbers = (chunk as Api.Message[]).map((m: Api.Message) => m.id);
         }
         chunk.push();
         const request = new Api.messages.ForwardMessages({
@@ -809,7 +808,7 @@ export async function forwardMessages(
         });
         const result = await client.invoke(request);
         sent.push(
-            client._getResponseMessage(request, result, entity) as Message
+            client._getResponseMessage(request, result, entity) as Api.Message
         );
     }
     return sent;
@@ -850,7 +849,7 @@ export async function editMessage(
         scheduleDate: schedule,
     });
     const result = await client.invoke(request);
-    return client._getResponseMessage(request, result, entity) as Message;
+    return client._getResponseMessage(request, result, entity) as Api.Message;
 }
 
 /** @hidden */

+ 1 - 2
gramjs/client/uploads.ts

@@ -1,5 +1,4 @@
 import { Api } from "../tl";
-import { Message } from "../tl/custom/message";
 
 import { TelegramClient } from "./TelegramClient";
 import { generateRandomBytes, readBigIntFromBuffer, sleep } from "../Helpers";
@@ -496,7 +495,7 @@ export async function sendFile(
         clearDraft: clearDraft,
     });
     const result = await client.invoke(request);
-    return client._getResponseMessage(request, result, entity) as Message;
+    return client._getResponseMessage(request, result, entity) as Api.Message;
 }
 
 function fileToBuffer(file: File | CustomFile) {

+ 17 - 3
gramjs/define.d.ts

@@ -1,12 +1,16 @@
 import type { Button } from "./tl/custom/button";
 import { Api } from "./tl";
 import type { CustomFile } from "./client/uploads";
+import TypeUser = Api.TypeUser;
+import TypeChat = Api.TypeChat;
+import TypeInputUser = Api.TypeInputUser;
+import TypeInputChannel = Api.TypeInputChannel;
 
 type ValueOf<T> = T[keyof T];
 type Phone = string;
 type Username = string;
 type PeerID = number;
-type Entity = Api.User | Api.Chat | Api.Channel;
+type Entity = Api.User | Api.Chat | Api.Channel | TypeUser | TypeChat;
 type FullEntity =
     | Api.UserFull
     | Api.messages.ChatFull
@@ -20,10 +24,18 @@ type EntityLike =
     | Api.TypePeer
     | Api.TypeInputPeer
     | Entity
-    | FullEntity;
+    | FullEntity
+    | TypeUser
+    | TypeChat
+    | TypeInputChannel
+    | TypeInputUser;
 
 type EntitiesLike = EntityLike[];
-type MessageIDLike = number | Api.Message | Api.TypeInputMessage;
+type MessageIDLike =
+    | number
+    | Api.Message
+    | Api.MessageService
+    | Api.TypeInputMessage;
 type MessageLike = string | Api.Message;
 
 type LocalPath = string;
@@ -39,6 +51,8 @@ type FileLike =
     | Api.TypeInputFile
     | Api.TypeInputFileLocation
     | File
+    | Api.TypePhoto
+    | Api.TypeDocument
     | CustomFile;
 
 type ProgressCallback = (total: number, downloaded: number) => void;

+ 18 - 12
gramjs/events/Album.ts

@@ -1,6 +1,5 @@
 import { DefaultEventInterface, EventBuilder, EventCommon } from "./common";
 import { Entity, EntityLike } from "../define";
-import { Message as CustomMessage } from "../tl/custom/message";
 import { Api } from "../tl";
 import { TelegramClient } from "..";
 
@@ -37,20 +36,17 @@ export class Album extends EventBuilder {
         others: any = null,
         dispatch?: CallableFunction
     ): any {
-        if (
-            !("message" in update) ||
-            typeof update.message == "string" ||
-            !("groupedId" in update.message)
-        ) {
+        if (!("message" in update && update.message instanceof Api.Message)) {
             return;
         }
+
         const groupedId = update.message.groupedId;
         if (!groupedId) {
             return;
         }
         const albums = this.client!._ALBUMS;
         const oldTimeout = albums.get(groupedId.toString());
-        let oldValues = [];
+        let oldValues: Api.TypeUpdate[] = [];
         if (oldTimeout) {
             clearTimeout(oldTimeout[0]);
             oldValues.push(...oldTimeout[1]);
@@ -62,26 +58,36 @@ export class Album extends EventBuilder {
                 if (!values) {
                     return;
                 }
-                const messages = values[1] as unknown as CustomMessage[];
+                const updates = values[1];
 
-                if (!messages) {
+                if (!updates) {
                     return;
                 }
+                const messages: Api.Message[] = [];
+                for (const update of updates) {
+                    // there is probably an easier way
+                    if (
+                        "message" in update &&
+                        update.message instanceof Api.Message
+                    ) {
+                        messages.push(update.message);
+                    }
+                }
                 const event = new AlbumEvent(messages, values[1]);
                 event._setClient(this.client!);
                 event._entities = messages[0]._entities!;
                 dispatch!(event);
             }, _ALBUM_DELAY),
-            [...oldValues, update.message],
+            [...oldValues, update],
         ]);
     }
 }
 
 export class AlbumEvent extends EventCommon {
-    messages: CustomMessage[];
+    messages: Api.Message[];
     originalUpdates: (Api.TypeUpdate & { _entities?: Map<number, Entity> })[];
 
-    constructor(messages: CustomMessage[], originalUpdates: Api.TypeUpdate[]) {
+    constructor(messages: Api.Message[], originalUpdates: Api.TypeUpdate[]) {
         super({
             msgId: messages[0].id,
             chatPeer: messages[0].peerId,

+ 13 - 16
gramjs/events/NewMessage.ts

@@ -7,8 +7,6 @@ import {
 import type { Entity, EntityLike } from "../define";
 import type { TelegramClient } from "..";
 import { Api } from "../tl";
-import { Message } from "../tl/patched";
-import type { Message as CustomMessage } from "../tl/custom/message";
 
 export interface NewMessageInterface extends DefaultEventInterface {
     func?: { (event: NewMessageEvent): boolean };
@@ -124,26 +122,20 @@ export class NewMessage extends EventBuilder {
         this.fromUsers = await _intoIdSet(client, this.fromUsers);
     }
 
-    build(update: Api.TypeUpdate, others: any = null) {
+    build(update: Api.TypeUpdate | Api.TypeUpdates, others: any = null) {
         if (
             update instanceof Api.UpdateNewMessage ||
             update instanceof Api.UpdateNewChannelMessage
         ) {
-            if (
-                !(update.message instanceof Api.Message) &&
-                !(update.message instanceof Message)
-            ) {
+            if (!(update.message instanceof Api.Message)) {
                 return undefined;
             }
-            const event = new NewMessageEvent(
-                update.message as Message,
-                update
-            );
+            const event = new NewMessageEvent(update.message, update);
             this.addAttributes(event);
             return event;
         } else if (update instanceof Api.UpdateShortMessage) {
             return new NewMessageEvent(
-                new Message({
+                new Api.Message({
                     out: update.out,
                     mentioned: update.mentioned,
                     mediaUnread: update.mediaUnread,
@@ -163,7 +155,7 @@ export class NewMessage extends EventBuilder {
             );
         } else if (update instanceof Api.UpdateShortChatMessage) {
             return new NewMessageEvent(
-                new Message({
+                new Api.Message({
                     out: update.out,
                     mentioned: update.mentioned,
                     mediaUnread: update.mediaUnread,
@@ -222,10 +214,15 @@ export class NewMessage extends EventBuilder {
 }
 
 export class NewMessageEvent extends EventCommon {
-    message: CustomMessage;
-    originalUpdate: Api.TypeUpdate & { _entities?: Map<number, Entity> };
+    message: Api.Message;
+    originalUpdate: (Api.TypeUpdate | Api.TypeUpdates) & {
+        _entities?: Map<number, Entity>;
+    };
 
-    constructor(message: CustomMessage, originalUpdate: Api.TypeUpdate) {
+    constructor(
+        message: Api.Message,
+        originalUpdate: Api.TypeUpdate | Api.TypeUpdates
+    ) {
         super({
             msgId: message.id,
             chatPeer: message.peerId,

+ 2 - 1
gramjs/events/common.ts

@@ -155,7 +155,8 @@ export class EventCommon extends ChatGetter {
         msgId = undefined,
         broadcast = undefined,
     }: EventCommonInterface) {
-        super({ chatPeer, broadcast });
+        super();
+        ChatGetter.initChatClass(this, { chatPeer, broadcast });
         this._entities = new Map();
         this._client = undefined;
         this._messageId = msgId;

+ 30 - 8
gramjs/sessions/Memory.ts

@@ -229,20 +229,42 @@ export class MemorySession extends Session {
     getInputEntity(key: EntityLike): Api.TypeInputPeer {
         let exact;
         if (typeof key === "object" && key.SUBCLASS_OF_ID) {
-            if (
-                [0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(
-                    key.SUBCLASS_OF_ID
-                )
-            ) {
-                // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))
-                // We already have an Input version, so nothing else required
+            if (key.SUBCLASS_OF_ID == 0xc91c90b6) {
                 return key;
             }
+            if (key.SUBCLASS_OF_ID == 0xe669bf46) {
+                if (key instanceof Api.InputUserSelf) {
+                    return new Api.InputPeerSelf();
+                }
+                if (key instanceof Api.InputUserEmpty) {
+                    return new Api.InputPeerEmpty();
+                }
+                if (key instanceof Api.InputUserFromMessage) {
+                    return key.peer;
+                }
+                return new Api.InputPeerUser({
+                    userId: key.userId,
+                    accessHash: key.accessHash,
+                });
+            }
+            if (key.SUBCLASS_OF_ID == 0x40f202fd) {
+                if (key instanceof Api.InputChannelEmpty) {
+                    return new Api.InputPeerEmpty();
+                }
+                if (key instanceof Api.InputChannelFromMessage) {
+                    return key.peer;
+                }
+                return new Api.InputPeerChannel({
+                    channelId: key.channelId,
+                    accessHash: key.accessHash,
+                });
+            }
+
             // Try to early return if this key can be casted as input peer
             return utils.getInputPeer(key);
         } else {
             // Not a TLObject or can't be cast into InputPeer
-            if (typeof key === "object" && key.classType === "constructor") {
+            if (typeof key === "object") {
                 key = utils.getPeerId(key);
                 exact = true;
             } else {

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1 - 206
gramjs/tl/api.d.ts


+ 3 - 0
gramjs/tl/api.js

@@ -288,6 +288,7 @@ function createClasses(classesType, params) {
 
             constructor(args) {
                 args = args || {};
+                this.init(args);
                 for (const argName in argsConfig) {
                     if (argName === "randomId" && !args[argName]) {
                         if (argsConfig[argName].isVector) {
@@ -305,6 +306,8 @@ function createClasses(classesType, params) {
                 }
             }
 
+            init(args) {}
+
             static fromReader(reader) {
                 const args = {};
 

+ 1 - 1
gramjs/tl/custom/button.ts

@@ -73,7 +73,7 @@ export class Button {
         return new Api.InputKeyboardButtonUrlAuth({
             text,
             url: url || text,
-            bot: utils.getInputPeer(bot || new Api.InputUserSelf()),
+            bot: utils.getInputUser(bot || new Api.InputUserSelf()),
             requestWriteAccess: writeAccess,
             fwdText: fwdText,
         });

+ 1 - 10
gramjs/tl/custom/chatGetter.ts

@@ -23,16 +23,7 @@ export class ChatGetter {
         return betterConsoleLog(this);
     }
 
-    constructor({
-        chatPeer,
-        inputChat,
-        chat,
-        broadcast,
-    }: ChatGetterConstructorParams) {
-        ChatGetter.initClass(this, { chatPeer, inputChat, chat, broadcast });
-    }
-
-    static initClass(
+    static initChatClass(
         c: any,
         { chatPeer, inputChat, chat, broadcast }: ChatGetterConstructorParams
     ) {

+ 2 - 3
gramjs/tl/custom/dialog.ts

@@ -3,7 +3,6 @@ import { Api } from "../api";
 import type { Entity } from "../../define";
 import { getDisplayName, getInputPeer, getPeerId } from "../../Utils";
 import { Draft } from "./draft";
-import { Message } from "./message";
 import { inspect } from "util";
 import { betterConsoleLog } from "../../Helpers";
 
@@ -13,7 +12,7 @@ export class Dialog {
     pinned: boolean;
     folderId?: number;
     archived: boolean;
-    message?: Api.Message | Message;
+    message?: Api.Message;
     date: number;
     entity?: Entity;
     inputEntity: Api.TypeInputPeer;
@@ -34,7 +33,7 @@ export class Dialog {
         client: TelegramClient,
         dialog: Api.Dialog,
         entities: Map<number, Entity>,
-        message?: Api.Message | Message
+        message?: Api.Message
     ) {
         this._client = client;
         this.dialog = dialog;

+ 4 - 5
gramjs/tl/custom/forward.ts

@@ -6,9 +6,8 @@ import type { Entity } from "../../define";
 import { _EntityType, _entityType, betterConsoleLog } from "../../Helpers";
 import { _getEntityPair, getPeerId } from "../../Utils";
 import { inspect } from "util";
-import { Mixin } from "ts-mixer";
 
-export class Forward extends Mixin(SenderGetter, ChatGetter) {
+export class Forward extends SenderGetter {
     private originalFwd: Api.MessageFwdHeader;
     [inspect.custom]() {
         return betterConsoleLog(this);
@@ -19,7 +18,7 @@ export class Forward extends Mixin(SenderGetter, ChatGetter) {
         original: Api.MessageFwdHeader,
         entities: Map<number, Entity>
     ) {
-        super({});
+        super();
         // contains info for the original header sent by telegram.
         this.originalFwd = original;
 
@@ -47,11 +46,11 @@ export class Forward extends Mixin(SenderGetter, ChatGetter) {
                 );
             }
         }
-        ChatGetter.initClass(this, {
+        ChatGetter.initChatClass(this, {
             chatPeer: peer,
             inputChat: inputChat,
         });
-        SenderGetter.initClass(this, {
+        SenderGetter.initSenderClass(this, {
             senderId: senderId,
             sender: sender,
             inputSender: inputSender,

+ 70 - 67
gramjs/tl/custom/message.ts

@@ -6,15 +6,12 @@ import { ChatGetter } from "./chatGetter";
 import * as utils from "../../Utils";
 import { Forward } from "./forward";
 import type { File } from "./file";
-import { Mixin } from "ts-mixer";
 import { EditMessageParams, SendMessageParams } from "../../client/messages";
-import {
-    DownloadFileParams,
-    DownloadMediaInterface,
-} from "../../client/downloads";
+import { DownloadMediaInterface } from "../../client/downloads";
 import { inspect } from "util";
 import { betterConsoleLog } from "../../Helpers";
 import { _selfId } from "../../client/users";
+import { BigInteger } from "big-integer";
 
 interface MessageBaseInterface {
     id: any;
@@ -55,7 +52,11 @@ interface MessageBaseInterface {
  * Remember that this class implements {@link ChatGetter} and {@link SenderGetter}<br/>
  * which means you have access to all their sender and chat properties and methods.
  */
-export class Message extends Mixin(SenderGetter, ChatGetter) {
+export class CustomMessage extends SenderGetter {
+    static CONSTRUCTOR_ID: number;
+    static SUBCLASS_OF_ID: number;
+    CONSTRUCTOR_ID!: number;
+    SUBCLASS_OF_ID!: number;
     /**
      * Whether the message is outgoing (i.e. you sent it from
      * another session) or incoming (i.e. someone else sent it).
@@ -109,7 +110,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
      * The ID of this message. This field is *always* present.
      * Any other member is optional and may be `undefined`.
      */
-    id: number;
+    id!: number;
     /**
      * The peer who sent this message, which is either
      * {@link Api.PeerUser}, {@link Api.PeerChat} or {@link Api.PeerChannel}.
@@ -121,7 +122,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
      * {@link Api.PeerUser}, {@link Api.PeerChat} or {@link Api.PeerChannel}.
      * This will always be present except for empty messages.
      */
-    peerId?: Api.TypePeer;
+    peerId!: Api.TypePeer;
     /**
      * The original forward header if this message is a forward.
      * You should probably use the `forward` property instead.
@@ -140,12 +141,12 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
      * The timestamp indicating when this message was sent.
      * This will always be present except for empty messages.
      */
-    date?: number;
+    date!: number;
     /**
      * The string text of the message for {@link Api.Message} instances,
      * which will be `undefined` for other types of messages.
      */
-    message?: string;
+    message!: string;
     /**
      * The media sent with this message if any (such as photos, videos, documents, gifs, stickers, etc.).
      *
@@ -177,7 +178,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
     /**
      *  The number of times another message has replied to this message.
      */
-    replies?: number;
+    replies?: Api.TypeMessageReplies;
     /**
      * The date when this message was last edited.
      */
@@ -190,7 +191,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
      *  If this message belongs to a group of messages (photo albums or video albums),
      *  all of them will have the same value here.
      */
-    groupedId?: number;
+    groupedId?: BigInteger;
     /**
      * An optional list of reasons why this message was restricted.
      * If the list is `undefined`, this message has not been restricted.
@@ -200,7 +201,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
      * The message action object of the message for {@link Api.MessageService}
      * instances, which will be `undefined` for other types of messages.
      */
-    action?: any;
+    action!: Api.TypeMessageAction;
     /**
      * The Time To Live period configured for this message.
      * The message should be erased from wherever it's stored (memory, a
@@ -216,7 +217,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
     /** @hidden */
     _file?: File;
     /** @hidden */
-    _replyMessage?: Message;
+    _replyMessage?: Api.Message;
     /** @hidden */
     _buttons?: undefined;
     /** @hidden */
@@ -241,42 +242,42 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
         return betterConsoleLog(this);
     }
 
-    constructor({
-        id,
-        peerId = undefined,
-        date = undefined,
-
-        out = undefined,
-        mentioned = undefined,
-        mediaUnread = undefined,
-        silent = undefined,
-        post = undefined,
-        fromId = undefined,
-        replyTo = undefined,
-
-        message = undefined,
-
-        fwdFrom = undefined,
-        viaBotId = undefined,
-        media = undefined,
-        replyMarkup = undefined,
-        entities = undefined,
-        views = undefined,
-        editDate = undefined,
-        postAuthor = undefined,
-        groupedId = undefined,
-        fromScheduled = undefined,
-        legacy = undefined,
-        editHide = undefined,
-        pinned = undefined,
-        restrictionReason = undefined,
-        forwards = undefined,
-        replies = undefined,
-
-        action = undefined,
-        ttlPeriod = undefined,
-        _entities = new Map<number, Entity>(),
-    }: MessageBaseInterface) {
+    init({
+             id,
+             peerId = undefined,
+             date = undefined,
+
+             out = undefined,
+             mentioned = undefined,
+             mediaUnread = undefined,
+             silent = undefined,
+             post = undefined,
+             fromId = undefined,
+             replyTo = undefined,
+
+             message = undefined,
+
+             fwdFrom = undefined,
+             viaBotId = undefined,
+             media = undefined,
+             replyMarkup = undefined,
+             entities = undefined,
+             views = undefined,
+             editDate = undefined,
+             postAuthor = undefined,
+             groupedId = undefined,
+             fromScheduled = undefined,
+             legacy = undefined,
+             editHide = undefined,
+             pinned = undefined,
+             restrictionReason = undefined,
+             forwards = undefined,
+             replies = undefined,
+
+             action = undefined,
+             ttlPeriod = undefined,
+             _entities = new Map<number, Entity>()
+         }: MessageBaseInterface) {
         if (!id) throw new Error("id is a required attribute for Message");
         let senderId = undefined;
         if (fromId) {
@@ -286,7 +287,6 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                 senderId = utils.getPeerId(peerId);
             }
         }
-        super({});
         // Common properties to all messages
         this._entities = _entities;
         this.out = out;
@@ -332,12 +332,17 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
         this._actionEntities = undefined;
 
         // Note: these calls would reset the client
-        ChatGetter.initClass(this, { chatPeer: peerId, broadcast: post });
-        SenderGetter.initClass(this, { senderId: senderId });
+        ChatGetter.initChatClass(this, { chatPeer: peerId, broadcast: post });
+        SenderGetter.initSenderClass(this, { senderId: senderId });
 
         this._forward = undefined;
     }
 
+    constructor(args: MessageBaseInterface) {
+        super();
+        this.init(args);
+    }
+
     _finishInit(
         client: TelegramClient,
         entities: Map<number, Entity>,
@@ -394,10 +399,10 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                     entities.get(
                         utils.getPeerId(
                             new Api.PeerChannel({
-                                channelId: this.action.inviterId,
+                                channelId: this.action.inviterId
                             })
                         )
-                    ),
+                    )
                 ];
             } else if (
                 this.action instanceof Api.MessageActionChannelMigrateFrom
@@ -407,7 +412,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                         utils.getPeerId(
                             new Api.PeerChat({ chatId: this.action.chatId })
                         )
-                    ),
+                    )
                 ];
             }
         }
@@ -473,17 +478,17 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
      */
     async _reloadMessage() {
         if (!this._client) return;
-        let msg: Message | undefined = undefined;
+        let msg: CustomMessage | undefined = undefined;
         try {
             const chat = this.isChannel ? await this.getInputChat() : undefined;
             let temp = await this._client.getMessages(chat, { ids: this.id });
             if (temp) {
-                msg = temp[0];
+                msg = temp[0] as CustomMessage;
             }
         } catch (e) {
             this._client._log.error(
                 "Got error while trying to finish init message with id " +
-                    this.id
+                this.id
             );
             if (this._client._log.canSend("error")) {
                 console.error(e);
@@ -685,7 +690,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
     get toId() {
         if (this._client && !this.out && this.isPrivate) {
             return new Api.PeerUser({
-                userId: _selfId(this._client)!,
+                userId: _selfId(this._client)!
             });
         }
         return this.peerId;
@@ -708,7 +713,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
         return zip([ent, texts]);
     }
 
-    async getReplyMessage() {
+    async getReplyMessage(): Promise<Api.Message | undefined> {
         if (!this._replyMessage && this._client) {
             if (!this.replyTo) return undefined;
 
@@ -718,7 +723,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                 await this._client.getMessages(
                     this.isChannel ? await this.getInputChat() : undefined,
                     {
-                        ids: new Api.InputMessageReplyTo({ id: this.id }),
+                        ids: new Api.InputMessageReplyTo({ id: this.id })
                     }
                 )
             )[0];
@@ -732,7 +737,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                     await this._client.getMessages(
                         this.isChannel ? this._inputChat : undefined,
                         {
-                            ids: this.replyToMsgId,
+                            ids: this.replyToMsgId
                         }
                     )
                 )[0];
@@ -765,7 +770,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
             entity = await this._client.getInputEntity(entity);
             const params = {
                 messages: [this.id],
-                fromPeer: (await this.getInputChat())!,
+                fromPeer: (await this.getInputChat())!
             };
 
             return this._client.forwardMessages(entity, params);
@@ -791,7 +796,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                 await this.getInputChat(),
                 [this.id],
                 {
-                    revoke,
+                    revoke
                 }
             );
         }
@@ -933,5 +938,3 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
         }
     }
 }
-
-export interface Message extends ChatGetter, SenderGetter {}

+ 3 - 10
gramjs/tl/custom/senderGetter.ts

@@ -3,6 +3,7 @@ import type { TelegramClient } from "../..";
 import { Api } from "../api";
 import { inspect } from "util";
 import { betterConsoleLog } from "../../Helpers";
+import { ChatGetter } from "./chatGetter";
 
 interface SenderGetterConstructorInterface {
     senderId?: number;
@@ -10,7 +11,7 @@ interface SenderGetterConstructorInterface {
     inputSender?: Api.TypeInputPeer;
 }
 
-export class SenderGetter {
+export class SenderGetter extends ChatGetter {
     _senderId?: number;
     _sender?: Entity;
     _inputSender?: Api.TypeInputPeer;
@@ -19,15 +20,7 @@ export class SenderGetter {
         return betterConsoleLog(this);
     }
 
-    constructor({
-        senderId,
-        sender,
-        inputSender,
-    }: SenderGetterConstructorInterface) {
-        SenderGetter.initClass(this, { senderId, sender, inputSender });
-    }
-
-    static initClass(
+    static initSenderClass(
         c: any,
         { senderId, sender, inputSender }: SenderGetterConstructorInterface
     ) {

+ 4 - 0
gramjs/tl/generationHelpers.ts

@@ -176,6 +176,10 @@ function buildArgConfig(name: string, argType: string) {
         //     this.type = 'date';
         // }
     }
+    // workaround
+    if (currentConfig.type == "future_salt") {
+        currentConfig.type = "FutureSalt";
+    }
     return currentConfig;
 }
 

+ 79 - 10
gramjs/tl/patched/index.ts

@@ -1,16 +1,85 @@
 import { Api } from "../api";
-import { Message as _Message } from "../custom/message";
-import { Mixin } from "ts-mixer";
+import { CustomMessage } from "../custom/message";
 import { tlobjects } from "../AllTLObjects";
 
-class MessageEmpty extends Mixin(_Message, Api.MessageEmpty) {}
+function getGetter(obj: any, prop: string) {
+    while (obj) {
+        let getter = Object.getOwnPropertyDescriptor(obj, prop);
+        if (getter && getter.get) {
+            return getter.get;
+        }
+        obj = Object.getPrototypeOf(obj);
+    }
+}
+
+function getSetter(obj: any, prop: string) {
+    while (obj) {
+        let getter = Object.getOwnPropertyDescriptor(obj, prop);
+        if (getter && getter.set) {
+            return getter.set;
+        }
+        obj = Object.getPrototypeOf(obj);
+    }
+}
+
+const getInstanceMethods = (obj: any) => {
+    let keys = {
+        methods: new Set<string>(),
+        setters: new Set<string>(),
+        getters: new Set<string>(),
+    };
+    let topObject = obj;
+
+    const mapAllMethods = (property: string) => {
+        const getter = getGetter(topObject, property);
+        const setter = getSetter(topObject, property);
+        if (getter) {
+            keys["getters"].add(property);
+        } else if (setter) {
+            keys["setters"].add(property);
+        } else {
+            if (!(property == "constructor")) {
+                keys["methods"].add(property);
+            }
+        }
+    };
 
-class MessageService extends Mixin(_Message, Api.MessageService) {}
+    do {
+        Object.getOwnPropertyNames(obj).map(mapAllMethods);
 
-class Message extends Mixin(_Message, Api.Message) {}
-export function patchAll() {
-    tlobjects[MessageEmpty.CONSTRUCTOR_ID.toString()] = MessageEmpty;
-    tlobjects[MessageService.CONSTRUCTOR_ID.toString()] = MessageService;
-    tlobjects[Message.CONSTRUCTOR_ID.toString()] = Message;
+        // walk-up the prototype chain
+        obj = Object.getPrototypeOf(obj);
+    } while (
+        // not the the Object prototype methods (hasOwnProperty, etc...)
+        obj &&
+        Object.getPrototypeOf(obj)
+    );
+
+    return keys;
+};
+
+function patchClass(clazz: Function) {
+    const { getters, setters, methods } = getInstanceMethods(
+        CustomMessage.prototype
+    );
+    for (const getter of getters) {
+        Object.defineProperty(clazz.prototype, getter, {
+            get: getGetter(CustomMessage.prototype, getter),
+        });
+    }
+    for (const setter of setters) {
+        Object.defineProperty(clazz.prototype, setter, {
+            set: getSetter(CustomMessage.prototype, setter),
+        });
+    }
+    for (const method of methods) {
+        clazz.prototype[method] = (CustomMessage.prototype as any)[method];
+    }
 }
-export { Message, MessageService, MessageEmpty };
+
+function patchAll() {
+    patchClass(Api.Message);
+    patchClass(Api.MessageService);
+}
+
+export { patchAll };

+ 125 - 116
gramjs/tl/types-generator/template.js

@@ -1,4 +1,3 @@
-
 // Not sure what they are for.
 const WEIRD_TYPES = new Set(["Bool", "X", "Type"]);
 
@@ -39,18 +38,41 @@ module.exports = ({ types, constructors, functions }) => {
         return constructors
             .map((args) => {
                 // console.log(args);
-                const { name, namespace, argsConfig,constructorId,subclassOfId }=args;
+                const {
+                    name,
+                    namespace,
+                    argsConfig,
+                    constructorId,
+                    subclassOfId,
+                } = args;
+                if (name == "Message") {
+                    return `export class Message extends CustomMessage {
+${indent}CONSTRUCTOR_ID: ${constructorId};
+${indent}SUBCLASS_OF_ID: ${subclassOfId};
+${indent}classType: "request";
+${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
+${indent}static fromReader(reader: Reader): ${upperFirst(name)};
+    }`;
+                } else if (name == "MessageService") {
+                    return `export class MessageService extends CustomMessage {
+${indent}CONSTRUCTOR_ID: ${constructorId};
+${indent}SUBCLASS_OF_ID: ${subclassOfId};
+${indent}classType: "request";
+${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
+${indent}static fromReader(reader: Reader): ${upperFirst(name)};
+    }`;
+                }
                 const argKeys = Object.keys(argsConfig);
                 // console.log(constructorId);
                 if (!argKeys.length) {
                     return `export class ${upperFirst(
                         name
                     )} extends VirtualClass<void> {
-    CONSTRUCTOR_ID: ${constructorId};
-    SUBCLASS_OF_ID: ${subclassOfId};
-    classType: "constructor";
-    className: "${getClassNameWithNameSpace(name, namespace)}";
-    static fromReader(reader: Reader): ${upperFirst(name)};
+${indent}CONSTRUCTOR_ID: ${constructorId};
+${indent}SUBCLASS_OF_ID: ${subclassOfId};
+${indent}classType: "constructor";
+${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
+${indent}static fromReader(reader: Reader): ${upperFirst(name)};
 }`;
                 }
 
@@ -69,9 +91,9 @@ ${indent}  ${Object.keys(argsConfig)
                     )
                     .join(`\n${indent}  `)}
 ${indent}}${!hasRequiredArgs ? "" : ""}> {
-    CONSTRUCTOR_ID: ${constructorId};
-    SUBCLASS_OF_ID: ${subclassOfId};
-    classType: "constructor";
+${indent}CONSTRUCTOR_ID: ${constructorId};
+${indent}SUBCLASS_OF_ID: ${subclassOfId};
+${indent}classType: "constructor";
 ${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
 ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
 ${indent}  ${Object.keys(argsConfig)
@@ -89,19 +111,25 @@ ${indent}}`.trim();
     function renderRequests(requests, indent) {
         return requests
             .map((args) => {
-                console.log(args);
-                const { name, argsConfig, result,constructorId,namespace,subclassOfId }=args;
+                const {
+                    name,
+                    argsConfig,
+                    result,
+                    constructorId,
+                    namespace,
+                    subclassOfId,
+                } = args;
                 const argKeys = Object.keys(argsConfig);
 
                 if (!argKeys.length) {
                     return `export class ${upperFirst(
                         name
                     )} extends Request<void, ${renderResult(result)}> {
-    CONSTRUCTOR_ID: ${constructorId};
-    SUBCLASS_OF_ID: ${subclassOfId};
-    classType: "request";
+${indent}CONSTRUCTOR_ID: ${constructorId};
+${indent}SUBCLASS_OF_ID: ${subclassOfId};
+${indent}classType: "request";
 ${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
-    static fromReader(reader: Reader): ${upperFirst(name)};
+${indent}static fromReader(reader: Reader): ${upperFirst(name)};
 }`;
                 }
 
@@ -120,9 +148,9 @@ ${indent}  ${argKeys
                     )
                     .join(`\n${indent}  `)}
 ${indent}}${!hasRequiredArgs ? "" : ""}>, ${renderResult(result)}> {
-    CONSTRUCTOR_ID: ${constructorId};
-    SUBCLASS_OF_ID: ${subclassOfId};
-    classType: "request";
+${indent}CONSTRUCTOR_ID: ${constructorId};
+${indent}SUBCLASS_OF_ID: ${subclassOfId};
+${indent}classType: "request";
 ${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
 ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
 ${indent}  ${argKeys
@@ -200,113 +228,94 @@ ${indent}}`.trim();
 
     // language=TypeScript
     return `
-        // This file is autogenerated. All changes will be overwritten.
-
-        import { BigInteger } from 'big-integer';
-        import { EntityLike, MessageIDLike } from "../define";
-
-
-        export namespace Api {
-
-            type AnyLiteral = Record<string, any> | void;
-
-            type Reader = any; // To be defined.
-            type Client = any; // To be defined.
-            type Utils = any; // To be defined.
-
-            type X = unknown;
-            type Type = unknown;
-            type Bool = boolean;
-            type int = number;
-            type double = number;
-            type float = number;
-            type int128 = BigInteger;
-            type int256 = BigInteger;
-            type long = BigInteger;
-            type bytes = Buffer;
-
-            class VirtualClass<Args extends AnyLiteral> {
-                static CONSTRUCTOR_ID: number;
-                static SUBCLASS_OF_ID: number;
-                static className: string;
-                static classType: 'constructor' | 'request';
-
-                static serializeBytes(data: Buffer | string): Buffer;
-
-                static serializeDate(date: Date | number): Buffer;
-
-                getBytes(): Buffer;
-
-                CONSTRUCTOR_ID: number;
-                SUBCLASS_OF_ID: number;
-                className: string;
-                classType: 'constructor' | 'request';
-
-                constructor(args: Args);
-            }
-
-            class Request<Args, Response> extends VirtualClass<Partial<Args>> {
-                static readResult(reader: Reader): Buffer;
-
-                resolve(client: Client, utils: Utils): Promise<void>;
-
-                __response: Response;
-            }
-
-
-            ${renderConstructors(constructorsByNs._, "  ")}
-            ${renderRequests(requestsByNs._, "  ")}
-
-
+// This file is autogenerated. All changes will be overwritten.
+import { BigInteger } from 'big-integer';
+import {EntityLike,MessageIDLike} from "../define";
+import { CustomMessage } from "./custom/message";
+
+
+export namespace Api {
+  type AnyLiteral = Record<string, any> | void;
+  type Reader = any; // To be defined.
+  type Client = any; // To be defined.
+  type Utils = any; // To be defined.
+  type X = unknown;
+  type Type = unknown;
+  type Bool = boolean;
+  type int = number;
+  type double = number;
+  type float = number;
+  type int128 = BigInteger;
+  type int256 = BigInteger;
+  type long = BigInteger;
+  type bytes = Buffer;
+  class VirtualClass<Args extends AnyLiteral> {
+    static CONSTRUCTOR_ID: number;
+    static SUBCLASS_OF_ID: number;
+    static className: string;
+    static classType: 'constructor' | 'request';
+    static serializeBytes(data: Buffer | string): Buffer;
+    static serializeDate(date: Date | number): Buffer;
+    getBytes():Buffer;
+    CONSTRUCTOR_ID: number;
+    SUBCLASS_OF_ID: number;
+    className: string;
+    classType: 'constructor' | 'request';
+    constructor(args: Args);
+  }
+  class Request<Args, Response> extends VirtualClass<Partial<Args>> {
+    static readResult(reader: Reader): Buffer;
+    resolve(client: Client, utils: Utils): Promise<void>;
+    __response: Response;
+  }
+  ${renderConstructors(constructorsByNs._, "  ")}
+  ${renderRequests(requestsByNs._, "  ")}
 // namespaces
-
-            ${Object.keys(constructorsByNs)
-                .map((namespace) =>
-                    namespace !== "_"
-                        ? `
+  ${Object.keys(constructorsByNs)
+      .map((namespace) =>
+          namespace !== "_"
+              ? `
   export namespace ${namespace} {
     ${renderConstructors(constructorsByNs[namespace], "    ")}
   }`
-                        : ""
-                )
-                .join("\n")}
-            ${Object.keys(typesByNs)
-                .map((namespace) =>
-                    namespace !== "_"
-                        ? `
+              : ""
+      )
+      .join("\n")}
+  ${Object.keys(typesByNs)
+      .map((namespace) =>
+          namespace !== "_"
+              ? `
   export namespace ${namespace} {
     ${renderTypes(typesByNs[namespace], "    ")}
   }`
-                        : ""
-                )
-                .join("\n")}
-            ${Object.keys(requestsByNs)
-                .map((namespace) =>
-                    namespace !== "_"
-                        ? `
+              : ""
+      )
+      .join("\n")}
+  ${Object.keys(requestsByNs)
+      .map((namespace) =>
+          namespace !== "_"
+              ? `
   export namespace ${namespace} {
     ${renderRequests(requestsByNs[namespace], "    ")}
   }`
-                        : ""
-                )
-                .join("\n")}
-
+              : ""
+      )
+      .join("\n")}
 // Types
-            export type TypeEntityLike = EntityLike;
-            ${renderTypes(typesByNs._, "  ")}
+  export type TypeEntityLike = EntityLike;
+  ${renderTypes(typesByNs._, "  ")}
 // All requests
-            export type AnyRequest = ${requestsByNs._.map(({ name }) =>
-                    upperFirst(name)
-                ).join(" | ")}
-                | ${Object.keys(requestsByNs)
-                .filter((ns) => ns !== "_")
-                .map((ns) =>
-                    requestsByNs[ns]
-                        .map(({ name }) => `${ns}.${upperFirst(name)}`)
-                        .join(" | ")
-                )
-                .join("\n    | ")};
-
-        }
-    `;
+  export type AnyRequest = ${requestsByNs._.map(({ name }) =>
+      upperFirst(name)
+  ).join(" | ")}
+    | ${Object.keys(requestsByNs)
+        .filter((ns) => ns !== "_")
+        .map((ns) =>
+            requestsByNs[ns]
+                .map(({ name }) => `${ns}.${upperFirst(name)}`)
+                .join(" | ")
+        )
+        .join("\n    | ")};
+}
+`;
 };

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 181 - 455
package-lock.json


+ 2 - 3
package.json

@@ -1,6 +1,6 @@
 {
   "name": "telegram",
-  "version": "1.9.6",
+  "version": "1.10.0",
   "description": "NodeJS/Browser MTProto API Telegram client library,",
   "main": "index.js",
   "types": "index.d.ts",
@@ -40,7 +40,7 @@
     "@types/pako": "^1.0.1",
     "@types/websocket": "^1.0.4",
     "babel-loader": "^8.2.2",
-    "jest": "^26.6.3",
+    "jest": "^27.2.5",
     "prettier": "2.3.1",
     "raw-loader": "^4.0.2",
     "ts-loader": "^8.0.16",
@@ -66,7 +66,6 @@
     "socks": "^2.6.1",
     "store2": "^2.12.0",
     "ts-custom-error": "^3.2.0",
-    "ts-mixer": "^6.0.0",
     "util": "^0.12.4",
     "websocket": "^1.0.34"
   }

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels