@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
package/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright 2023 Alina Sireneva
1
+ Copyright 2023 alina sireneva
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
4
 
package/README.md CHANGED
@@ -2,16 +2,20 @@
2
2
 
3
3
  📖 [API Reference](https://ref.mtcute.dev/modules/_mtcute_node.html)
4
4
 
5
- All-in-one package for NodeJS. Includes support for native crypto addon
6
- (must be installed separately, `@mtcute/crypto-node`), terminal I/O via
7
- `readline` and includes HTML and Markdown parsers.
5
+ Node.js support package for mtcute. Includes:
6
+ - Support for native crypto addon (must be installed separately, `@mtcute/crypto-node`)
7
+ - Terminal I/O via `readline`
8
+ - SQLite storage (via `better-sqlite3`)
9
+ - TCP transport (via `node:net`)
10
+ - `TelegramClient` implementation using the above
11
+ - HTML and Markdown parsers
8
12
 
9
13
  ## Usage
10
14
 
11
15
  ```typescript
12
- import { NodeTelegramClient } from '@mtcute/node'
16
+ import { TelegramClient } from '@mtcute/node'
13
17
 
14
- const tg = new NodeTelegramClient({
18
+ const tg = new TelegramClient({
15
19
  apiId: 12345,
16
20
  apiHash: 'abcdef',
17
21
  storage: 'my-account'
@@ -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/cjs/client.js ADDED
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TelegramClient = exports.BaseTelegramClient = void 0;
4
+ const readline_1 = require("readline");
5
+ const client_js_1 = require("@mtcute/core/client.js");
6
+ const platform_js_1 = require("@mtcute/core/platform.js");
7
+ const platform_js_2 = require("./common-internals-node/platform.js");
8
+ const download_file_js_1 = require("./methods/download-file.js");
9
+ const download_node_stream_js_1 = require("./methods/download-node-stream.js");
10
+ const index_js_1 = require("./sqlite/index.js");
11
+ const crypto_js_1 = require("./utils/crypto.js");
12
+ const tcp_js_1 = require("./utils/tcp.js");
13
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
+ let nativeCrypto;
15
+ try {
16
+ //
17
+ // eslint-disable-next-line
18
+ nativeCrypto = require('@mtcute/crypto-node').NodeNativeCryptoProvider;
19
+ }
20
+ catch (e) { }
21
+ class BaseTelegramClient extends client_js_1.BaseTelegramClient {
22
+ constructor(opts) {
23
+ if (!opts.platformless)
24
+ (0, platform_js_1.setPlatform)(new platform_js_2.NodePlatform());
25
+ super({
26
+ // eslint-disable-next-line
27
+ crypto: nativeCrypto ? new nativeCrypto() : new crypto_js_1.NodeCryptoProvider(),
28
+ transport: () => new tcp_js_1.TcpTransport(),
29
+ ...opts,
30
+ storage: typeof opts.storage === 'string' ?
31
+ new index_js_1.SqliteStorage(opts.storage) :
32
+ opts.storage ?? new index_js_1.SqliteStorage('client.session'),
33
+ });
34
+ }
35
+ }
36
+ exports.BaseTelegramClient = BaseTelegramClient;
37
+ /**
38
+ * Telegram client for use in Node.js
39
+ */
40
+ class TelegramClient extends client_js_1.TelegramClient {
41
+ constructor(opts) {
42
+ if ('client' in opts) {
43
+ super(opts);
44
+ return;
45
+ }
46
+ super({
47
+ client: new BaseTelegramClient(opts),
48
+ });
49
+ }
50
+ /**
51
+ * Tiny wrapper over Node `readline` package
52
+ * for simpler user input for `.run()` method.
53
+ *
54
+ * Associated `readline` interface is closed
55
+ * after `run()` returns, or with the client.
56
+ *
57
+ * @param text Text of the question
58
+ */
59
+ input(text) {
60
+ if (!this._rl) {
61
+ this._rl = (0, readline_1.createInterface)({
62
+ input: process.stdin,
63
+ output: process.stdout,
64
+ });
65
+ }
66
+ return new Promise((res) => this._rl?.question(text, res));
67
+ }
68
+ close() {
69
+ this._rl?.close();
70
+ return super.close();
71
+ }
72
+ start(params = {}) {
73
+ if (!params.botToken) {
74
+ if (!params.phone)
75
+ params.phone = () => this.input('phone > ');
76
+ if (!params.code)
77
+ params.code = () => this.input('code > ');
78
+ if (!params.password) {
79
+ params.password = () => this.input('2fa password > ');
80
+ }
81
+ }
82
+ return super.start(params).then((user) => {
83
+ if (this._rl) {
84
+ this._rl.close();
85
+ delete this._rl;
86
+ }
87
+ return user;
88
+ });
89
+ }
90
+ run(params, then) {
91
+ if (typeof params === 'function') {
92
+ then = params;
93
+ params = {};
94
+ }
95
+ this.start(params)
96
+ .then(then)
97
+ .catch((err) => this.emitError(err));
98
+ }
99
+ downloadToFile(filename, location, params) {
100
+ return (0, download_file_js_1.downloadToFile)(this, filename, location, params);
101
+ }
102
+ downloadAsNodeStream(location, params) {
103
+ return (0, download_node_stream_js_1.downloadAsNodeStream)(this, location, params);
104
+ }
105
+ }
106
+ exports.TelegramClient = TelegramClient;
107
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":";;;AACA,uCAAoE;AAGpE,sDAK+B;AAC/B,0DAAsD;A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AAA;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;IAED,cAAc,CACV,QAAgB,EAChB,QAA8B,EAC9B,MAA2C;QAE3C,OAAO,IAAA,iCAAc,EAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;IAC3D,CAAC;IAED,oBAAoB,CAAC,QAA8B,EAAE,MAA2C;QAC5F,OAAO,IAAA,8CAAoB,EAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;IACvD,CAAC;CACJ;AAtFD,wCAsFC","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 // \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,45 @@
1
+ "use strict";
2
+ // roughly based on https://github.com/sindresorhus/exit-hook/blob/main/index.js, MIT license
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.beforeExit = void 0;
5
+ let installed = false;
6
+ let handled = false;
7
+ const callbacks = new Set();
8
+ function exit(shouldManuallyExit, signal, event) {
9
+ return function eventHandler() {
10
+ if (handled) {
11
+ return;
12
+ }
13
+ handled = true;
14
+ const exitCode = 128 + signal;
15
+ for (const callback of callbacks) {
16
+ callback();
17
+ }
18
+ if (shouldManuallyExit) {
19
+ // if the user has some custom handlers after us, we don't want to exit the process
20
+ const listeners = process.rawListeners(event);
21
+ const idx = listeners.indexOf(eventHandler);
22
+ if (idx === listeners.length - 1) {
23
+ process.exit(exitCode);
24
+ }
25
+ }
26
+ };
27
+ }
28
+ function beforeExit(fn) {
29
+ // unsupported platform
30
+ if (typeof process === 'undefined')
31
+ return () => { };
32
+ if (!installed) {
33
+ installed = true;
34
+ process.on('beforeExit', exit(true, -128, 'beforeExit'));
35
+ process.on('SIGINT', exit(true, 2, 'SIGINT'));
36
+ process.on('SIGTERM', exit(true, 15, 'SIGINT'));
37
+ process.on('exit', exit(false, 15, 'exit'));
38
+ }
39
+ callbacks.add(fn);
40
+ return () => {
41
+ callbacks.delete(fn);
42
+ };
43
+ }
44
+ exports.beforeExit = beforeExit;
45
+ //# sourceMappingURL=exit-hook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ex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AC,SAAS,EAAE,IAAI,CAAC,IAAI,EAAE,EAAE,EAAE,QAAQ,CAAC,CAAC,CAAA;QAC/C,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC,CAAA;KAC9C;IAED,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IAEjB,OAAO,GAAG,EAAE;QACR,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;IACxB,CAAC,CAAA;AACL,CAAC;AAlBD,gCAkBC","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,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultLoggingHandler = void 0;
4
+ const isTty = typeof process === 'object' && Boolean(process.stdout?.isTTY);
5
+ const BASE_FORMAT = isTty ? '%s [%s] [%s%s\x1b[0m] ' : '%s [%s] [%s] ';
6
+ const LEVEL_NAMES = isTty ?
7
+ [
8
+ '',
9
+ '\x1b[31mERR\x1b[0m',
10
+ '\x1b[33mWRN\x1b[0m',
11
+ '\x1b[34mINF\x1b[0m',
12
+ '\x1b[36mDBG\x1b[0m',
13
+ '\x1b[35mVRB\x1b[0m',
14
+ ] :
15
+ [
16
+ '',
17
+ 'ERR',
18
+ 'WRN',
19
+ 'INF',
20
+ 'DBG',
21
+ 'VRB',
22
+ ];
23
+ const TAG_COLORS = [6, 2, 3, 4, 5, 1].map((i) => `\x1b[3${i};1m`);
24
+ /** @internal */
25
+ exports.defaultLoggingHandler = isTty ?
26
+ (color, level, tag, fmt, args) => {
27
+ // eslint-disable-next-line no-console
28
+ console.log(BASE_FORMAT + fmt, new Date().toISOString(), LEVEL_NAMES[level], TAG_COLORS[color], tag, ...args);
29
+ } :
30
+ (color, level, tag, fmt, args) => {
31
+ // eslint-disable-next-line no-console
32
+ console.log(BASE_FORMAT + fmt, new Date().toISOString(), LEVEL_NAMES[level], tag, ...args);
33
+ };
34
+ //# 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;AACH,QAAA,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,85 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.NodePlatform = void 0;
27
+ const os = __importStar(require("os"));
28
+ const normalize_file_js_1 = require("../utils/normalize-file.js");
29
+ const exit_hook_js_1 = require("./exit-hook.js");
30
+ const logging_js_1 = require("./logging.js");
31
+ const BUFFER_BASE64_URL_AVAILABLE = typeof Buffer.isEncoding === 'function' && Buffer.isEncoding('base64url');
32
+ const toBuffer = (buf) => Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
33
+ class NodePlatform {
34
+ getDeviceModel() {
35
+ return `${os.type()} ${os.arch()} ${os.release()}`;
36
+ }
37
+ getDefaultLogLevel() {
38
+ const envLogLevel = parseInt(process.env.MTCUTE_LOG_LEVEL ?? '');
39
+ if (!isNaN(envLogLevel)) {
40
+ return envLogLevel;
41
+ }
42
+ return null;
43
+ }
44
+ // ITlPlatform
45
+ utf8ByteLength(str) {
46
+ return Buffer.byteLength(str, 'utf8');
47
+ }
48
+ utf8Encode(str) {
49
+ return Buffer.from(str, 'utf8');
50
+ }
51
+ utf8Decode(buf) {
52
+ return toBuffer(buf).toString('utf8');
53
+ }
54
+ hexEncode(buf) {
55
+ return toBuffer(buf).toString('hex');
56
+ }
57
+ hexDecode(str) {
58
+ return Buffer.from(str, 'hex');
59
+ }
60
+ base64Encode(buf, url = false) {
61
+ const nodeBuffer = toBuffer(buf);
62
+ if (url && BUFFER_BASE64_URL_AVAILABLE)
63
+ return nodeBuffer.toString('base64url');
64
+ const str = nodeBuffer.toString('base64');
65
+ if (url)
66
+ return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
67
+ return str;
68
+ }
69
+ base64Decode(string, url = false) {
70
+ if (url && BUFFER_BASE64_URL_AVAILABLE) {
71
+ return Buffer.from(string, 'base64url');
72
+ }
73
+ if (url) {
74
+ string = string.replace(/-/g, '+').replace(/_/g, '/');
75
+ while (string.length % 4)
76
+ string += '=';
77
+ }
78
+ return Buffer.from(string, 'base64');
79
+ }
80
+ }
81
+ exports.NodePlatform = NodePlatform;
82
+ NodePlatform.prototype.log = logging_js_1.defaultLoggingHandler;
83
+ NodePlatform.prototype.beforeExit = exit_hook_js_1.beforeExit;
84
+ NodePlatform.prototype.normalizeFile = normalize_file_js_1.normalizeFile;
85
+ //# sourceMappingURL=platform.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform.js","sourceRoot":"","sources":["../../../src/common-internals-node/platform.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAwB;AAIxB,kEAA0D;AAC1D,iDAA2C;AAC3C,6CAAoD;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,MAAa,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,kBAAkB;QACd,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAA;QAEhE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;YACrB,OAAO,WAAW,CAAA;SACrB;QAED,OAAO,IAAI,C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AAC,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;AA5DD,oCA4DC;AAED,YAAY,CAAC,SAAS,CAAC,GAAG,GAAG,kCAAqB,CAAA;AAClD,YAAY,CAAC,SAAS,CAAC,UAAU,GAAG,yBAAU,CAAA;AAC9C,YAAY,CAAC,SAAS,CAAC,aAAa,GAAG,iCAAa,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/cjs/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/cjs/index.js CHANGED
@@ -14,93 +14,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.NodeTelegramClient = exports.SqliteStorage = void 0;
18
- const readline_1 = require("readline");
19
- const core_1 = require("@mtcute/core");
20
- const sqlite_1 = require("@mtcute/sqlite");
21
- Object.defineProperty(exports, "SqliteStorage", { enumerable: true, get: function () { return sqlite_1.SqliteStorage; } });
17
+ __exportStar(require("./client.js"), exports);
18
+ __exportStar(require("./common-internals-node/platform.js"), exports);
19
+ __exportStar(require("./sqlite/index.js"), exports);
20
+ __exportStar(require("./utils/crypto.js"), exports);
21
+ __exportStar(require("./utils/tcp.js"), exports);
22
+ __exportStar(require("./worker.js"), exports);
22
23
  __exportStar(require("@mtcute/core"), exports);
23
24
  __exportStar(require("@mtcute/html-parser"), exports);
24
25
  __exportStar(require("@mtcute/markdown-parser"), exports);
25
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
26
- let nativeCrypto;
27
- try {
28
- //
29
- // eslint-disable-next-line
30
- nativeCrypto = require('@mtcute/crypto-node').NodeNativeCryptoProvider;
31
- }
32
- catch (e) { }
33
- /**
34
- * Tiny wrapper over {@link TelegramClient} for usage inside Node JS.
35
- *
36
- * This class automatically manages native
37
- * crypto addon and defaults to SQLite session (unlike `TelegarmClient`,
38
- * which defaults to a JSON file on Node).
39
- */
40
- class NodeTelegramClient extends core_1.TelegramClient {
41
- constructor(opts) {
42
- if ('client' in opts) {
43
- super(opts);
44
- return;
45
- }
46
- super({
47
- // eslint-disable-next-line
48
- crypto: nativeCrypto ? () => new nativeCrypto() : undefined,
49
- ...opts,
50
- storage: typeof opts.storage === 'string' ?
51
- new sqlite_1.SqliteStorage(opts.storage) :
52
- opts.storage ?? new sqlite_1.SqliteStorage('client.session'),
53
- });
54
- }
55
- /**
56
- * Tiny wrapper over Node `readline` package
57
- * for simpler user input for `.run()` method.
58
- *
59
- * Associated `readline` interface is closed
60
- * after `run()` returns, or with the client.
61
- *
62
- * @param text Text of the question
63
- */
64
- input(text) {
65
- if (!this._rl) {
66
- this._rl = (0, readline_1.createInterface)({
67
- input: process.stdin,
68
- output: process.stdout,
69
- });
70
- }
71
- return new Promise((res) => this._rl?.question(text, res));
72
- }
73
- close() {
74
- this._rl?.close();
75
- return super.close();
76
- }
77
- start(params = {}) {
78
- if (!params.botToken) {
79
- if (!params.phone)
80
- params.phone = () => this.input('phone > ');
81
- if (!params.code)
82
- params.code = () => this.input('code > ');
83
- if (!params.password) {
84
- params.password = () => this.input('2fa password > ');
85
- }
86
- }
87
- return super.start(params).then((user) => {
88
- if (this._rl) {
89
- this._rl.close();
90
- delete this._rl;
91
- }
92
- return user;
93
- });
94
- }
95
- run(params, then) {
96
- if (typeof params === 'function') {
97
- then = params;
98
- params = {};
99
- }
100
- this.start(params)
101
- .then(then)
102
- .catch((err) => this.emitError(err));
103
- }
104
- }
105
- exports.NodeTelegramClient = NodeTelegramClient;
106
26
  //# sourceMappingURL=index.js.map
package/cjs/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AACA,uCAAoE;AAEpE,uCAA0E;AAC1E,2CAA8C;AAKrC,8FALA,sBAAa,OAKA;AAHtB,+CAA4B;AAC5B,sDAAmC;AACnC,0DAAuC;AAGvC,8DAA8D;AAC9D,IAAI,YAAiB,CAAA;AAErB,IAAI;IACA,GAAG;IACH,2BAA2B;IAC3B,YAAY,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAAC,wBAAwB,CAAA;CACzE;AAAC,OAAO,CAAC,EAAE,GAAE;AA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AAI,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;AAhFD,gDAgFC","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 // \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,8CAA2B;AAC3B,sEAAmD;AACnD,oDAAiC;AACjC,oDAAiC;AACjC,iDAA8B;AAC9B,8CAA2B;AAC3B,+CAA4B;AAC5B,sDAAmC;AACnC,0DAAuC","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,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.downloadToFile = void 0;
4
+ const fs_1 = require("fs");
5
+ const promises_1 = require("fs/promises");
6
+ const core_1 = require("@mtcute/core");
7
+ const methods_js_1 = require("@mtcute/core/methods.js");
8
+ /**
9
+ * Download a remote file to a local file (only for NodeJS).
10
+ * Promise will resolve once the download is complete.
11
+ *
12
+ * @param filename Local file name to which the remote file will be downloaded
13
+ * @param params File download parameters
14
+ */
15
+ async function downloadToFile(client, filename, location, params) {
16
+ if (location instanceof core_1.FileLocation && ArrayBuffer.isView(location.location)) {
17
+ // early return for inline files
18
+ await (0, promises_1.writeFile)(filename, location.location);
19
+ }
20
+ const output = (0, fs_1.createWriteStream)(filename);
21
+ if (params?.abortSignal) {
22
+ params.abortSignal.addEventListener('abort', () => {
23
+ client.log.debug('aborting file download %s - cleaning up', filename);
24
+ output.destroy();
25
+ (0, fs_1.rmSync)(filename);
26
+ });
27
+ }
28
+ for await (const chunk of (0, methods_js_1.downloadAsIterable)(client, location, params)) {
29
+ output.write(chunk);
30
+ }
31
+ output.end();
32
+ }
33
+ exports.downloadToFile = downloadToFile;
34
+ //# 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,2BAA8C;AAC9C,0CAAuC;AAEvC,uCAA0G;AAC1G,wDAA4D;AAE5D;;;;;;GAMG;AACI,KAAK,UAAU,cAAc,CAChC,MAAuB,EACvB,QAAgB,EAChB,QAA8B,EAC9B,MAA+B;IAE/B,IAAI,QAAQ,YAAY,mBAAY,IAAI,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;QAC3E,gCAAgC;QAChC,MAAM,IAAA,oBAAS,EAAC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAA;KAC/C;IAED,MAAM,MAAM,GAAG,IAAA,sBAAiB,EAAC,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,IAAA,WAAM,EAAC,QAAQ,CAAC,CAAA;QACpB,CAAC,CAAC,CAAA;KACL;IAED,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAAA,+BAAkB,EAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,EAAE;QACpE,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;KACtB;IAED,MAAM,CAAC,GAAG,EAAE,CAAA;AAChB,CAAC;AA1BD,wCA0BC","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"]}