@mtcute/node 0.7.0 → 0.9.0

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.
Files changed (105) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +9 -5
  3. package/cjs/client.d.ts +47 -0
  4. package/cjs/client.js +107 -0
  5. package/cjs/client.js.map +1 -0
  6. package/cjs/common-internals-node/exit-hook.d.ts +1 -0
  7. package/cjs/common-internals-node/exit-hook.js +45 -0
  8. package/cjs/common-internals-node/exit-hook.js.map +1 -0
  9. package/cjs/common-internals-node/logging.d.ts +1 -0
  10. package/cjs/common-internals-node/logging.js +34 -0
  11. package/cjs/common-internals-node/logging.js.map +1 -0
  12. package/cjs/common-internals-node/platform.d.ts +18 -0
  13. package/cjs/common-internals-node/platform.js +85 -0
  14. package/cjs/common-internals-node/platform.js.map +1 -0
  15. package/cjs/index.d.ts +6 -27
  16. package/cjs/index.js +6 -86
  17. package/cjs/index.js.map +1 -1
  18. package/cjs/methods/download-file.d.ts +9 -0
  19. package/cjs/methods/download-file.js +34 -0
  20. package/cjs/methods/download-file.js.map +1 -0
  21. package/cjs/methods/download-node-stream.d.ts +9 -0
  22. package/cjs/methods/download-node-stream.js +15 -0
  23. package/cjs/methods/download-node-stream.js.map +1 -0
  24. package/cjs/methods.d.ts +3 -0
  25. package/cjs/methods.js +23 -0
  26. package/cjs/methods.js.map +1 -0
  27. package/cjs/sqlite/driver.d.ts +25 -0
  28. package/cjs/sqlite/driver.js +27 -0
  29. package/cjs/sqlite/driver.js.map +1 -0
  30. package/cjs/sqlite/index.d.ts +8 -0
  31. package/cjs/sqlite/index.js +16 -0
  32. package/cjs/sqlite/index.js.map +1 -0
  33. package/cjs/utils/crypto.d.ts +16 -0
  34. package/cjs/utils/crypto.js +73 -0
  35. package/cjs/utils/crypto.js.map +1 -0
  36. package/cjs/utils/normalize-file.d.ts +10 -0
  37. package/cjs/utils/normalize-file.js +31 -0
  38. package/cjs/utils/normalize-file.js.map +1 -0
  39. package/cjs/utils/stream-utils.d.ts +4 -0
  40. package/cjs/utils/stream-utils.js +77 -0
  41. package/cjs/utils/stream-utils.js.map +1 -0
  42. package/cjs/utils/tcp.d.ts +31 -0
  43. package/cjs/utils/tcp.js +128 -0
  44. package/cjs/utils/tcp.js.map +1 -0
  45. package/cjs/utils/version.d.ts +3 -0
  46. package/cjs/utils/version.js +21 -0
  47. package/cjs/utils/version.js.map +1 -0
  48. package/cjs/utils.d.ts +1 -0
  49. package/cjs/utils.js +1 -0
  50. package/cjs/utils.js.map +1 -1
  51. package/cjs/worker.d.ts +10 -0
  52. package/cjs/worker.js +47 -0
  53. package/cjs/worker.js.map +1 -0
  54. package/esm/client.d.ts +47 -0
  55. package/esm/client.js +105 -0
  56. package/esm/client.js.map +1 -0
  57. package/esm/common-internals-node/exit-hook.d.ts +1 -0
  58. package/esm/common-internals-node/exit-hook.js +41 -0
  59. package/esm/common-internals-node/exit-hook.js.map +1 -0
  60. package/esm/common-internals-node/logging.d.ts +1 -0
  61. package/esm/common-internals-node/logging.js +31 -0
  62. package/esm/common-internals-node/logging.js.map +1 -0
  63. package/esm/common-internals-node/platform.d.ts +18 -0
  64. package/esm/common-internals-node/platform.js +58 -0
  65. package/esm/common-internals-node/platform.js.map +1 -0
  66. package/esm/index.d.ts +6 -27
  67. package/esm/index.js +6 -87
  68. package/esm/index.js.map +1 -1
  69. package/esm/methods/download-file.d.ts +9 -0
  70. package/esm/methods/download-file.js +30 -0
  71. package/esm/methods/download-file.js.map +1 -0
  72. package/esm/methods/download-node-stream.d.ts +9 -0
  73. package/esm/methods/download-node-stream.js +11 -0
  74. package/esm/methods/download-node-stream.js.map +1 -0
  75. package/esm/methods.d.ts +3 -0
  76. package/esm/methods.js +4 -0
  77. package/esm/methods.js.map +1 -0
  78. package/esm/sqlite/driver.d.ts +25 -0
  79. package/esm/sqlite/driver.js +20 -0
  80. package/esm/sqlite/driver.js.map +1 -0
  81. package/esm/sqlite/index.d.ts +8 -0
  82. package/esm/sqlite/index.js +11 -0
  83. package/esm/sqlite/index.js.map +1 -0
  84. package/esm/utils/crypto.d.ts +16 -0
  85. package/esm/utils/crypto.js +71 -0
  86. package/esm/utils/crypto.js.map +1 -0
  87. package/esm/utils/normalize-file.d.ts +10 -0
  88. package/esm/utils/normalize-file.js +27 -0
  89. package/esm/utils/normalize-file.js.map +1 -0
  90. package/esm/utils/stream-utils.d.ts +4 -0
  91. package/esm/utils/stream-utils.js +72 -0
  92. package/esm/utils/stream-utils.js.map +1 -0
  93. package/esm/utils/tcp.d.ts +31 -0
  94. package/esm/utils/tcp.js +120 -0
  95. package/esm/utils/tcp.js.map +1 -0
  96. package/esm/utils/version.d.ts +3 -0
  97. package/esm/utils/version.js +17 -0
  98. package/esm/utils/version.js.map +1 -0
  99. package/esm/utils.d.ts +1 -0
  100. package/esm/utils.js +1 -0
  101. package/esm/utils.js.map +1 -1
  102. package/esm/worker.d.ts +10 -0
  103. package/esm/worker.js +42 -0
  104. package/esm/worker.js.map +1 -0
  105. package/package.json +13 -11
