@mtcute/core 0.12.2 → 0.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,7 +28,7 @@ function _initializeClient(opts) {
28
28
  this._client.onUpdate(makeParsedUpdateHandler({
29
29
  messageGroupingInterval,
30
30
  onUpdate: (update) => {
31
- if (Conversation.handleUpdate(this._client, update) && skipConversationUpdates)
31
+ if (Conversation.handleUpdate(this, update) && skipConversationUpdates)
32
32
  return;
33
33
  this.emit('update', update);
34
34
  this.emit(update.name, update.data);
@@ -1 +1 @@
1
- {"version":3,"file":"_init.js","sourceRoot":"","sources":["../../../../src/highlevel/methods/_init.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAEtD,QAAQ;AACR,OAAO,EAAE,kBAAkB,EAAe,MAAM,sBAAsB,CAAA;AACtE,OAAO,EAAE,kBAAkB,EAA6B,MAAM,YAAY,CAAA;AAK1E,QAAQ;AACR,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AACvD,QAAQ;AACR,OAAO,EAAE,uBAAuB,EAA6B,MAAM,sBAAsB,CAAA;AAmCzF,cAAc;AACd,gBAAgB;AAChB,SAAS,iBAAiB,CAAuB,IAA2B;IACxE,IAAI,QAAQ,IAAI,IAAI,EAAE,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,MAAM,CAAA;IAC9B,CAAC;SAAM,CAAC;QACJ,IAAI,CAAC,IAAI,CAAC,OAAO,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACvF,MAAM,IAAI,kBAAkB,CACxB,+EAA+E,CAClF,CAAA;QACL,CAAC;QAED,IAAI,CAAC,OAAO,GAAG,IAAI,kBAAkB,CAAC,IAAiC,CAAC,CAAA;IAC5E,CAAC;IAED,2BAA2B;IAC3B,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAA;IAC3B,2BAA2B;IAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAA;IAEnC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;QACvB,MAAM,uBAAuB,GAAG,IAAI,CAAC,uBAAuB,IAAI,IAAI,CAAA;QACpE,MAAM,EAAE,uBAAuB,EAAE,GAAG,IAAI,CAAC,OAAO,IAAI,EAAE,CAAA;QAEtD,IAAI,CAAC,OAAO,CAAC,QAAQ,CACjB,uBAAuB,CAAC;YACpB,uBAAuB;YACvB,QAAQ,EAAE,CAAC,MAAM,EAAE,EAAE;gBACjB,IAAI,YAAY,CAAC,YAAY,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,uBAAuB;oBAAE,OAAM;gBAEtF,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;gBAC3B,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAA;YACvC,CAAC;YACD,WAAW,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE;gBAC3B,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YAC1C,CAAC;SACJ,CAAC,CACL,CAAA;IACL,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n// @copy\nimport { MtUnsupportedError, PartialOnly } from '../../types/index.js'\nimport { BaseTelegramClient, BaseTelegramClientOptions } from '../base.js'\nimport { TelegramClient } from '../client.js'\nimport { ITelegramClient } from '../client.types.js'\n// @copy\nimport { ITelegramStorageProvider } from '../storage/provider.js'\n// @copy\nimport { Conversation } from '../types/conversation.js'\n// @copy\nimport { makeParsedUpdateHandler, ParsedUpdateHandlerParams } from '../updates/parsed.js'\n\n// @copy\ntype TelegramClientOptions = (\n | (PartialOnly<Omit<BaseTelegramClientOptions, 'storage'>, 'transport' | 'crypto'> & {\n /**\n * Storage to use for this client.\n *\n * If a string is passed, it will be used as\n * a name for the default platform-specific storage provider to use.\n *\n * @default `\"client.session\"`\n */\n storage?: string | ITelegramStorageProvider\n })\n | { client: ITelegramClient }\n) & {\n /**\n * If true, all API calls will be wrapped with `tl.invokeWithoutUpdates`,\n * effectively disabling the server-sent events for the clients.\n * May be useful in some cases.\n *\n * @default false\n */\n disableUpdates?: boolean\n updates?: Omit<ParsedUpdateHandlerParams, 'onUpdate'>\n /**\n * If `true`, the updates that were handled by some {@link Conversation}\n * will not be dispatched any further.\n *\n * @default true\n */\n skipConversationUpdates?: boolean\n}\n\n// @initialize\n/** @internal */\nfunction _initializeClient(this: TelegramClient, opts: TelegramClientOptions) {\n if ('client' in opts) {\n this._client = opts.client\n } else {\n if (!opts.storage || typeof opts.storage === 'string' || !opts.transport || !opts.crypto) {\n throw new MtUnsupportedError(\n 'You need to explicitly provide storage, transport and crypto for @mtcute/core',\n )\n }\n\n this._client = new BaseTelegramClient(opts as BaseTelegramClientOptions)\n }\n\n // @ts-expect-error codegen\n this.log = this._client.log\n // @ts-expect-error codegen\n this.storage = this._client.storage\n\n if (!opts.disableUpdates) {\n const skipConversationUpdates = opts.skipConversationUpdates ?? true\n const { messageGroupingInterval } = opts.updates ?? {}\n\n this._client.onUpdate(\n makeParsedUpdateHandler({\n messageGroupingInterval,\n onUpdate: (update) => {\n if (Conversation.handleUpdate(this._client, update) && skipConversationUpdates) return\n\n this.emit('update', update)\n this.emit(update.name, update.data)\n },\n onRawUpdate: (update, peers) => {\n this.emit('raw_update', update, peers)\n },\n }),\n )\n }\n}\n"]}
1
+ {"version":3,"file":"_init.js","sourceRoot":"","sources":["../../../../src/highlevel/methods/_init.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAEtD,QAAQ;AACR,OAAO,EAAE,kBAAkB,EAAe,MAAM,sBAAsB,CAAA;AACtE,OAAO,EAAE,kBAAkB,EAA6B,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E,MAAM,CAAC,CAAA;gBAC3B,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAA;YACvC,CAAC;YACD,WAAW,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE;gBAC3B,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YAC1C,CAAC;SACJ,CAAC,CACL,CAAA;IACL,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n// @copy\nimport { MtUnsupportedError, PartialOnly } from '../../types/index.js'\nimport { BaseTelegramClient, BaseTelegramClientOptions } from '../base.js'\nimport { TelegramClient } from '../client.js'\nimport { ITelegramClient } from '../client.types.js'\n// @copy\nimport { ITelegramStorageProvider } from '../storage/provider.js'\n// @copy\nimport { Conversation } from '../types/conversation.js'\n// @copy\nimport { makeParsedUpdateHandler, ParsedUpdateHandlerParams } from '../updates/parsed.js'\n\n// @copy\ntype TelegramClientOptions = (\n | (PartialOnly<Omit<BaseTelegramClientOptions, 'storage'>, 'transport' | 'crypto'> & {\n /**\n * Storage to use for this client.\n *\n * If a string is passed, it will be used as\n * a name for the default platform-specific storage provider to use.\n *\n * @default `\"client.session\"`\n */\n storage?: string | ITelegramStorageProvider\n })\n | { client: ITelegramClient }\n) & {\n /**\n * If true, all API calls will be wrapped with `tl.invokeWithoutUpdates`,\n * effectively disabling the server-sent events for the clients.\n * May be useful in some cases.\n *\n * @default false\n */\n disableUpdates?: boolean\n updates?: Omit<ParsedUpdateHandlerParams, 'onUpdate'>\n /**\n * If `true`, the updates that were handled by some {@link Conversation}\n * will not be dispatched any further.\n *\n * @default true\n */\n skipConversationUpdates?: boolean\n}\n\n// @initialize\n/** @internal */\nfunction _initializeClient(this: TelegramClient, opts: TelegramClientOptions) {\n if ('client' in opts) {\n this._client = opts.client\n } else {\n if (!opts.storage || typeof opts.storage === 'string' || !opts.transport || !opts.crypto) {\n throw new MtUnsupportedError(\n 'You need to explicitly provide storage, transport and crypto for @mtcute/core',\n )\n }\n\n this._client = new BaseTelegramClient(opts as BaseTelegramClientOptions)\n }\n\n // @ts-expect-error codegen\n this.log = this._client.log\n // @ts-expect-error codegen\n this.storage = this._client.storage\n\n if (!opts.disableUpdates) {\n const skipConversationUpdates = opts.skipConversationUpdates ?? true\n const { messageGroupingInterval } = opts.updates ?? {}\n\n this._client.onUpdate(\n makeParsedUpdateHandler({\n messageGroupingInterval,\n onUpdate: (update) => {\n if (Conversation.handleUpdate(this, update) && skipConversationUpdates) return\n\n this.emit('update', update)\n this.emit(update.name, update.data)\n },\n onRawUpdate: (update, peers) => {\n this.emit('raw_update', update, peers)\n },\n }),\n )\n }\n}\n"]}
@@ -16,6 +16,17 @@ export declare function getCallbackAnswer(client: ITelegramClient, params: Input
16
16
  * @default `10000` (10 sec)
17
17
  */
18
18
  timeout?: number;
19
+ /**
20
+ * Whether to "fire and forget" this request,
21
+ * in which case the promise will resolve as soon
22
+ * as the request is sent with an empty response.
23
+ *
24
+ * Useful for interacting with bots that don't correctly
25
+ * answer to callback queries and the request always times out.
26
+ *
27
+ * **Note**: any errors will be silently ignored.
28
+ */
29
+ fireAndForget?: boolean;
19
30
  /**
20
31
  * Whether this is a "play game" button
21
32
  */
@@ -9,13 +9,13 @@ import { resolvePeer } from '../users/resolve-peer.js';
9
9
  */
10
10
  export async function getCallbackAnswer(client, params) {
11
11
  const { chatId, message } = normalizeInputMessageId(params);
12
- const { data, game, timeout = 10000 } = params;
12
+ const { data, game, timeout = 10000, fireAndForget } = params;
13
13
  let password = undefined;
14
14
  if (params?.password) {
15
15
  const pwd = await client.call({ _: 'account.getPassword' });
16
16
  password = await client.computeSrpParams(pwd, params.password);
17
17
  }
18
- return await client.call({
18
+ const promise = client.call({
19
19
  _: 'messages.getBotCallbackAnswer',
20
20
  peer: await resolvePeer(client, chatId),
21
21
  msgId: message,
@@ -23,5 +23,13 @@ export async function getCallbackAnswer(client, params) {
23
23
  password,
24
24
  game: game,
25
25
  }, { timeout, throw503: true });
26
+ if (fireAndForget) {
27
+ promise.catch(() => { });
28
+ return {
29
+ _: 'messages.botCallbackAnswer',
30
+ cacheTime: 0,
31
+ };
32
+ }
33
+ return promise;
26
34
  }
27
35
  //# sourceMappingURL=get-callback-answer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"get-callback-answer.js","sourceRoot":"","sources":["../../../../../src/highlevel/methods/bots/get-callback-answer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAElD,OAAO,EAAkB,uBAAuB,EAAE,MAAM,sBAAsB,CAAA;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAEtD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACnC,MAAuB,EACvB,MAuBC;IAED,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,uBAAuB,CAAC,MAAM,CAAC,CAAA;IAC3D,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,GAAG,KAAK,EAAE,GAAG,MAAM,CAAA;IAE9C,IAAI,QAAQ,GAA6C,SAAS,CAAA;IAElE,IAAI,MAAM,EAAE,QAAQ,EAAE,CAAC;QACnB,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,qBAAqB,EAAE,CAAC,CAAA;QAC3D,QAAQ,GAAG,MAAM,MAAM,CAAC,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAA;IAClE,CAAC;IAED,OAAO,MAAM,MAAM,CAAC,IAAI,CACpB;QACI,CAAC,EAAE,+BAA+B;QAClC,IAAI,EAAE,MAAM,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC;QACvC,KAAK,EAAE,OAAO;QACd,IAAI,EAAE,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI;QACtE,QAAQ;QACR,IAAI,EAAE,IAAI;KACb,EACD,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAC9B,CAAA;AACL,CAAC","sourcesContent":["import { tl } from '@mtcute/tl'\n\nimport { getPlatform } from '../../../platform.js'\nimport { ITelegramClient } from '../../client.types.js'\nimport { InputMessageId, normalizeInputMessageId } from '../../types/index.js'\nimport { resolvePeer } from '../users/resolve-peer.js'\n\n/**\n * Request a callback answer from a bot,\n * i.e. click an inline button that contains data.\n *\n * @param params\n */\nexport async function getCallbackAnswer(\n client: ITelegramClient,\n params: InputMessageId & {\n /** Data contained in the button */\n data: string | Uint8Array\n\n /**\n * Timeout for the query in ms.\n *\n * @default `10000` (10 sec)\n */\n timeout?: number\n\n /**\n * Whether this is a \"play game\" button\n */\n game?: boolean\n\n /**\n * If the button requires password entry, your 2FA password.\n *\n * Your password is never exposed to the bot,\n * it is checked by Telegram.\n */\n password?: string\n },\n): Promise<tl.messages.TypeBotCallbackAnswer> {\n const { chatId, message } = normalizeInputMessageId(params)\n const { data, game, timeout = 10000 } = params\n\n let password: tl.TypeInputCheckPasswordSRP | undefined = undefined\n\n if (params?.password) {\n const pwd = await client.call({ _: 'account.getPassword' })\n password = await client.computeSrpParams(pwd, params.password)\n }\n\n return await client.call(\n {\n _: 'messages.getBotCallbackAnswer',\n peer: await resolvePeer(client, chatId),\n msgId: message,\n data: typeof data === 'string' ? getPlatform().utf8Encode(data) : data,\n password,\n game: game,\n },\n { timeout, throw503: true },\n )\n}\n"]}
1
+ {"version":3,"file":"get-callback-answer.js","sourceRoot":"","sources":["../../../../../src/highlevel/methods/bots/get-callback-answer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAElD,OAAO,EAAkB,uBAAuB,EAAE,MAAM,sBAAsB,CAAA;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,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Client } from '../../client.types.js'\nimport { InputMessageId, normalizeInputMessageId } from '../../types/index.js'\nimport { resolvePeer } from '../users/resolve-peer.js'\n\n/**\n * Request a callback answer from a bot,\n * i.e. click an inline button that contains data.\n *\n * @param params\n */\nexport async function getCallbackAnswer(\n client: ITelegramClient,\n params: InputMessageId & {\n /** Data contained in the button */\n data: string | Uint8Array\n\n /**\n * Timeout for the query in ms.\n *\n * @default `10000` (10 sec)\n */\n timeout?: number\n\n /**\n * Whether to \"fire and forget\" this request,\n * in which case the promise will resolve as soon\n * as the request is sent with an empty response.\n *\n * Useful for interacting with bots that don't correctly\n * answer to callback queries and the request always times out.\n *\n * **Note**: any errors will be silently ignored.\n */\n fireAndForget?: boolean\n\n /**\n * Whether this is a \"play game\" button\n */\n game?: boolean\n\n /**\n * If the button requires password entry, your 2FA password.\n *\n * Your password is never exposed to the bot,\n * it is checked by Telegram.\n */\n password?: string\n },\n): Promise<tl.messages.TypeBotCallbackAnswer> {\n const { chatId, message } = normalizeInputMessageId(params)\n const { data, game, timeout = 10000, fireAndForget } = params\n\n let password: tl.TypeInputCheckPasswordSRP | undefined = undefined\n\n if (params?.password) {\n const pwd = await client.call({ _: 'account.getPassword' })\n password = await client.computeSrpParams(pwd, params.password)\n }\n\n const promise = client.call(\n {\n _: 'messages.getBotCallbackAnswer',\n peer: await resolvePeer(client, chatId),\n msgId: message,\n data: typeof data === 'string' ? getPlatform().utf8Encode(data) : data,\n password,\n game: game,\n },\n { timeout, throw503: true },\n )\n\n if (fireAndForget) {\n promise.catch(() => {})\n\n return {\n _: 'messages.botCallbackAnswer',\n cacheTime: 0,\n }\n }\n\n return promise\n}\n"]}
@@ -9,7 +9,6 @@ import { ConfigManager } from './config-manager.js';
9
9
  import { NetworkManager, NetworkManagerExtraParams, RpcCallOptions } from './network-manager.js';
10
10
  import { PersistentConnectionParams } from './persistent-connection.js';
11
11
  import { ReconnectionStrategy } from './reconnection.js';
12
- import { SessionConnection } from './session-connection.js';
13
12
  import { TransportFactory } from './transports/index.js';
14
13
  /** Options for {@link MtClient} */
15
14
  export interface MtClientOptions {
@@ -196,7 +195,7 @@ export declare class MtClient extends EventEmitter {
196
195
  readonly log: Logger;
197
196
  readonly network: NetworkManager;
198
197
  constructor(params: MtClientOptions);
199
- emitError(err: unknown, connection?: SessionConnection): void;
198
+ emitError(err: unknown): void;
200
199
  private _prepare;
201
200
  /**
202
201
  * **ADVANCED**
@@ -96,9 +96,9 @@ export class MtClient extends EventEmitter {
96
96
  ...params.network,
97
97
  }, this._config);
98
98
  }
99
- emitError(err, connection) {
99
+ emitError(err) {
100
100
  if (this._emitError) {
101
- this._emitError(err, connection);
101
+ this._emitError(err);
102
102
  }
103
103
  else {
104
104
  this.log.error('unhandled error:', err);
@@ -170,7 +170,7 @@ export class MtClient extends EventEmitter {
170
170
  * @param handler Error handler.
171
171
  */
172
172
  onError(handler) {
173
- this.emitError = handler;
173
+ this._emitError = handler;
174
174
  }
175
175
  }
176
176
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/network/client.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,OAAO,YAAY,MAAM,QAAQ,CAAA;AAEjC,OAAO,EAAE,EAAE,EAAE,MAAM,YAAY,CAAA;AAC/B,OAAO,EAAE,aAAa,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAC/E,OAAO,EAAE,aAAa,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAI/E,OAAO,EAAE,cAAc,EAA8B,MAAM,uBAAuB,CAAA;AAElF,OAAO,EACH,eAAe,EAEf,mBAAmB,EACnB,uBAAuB,EACvB,aAAa,EACb,iBAAiB,EAGjB,UAAU,GACb,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AACnD,OAAO,EAAE,cAAc,EAA6C,MAAM,sBAAsB,CAAA;AAkLhG;;;;GAIG;AACH,MAAM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-explicit-any */\nimport EventEmitter from 'events'\n\nimport { tl } from '@mtcute/tl'\nimport { __tlReaderMap as defaultReaderMap } from '@mtcute/tl/binary/reader.js'\nimport { __tlWriterMap as defaultWriterMap } from '@mtcute/tl/binary/writer.js'\nimport { TlReaderMap, TlWriterMap } from '@mtcute/tl-runtime'\n\nimport { IMtStorageProvider } from '../storage/provider.js'\nimport { StorageManager, StorageManagerExtraOptions } from '../storage/storage.js'\nimport { MustEqual } from '../types/index.js'\nimport {\n asyncResettable,\n DcOptions,\n defaultProductionDc,\n defaultProductionIpv6Dc,\n defaultTestDc,\n defaultTestIpv6Dc,\n ICryptoProvider,\n Logger,\n LogManager,\n} from '../utils/index.js'\nimport { ConfigManager } from './config-manager.js'\nimport { NetworkManager, NetworkManagerExtraParams, RpcCallOptions } from './network-manager.js'\nimport { PersistentConnectionParams } from './persistent-connection.js'\nimport { ReconnectionStrategy } from './reconnection.js'\nimport { SessionConnection } from './session-connection.js'\nimport { TransportFactory } from './transports/index.js'\n\n/** Options for {@link MtClient} */\nexport interface MtClientOptions {\n /**\n * API ID from my.telegram.org\n */\n apiId: number\n /**\n * API hash from my.telegram.org\n */\n apiHash: string\n\n /**\n * Storage to use for this client.\n */\n storage: IMtStorageProvider\n\n /** Additional options for the storage manager */\n storageOptions?: StorageManagerExtraOptions\n\n /**\n * Cryptography provider to allow delegating\n * crypto to native addon, worker, etc.\n */\n crypto: ICryptoProvider\n\n /**\n * Whether to use IPv6 datacenters\n * (IPv6 will be preferred when choosing a DC by id)\n * (default: false)\n */\n useIpv6?: boolean\n\n /**\n * Primary DC to use for initial connection.\n * This does not mean this will be the only DC used,\n * nor that this DC will actually be primary, this only\n * determines the first DC the library will try to connect to.\n * Can be used to connect to other networks (like test DCs).\n *\n * When session already contains primary DC, this parameter is ignored.\n *\n * @default Production DC 2.\n */\n defaultDcs?: DcOptions\n\n /**\n * Whether to connect to test servers.\n *\n * If passed, {@link defaultDc} defaults to Test DC 2.\n *\n * **Must** be passed if using test servers, even if\n * you passed custom {@link defaultDc}\n */\n testMode?: boolean\n\n /**\n * Additional options for initConnection call.\n * `apiId` and `query` are not available and will be ignored.\n * Omitted values will be filled with defaults\n */\n initConnectionOptions?: Partial<Omit<tl.RawInitConnectionRequest, 'apiId' | 'query'>>\n\n /**\n * Transport factory to use in the client.\n *\n * @default platform-specific transport: WebSocket on the web, TCP in node\n */\n transport: TransportFactory\n\n /**\n * Reconnection strategy.\n *\n * @default simple reconnection strategy: first 0ms, then up to 5s (increasing by 1s)\n */\n reconnectionStrategy?: ReconnectionStrategy<PersistentConnectionParams>\n\n /**\n * Maximum duration of a flood_wait that will be waited automatically.\n * Flood waits above this threshold will throw a FloodWaitError.\n * Set to 0 to disable. Can be overridden with `throwFlood` parameter in call() params\n *\n * @default 10000\n */\n floodSleepThreshold?: number\n\n /**\n * Maximum number of retries when calling RPC methods.\n * Call is retried when InternalError or FloodWaitError is encountered.\n * Can be set to Infinity.\n *\n * @default 5\n */\n maxRetryCount?: number\n\n /**\n * If true, all API calls will be wrapped with `tl.invokeWithoutUpdates`,\n * effectively disabling the server-sent events for the clients.\n * May be useful in some cases.\n *\n * @default false\n */\n disableUpdates?: boolean\n\n /**\n * mtcute can send all unknown RPC errors to [danog](https://github.com/danog)'s\n * [error reporting service](https://rpc.pwrtelegram.xyz/).\n *\n * This is fully anonymous (except maybe IP) and is only used to improve the library\n * and developer experience for everyone working with MTProto. This is fully opt-in,\n * and if you're too paranoid, you can disable it by manually passing `enableErrorReporting: false` to the client.\n *\n * @default false\n */\n enableErrorReporting?: boolean\n\n /**\n * If true, RPC errors will have a stack trace of the initial `.call()`\n * or `.sendForResult()` call position, which drastically improves\n * debugging experience.<br>\n * If false, they will have a stack trace of mtcute internals.\n *\n * Internally this creates a stack capture before every RPC call\n * and stores it until the result is received. This might\n * use a lot more memory than normal, thus can be disabled here.\n *\n * @default true\n */\n niceStacks?: boolean\n\n /**\n * Extra parameters for {@link NetworkManager}\n */\n network?: NetworkManagerExtraParams\n\n /**\n * Logger instance for the client.\n * If not passed, a new one will be created.\n */\n logger?: Logger\n\n /**\n * Set logging level for the client.\n * Shorthand for `client.log.level = level`.\n *\n * See static members of {@link LogManager} for possible values.\n */\n logLevel?: number\n\n /**\n * **EXPERT USE ONLY!**\n *\n * Override TL layer used for the connection.\n *\n * **Does not** change the schema used.\n */\n overrideLayer?: number\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override reader map used for the connection.\n */\n readerMap?: TlReaderMap\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override writer map used for the connection.\n */\n writerMap?: TlWriterMap\n}\n\n/**\n * Basic MTProto client implementation, only doing the bare minimum\n * to make RPC calls and receive low-level updates, as well as providing\n * some APIs to manage that.\n */\nexport class MtClient extends EventEmitter {\n /**\n * Crypto provider taken from {@link MtClientOptions.crypto}\n */\n readonly crypto: ICryptoProvider\n\n /** Storage manager */\n readonly storage: StorageManager\n\n /**\n * \"Test mode\" taken from {@link MtClientOptions.testMode}\n */\n protected readonly _testMode: boolean\n\n /**\n * Primary DCs taken from {@link MtClientOptions.defaultDcs},\n * loaded from session or changed by other means (like redirecting).\n */\n _defaultDcs: DcOptions\n\n private _niceStacks: boolean\n /** TL layer used by the client */\n readonly _layer: number\n /** TL readers map used by the client */\n readonly _readerMap: TlReaderMap\n /** TL writers map used by the client */\n readonly _writerMap: TlWriterMap\n\n readonly _config = new ConfigManager(() => this.call({ _: 'help.getConfig' }))\n\n private _emitError?: (err: unknown, connection?: SessionConnection) => void\n\n readonly log: Logger\n readonly network: NetworkManager\n\n constructor(readonly params: MtClientOptions) {\n super()\n\n this.log = params.logger ?? new LogManager()\n\n if (params.logLevel !== undefined) {\n this.log.mgr.level = params.logLevel\n }\n\n this.crypto = params.crypto\n this._testMode = Boolean(params.testMode)\n\n let dc = params.defaultDcs\n\n if (!dc) {\n if (params.testMode) {\n dc = params.useIpv6 ? defaultTestIpv6Dc : defaultTestDc\n } else {\n dc = params.useIpv6 ? defaultProductionIpv6Dc : defaultProductionDc\n }\n }\n\n this._defaultDcs = dc\n this._niceStacks = params.niceStacks ?? true\n\n this._layer = params.overrideLayer ?? tl.LAYER\n this._readerMap = params.readerMap ?? defaultReaderMap\n this._writerMap = params.writerMap ?? defaultWriterMap\n\n this.storage = new StorageManager({\n provider: params.storage,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n ...params.storageOptions,\n })\n\n this.network = new NetworkManager(\n {\n apiId: params.apiId,\n crypto: this.crypto,\n disableUpdates: params.disableUpdates ?? false,\n initConnectionOptions: params.initConnectionOptions,\n layer: this._layer,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n reconnectionStrategy: params.reconnectionStrategy,\n storage: this.storage,\n testMode: Boolean(params.testMode),\n transport: params.transport,\n emitError: this.emitError.bind(this),\n floodSleepThreshold: params.floodSleepThreshold ?? 10000,\n maxRetryCount: params.maxRetryCount ?? 5,\n isPremium: false,\n useIpv6: Boolean(params.useIpv6),\n enableErrorReporting: params.enableErrorReporting ?? false,\n onUsable: () => this.emit('usable'),\n onConnecting: () => this.emit('connecting'),\n onNetworkChanged: (connected) => this.emit('networkChanged', connected),\n onUpdate: (upd) => this.emit('update', upd),\n ...params.network,\n },\n this._config,\n )\n }\n\n emitError(err: unknown, connection?: SessionConnection): void {\n if (this._emitError) {\n this._emitError(err, connection)\n } else {\n this.log.error('unhandled error:', err)\n }\n }\n\n private _prepare = asyncResettable(async () => {\n await this.crypto.initialize?.()\n await this.storage.load()\n\n const primaryDc = await this.storage.dcs.fetch()\n if (primaryDc !== null) this._defaultDcs = primaryDc\n })\n\n /**\n * **ADVANCED**\n *\n * Do all the preparations, but don't connect just yet.\n * Useful when you want to do some preparations before\n * connecting, like setting up session.\n *\n * Call {@link connect} to actually connect.\n */\n prepare() {\n return this._prepare.run()\n }\n\n private _connect = asyncResettable(async () => {\n await this._prepare.run()\n await this.network.connect(this._defaultDcs)\n })\n\n /**\n * Initialize the connection to the primary DC.\n *\n * You shouldn't usually call this method directly as it is called\n * implicitly the first time you call {@link call}.\n */\n async connect(): Promise<void> {\n return this._connect.run()\n }\n\n /**\n * Close all connections and finalize the client.\n */\n async close(): Promise<void> {\n this._config.destroy()\n await this.network.destroy()\n\n await this.storage.save()\n await this.storage.destroy?.()\n\n this._prepare.reset()\n this._connect.reset()\n }\n\n /**\n * Make an RPC call.\n *\n * The connection must have been {@link connect}-ed\n * before calling this method.\n *\n * This method is still quite low-level and you shouldn't use this\n * when using high-level API provided by `@mtcute/client`.\n *\n * @param message RPC method to call\n * @param params Additional call parameters\n */\n async call<T extends tl.RpcMethod>(\n message: MustEqual<T, tl.RpcMethod>,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']]> {\n const stack = this._niceStacks ? new Error().stack : undefined\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return this.network.call(message, params, stack)\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler Error handler.\n */\n onError(handler: (err: unknown) => void): void {\n this.emitError = handler\n }\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/network/client.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,OAAO,YAAY,MAAM,QAAQ,CAAA;AAEjC,OAAO,EAAE,EAAE,EAAE,MAAM,YAAY,CAAA;AAC/B,OAAO,EAAE,aAAa,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAC/E,OAAO,EAAE,aAAa,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAI/E,OAAO,EAAE,cAAc,EAA8B,MAAM,uBAAuB,CAAA;AAElF,OAAO,EACH,eAAe,EAEf,mBAAmB,EACnB,uBAAuB,EACvB,aAAa,EACb,iBAAiB,EAGjB,UAAU,GACb,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AACnD,OAAO,EAAE,cAAc,EAA6C,MAAM,sBAAsB,CAAA;AAiLhG;;;;GAIG;AACH,MAAM,OA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\nimport { tl } from '@mtcute/tl'\nimport { __tlReaderMap as defaultReaderMap } from '@mtcute/tl/binary/reader.js'\nimport { __tlWriterMap as defaultWriterMap } from '@mtcute/tl/binary/writer.js'\nimport { TlReaderMap, TlWriterMap } from '@mtcute/tl-runtime'\n\nimport { IMtStorageProvider } from '../storage/provider.js'\nimport { StorageManager, StorageManagerExtraOptions } from '../storage/storage.js'\nimport { MustEqual } from '../types/index.js'\nimport {\n asyncResettable,\n DcOptions,\n defaultProductionDc,\n defaultProductionIpv6Dc,\n defaultTestDc,\n defaultTestIpv6Dc,\n ICryptoProvider,\n Logger,\n LogManager,\n} from '../utils/index.js'\nimport { ConfigManager } from './config-manager.js'\nimport { NetworkManager, NetworkManagerExtraParams, RpcCallOptions } from './network-manager.js'\nimport { PersistentConnectionParams } from './persistent-connection.js'\nimport { ReconnectionStrategy } from './reconnection.js'\nimport { TransportFactory } from './transports/index.js'\n\n/** Options for {@link MtClient} */\nexport interface MtClientOptions {\n /**\n * API ID from my.telegram.org\n */\n apiId: number\n /**\n * API hash from my.telegram.org\n */\n apiHash: string\n\n /**\n * Storage to use for this client.\n */\n storage: IMtStorageProvider\n\n /** Additional options for the storage manager */\n storageOptions?: StorageManagerExtraOptions\n\n /**\n * Cryptography provider to allow delegating\n * crypto to native addon, worker, etc.\n */\n crypto: ICryptoProvider\n\n /**\n * Whether to use IPv6 datacenters\n * (IPv6 will be preferred when choosing a DC by id)\n * (default: false)\n */\n useIpv6?: boolean\n\n /**\n * Primary DC to use for initial connection.\n * This does not mean this will be the only DC used,\n * nor that this DC will actually be primary, this only\n * determines the first DC the library will try to connect to.\n * Can be used to connect to other networks (like test DCs).\n *\n * When session already contains primary DC, this parameter is ignored.\n *\n * @default Production DC 2.\n */\n defaultDcs?: DcOptions\n\n /**\n * Whether to connect to test servers.\n *\n * If passed, {@link defaultDc} defaults to Test DC 2.\n *\n * **Must** be passed if using test servers, even if\n * you passed custom {@link defaultDc}\n */\n testMode?: boolean\n\n /**\n * Additional options for initConnection call.\n * `apiId` and `query` are not available and will be ignored.\n * Omitted values will be filled with defaults\n */\n initConnectionOptions?: Partial<Omit<tl.RawInitConnectionRequest, 'apiId' | 'query'>>\n\n /**\n * Transport factory to use in the client.\n *\n * @default platform-specific transport: WebSocket on the web, TCP in node\n */\n transport: TransportFactory\n\n /**\n * Reconnection strategy.\n *\n * @default simple reconnection strategy: first 0ms, then up to 5s (increasing by 1s)\n */\n reconnectionStrategy?: ReconnectionStrategy<PersistentConnectionParams>\n\n /**\n * Maximum duration of a flood_wait that will be waited automatically.\n * Flood waits above this threshold will throw a FloodWaitError.\n * Set to 0 to disable. Can be overridden with `throwFlood` parameter in call() params\n *\n * @default 10000\n */\n floodSleepThreshold?: number\n\n /**\n * Maximum number of retries when calling RPC methods.\n * Call is retried when InternalError or FloodWaitError is encountered.\n * Can be set to Infinity.\n *\n * @default 5\n */\n maxRetryCount?: number\n\n /**\n * If true, all API calls will be wrapped with `tl.invokeWithoutUpdates`,\n * effectively disabling the server-sent events for the clients.\n * May be useful in some cases.\n *\n * @default false\n */\n disableUpdates?: boolean\n\n /**\n * mtcute can send all unknown RPC errors to [danog](https://github.com/danog)'s\n * [error reporting service](https://rpc.pwrtelegram.xyz/).\n *\n * This is fully anonymous (except maybe IP) and is only used to improve the library\n * and developer experience for everyone working with MTProto. This is fully opt-in,\n * and if you're too paranoid, you can disable it by manually passing `enableErrorReporting: false` to the client.\n *\n * @default false\n */\n enableErrorReporting?: boolean\n\n /**\n * If true, RPC errors will have a stack trace of the initial `.call()`\n * or `.sendForResult()` call position, which drastically improves\n * debugging experience.<br>\n * If false, they will have a stack trace of mtcute internals.\n *\n * Internally this creates a stack capture before every RPC call\n * and stores it until the result is received. This might\n * use a lot more memory than normal, thus can be disabled here.\n *\n * @default true\n */\n niceStacks?: boolean\n\n /**\n * Extra parameters for {@link NetworkManager}\n */\n network?: NetworkManagerExtraParams\n\n /**\n * Logger instance for the client.\n * If not passed, a new one will be created.\n */\n logger?: Logger\n\n /**\n * Set logging level for the client.\n * Shorthand for `client.log.level = level`.\n *\n * See static members of {@link LogManager} for possible values.\n */\n logLevel?: number\n\n /**\n * **EXPERT USE ONLY!**\n *\n * Override TL layer used for the connection.\n *\n * **Does not** change the schema used.\n */\n overrideLayer?: number\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override reader map used for the connection.\n */\n readerMap?: TlReaderMap\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override writer map used for the connection.\n */\n writerMap?: TlWriterMap\n}\n\n/**\n * Basic MTProto client implementation, only doing the bare minimum\n * to make RPC calls and receive low-level updates, as well as providing\n * some APIs to manage that.\n */\nexport class MtClient extends EventEmitter {\n /**\n * Crypto provider taken from {@link MtClientOptions.crypto}\n */\n readonly crypto: ICryptoProvider\n\n /** Storage manager */\n readonly storage: StorageManager\n\n /**\n * \"Test mode\" taken from {@link MtClientOptions.testMode}\n */\n protected readonly _testMode: boolean\n\n /**\n * Primary DCs taken from {@link MtClientOptions.defaultDcs},\n * loaded from session or changed by other means (like redirecting).\n */\n _defaultDcs: DcOptions\n\n private _niceStacks: boolean\n /** TL layer used by the client */\n readonly _layer: number\n /** TL readers map used by the client */\n readonly _readerMap: TlReaderMap\n /** TL writers map used by the client */\n readonly _writerMap: TlWriterMap\n\n readonly _config = new ConfigManager(() => this.call({ _: 'help.getConfig' }))\n\n private _emitError?: (err: unknown) => void\n\n readonly log: Logger\n readonly network: NetworkManager\n\n constructor(readonly params: MtClientOptions) {\n super()\n\n this.log = params.logger ?? new LogManager()\n\n if (params.logLevel !== undefined) {\n this.log.mgr.level = params.logLevel\n }\n\n this.crypto = params.crypto\n this._testMode = Boolean(params.testMode)\n\n let dc = params.defaultDcs\n\n if (!dc) {\n if (params.testMode) {\n dc = params.useIpv6 ? defaultTestIpv6Dc : defaultTestDc\n } else {\n dc = params.useIpv6 ? defaultProductionIpv6Dc : defaultProductionDc\n }\n }\n\n this._defaultDcs = dc\n this._niceStacks = params.niceStacks ?? true\n\n this._layer = params.overrideLayer ?? tl.LAYER\n this._readerMap = params.readerMap ?? defaultReaderMap\n this._writerMap = params.writerMap ?? defaultWriterMap\n\n this.storage = new StorageManager({\n provider: params.storage,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n ...params.storageOptions,\n })\n\n this.network = new NetworkManager(\n {\n apiId: params.apiId,\n crypto: this.crypto,\n disableUpdates: params.disableUpdates ?? false,\n initConnectionOptions: params.initConnectionOptions,\n layer: this._layer,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n reconnectionStrategy: params.reconnectionStrategy,\n storage: this.storage,\n testMode: Boolean(params.testMode),\n transport: params.transport,\n emitError: this.emitError.bind(this),\n floodSleepThreshold: params.floodSleepThreshold ?? 10000,\n maxRetryCount: params.maxRetryCount ?? 5,\n isPremium: false,\n useIpv6: Boolean(params.useIpv6),\n enableErrorReporting: params.enableErrorReporting ?? false,\n onUsable: () => this.emit('usable'),\n onConnecting: () => this.emit('connecting'),\n onNetworkChanged: (connected) => this.emit('networkChanged', connected),\n onUpdate: (upd) => this.emit('update', upd),\n ...params.network,\n },\n this._config,\n )\n }\n\n emitError(err: unknown): void {\n if (this._emitError) {\n this._emitError(err)\n } else {\n this.log.error('unhandled error:', err)\n }\n }\n\n private _prepare = asyncResettable(async () => {\n await this.crypto.initialize?.()\n await this.storage.load()\n\n const primaryDc = await this.storage.dcs.fetch()\n if (primaryDc !== null) this._defaultDcs = primaryDc\n })\n\n /**\n * **ADVANCED**\n *\n * Do all the preparations, but don't connect just yet.\n * Useful when you want to do some preparations before\n * connecting, like setting up session.\n *\n * Call {@link connect} to actually connect.\n */\n prepare() {\n return this._prepare.run()\n }\n\n private _connect = asyncResettable(async () => {\n await this._prepare.run()\n await this.network.connect(this._defaultDcs)\n })\n\n /**\n * Initialize the connection to the primary DC.\n *\n * You shouldn't usually call this method directly as it is called\n * implicitly the first time you call {@link call}.\n */\n async connect(): Promise<void> {\n return this._connect.run()\n }\n\n /**\n * Close all connections and finalize the client.\n */\n async close(): Promise<void> {\n this._config.destroy()\n await this.network.destroy()\n\n await this.storage.save()\n await this.storage.destroy?.()\n\n this._prepare.reset()\n this._connect.reset()\n }\n\n /**\n * Make an RPC call.\n *\n * The connection must have been {@link connect}-ed\n * before calling this method.\n *\n * This method is still quite low-level and you shouldn't use this\n * when using high-level API provided by `@mtcute/client`.\n *\n * @param message RPC method to call\n * @param params Additional call parameters\n */\n async call<T extends tl.RpcMethod>(\n message: MustEqual<T, tl.RpcMethod>,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']]> {\n const stack = this._niceStacks ? new Error().stack : undefined\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return this.network.call(message, params, stack)\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler Error handler.\n */\n onError(handler: (err: unknown) => void): void {\n this._emitError = handler\n }\n}\n"]}
@@ -244,7 +244,7 @@ export class NetworkManager {
244
244
  _: 'initConnection',
245
245
  deviceModel,
246
246
  systemVersion: '1.0',
247
- appVersion: '0.12.2',
247
+ appVersion: '0.12.5',
248
248
  systemLangCode: 'en',
249
249
  langPack: '', // "langPacks are for official apps only"
250
250
  langCode: 'en',
@@ -1090,7 +1090,7 @@ export class SessionConnection extends PersistentConnection {
1090
1090
  return pending.promise;
1091
1091
  }
1092
1092
  if (timeout) {
1093
- pending.timeout = setTimeout(this._cancelRpc, timeout, pending, true);
1093
+ pending.timeout = setTimeout(() => this._cancelRpc(pending, true), timeout);
1094
1094
  }
1095
1095
  if (abortSignal) {
1096
1096
  abortSignal.addEventListener('abort', () => this._cancelRpc(pending, false, abortSignal));