@@ -0,0 +1,10 @@
1
+ import { ClientMessageHandler, RespondFn, SendFn, SomeWorker, TelegramWorker as TelegramWorkerBase, TelegramWorkerOptions, TelegramWorkerPort as TelegramWorkerPortBase, TelegramWorkerPortOptions, WorkerCustomMethods, WorkerMessageHandler } from '@mtcute/core/worker.js';
2
+ export type { TelegramWorkerOptions, TelegramWorkerPortOptions, WorkerCustomMethods };
3
+ export declare class TelegramWorker<T extends WorkerCustomMethods> extends TelegramWorkerBase<T> {
4
+ registerWorker(handler: WorkerMessageHandler): RespondFn;
5
+ }
6
+ export declare class TelegramWorkerPort<T extends WorkerCustomMethods> extends TelegramWorkerPortBase<T> {
7
+ readonly options: TelegramWorkerPortOptions;
8
+ constructor(options: TelegramWorkerPortOptions);
9
+ connectToWorker(worker: SomeWorker, handler: ClientMessageHandler): [SendFn, () => void];
10
+ }
package/cjs/worker.js ADDED
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TelegramWorkerPort = exports.TelegramWorker = void 0;
4
+ const worker_threads_1 = require("worker_threads");
5
+ const platform_js_1 = require("@mtcute/core/platform.js");
6
+ const worker_js_1 = require("@mtcute/core/worker.js");
7
+ const platform_js_2 = require("./common-internals-node/platform.js");
8
+ let _registered = false;
9
+ class TelegramWorker extends worker_js_1.TelegramWorker {
10
+ registerWorker(handler) {
11
+ if (!worker_threads_1.parentPort) {
12
+ throw new Error('TelegramWorker must be created from a worker thread');
13
+ }
14
+ if (_registered) {
15
+ throw new Error('TelegramWorker must be created only once');
16
+ }
17
+ _registered = true;
18
+ const port = worker_threads_1.parentPort;
19
+ const respond = port.postMessage.bind(port);
20
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
21
+ worker_threads_1.parentPort.on('message', (message) => handler(message, respond));
22
+ return respond;
23
+ }
24
+ }
25
+ exports.TelegramWorker = TelegramWorker;
26
+ class TelegramWorkerPort extends worker_js_1.TelegramWorkerPort {
27
+ constructor(options) {
28
+ (0, platform_js_1.setPlatform)(new platform_js_2.NodePlatform());
29
+ super(options);
30
+ this.options = options;
31
+ }
32
+ connectToWorker(worker, handler) {
33
+ if (!(worker instanceof worker_threads_1.Worker)) {
34
+ throw new Error('Only worker_threads are supported');
35
+ }
36
+ const send = worker.postMessage.bind(worker);
37
+ worker.on('message', handler);
38
+ return [
39
+ send,
40
+ () => {
41
+ worker.off('message', handler);
42
+ },
43
+ ];
44
+ }
45
+ }
46
+ exports.TelegramWorkerPort = TelegramWorkerPort;
47
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../src/worker.ts"],"names":[],"mappings":";;;AAAA,mDAAmD;AAEnD,0DAAsD;AACtD,sDAW+B;AAE/B,qEAAkE;AAIlE,IAAI,WAAW,GAAG,KAAK,CAAA;AAEvB,MAAa,cAA8C,SAAQ,0BAAqB;IACpF,cAAc,CAAC,OAA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ientMessageHandler,\n RespondFn,\n SendFn,\n SomeWorker,\n TelegramWorker as TelegramWorkerBase,\n TelegramWorkerOptions,\n TelegramWorkerPort as TelegramWorkerPortBase,\n TelegramWorkerPortOptions,\n WorkerCustomMethods,\n WorkerMessageHandler,\n} from '@mtcute/core/worker.js'\n\nimport { NodePlatform } from './common-internals-node/platform.js'\n\nexport type { TelegramWorkerOptions, TelegramWorkerPortOptions, WorkerCustomMethods }\n\nlet _registered = false\n\nexport class TelegramWorker<T extends WorkerCustomMethods> extends TelegramWorkerBase<T> {\n registerWorker(handler: WorkerMessageHandler): RespondFn {\n if (!parentPort) {\n throw new Error('TelegramWorker must be created from a worker thread')\n }\n if (_registered) {\n throw new Error('TelegramWorker must be created only once')\n }\n\n _registered = true\n\n const port = parentPort\n\n const respond: RespondFn = port.postMessage.bind(port)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n parentPort.on('message', (message) => handler(message, respond))\n\n return respond\n }\n}\n\nexport class TelegramWorkerPort<T extends WorkerCustomMethods> extends TelegramWorkerPortBase<T> {\n constructor(readonly options: TelegramWorkerPortOptions) {\n setPlatform(new NodePlatform())\n super(options)\n }\n\n connectToWorker(worker: SomeWorker, handler: ClientMessageHandler): [SendFn, () => void] {\n if (!(worker instanceof Worker)) {\n throw new Error('Only worker_threads are supported')\n }\n\n const send: SendFn = worker.postMessage.bind(worker)\n\n worker.on('message', handler)\n\n return [\n send,\n () => {\n worker.off('message', handler)\n },\n ]\n }\n}\n"]}
@@ -0,0 +1,47 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import { FileDownloadLocation, FileDownloadParameters, ITelegramStorageProvider, PartialOnly, User } from '@mtcute/core';
3
+ import { BaseTelegramClient as BaseTelegramClientBase, BaseTelegramClientOptions as BaseTelegramClientOptionsBase, TelegramClient as TelegramClientBase, TelegramClientOptions } from '@mtcute/core/client.js';
4
+ export type { TelegramClientOptions };
5
+ export interface BaseTelegramClientOptions extends PartialOnly<Omit<BaseTelegramClientOptionsBase, 'storage'>, 'transport' | 'crypto'> {
6
+ /**
7
+ * Storage to use for this client.
8
+ *
9
+ * If a string is passed, it will be used as
10
+ * a name for an SQLite database file.
11
+ *
12
+ * @default `"client.session"`
13
+ */
14
+ storage?: string | ITelegramStorageProvider;
15
+ /**
16
+ * **ADVANCED USE ONLY**
17
+ *
18
+ * Whether to not set up the platform.
19
+ * This is useful if you call `setPlatform` yourself.
20
+ */
21
+ platformless?: boolean;
22
+ }
23
+ export declare class BaseTelegramClient extends BaseTelegramClientBase {
24
+ constructor(opts: BaseTelegramClientOptions);
25
+ }
26
+ /**
27
+ * Telegram client for use in Node.js
28
+ */
29
+ export declare class TelegramClient extends TelegramClientBase {
30
+ constructor(opts: TelegramClientOptions);
31
+ private _rl?;
32
+ /**
33
+ * Tiny wrapper over Node `readline` package
34
+ * for simpler user input for `.run()` method.
35
+ *
36
+ * Associated `readline` interface is closed
37
+ * after `run()` returns, or with the client.
38
+ *
39
+ * @param text Text of the question
40
+ */
41
+ input(text: string): Promise<string>;
42
+ close(): Promise<void>;
43
+ start(params?: Parameters<TelegramClientBase['start']>[0]): Promise<User>;
44
+ run(params: Parameters<TelegramClient['start']>[0] | ((user: User) => void | Promise<void>), then?: (user: User) => void | Promise<void>): void;
45
+ downloadToFile(filename: string, location: FileDownloadLocation, params?: FileDownloadParameters | undefined): Promise<void>;
46
+ downloadAsNodeStream(location: FileDownloadLocation, params?: FileDownloadParameters | undefined): import("stream").Readable;
47
+ }
package/esm/client.js ADDED
@@ -0,0 +1,105 @@
1
+ import { createRequire } from 'module';
2
+ import { createInterface } from 'readline';
3
+ import { BaseTelegramClient as BaseTelegramClientBase, TelegramClient as TelegramClientBase, } from '@mtcute/core/client.js';
4
+ import { setPlatform } from '@mtcute/core/platform.js';
5
+ import { NodePlatform } from './common-internals-node/platform.js';
6
+ import { downloadToFile } from './methods/download-file.js';
7
+ import { downloadAsNodeStream } from './methods/download-node-stream.js';
8
+ import { SqliteStorage } from './sqlite/index.js';
9
+ import { NodeCryptoProvider } from './utils/crypto.js';
10
+ import { TcpTransport } from './utils/tcp.js';
11
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
12
+ let nativeCrypto;
13
+ try {
14
+ // @only-if-esm
15
+ const require = createRequire(import.meta.url);
16
+ // @/only-if-esm
17
+ // eslint-disable-next-line
18
+ nativeCrypto = require('@mtcute/crypto-node').NodeNativeCryptoProvider;
19
+ }
20
+ catch (e) { }
21
+ export class BaseTelegramClient extends BaseTelegramClientBase {
22
+ constructor(opts) {
23
+ if (!opts.platformless)
24
+ setPlatform(new NodePlatform());
25
+ super({
26
+ // eslint-disable-next-line
27
+ crypto: nativeCrypto ? new nativeCrypto() : new NodeCryptoProvider(),
28
+ transport: () => new TcpTransport(),
29
+ ...opts,
30
+ storage: typeof opts.storage === 'string' ?
31
+ new SqliteStorage(opts.storage) :
32
+ opts.storage ?? new SqliteStorage('client.session'),
33
+ });
34
+ }
35
+ }
36
+ /**
37
+ * Telegram client for use in Node.js
38
+ */
39
+ export class TelegramClient extends TelegramClientBase {
40
+ constructor(opts) {
41
+ if ('client' in opts) {
42
+ super(opts);
43
+ return;
44
+ }
45
+ super({
46
+ client: new BaseTelegramClient(opts),
47
+ });
48
+ }
49
+ /**
50
+ * Tiny wrapper over Node `readline` package
51
+ * for simpler user input for `.run()` method.
52
+ *
53
+ * Associated `readline` interface is closed
54
+ * after `run()` returns, or with the client.
55
+ *
56
+ * @param text Text of the question
57
+ */
58
+ input(text) {
59
+ if (!this._rl) {
60
+ this._rl = createInterface({
61
+ input: process.stdin,
62
+ output: process.stdout,
63
+ });
64
+ }
65
+ return new Promise((res) => this._rl?.question(text, res));
66
+ }
67
+ close() {
68
+ this._rl?.close();
69
+ return super.close();
70
+ }
71
+ start(params = {}) {
72
+ if (!params.botToken) {
73
+ if (!params.phone)
74
+ params.phone = () => this.input('phone > ');
75
+ if (!params.code)
76
+ params.code = () => this.input('code > ');
77
+ if (!params.password) {
78
+ params.password = () => this.input('2fa password > ');
79
+ }
80
+ }
81
+ return super.start(params).then((user) => {
82
+ if (this._rl) {
83
+ this._rl.close();
84
+ delete this._rl;
85
+ }
86
+ return user;
87
+ });
88
+ }
89
+ run(params, then) {
90
+ if (typeof params === 'function') {
91
+ then = params;
92
+ params = {};
93
+ }
94
+ this.start(params)
95
+ .then(then)
96
+ .catch((err) => this.emitError(err));
97
+ }
98
+ downloadToFile(filename, location, params) {
99
+ return downloadToFile(this, filename, location, params);
100
+ }
101
+ downloadAsNodeStream(location, params) {
102
+ return downloadAsNodeStream(this, location, params);
103
+ }
104
+ }
105
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAA;AACtC,OAAO,EAAE,eAAe,EAA4B,MAAM,UAAU,CAAA;AAGpE,OAAO,EACH,kBAAkB,IAAI,sBAAsB,EAE5C,cAAc,IAAI,kBAAkB,GAEvC,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAEtD,OAAO,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAA;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAA;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAI7C,8DAA8D;AAC9D,IAAI,YAAiB,CAAA;AAErB,IAAI;IACA,eAAe;IACf,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAC9C,gBAAgB;IAChB,2BAA2B;IAC3B,YAAY,GAAG,OAAO,CAAC,qBAAq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Ac,CACV,QAAgB,EAChB,QAA8B,EAC9B,MAA2C;QAE3C,OAAO,cAAc,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;IAC3D,CAAC;IAED,oBAAoB,CAAC,QAA8B,EAAE,MAA2C;QAC5F,OAAO,oBAAoB,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;IACvD,CAAC;CACJ","sourcesContent":["import { createRequire } from 'module'\nimport { createInterface, Interface as RlInterface } from 'readline'\n\nimport { FileDownloadLocation, FileDownloadParameters, ITelegramStorageProvider, PartialOnly, User } from '@mtcute/core'\nimport {\n BaseTelegramClient as BaseTelegramClientBase,\n BaseTelegramClientOptions as BaseTelegramClientOptionsBase,\n TelegramClient as TelegramClientBase,\n TelegramClientOptions,\n} from '@mtcute/core/client.js'\nimport { setPlatform } from '@mtcute/core/platform.js'\n\nimport { NodePlatform } from './common-internals-node/platform.js'\nimport { downloadToFile } from './methods/download-file.js'\nimport { downloadAsNodeStream } from './methods/download-node-stream.js'\nimport { SqliteStorage } from './sqlite/index.js'\nimport { NodeCryptoProvider } from './utils/crypto.js'\nimport { TcpTransport } from './utils/tcp.js'\n\nexport type { TelegramClientOptions }\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet nativeCrypto: any\n\ntry {\n // @only-if-esm\n const require = createRequire(import.meta.url)\n // @/only-if-esm\n // eslint-disable-next-line\n nativeCrypto = require('@mtcute/crypto-node').NodeNativeCryptoProvider\n} catch (e) {}\n\nexport interface BaseTelegramClientOptions\n extends PartialOnly<Omit<BaseTelegramClientOptionsBase, '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 an SQLite database file.\n *\n * @default `\"client.session\"`\n */\n storage?: string | ITelegramStorageProvider\n\n /**\n * **ADVANCED USE ONLY**\n *\n * Whether to not set up the platform.\n * This is useful if you call `setPlatform` yourself.\n */\n platformless?: boolean\n}\n\nexport class BaseTelegramClient extends BaseTelegramClientBase {\n constructor(opts: BaseTelegramClientOptions) {\n if (!opts.platformless) setPlatform(new NodePlatform())\n\n super({\n // eslint-disable-next-line\n crypto: nativeCrypto ? new nativeCrypto() : new NodeCryptoProvider(),\n transport: () => new TcpTransport(),\n ...opts,\n storage:\n typeof opts.storage === 'string' ?\n new SqliteStorage(opts.storage) :\n opts.storage ?? new SqliteStorage('client.session'),\n })\n }\n}\n\n/**\n * Telegram client for use in Node.js\n */\nexport class TelegramClient extends TelegramClientBase {\n constructor(opts: TelegramClientOptions) {\n if ('client' in opts) {\n super(opts)\n\n return\n }\n\n super({\n client: new BaseTelegramClient(opts),\n })\n }\n\n private _rl?: RlInterface\n\n /**\n * Tiny wrapper over Node `readline` package\n * for simpler user input for `.run()` method.\n *\n * Associated `readline` interface is closed\n * after `run()` returns, or with the client.\n *\n * @param text Text of the question\n */\n input(text: string): Promise<string> {\n if (!this._rl) {\n this._rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n })\n }\n\n return new Promise((res) => this._rl?.question(text, res))\n }\n\n close(): Promise<void> {\n this._rl?.close()\n\n return super.close()\n }\n\n start(params: Parameters<TelegramClientBase['start']>[0] = {}): Promise<User> {\n if (!params.botToken) {\n if (!params.phone) params.phone = () => this.input('phone > ')\n if (!params.code) params.code = () => this.input('code > ')\n\n if (!params.password) {\n params.password = () => this.input('2fa password > ')\n }\n }\n\n return super.start(params).then((user) => {\n if (this._rl) {\n this._rl.close()\n delete this._rl\n }\n\n return user\n })\n }\n\n run(\n params: Parameters<TelegramClient['start']>[0] | ((user: User) => void | Promise<void>),\n then?: (user: User) => void | Promise<void>,\n ): void {\n if (typeof params === 'function') {\n then = params\n params = {}\n }\n\n this.start(params)\n .then(then)\n .catch((err) => this.emitError(err))\n }\n\n downloadToFile(\n filename: string,\n location: FileDownloadLocation,\n params?: FileDownloadParameters | undefined,\n ): Promise<void> {\n return downloadToFile(this, filename, location, params)\n }\n\n downloadAsNodeStream(location: FileDownloadLocation, params?: FileDownloadParameters | undefined) {\n return downloadAsNodeStream(this, location, params)\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export declare function beforeExit(fn: () => void): () => void;
@@ -0,0 +1,41 @@
1
+ // roughly based on https://github.com/sindresorhus/exit-hook/blob/main/index.js, MIT license
2
+ let installed = false;
3
+ let handled = false;
4
+ const callbacks = new Set();
5
+ function exit(shouldManuallyExit, signal, event) {
6
+ return function eventHandler() {
7
+ if (handled) {
8
+ return;
9
+ }
10
+ handled = true;
11
+ const exitCode = 128 + signal;
12
+ for (const callback of callbacks) {
13
+ callback();
14
+ }
15
+ if (shouldManuallyExit) {
16
+ // if the user has some custom handlers after us, we don't want to exit the process
17
+ const listeners = process.rawListeners(event);
18
+ const idx = listeners.indexOf(eventHandler);
19
+ if (idx === listeners.length - 1) {
20
+ process.exit(exitCode);
21
+ }
22
+ }
23
+ };
24
+ }
25
+ export function beforeExit(fn) {
26
+ // unsupported platform
27
+ if (typeof process === 'undefined')
28
+ return () => { };
29
+ if (!installed) {
30
+ installed = true;
31
+ process.on('beforeExit', exit(true, -128, 'beforeExit'));
32
+ process.on('SIGINT', exit(true, 2, 'SIGINT'));
33
+ process.on('SIGTERM', exit(true, 15, 'SIGINT'));
34
+ process.on('exit', exit(false, 15, 'exit'));
35
+ }
36
+ callbacks.add(fn);
37
+ return () => {
38
+ callbacks.delete(fn);
39
+ };
40
+ }
41
+ //# sourceMappingURL=exit-hook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exit-hook.js","sourceRoot":"","sources":["../../../src/common-internals-node/exit-hook.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAE7F,IAAI,SAAS,GAAG,KAAK,CAAA;AACrB,IAAI,OAAO,GAAG,KAAK,CAAA;AAEnB,MAAM,SAAS,GAAG,IAAI,GAAG,EAAc,CAAA;AAEvC,SAAS,IAAI,CAAC,kBAA2B,EAAE,MAAc,EAAE,KAAa;IACpE,OAAO,SAAS,YAAY;QACxB,IAAI,OAAO,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C,CAAA;IACxB,CAAC,CAAA;AACL,CAAC","sourcesContent":["// roughly based on https://github.com/sindresorhus/exit-hook/blob/main/index.js, MIT license\n\nlet installed = false\nlet handled = false\n\nconst callbacks = new Set<() => void>()\n\nfunction exit(shouldManuallyExit: boolean, signal: number, event: string) {\n return function eventHandler() {\n if (handled) {\n return\n }\n\n handled = true\n\n const exitCode = 128 + signal\n\n for (const callback of callbacks) {\n callback()\n }\n\n if (shouldManuallyExit) {\n // if the user has some custom handlers after us, we don't want to exit the process\n\n const listeners = process.rawListeners(event)\n const idx = listeners.indexOf(eventHandler)\n\n if (idx === listeners.length - 1) {\n process.exit(exitCode)\n }\n }\n }\n}\n\nexport function beforeExit(fn: () => void): () => void {\n // unsupported platform\n if (typeof process === 'undefined') return () => {}\n\n if (!installed) {\n installed = true\n\n process.on('beforeExit', exit(true, -128, 'beforeExit'))\n process.on('SIGINT', exit(true, 2, 'SIGINT'))\n process.on('SIGTERM', exit(true, 15, 'SIGINT'))\n process.on('exit', exit(false, 15, 'exit'))\n }\n\n callbacks.add(fn)\n\n return () => {\n callbacks.delete(fn)\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,31 @@
1
+ const isTty = typeof process === 'object' && Boolean(process.stdout?.isTTY);
2
+ const BASE_FORMAT = isTty ? '%s [%s] [%s%s\x1b[0m] ' : '%s [%s] [%s] ';
3
+ const LEVEL_NAMES = isTty ?
4
+ [
5
+ '',
6
+ '\x1b[31mERR\x1b[0m',
7
+ '\x1b[33mWRN\x1b[0m',
8
+ '\x1b[34mINF\x1b[0m',
9
+ '\x1b[36mDBG\x1b[0m',
10
+ '\x1b[35mVRB\x1b[0m',
11
+ ] :
12
+ [
13
+ '',
14
+ 'ERR',
15
+ 'WRN',
16
+ 'INF',
17
+ 'DBG',
18
+ 'VRB',
19
+ ];
20
+ const TAG_COLORS = [6, 2, 3, 4, 5, 1].map((i) => `\x1b[3${i};1m`);
21
+ /** @internal */
22
+ export const defaultLoggingHandler = isTty ?
23
+ (color, level, tag, fmt, args) => {
24
+ // eslint-disable-next-line no-console
25
+ console.log(BASE_FORMAT + fmt, new Date().toISOString(), LEVEL_NAMES[level], TAG_COLORS[color], tag, ...args);
26
+ } :
27
+ (color, level, tag, fmt, args) => {
28
+ // eslint-disable-next-line no-console
29
+ console.log(BASE_FORMAT + fmt, new Date().toISOString(), LEVEL_NAMES[level], tag, ...args);
30
+ };
31
+ //# sourceMappingURL=logging.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logging.js","sourceRoot":"","sources":["../../../src/common-internals-node/logging.ts"],"names":[],"mappings":"AAAA,MAAM,KAAK,GAAG,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;AAE3E,MAAM,WAAW,GAAG,KAAK,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,eAAe,CAAA;AACtE,MAAM,WAAW,GAAG,KAAK,CAAC,CAAC;IACvB;QACI,EAAE;QACF,oBAAoB;QACpB,oBAAoB;QACpB,oBAAoB;QACpB,oBAAoB;QACpB,oBAAoB;KACvB,CAAC,CAAC;IACH;QACI,EAAE;QACF,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;KACR,CAAA;AACL,MAAM,UAAU,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;AAEjE,gBAAgB;AAChB,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,CAAC,CAAC;IACxC,CAAC,KAAa,EAAE,KAAa,EAAE,GAAW,EAAE,GAAW,EAAE,IAAe,EAAQ,EAAE;QAC9E,sCAAsC;QACtC,OAAO,CAAC,GAAG,CAAC,WAAW,GAAG,GAAG,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,WAAW,CAAC,KAAK,CAAC,EAAE,UAAU,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;IACjH,CAAC,CAAC,CAAC;IACH,CAAC,KAAa,EAAE,KAAa,EAAE,GAAW,EAAE,GAAW,EAAE,IAAe,EAAQ,EAAE;QAC9E,sCAAsC;QACtC,OAAO,CAAC,GAAG,CAAC,WAAW,GAAG,GAAG,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,WAAW,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;IAC9F,CAAC,CAAA","sourcesContent":["const isTty = typeof process === 'object' && Boolean(process.stdout?.isTTY)\n\nconst BASE_FORMAT = isTty ? '%s [%s] [%s%s\\x1b[0m] ' : '%s [%s] [%s] '\nconst LEVEL_NAMES = isTty ?\n [\n '', // OFF\n '\\x1b[31mERR\\x1b[0m',\n '\\x1b[33mWRN\\x1b[0m',\n '\\x1b[34mINF\\x1b[0m',\n '\\x1b[36mDBG\\x1b[0m',\n '\\x1b[35mVRB\\x1b[0m',\n ] :\n [\n '', // OFF\n 'ERR',\n 'WRN',\n 'INF',\n 'DBG',\n 'VRB',\n ]\nconst TAG_COLORS = [6, 2, 3, 4, 5, 1].map((i) => `\\x1b[3${i};1m`)\n\n/** @internal */\nexport const defaultLoggingHandler = isTty ?\n (color: number, level: number, tag: string, fmt: string, args: unknown[]): void => {\n // eslint-disable-next-line no-console\n console.log(BASE_FORMAT + fmt, new Date().toISOString(), LEVEL_NAMES[level], TAG_COLORS[color], tag, ...args)\n } :\n (color: number, level: number, tag: string, fmt: string, args: unknown[]): void => {\n // eslint-disable-next-line no-console\n console.log(BASE_FORMAT + fmt, new Date().toISOString(), LEVEL_NAMES[level], tag, ...args)\n }\n"]}
@@ -0,0 +1,18 @@
1
+ import { ICorePlatform } from '@mtcute/core/platform.js';
2
+ import { normalizeFile } from '../utils/normalize-file.js';
3
+ import { beforeExit } from './exit-hook.js';
4
+ import { defaultLoggingHandler } from './logging.js';
5
+ export declare class NodePlatform implements ICorePlatform {
6
+ log: typeof defaultLoggingHandler;
7
+ beforeExit: typeof beforeExit;
8
+ normalizeFile: typeof normalizeFile;
9
+ getDeviceModel(): string;
10
+ getDefaultLogLevel(): number | null;
11
+ utf8ByteLength(str: string): number;
12
+ utf8Encode(str: string): Uint8Array;
13
+ utf8Decode(buf: Uint8Array): string;
14
+ hexEncode(buf: Uint8Array): string;
15
+ hexDecode(str: string): Uint8Array;
16
+ base64Encode(buf: Uint8Array, url?: boolean): string;
17
+ base64Decode(string: string, url?: boolean): Uint8Array;
18
+ }
@@ -0,0 +1,58 @@
1
+ import * as os from 'os';
2
+ import { normalizeFile } from '../utils/normalize-file.js';
3
+ import { beforeExit } from './exit-hook.js';
4
+ import { defaultLoggingHandler } from './logging.js';
5
+ const BUFFER_BASE64_URL_AVAILABLE = typeof Buffer.isEncoding === 'function' && Buffer.isEncoding('base64url');
6
+ const toBuffer = (buf) => Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
7
+ export class NodePlatform {
8
+ getDeviceModel() {
9
+ return `${os.type()} ${os.arch()} ${os.release()}`;
10
+ }
11
+ getDefaultLogLevel() {
12
+ const envLogLevel = parseInt(process.env.MTCUTE_LOG_LEVEL ?? '');
13
+ if (!isNaN(envLogLevel)) {
14
+ return envLogLevel;
15
+ }
16
+ return null;
17
+ }
18
+ // ITlPlatform
19
+ utf8ByteLength(str) {
20
+ return Buffer.byteLength(str, 'utf8');
21
+ }
22
+ utf8Encode(str) {
23
+ return Buffer.from(str, 'utf8');
24
+ }
25
+ utf8Decode(buf) {
26
+ return toBuffer(buf).toString('utf8');
27
+ }
28
+ hexEncode(buf) {
29
+ return toBuffer(buf).toString('hex');
30
+ }
31
+ hexDecode(str) {
32
+ return Buffer.from(str, 'hex');
33
+ }
34
+ base64Encode(buf, url = false) {
35
+ const nodeBuffer = toBuffer(buf);
36
+ if (url && BUFFER_BASE64_URL_AVAILABLE)
37
+ return nodeBuffer.toString('base64url');
38
+ const str = nodeBuffer.toString('base64');
39
+ if (url)
40
+ return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
41
+ return str;
42
+ }
43
+ base64Decode(string, url = false) {
44
+ if (url && BUFFER_BASE64_URL_AVAILABLE) {
45
+ return Buffer.from(string, 'base64url');
46
+ }
47
+ if (url) {
48
+ string = string.replace(/-/g, '+').replace(/_/g, '/');
49
+ while (string.length % 4)
50
+ string += '=';
51
+ }
52
+ return Buffer.from(string, 'base64');
53
+ }
54
+ }
55
+ NodePlatform.prototype.log = defaultLoggingHandler;
56
+ NodePlatform.prototype.beforeExit = beforeExit;
57
+ NodePlatform.prototype.normalizeFile = normalizeFile;
58
+ //# sourceMappingURL=platform.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform.js","sourceRoot":"","sources":["../../../src/common-internals-node/platform.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAA;AAIxB,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAA;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAC3C,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;AAEpD,MAAM,2BAA2B,GAAG,OAAO,MAAM,CAAC,UAAU,KAAK,UAAU,IAAI,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAA;AAE7G,MAAM,QAAQ,GAAG,CAAC,GAAe,EAAU,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAA;AAErG,MAAM,OAAO,YAAY;IAMrB,cAAc;QACV,OAAO,GAAG,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE,CAAA;IACtD,CAAC;IAED,kBAA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AAE,GAAG,GAAG,KAAK;QACpC,IAAI,GAAG,IAAI,2BAA2B,EAAE;YACpC,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;SAC1C;QAED,IAAI,GAAG,EAAE;YACL,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YACrD,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,GAAG,CAAA;SAC1C;QAED,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IACxC,CAAC;CACJ;AAED,YAAY,CAAC,SAAS,CAAC,GAAG,GAAG,qBAAqB,CAAA;AAClD,YAAY,CAAC,SAAS,CAAC,UAAU,GAAG,UAAU,CAAA;AAC9C,YAAY,CAAC,SAAS,CAAC,aAAa,GAAG,aAAa,CAAA","sourcesContent":["import * as os from 'os'\n\nimport { ICorePlatform } from '@mtcute/core/platform.js'\n\nimport { normalizeFile } from '../utils/normalize-file.js'\nimport { beforeExit } from './exit-hook.js'\nimport { defaultLoggingHandler } from './logging.js'\n\nconst BUFFER_BASE64_URL_AVAILABLE = typeof Buffer.isEncoding === 'function' && Buffer.isEncoding('base64url')\n\nconst toBuffer = (buf: Uint8Array): Buffer => Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n\nexport class NodePlatform implements ICorePlatform {\n // ICorePlatform\n log!: typeof defaultLoggingHandler\n beforeExit!: typeof beforeExit\n normalizeFile!: typeof normalizeFile\n\n getDeviceModel(): string {\n return `${os.type()} ${os.arch()} ${os.release()}`\n }\n\n getDefaultLogLevel(): number | null {\n const envLogLevel = parseInt(process.env.MTCUTE_LOG_LEVEL ?? '')\n\n if (!isNaN(envLogLevel)) {\n return envLogLevel\n }\n\n return null\n }\n\n // ITlPlatform\n utf8ByteLength(str: string): number {\n return Buffer.byteLength(str, 'utf8')\n }\n utf8Encode(str: string): Uint8Array {\n return Buffer.from(str, 'utf8')\n }\n utf8Decode(buf: Uint8Array): string {\n return toBuffer(buf).toString('utf8')\n }\n\n hexEncode(buf: Uint8Array): string {\n return toBuffer(buf).toString('hex')\n }\n hexDecode(str: string): Uint8Array {\n return Buffer.from(str, 'hex')\n }\n\n base64Encode(buf: Uint8Array, url = false): string {\n const nodeBuffer = toBuffer(buf)\n\n if (url && BUFFER_BASE64_URL_AVAILABLE) return nodeBuffer.toString('base64url')\n\n const str = nodeBuffer.toString('base64')\n if (url) return str.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n\n return str\n }\n base64Decode(string: string, url = false): Uint8Array {\n if (url && BUFFER_BASE64_URL_AVAILABLE) {\n return Buffer.from(string, 'base64url')\n }\n\n if (url) {\n string = string.replace(/-/g, '+').replace(/_/g, '/')\n while (string.length % 4) string += '='\n }\n\n return Buffer.from(string, 'base64')\n }\n}\n\nNodePlatform.prototype.log = defaultLoggingHandler\nNodePlatform.prototype.beforeExit = beforeExit\nNodePlatform.prototype.normalizeFile = normalizeFile\n"]}
package/esm/index.d.ts CHANGED
@@ -1,30 +1,9 @@
1
- import { TelegramClient, TelegramClientOptions, User } from '@mtcute/core';
2
- import { SqliteStorage } from '@mtcute/sqlite';
1
+ export * from './client.js';
2
+ export * from './common-internals-node/platform.js';
3
+ export * from './sqlite/index.js';
4
+ export * from './utils/crypto.js';
5
+ export * from './utils/tcp.js';
6
+ export * from './worker.js';
3
7
  export * from '@mtcute/core';
4
8
  export * from '@mtcute/html-parser';
5
9
  export * from '@mtcute/markdown-parser';
6
- export { SqliteStorage };
7
- /**
8
- * Tiny wrapper over {@link TelegramClient} for usage inside Node JS.
9
- *
10
- * This class automatically manages native
11
- * crypto addon and defaults to SQLite session (unlike `TelegarmClient`,
12
- * which defaults to a JSON file on Node).
13
- */
14
- export declare class NodeTelegramClient extends TelegramClient {
15
- constructor(opts: TelegramClientOptions);
16
- private _rl?;
17
- /**
18
- * Tiny wrapper over Node `readline` package
19
- * for simpler user input for `.run()` method.
20
- *
21
- * Associated `readline` interface is closed
22
- * after `run()` returns, or with the client.
23
- *
24
- * @param text Text of the question
25
- */
26
- input(text: string): Promise<string>;
27
- close(): Promise<void>;
28
- start(params?: Parameters<TelegramClient['start']>[0]): Promise<User>;
29
- run(params: Parameters<TelegramClient['start']>[0] | ((user: User) => void | Promise<void>), then?: (user: User) => void | Promise<void>): void;
30
- }
package/esm/index.js CHANGED
@@ -1,91 +1,10 @@
1
- import { createRequire } from 'module';
2
- import { createInterface } from 'readline';
3
- import { TelegramClient } from '@mtcute/core';
4
- import { SqliteStorage } from '@mtcute/sqlite';
1
+ export * from './client.js';
2
+ export * from './common-internals-node/platform.js';
3
+ export * from './sqlite/index.js';
4
+ export * from './utils/crypto.js';
5
+ export * from './utils/tcp.js';
6
+ export * from './worker.js';
5
7
  export * from '@mtcute/core';
6
8
  export * from '@mtcute/html-parser';
7
9
  export * from '@mtcute/markdown-parser';
8
- export { SqliteStorage };
9
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
- let nativeCrypto;
11
- try {
12
- // @only-if-esm
13
- const require = createRequire(import.meta.url);
14
- // @/only-if-esm
15
- // eslint-disable-next-line
16
- nativeCrypto = require('@mtcute/crypto-node').NodeNativeCryptoProvider;
17
- }
18
- catch (e) { }
19
- /**
20
- * Tiny wrapper over {@link TelegramClient} for usage inside Node JS.
21
- *
22
- * This class automatically manages native
23
- * crypto addon and defaults to SQLite session (unlike `TelegarmClient`,
24
- * which defaults to a JSON file on Node).
25
- */
26
- export class NodeTelegramClient extends TelegramClient {
27
- constructor(opts) {
28
- if ('client' in opts) {
29
- super(opts);
30
- return;
31
- }
32
- super({
33
- // eslint-disable-next-line
34
- crypto: nativeCrypto ? () => new nativeCrypto() : undefined,
35
- ...opts,
36
- storage: typeof opts.storage === 'string' ?
37
- new SqliteStorage(opts.storage) :
38
- opts.storage ?? new SqliteStorage('client.session'),
39
- });
40
- }
41
- /**
42
- * Tiny wrapper over Node `readline` package
43
- * for simpler user input for `.run()` method.
44
- *
45
- * Associated `readline` interface is closed
46
- * after `run()` returns, or with the client.
47
- *
48
- * @param text Text of the question
49
- */
50
- input(text) {
51
- if (!this._rl) {
52
- this._rl = createInterface({
53
- input: process.stdin,
54
- output: process.stdout,
55
- });
56
- }
57
- return new Promise((res) => this._rl?.question(text, res));
58
- }
59
- close() {
60
- this._rl?.close();
61
- return super.close();
62
- }
63
- start(params = {}) {
64
- if (!params.botToken) {
65
- if (!params.phone)
66
- params.phone = () => this.input('phone > ');
67
- if (!params.code)
68
- params.code = () => this.input('code > ');
69
- if (!params.password) {
70
- params.password = () => this.input('2fa password > ');
71
- }
72
- }
73
- return super.start(params).then((user) => {
74
- if (this._rl) {
75
- this._rl.close();
76
- delete this._rl;
77
- }
78
- return user;
79
- });
80
- }
81
- run(params, then) {
82
- if (typeof params === 'function') {
83
- then = params;
84
- params = {};
85
- }
86
- this.start(params)
87
- .then(then)
88
- .catch((err) => this.emitError(err));
89
- }
90
- }
91
10
  //# sourceMappingURL=index.js.map
package/esm/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAA;AACtC,OAAO,EAAE,eAAe,EAA4B,MAAM,UAAU,CAAA;AAEpE,OAAO,EAAE,cAAc,EAA+B,MAAM,cAAc,CAAA;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAE9C,cAAc,cAAc,CAAA;AAC5B,cAAc,qBAAqB,CAAA;AACnC,cAAc,yBAAyB,CAAA;AACvC,OAAO,EAAE,aAAa,EAAE,CAAA;AAExB,8DAA8D;AAC9D,IAAI,YAAiB,CAAA;AAErB,IAAI;IACA,eAAe;IACf,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAC9C,gBAAg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AAM,CAAC,KAAK;gBAAE,MAAM,CAAC,KAAK,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;YAC9D,IAAI,CAAC,MAAM,CAAC,IAAI;gBAAE,MAAM,CAAC,IAAI,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAA;YAE3D,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;gBAClB,MAAM,CAAC,QAAQ,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAA;aACxD;SACJ;QAED,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;YACrC,IAAI,IAAI,CAAC,GAAG,EAAE;gBACV,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAA;gBAChB,OAAO,IAAI,CAAC,GAAG,CAAA;aAClB;YAED,OAAO,IAAI,CAAA;QACf,CAAC,CAAC,CAAA;IACN,CAAC;IAED,GAAG,CACC,MAAuF,EACvF,IAA2C;QAE3C,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE;YAC9B,IAAI,GAAG,MAAM,CAAA;YACb,MAAM,GAAG,EAAE,CAAA;SACd;QAED,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;aACb,IAAI,CAAC,IAAI,CAAC;aACV,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAA;IAC5C,CAAC;CACJ","sourcesContent":["import { createRequire } from 'module'\nimport { createInterface, Interface as RlInterface } from 'readline'\n\nimport { TelegramClient, TelegramClientOptions, User } from '@mtcute/core'\nimport { SqliteStorage } from '@mtcute/sqlite'\n\nexport * from '@mtcute/core'\nexport * from '@mtcute/html-parser'\nexport * from '@mtcute/markdown-parser'\nexport { SqliteStorage }\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet nativeCrypto: any\n\ntry {\n // @only-if-esm\n const require = createRequire(import.meta.url)\n // @/only-if-esm\n // eslint-disable-next-line\n nativeCrypto = require('@mtcute/crypto-node').NodeNativeCryptoProvider\n} catch (e) {}\n\n/**\n * Tiny wrapper over {@link TelegramClient} for usage inside Node JS.\n *\n * This class automatically manages native\n * crypto addon and defaults to SQLite session (unlike `TelegarmClient`,\n * which defaults to a JSON file on Node).\n */\nexport class NodeTelegramClient extends TelegramClient {\n constructor(opts: TelegramClientOptions) {\n if ('client' in opts) {\n super(opts)\n\n return\n }\n\n super({\n // eslint-disable-next-line\n crypto: nativeCrypto ? () => new nativeCrypto() : undefined,\n ...opts,\n storage:\n typeof opts.storage === 'string' ?\n new SqliteStorage(opts.storage) :\n opts.storage ?? new SqliteStorage('client.session'),\n })\n }\n\n private _rl?: RlInterface\n\n /**\n * Tiny wrapper over Node `readline` package\n * for simpler user input for `.run()` method.\n *\n * Associated `readline` interface is closed\n * after `run()` returns, or with the client.\n *\n * @param text Text of the question\n */\n input(text: string): Promise<string> {\n if (!this._rl) {\n this._rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n })\n }\n\n return new Promise((res) => this._rl?.question(text, res))\n }\n\n close(): Promise<void> {\n this._rl?.close()\n\n return super.close()\n }\n\n start(params: Parameters<TelegramClient['start']>[0] = {}): Promise<User> {\n if (!params.botToken) {\n if (!params.phone) params.phone = () => this.input('phone > ')\n if (!params.code) params.code = () => this.input('code > ')\n\n if (!params.password) {\n params.password = () => this.input('2fa password > ')\n }\n }\n\n return super.start(params).then((user) => {\n if (this._rl) {\n this._rl.close()\n delete this._rl\n }\n\n return user\n })\n }\n\n run(\n params: Parameters<TelegramClient['start']>[0] | ((user: User) => void | Promise<void>),\n then?: (user: User) => void | Promise<void>,\n ): void {\n if (typeof params === 'function') {\n then = params\n params = {}\n }\n\n this.start(params)\n .then(then)\n .catch((err) => this.emitError(err))\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA;AAC3B,cAAc,qCAAqC,CAAA;AACnD,cAAc,mBAAmB,CAAA;AACjC,cAAc,mBAAmB,CAAA;AACjC,cAAc,gBAAgB,CAAA;AAC9B,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,qBAAqB,CAAA;AACnC,cAAc,yBAAyB,CAAA","sourcesContent":["export * from './client.js'\nexport * from './common-internals-node/platform.js'\nexport * from './sqlite/index.js'\nexport * from './utils/crypto.js'\nexport * from './utils/tcp.js'\nexport * from './worker.js'\nexport * from '@mtcute/core'\nexport * from '@mtcute/html-parser'\nexport * from '@mtcute/markdown-parser'\n"]}
@@ -0,0 +1,9 @@
1
+ import { FileDownloadLocation, FileDownloadParameters, ITelegramClient } from '@mtcute/core';
2
+ /**
3
+ * Download a remote file to a local file (only for NodeJS).
4
+ * Promise will resolve once the download is complete.
5
+ *
6
+ * @param filename Local file name to which the remote file will be downloaded
7
+ * @param params File download parameters
8
+ */
9
+ export declare function downloadToFile(client: ITelegramClient, filename: string, location: FileDownloadLocation, params?: FileDownloadParameters): Promise<void>;
@@ -0,0 +1,30 @@
1
+ import { createWriteStream, rmSync } from 'fs';
2
+ import { writeFile } from 'fs/promises';
3
+ import { FileLocation } from '@mtcute/core';
4
+ import { downloadAsIterable } from '@mtcute/core/methods.js';
5
+ /**
6
+ * Download a remote file to a local file (only for NodeJS).
7
+ * Promise will resolve once the download is complete.
8
+ *
9
+ * @param filename Local file name to which the remote file will be downloaded
10
+ * @param params File download parameters
11
+ */
12
+ export async function downloadToFile(client, filename, location, params) {
13
+ if (location instanceof FileLocation && ArrayBuffer.isView(location.location)) {
14
+ // early return for inline files
15
+ await writeFile(filename, location.location);
16
+ }
17
+ const output = createWriteStream(filename);
18
+ if (params?.abortSignal) {
19
+ params.abortSignal.addEventListener('abort', () => {
20
+ client.log.debug('aborting file download %s - cleaning up', filename);
21
+ output.destroy();
22
+ rmSync(filename);
23
+ });
24
+ }
25
+ for await (const chunk of downloadAsIterable(client, location, params)) {
26
+ output.write(chunk);
27
+ }
28
+ output.end();
29
+ }
30
+ //# sourceMappingURL=download-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"download-file.js","sourceRoot":"","sources":["../../../src/methods/download-file.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,IAAI,CAAA;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAEvC,OAAO,EAAgD,YAAY,EAAmB,MAAM,cAAc,CAAA;AAC1G,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAA;AAE5D;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAChC,MAAuB,EACvB,QAAgB,EAChB,QAA8B,EAC9B,MAA+B;IAE/B,IAAI,QAAQ,YAAY,YAAY,IAAI,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;QAC3E,gCAAgC;QAChC,MAAM,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAA;KAC/C;IAED,MAAM,MAAM,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAA;IAE1C,IAAI,MAAM,EAAE,WAAW,EAAE;QACrB,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE;YAC9C,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,yCAAyC,EAAE,QAAQ,CAAC,CAAA;YACrE,MAAM,CAAC,OAAO,EAAE,CAAA;YAChB,MAAM,CAAC,QAAQ,CAAC,CAAA;QACpB,CAAC,CAAC,CAAA;KACL;IAED,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,kBAAkB,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,EAAE;QACpE,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;KACtB;IAED,MAAM,CAAC,GAAG,EAAE,CAAA;AAChB,CAAC","sourcesContent":["import { createWriteStream, rmSync } from 'fs'\nimport { writeFile } from 'fs/promises'\n\nimport { FileDownloadLocation, FileDownloadParameters, FileLocation, ITelegramClient } from '@mtcute/core'\nimport { downloadAsIterable } from '@mtcute/core/methods.js'\n\n/**\n * Download a remote file to a local file (only for NodeJS).\n * Promise will resolve once the download is complete.\n *\n * @param filename Local file name to which the remote file will be downloaded\n * @param params File download parameters\n */\nexport async function downloadToFile(\n client: ITelegramClient,\n filename: string,\n location: FileDownloadLocation,\n params?: FileDownloadParameters,\n): Promise<void> {\n if (location instanceof FileLocation && ArrayBuffer.isView(location.location)) {\n // early return for inline files\n await writeFile(filename, location.location)\n }\n\n const output = createWriteStream(filename)\n\n if (params?.abortSignal) {\n params.abortSignal.addEventListener('abort', () => {\n client.log.debug('aborting file download %s - cleaning up', filename)\n output.destroy()\n rmSync(filename)\n })\n }\n\n for await (const chunk of downloadAsIterable(client, location, params)) {\n output.write(chunk)\n }\n\n output.end()\n}\n"]}
@@ -0,0 +1,9 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import { Readable } from 'stream';
3
+ import { FileDownloadLocation, FileDownloadParameters, ITelegramClient } from '@mtcute/core';
4
+ /**
5
+ * Download a remote file as a Node.js Readable stream.
6
+ *
7
+ * @param params File download parameters
8
+ */
9
+ export declare function downloadAsNodeStream(client: ITelegramClient, location: FileDownloadLocation, params?: FileDownloadParameters): Readable;