diff --git a/.config/eslint.ci.js b/.config/eslint.ci.js
deleted file mode 100644
index c7bbe2f9..00000000
--- a/.config/eslint.ci.js
+++ /dev/null
@@ -1,30 +0,0 @@
-const baseConfig = require('./eslint.cjs')
-
-module.exports = {
- ...baseConfig,
- overrides: [
- baseConfig.overrides[0],
- {
- ...baseConfig.overrides[0],
- files: ['packages/**/*.ts'],
- extends: ['plugin:@typescript-eslint/strict-type-checked', 'plugin:import/typescript'],
- parser: '@typescript-eslint/parser',
- parserOptions: {
- project: true,
- tsconfigRootDir: __dirname,
- },
- rules: {
- ...baseConfig.overrides[0].rules,
- '@typescript-eslint/restrict-template-expressions': ['error', { allowNever: true }],
- },
- reportUnusedDisableDirectives: false,
- },
- ...baseConfig.overrides.slice(1),
- {
- files: ['e2e/**'],
- rules: {
- 'import/no-unresolved': 'off',
- },
- },
- ],
-}
diff --git a/.config/eslint.cjs b/.config/eslint.cjs
deleted file mode 100644
index 02b8bd5b..00000000
--- a/.config/eslint.cjs
+++ /dev/null
@@ -1,301 +0,0 @@
-module.exports = {
- env: {
- browser: true,
- es2021: true,
- node: true,
- },
- extends: ['eslint:recommended', 'plugin:import/recommended', 'prettier'],
- parserOptions: {
- ecmaVersion: 'latest',
- sourceType: 'module',
- },
- plugins: ['ascii', 'import', 'simple-import-sort'],
- reportUnusedDisableDirectives: true,
- rules: {
- // see https://github.com/airbnb/javascript/blob/master/packages/eslint-config-airbnb-base/rules/style.js#L122
- indent: [
- 2,
- 4,
- {
- SwitchCase: 1,
- VariableDeclarator: 1,
- outerIIFEBody: 1,
- // MemberExpression: null,
- FunctionDeclaration: {
- parameters: 1,
- body: 1,
- },
- FunctionExpression: {
- parameters: 1,
- body: 1,
- },
- CallExpression: {
- arguments: 1,
- },
- ArrayExpression: 1,
- ObjectExpression: 1,
- ImportDeclaration: 1,
- flatTernaryExpressions: false,
- // list derived from https://github.com/benjamn/ast-types/blob/HEAD/def/jsx.js
- ignoredNodes: [
- 'JSXElement',
- 'JSXElement > *',
- 'JSXAttribute',
- 'JSXIdentifier',
- 'JSXNamespacedName',
- 'JSXMemberExpression',
- 'JSXSpreadAttribute',
- 'JSXExpressionContainer',
- 'JSXOpeningElement',
- 'JSXClosingElement',
- 'JSXText',
- 'JSXEmptyExpression',
- 'JSXSpreadChild',
- ],
- ignoreComments: false,
- },
- ],
-
- semi: [2, 'never', { beforeStatementContinuationChars: 'never' }],
- 'semi-spacing': [2, { before: false, after: true }],
- 'wrap-iife': [2, 'inside'],
- 'no-caller': 2,
- 'no-cond-assign': [2, 'except-parens'],
- 'no-constant-condition': 0,
- 'no-debugger': 2,
- 'no-dupe-args': 2,
- 'no-dupe-keys': 2,
- 'no-duplicate-case': 2,
- 'no-empty': [2, { allowEmptyCatch: true }],
- 'no-empty-function': 'off',
- 'no-extra-boolean-cast': 2,
- // "no-extra-parens": [2, "all"],
- 'no-extra-semi': 2,
- 'no-func-assign': 2,
- 'no-new': 2,
- 'no-sparse-arrays': 2,
- 'no-unexpected-multiline': 2,
- 'no-unreachable': 2,
-
- 'max-params': [1, 5],
- 'max-depth': [1, 4],
- 'no-eq-null': 0,
- 'no-unused-expressions': 0,
- 'dot-notation': 2,
- 'use-isnan': 2,
-
- // Best practices
- 'block-scoped-var': 2,
- complexity: [0, 11],
- curly: [2, 'multi-line'],
- eqeqeq: [2, 'always', { null: 'ignore' }],
- 'no-else-return': 2,
- 'no-extra-bind': 2,
- 'no-implicit-coercion': 2,
- 'no-return-assign': 0,
- 'no-sequences': 2,
- yoda: 2,
-
- // Variables
- 'no-restricted-globals': ['error'],
- 'no-var': 1,
-
- // Codestyle
- 'arrow-parens': [2, 'always'],
- 'array-bracket-spacing': [2, 'never'],
- 'brace-style': [2, '1tbs', { allowSingleLine: true }],
- camelcase: [2, { properties: 'never' }],
- 'comma-dangle': ['warn', 'always-multiline'],
- 'comma-spacing': [2, { before: false, after: true }],
- 'eol-last': 2,
- 'func-call-spacing': [2, 'never'],
- 'block-spacing': 2,
- 'keyword-spacing': [2, { before: true, after: true }],
- 'max-len': [
- 2,
- {
- code: 120,
- ignoreUrls: true,
- ignoreComments: false,
- ignoreRegExpLiterals: true,
- ignoreStrings: true,
- ignoreTemplateLiterals: true,
- ignorePattern: 'require',
- },
- ],
- 'no-lonely-if': 2,
- 'no-mixed-spaces-and-tabs': 2,
- 'no-multi-spaces': 2,
- 'no-multiple-empty-lines': [2, { max: 1, maxBOF: 0, maxEOF: 0 }],
- 'no-trailing-spaces': 2,
- 'ascii/valid-name': 2,
- 'no-unneeded-ternary': 2,
- 'no-nested-ternary': 2,
- 'object-curly-spacing': [2, 'always'],
- 'one-var-declaration-per-line': [2, 'initializations'],
- 'one-var': [2, { let: 'never', const: 'never' }],
- 'operator-linebreak': [2, 'after'],
- 'padded-blocks': [2, 'never'],
- 'quote-props': [2, 'as-needed', { numbers: true }],
- quotes: [2, 'single', { avoidEscape: true }],
- 'space-before-blocks': [2, 'always'],
- 'space-before-function-paren': [
- 2,
- {
- named: 'never',
- anonymous: 'always',
- },
- ],
- 'space-in-parens': 2,
- 'key-spacing': [2, { beforeColon: false, afterColon: true, mode: 'strict' }],
- 'space-infix-ops': 2,
- 'padding-line-between-statements': [
- 'error',
- { blankLine: 'always', prev: '*', next: 'return' },
- { blankLine: 'always', prev: '*', next: 'block-like' },
- { blankLine: 'any', prev: 'block-like', next: 'block-like' },
- { blankLine: 'any', prev: 'case', next: 'case' },
- ],
-
- 'simple-import-sort/imports': [
- 'error',
- {
- groups: [['^[a-z]'], ['^@?mtcute'], ['^@/'], ['^~/'], ['^\\.']],
- },
- ],
- 'simple-import-sort/exports': 'error',
- 'import/no-relative-packages': 'error',
- 'import/no-mutable-exports': 'error',
- 'import/no-default-export': 'error',
- 'no-console': ['error', { allow: ['warn', 'error'] }],
- },
- ignorePatterns: [
- 'node_modules/',
- '.config/',
- '.idea/',
- '.vscode/',
-
- 'private/',
- 'docs/',
- 'dist/',
-
- '*.json',
-
- // codegen
- 'packages/tl/binary/rsa-keys.js',
- 'packages/tl/binary/reader.js',
- 'packages/tl/binary/writer.js',
- 'packages/tl/index.js',
- 'packages/tl/index.d.ts',
- 'packages/tl/*.json',
-
- 'packages/client/utils.ts',
- 'packages/core/utils.ts'
- ],
- overrides: [
- {
- files: ['**/*.ts', '**/*.tsx'],
- env: { browser: true, es6: true, node: true },
- extends: ['plugin:@typescript-eslint/strict', 'plugin:import/typescript'],
- globals: { Atomics: 'readonly', SharedArrayBuffer: 'readonly' },
- parser: '@typescript-eslint/parser',
- plugins: ['@typescript-eslint'],
- rules: {
- // https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#supported-rules
- '@typescript-eslint/member-delimiter-style': [
- 'error',
- {
- multiline: {
- delimiter: 'none',
- },
- singleline: {
- delimiter: 'semi', // because prettier
- },
- },
- ],
- '@typescript-eslint/consistent-type-assertions': 2,
- '@typescript-eslint/no-explicit-any': 2,
- '@typescript-eslint/no-unused-vars': [
- 2,
- {
- args: 'after-used',
- argsIgnorePattern: '^_',
- ignoreRestSiblings: true,
- vars: 'all',
- varsIgnorePattern: '^_',
- },
- ],
- '@typescript-eslint/no-non-null-assertion': 'off', // todo MTQ-36
- '@typescript-eslint/no-empty-function': 'off',
- '@typescript-eslint/no-confusing-void-expression': 'off',
- '@typescript-eslint/no-unnecessary-condition': 'off',
- '@typescript-eslint/no-var-requires': 'off',
-
- '@typescript-eslint/no-unsafe-enum-comparison': 'off',
- '@typescript-eslint/no-invalid-void-type': 'off',
- '@typescript-eslint/unbound-method': 'off',
- '@typescript-eslint/no-dynamic-delete': 'off',
- '@typescript-eslint/no-unsafe-member-access': 'off',
- 'no-restricted-globals': ['error', 'Buffer', '__dirname', 'require'],
- 'no-restricted-imports': [
- 'error',
- {
- paths: ['buffer', 'crypto', 'fs', 'path', 'stream'],
- patterns: ['@mtcute/*/dist**'],
- },
- ],
- },
- reportUnusedDisableDirectives: false,
- settings: {
- 'import/resolver': {
- node: true,
- typescript: true,
- },
- },
- },
- {
- files: ['**/scripts/**', '*.test.ts', 'packages/create-*/**', '**/build.config.cjs', 'packages/node/**'],
- rules: {
- 'no-console': 'off',
- 'no-restricted-imports': [
- 'error',
- {
- patterns: ['@mtcute/*/dist**'],
- },
- ],
- },
- },
- {
- files: ['packages/client/src/methods/**/*.ts'],
- rules: {
- // this + max 3 more
- 'max-params': ['error', 4],
- },
- },
- {
- files: ['e2e/**', 'packages/node/**', 'packages/bun/**'],
- rules: {
- 'no-restricted-globals': 'off',
- },
- },
- {
- files: ['packages/bun/**', 'packages/deno/**'],
- rules: {
- 'import/no-unresolved': 'off',
- 'no-restricted-imports': 'off',
- 'import/no-relative-packages': 'off', // common-internals is symlinked from node
- }
- },
- {
- files: ['e2e/deno/**'],
- rules: {
- 'import/no-unresolved': 'off',
- }
- },
- ],
- settings: {
- 'import/resolver': {
- node: true,
- },
- },
-}
diff --git a/.config/prettier.cjs b/.config/prettier.cjs
index 616469ff..59959378 100644
--- a/.config/prettier.cjs
+++ b/.config/prettier.cjs
@@ -27,9 +27,9 @@ module.exports = {
'packages/tl/*.json',
'*.d.ts',
- '**/dist'
+ '**/dist',
],
options: { requirePragma: true },
- }
+ },
],
}
diff --git a/.config/tsconfig.build.json b/.config/tsconfig.build.json
index 24ed8f74..bd168a0e 100644
--- a/.config/tsconfig.build.json
+++ b/.config/tsconfig.build.json
@@ -1,8 +1,8 @@
{
- "extends": "../tsconfig.json",
- "exclude": [
- "../**/*.test.ts",
- "../**/*.test-utils.ts",
- "../**/__fixtures__/**",
- ]
+ "extends": "../tsconfig.json",
+ "exclude": [
+ "../**/*.test.ts",
+ "../**/*.test-utils.ts",
+ "../**/__fixtures__/**"
+ ]
}
diff --git a/.config/typedoc/config.cjs b/.config/typedoc/config.cjs
index c70df48b..89b87976 100644
--- a/.config/typedoc/config.cjs
+++ b/.config/typedoc/config.cjs
@@ -1,5 +1,5 @@
-const fs = require('fs')
-const path = require('path')
+const fs = require('node:fs')
+const path = require('node:path')
module.exports = {
...require('./config.base.cjs'),
@@ -7,8 +7,8 @@ module.exports = {
out: '../../docs',
entryPoints: fs
.readdirSync(path.join(__dirname, '../../packages'))
- .filter((it) => !['crypto', 'tl', 'create-bot'].includes(it))
- .map((it) => `../../packages/${it}`),
+ .filter(it => !['crypto', 'tl', 'create-bot'].includes(it))
+ .map(it => `../../packages/${it}`),
entryPointStrategy: 'packages',
// logLevel: 'Verbose',
}
diff --git a/.config/typedoc/plugin-external-links.cjs b/.config/typedoc/plugin-external-links.cjs
index feb58bc4..b43462db 100644
--- a/.config/typedoc/plugin-external-links.cjs
+++ b/.config/typedoc/plugin-external-links.cjs
@@ -1,6 +1,6 @@
function load(app) {
app.converter.addUnknownSymbolResolver((declaration) => {
- const symbol = declaration.symbolReference?.path?.map((path) => path.path).join('.')
+ const symbol = declaration.symbolReference?.path?.map(path => path.path).join('.')
if (symbol === 'Long' || symbol === 'tl.Long') {
return {
@@ -40,7 +40,7 @@ function load(app) {
}
}
- name = (ns ? ns + '.' : '') + name
+ name = (ns ? `${ns}.` : '') + name
let url
diff --git a/.config/typedoc/plugin-umami.cjs b/.config/typedoc/plugin-umami.cjs
index add840a5..c79cbec5 100644
--- a/.config/typedoc/plugin-umami.cjs
+++ b/.config/typedoc/plugin-umami.cjs
@@ -7,14 +7,14 @@ const UMAMI_NOSCRIPT = `https://tei.su/zond.php?website=${WEBSITE_ID}`
const { createElement: h } = JSX
function load(app) {
- app.renderer.hooks.on('head.end', (event) => {
+ app.renderer.hooks.on('head.end', () => {
return h('script', {
- async: true,
- src: `${UMAMI_URL}/script.js`,
+ 'async': true,
+ 'src': `${UMAMI_URL}/script.js`,
'data-website-id': WEBSITE_ID,
})
})
- app.renderer.hooks.on('body.begin', (event) => {
+ app.renderer.hooks.on('body.begin', () => {
return h(
'noscript',
null,
diff --git a/.config/vite-utils/collect-test-entrypoints.ts b/.config/vite-utils/collect-test-entrypoints.ts
index 45aa9e44..0864f5d1 100644
--- a/.config/vite-utils/collect-test-entrypoints.ts
+++ b/.config/vite-utils/collect-test-entrypoints.ts
@@ -1,13 +1,15 @@
-import { join, resolve } from 'path'
-import * as fs from 'fs'
+import { join, resolve } from 'node:path'
+import * as fs from 'node:fs'
+
import { globSync } from 'glob'
-export function collectTestEntrypoints(params: { skipPackages: string[]; skipTests: string[] }) {
+export function collectTestEntrypoints(params: { skipPackages: string[], skipTests: string[] }) {
const files: string[] = []
+ // eslint-disable-next-line no-restricted-globals
const packages = resolve(__dirname, '../../packages')
- const skipTests = params.skipTests.map((path) => resolve(packages, path))
+ const skipTests = params.skipTests.map(path => resolve(packages, path))
for (const dir of fs.readdirSync(packages)) {
if (dir.startsWith('.') || params.skipPackages.includes(dir)) continue
diff --git a/.config/vite-utils/fixup-cjs.ts b/.config/vite-utils/fixup-cjs.ts
index f43da923..1a650361 100644
--- a/.config/vite-utils/fixup-cjs.ts
+++ b/.config/vite-utils/fixup-cjs.ts
@@ -1,4 +1,4 @@
-import { Plugin } from 'vite'
+import type { Plugin } from 'vite'
import * as cjsLexer from 'cjs-module-lexer'
import esbuild from 'esbuild'
diff --git a/.config/vite-utils/polyfills-bun.ts b/.config/vite-utils/polyfills-bun.ts
index dfd88472..479da870 100644
--- a/.config/vite-utils/polyfills-bun.ts
+++ b/.config/vite-utils/polyfills-bun.ts
@@ -1,9 +1,9 @@
-import { describe, it, beforeEach, afterEach, beforeAll, afterAll, jest, vi as bunVi } from 'bun:test'
+import { afterAll, afterEach, beforeAll, beforeEach, vi as bunVi, it, jest } from 'bun:test'
// https://github.com/oven-sh/bun/issues/6044
-import console from 'console'
import * as chai from 'chai'
import * as vitestExpect from '@vitest/expect'
import * as vitestSpy from '@vitest/spy'
+
import { setupChai, stubGlobal, unstubAllGlobals, waitFor } from './polyfills'
setupChai(chai, vitestExpect)
@@ -15,7 +15,7 @@ export const vi = {
...jest,
...bunVi,
...vitestSpy,
- mocked: (fn) => fn,
+ mocked: fn => fn,
stubGlobal,
unstubAllGlobals,
waitFor,
diff --git a/.config/vite-utils/polyfills-deno.ts b/.config/vite-utils/polyfills-deno.ts
index 564280b0..7021a58c 100644
--- a/.config/vite-utils/polyfills-deno.ts
+++ b/.config/vite-utils/polyfills-deno.ts
@@ -1,12 +1,14 @@
// @ts-expect-error no typings
-import { describe as _describe, it, beforeEach, afterEach, beforeAll, afterAll } from 'jsr:@std/testing/bdd'
+import util from 'node:util'
+
+import { describe as _describe, afterAll, afterEach, beforeAll, beforeEach, it } from 'jsr:@std/testing/bdd'
// @ts-expect-error no typings
import * as vitestSpy from 'npm:@vitest/spy@1.4.0'
// @ts-expect-error no typings
import * as chai from 'npm:chai'
// @ts-expect-error no typings
import * as vitestExpect from 'npm:@vitest/expect@1.4.0'
-import util from 'node:util'
+
import { setupChai, stubGlobal, unstubAllGlobals, waitFor } from './polyfills'
export { it, beforeEach, afterEach, beforeAll, afterAll }
@@ -15,6 +17,7 @@ setupChai(chai, vitestExpect)
// https://github.com/denoland/deno_std/issues/2213
Object.defineProperty(it, 'each', {
+ // eslint-disable-next-line ts/no-unsafe-function-type
value: (items: any[][]) => (name: string, fn: Function) => {
return items.map((item) => {
return it(`${util.format(name, ...item)}`, () => fn(...item))
@@ -23,8 +26,8 @@ Object.defineProperty(it, 'each', {
})
// https://github.com/denoland/deno_std/issues/4634
-export const describe = (...args) => {
- const fn = args.find((arg) => typeof arg === 'function')
+export function describe(...args) {
+ const fn = args.find(arg => typeof arg === 'function')
if (fn.toString().startsWith('async')) {
return
}
diff --git a/.config/vite-utils/polyfills.ts b/.config/vite-utils/polyfills.ts
index 35cd70f3..85710032 100644
--- a/.config/vite-utils/polyfills.ts
+++ b/.config/vite-utils/polyfills.ts
@@ -6,32 +6,32 @@ export function setupChai(chai: any, vitestExpect: any) {
utils.addMethod(
chai.Assertion.prototype,
'toMatchInlineSnapshot',
- function (properties?: object, inlineSnapshot?: string, message?: string) {
+ function (properties?: object, inlineSnapshot?: string) {
// based on https://github.com/vitest-dev/vitest/blob/main/packages/vitest/src/integrations/snapshot/chai.ts
const received = utils.flag(this, 'object')
if (typeof properties === 'string') {
- message = inlineSnapshot
inlineSnapshot = properties
properties = undefined
}
if (typeof inlineSnapshot !== 'string') {
- throw new Error('toMatchInlineSnapshot requires a string argument')
+ throw new TypeError('toMatchInlineSnapshot requires a string argument')
}
// todo use @vitest/snapshot
if (typeof received === 'string') {
- const snapshot = '"' + received + '"'
+ const snapshot = `"${received}"`
return chai.expect(snapshot).eql(inlineSnapshot.trim())
} else {
- const obj = eval('(' + inlineSnapshot + ')') // idc lol
+ // eslint-disable-next-line no-eval
+ const obj = eval(`(${inlineSnapshot})`) // idc lol
return chai.expect(received).eql(obj)
}
},
)
- utils.addMethod(chai.Assertion.prototype, 'toMatchSnapshot', function () {
+ utils.addMethod(chai.Assertion.prototype, 'toMatchSnapshot', () => {
// todo use @vitest/snapshot
})
})
@@ -71,6 +71,7 @@ export function unstubAllGlobals() {
stubbedGlobal.clear()
}
+// eslint-disable-next-line ts/no-unsafe-function-type
export async function waitFor(fn: Function) {
// less customizations than vi.waitFor but it's good enough for now
const timeout = Date.now() + 5000
@@ -81,7 +82,7 @@ export async function waitFor(fn: Function) {
return await fn()
} catch (e) {
lastError = e
- await new Promise((resolve) => setTimeout(resolve, 10))
+ await new Promise(resolve => setTimeout(resolve, 10))
}
}
diff --git a/.config/vite-utils/test-setup-plugin.ts b/.config/vite-utils/test-setup-plugin.ts
index 4e638511..bd8515ff 100644
--- a/.config/vite-utils/test-setup-plugin.ts
+++ b/.config/vite-utils/test-setup-plugin.ts
@@ -1,7 +1,8 @@
-import { Plugin } from 'vite'
-import { fileURLToPath } from 'url'
+import { fileURLToPath } from 'node:url'
-const setupFile = fileURLToPath(new URL('./test-setup.mts', import.meta.url))
+import type { Plugin } from 'vite'
+
+const setupFile = fileURLToPath(new URL('./test-setup.ts', import.meta.url))
export function testSetup(params?: { additionalCode?: string }): Plugin {
const { additionalCode = '' } = params || {}
@@ -12,7 +13,7 @@ export function testSetup(params?: { additionalCode?: string }): Plugin {
if (!id.match(/\.test\.m?[tj]s/)) return
return {
- code: `import '${setupFile}'\n` + additionalCode + code,
+ code: `import '${setupFile}'\n${additionalCode}${code}`,
map: null,
}
},
diff --git a/.config/vite-utils/test-setup.mts b/.config/vite-utils/test-setup.ts
similarity index 98%
rename from .config/vite-utils/test-setup.mts
rename to .config/vite-utils/test-setup.ts
index 1be216bc..5c66fba7 100644
--- a/.config/vite-utils/test-setup.mts
+++ b/.config/vite-utils/test-setup.ts
@@ -1,4 +1,5 @@
import { expect } from 'vitest'
+
import { setPlatform } from '../../packages/core/src/platform.js'
import { buffersEqual } from '../../packages/core/src/utils/buffer-utils.js'
@@ -15,5 +16,5 @@ expect.addEqualityTesters([
if (a instanceof Uint8Array && b instanceof Uint8Array) {
return buffersEqual(a, b)
}
- }
-])
\ No newline at end of file
+ },
+])
diff --git a/.config/vite.browser.mts b/.config/vite.browser.ts
similarity index 72%
rename from .config/vite.browser.mts
rename to .config/vite.browser.ts
index 34508d53..d2586158 100644
--- a/.config/vite.browser.mts
+++ b/.config/vite.browser.ts
@@ -1,11 +1,11 @@
///
-import { defineConfig, mergeConfig } from 'vite'
+import { mergeConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
-import baseConfig from './vite.mjs'
+import baseConfig from './vite.js'
import { fixupCjs } from './vite-utils/fixup-cjs'
-export default mergeConfig(baseConfig, defineConfig({
+export default mergeConfig(baseConfig, {
test: {
browser: {
enabled: true,
@@ -14,7 +14,7 @@ export default mergeConfig(baseConfig, defineConfig({
slowHijackESM: false,
},
fakeTimers: {
- toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date']
+ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],
},
retry: process.env.CI ? 3 : 0,
isolate: false,
@@ -28,15 +28,20 @@ export default mergeConfig(baseConfig, defineConfig({
plugins: [
fixupCjs(),
nodePolyfills({
- include: ['stream', 'path', 'zlib', 'util'],
+ include: ['stream', 'path', 'zlib', 'util', 'events'],
globals: {
Buffer: false,
global: false,
process: false,
},
- })
+ }),
],
+ build: {
+ rollupOptions: {
+ external: ['bun:sqlite'],
+ },
+ },
define: {
- 'import.meta.env.TEST_ENV': '"browser"'
- }
-}))
+ 'import.meta.env.TEST_ENV': '"browser"',
+ },
+})
diff --git a/.config/vite.bun.mts b/.config/vite.bun.ts
similarity index 61%
rename from .config/vite.bun.mts
rename to .config/vite.bun.ts
index 66f62f5e..ac2bdad6 100644
--- a/.config/vite.bun.mts
+++ b/.config/vite.bun.ts
@@ -1,7 +1,8 @@
+/* eslint-disable no-restricted-globals */
+import { resolve } from 'node:path'
+
import { defineConfig } from 'vite'
-import { globSync } from 'glob'
-import { resolve, join } from 'path'
-import * as fs from 'fs'
+
import { fixupCjs } from './vite-utils/fixup-cjs'
import { testSetup } from './vite-utils/test-setup-plugin'
import { collectTestEntrypoints } from './vite-utils/collect-test-entrypoints'
@@ -11,39 +12,26 @@ const POLYFILLS = resolve(__dirname, 'vite-utils/polyfills-bun.ts')
export default defineConfig({
build: {
lib: {
- entry: process.env.ENTRYPOINT ? [process.env.ENTRYPOINT] : collectTestEntrypoints({
- // https://github.com/oven-sh/bun/issues/4145 prevents us from using vitest directly
- // so we have to use bun's native test runner
- skipPackages: ['create-bot', 'crypto-node'],
- // bun:test doesn't support certain features of vitest, so we'll skip them for now
- // https://github.com/oven-sh/bun/issues/1825
- skipTests: [
+ entry: process.env.ENTRYPOINT
+ ? [process.env.ENTRYPOINT]
+ : collectTestEntrypoints({
+ // https://github.com/oven-sh/bun/issues/4145 prevents us from using vitest directly
+ // so we have to use bun's native test runner
+ skipPackages: ['create-bot', 'crypto-node'],
+ // bun:test doesn't support certain features of vitest, so we'll skip them for now
+ // https://github.com/oven-sh/bun/issues/1825
+ skipTests: [
// uses timers
- 'core/src/network/config-manager.test.ts',
- 'core/src/network/persistent-connection.test.ts',
- ],
- }),
+ 'core/src/network/config-manager.test.ts',
+ 'core/src/network/persistent-connection.test.ts',
+ ],
+ }),
formats: ['es'],
},
rollupOptions: {
external: [
- 'node:zlib',
+ /^(node|bun):.*/,
'vitest',
- 'stream',
- 'net',
- 'crypto',
- 'module',
- 'fs',
- 'fs/promises',
- 'node:fs',
- 'readline',
- 'worker_threads',
- 'events',
- 'path',
- 'util',
- 'os',
- 'bun:test',
- 'bun:sqlite',
],
output: {
chunkFileNames: 'chunk-[hash].js',
@@ -66,8 +54,8 @@ export default defineConfig({
name: 'polyfills',
transform(code) {
if (!code.includes('vitest')) return code
- code = code.replace(/^import {(.+?)} from ['"]vitest['"]/gms, (_, names) => {
- const namesParsed = names.split(',').map((name) => name.trim())
+ code = code.replace(/^import \{(.+?)\} from ['"]vitest['"]/gms, (_, names) => {
+ const namesParsed = names.split(',').map(name => name.trim())
const namesFromFixup: string[] = []
const newNames = namesParsed
@@ -92,13 +80,13 @@ export default defineConfig({
},
{
name: 'fix-wasm-load',
- async transform(code, id) {
+ async transform(code) {
if (code.includes('@mtcute/wasm/mtcute.wasm')) {
return code.replace('@mtcute/wasm/mtcute.wasm', resolve(__dirname, '../packages/wasm/mtcute.wasm'))
}
return code
- }
+ },
},
testSetup(),
],
diff --git a/.config/vite.deno.mts b/.config/vite.deno.ts
similarity index 67%
rename from .config/vite.deno.mts
rename to .config/vite.deno.ts
index 073611d4..796d847f 100644
--- a/.config/vite.deno.mts
+++ b/.config/vite.deno.ts
@@ -1,26 +1,31 @@
+import { resolve } from 'node:path'
+
import { defineConfig } from 'vite'
-import { resolve, join } from 'path'
+
import { fixupCjs } from './vite-utils/fixup-cjs'
import { testSetup } from './vite-utils/test-setup-plugin'
import { collectTestEntrypoints } from './vite-utils/collect-test-entrypoints'
+// eslint-disable-next-line no-restricted-globals
const POLYFILLS = resolve(__dirname, 'vite-utils/polyfills-deno.ts')
export default defineConfig({
build: {
lib: {
- entry: process.env.ENTRYPOINT ? [process.env.ENTRYPOINT] : collectTestEntrypoints({
- // these packages rely on node apis and are not meant to be run under deno
- skipPackages: ['create-bot', 'crypto-node', 'bun', 'node', 'http-proxy', 'socks-proxy', 'mtproxy'],
- skipTests: [
+ entry: process.env.ENTRYPOINT
+ ? [process.env.ENTRYPOINT]
+ : collectTestEntrypoints({
+ // these packages rely on node apis and are not meant to be run under deno
+ skipPackages: ['create-bot', 'crypto-node', 'bun', 'node', 'http-proxy', 'socks-proxy', 'mtproxy'],
+ skipTests: [
// uses timers
- 'core/src/network/config-manager.test.ts',
- 'core/src/network/persistent-connection.test.ts',
- // https://github.com/denoland/deno/issues/22470
- 'wasm/tests/gunzip.test.ts',
- 'wasm/tests/zlib.test.ts',
- ],
- }),
+ 'core/src/network/config-manager.test.ts',
+ 'core/src/network/persistent-connection.test.ts',
+ // https://github.com/denoland/deno/issues/22470
+ 'wasm/tests/gunzip.test.ts',
+ 'wasm/tests/zlib.test.ts',
+ ],
+ }),
formats: ['es'],
},
rollupOptions: {
@@ -48,8 +53,8 @@ export default defineConfig({
name: 'polyfills',
transform(code) {
if (!code.includes('vitest')) return code
- code = code.replace(/^import {(.+?)} from ['"]vitest['"]/gms, (_, names) => {
- const namesParsed = names.split(',').map((name) => name.trim())
+ code = code.replace(/^import \{(.+?)\} from ['"]vitest['"]/gms, (_, names) => {
+ const namesParsed = names.split(',').map(name => name.trim())
return `import {${namesParsed.join(', ')}} from '${POLYFILLS}'`
})
diff --git a/.config/vite.mts b/.config/vite.ts
similarity index 58%
rename from .config/vite.mts
rename to .config/vite.ts
index f4ee57c5..39bbe63b 100644
--- a/.config/vite.mts
+++ b/.config/vite.ts
@@ -17,13 +17,21 @@ export default defineConfig({
],
exclude: [
'packages/**/index.ts',
- ]
+ ],
},
setupFiles: [
- './.config/vite-utils/test-setup.mts'
- ]
+ './.config/vite-utils/test-setup.ts',
+ ],
},
define: {
- 'import.meta.env.TEST_ENV': '"node"'
- }
+ 'import.meta.env.TEST_ENV': '"node"',
+ },
+ optimizeDeps: {
+ esbuildOptions: {
+ // for WHATEVER REASON browserify-zlib uses `global` and it dies in browser lol
+ define: {
+ global: 'globalThis',
+ },
+ },
+ },
})
diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml
index 19493cc8..9b22cf51 100644
--- a/.github/workflows/release.yaml
+++ b/.github/workflows/release.yaml
@@ -59,14 +59,14 @@ jobs:
GH_RELEASE: 1
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: node scripts/publish.js ${{ steps.find.outputs.modified }}
- - uses: denoland/setup-deno@v1
- with:
- deno-version: '1.43.1'
- - name: Build packages and publish to JSR
- env:
- JSR: 1
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- run: node scripts/publish.js ${{ steps.find.outputs.modified }}
+ # - uses: denoland/setup-deno@v1
+ # with:
+ # deno-version: '1.45.5'
+ # - name: Build packages and publish to JSR
+ # env:
+ # JSR: 1
+ # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ # run: node scripts/publish.js ${{ steps.find.outputs.modified }}
- name: Commit version bumps
run: |
git commit -am "v${{ steps.bump.outputs.version }}"
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index 1ae23c58..fd30eed6 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -52,7 +52,7 @@ jobs:
with:
bun-version: '1.1.4'
- name: 'Build tests'
- run: pnpm exec vite build -c .config/vite.bun.mts
+ run: pnpm exec vite build -c .config/vite.bun.ts
- name: 'Run tests'
run: cd dist/tests && bun test
@@ -63,9 +63,9 @@ jobs:
- uses: ./.github/actions/init
- uses: denoland/setup-deno@v1
with:
- deno-version: '1.43.1'
+ deno-version: '1.45.5'
- name: 'Build tests'
- run: pnpm exec vite build -c .config/vite.deno.mts
+ run: pnpm exec vite build -c .config/vite.deno.ts
- name: 'Run tests'
run: cd dist/tests && deno test -A --unstable-ffi
@@ -110,22 +110,22 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REGISTRY: 'https://npm.tei.su'
run: cd e2e/node && ./cli.sh ci-publish
- e2e-deno:
- runs-on: ubuntu-latest
- needs: [lint, test-node, test-web, test-bun, test-deno]
- permissions:
- contents: read
- actions: write
- steps:
- - uses: actions/checkout@v4
- - name: Run end-to-end tests under Deno
- env:
- API_ID: ${{ secrets.TELEGRAM_API_ID }}
- API_HASH: ${{ secrets.TELEGRAM_API_HASH }}
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- uses: nick-fields/retry@v2
- # thanks docker networking very cool
- with:
- max_attempts: 3
- timeout_minutes: 30
- command: cd e2e/deno && ./cli.sh ci
+ # e2e-deno:
+ # runs-on: ubuntu-latest
+ # needs: [lint, test-node, test-web, test-bun, test-deno]
+ # permissions:
+ # contents: read
+ # actions: write
+ # steps:
+ # - uses: actions/checkout@v4
+ # - name: Run end-to-end tests under Deno
+ # env:
+ # API_ID: ${{ secrets.TELEGRAM_API_ID }}
+ # API_HASH: ${{ secrets.TELEGRAM_API_HASH }}
+ # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ # uses: nick-fields/retry@v2
+ # # thanks docker networking very cool
+ # with:
+ # max_attempts: 3
+ # timeout_minutes: 30
+ # command: cd e2e/deno && ./cli.sh ci
diff --git a/README.md b/README.md
index 4657fb0f..74f24c53 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@
> [!WARNING]
-> mtcute is currently in alpha stage: the api is not very stable yet, and there may be a lot of bugs
+> mtcute is currently in alpha stage: the api is not very stable yet, and there may be a lot of bugs
> feel free to try it out, though, any feedback is appreciated!
>
> releases may not follow semver just yet, so please pin the versions for now
@@ -29,7 +29,7 @@ import { TelegramClient } from '@mtcute/node'
import { Dispatcher, filters } from '@mtcute/dispatcher'
const tg = new TelegramClient({
- apiId: parseInt(process.env.API_ID),
+ apiId: Number.parseInt(process.env.API_ID),
apiHash: process.env.API_HASH,
storage: 'my-account'
})
diff --git a/e2e/deno/Dockerfile.build b/e2e/deno/Dockerfile.build
index fa6b5552..5d1df581 100644
--- a/e2e/deno/Dockerfile.build
+++ b/e2e/deno/Dockerfile.build
@@ -1,4 +1,4 @@
-FROM denoland/deno:bin-1.43.1 as deno-bin
+FROM denoland/deno:bin-1.45.5 as deno-bin
FROM node:20
WORKDIR /app
diff --git a/e2e/deno/Dockerfile.test b/e2e/deno/Dockerfile.test
index e7137cd9..ad9b1efb 100644
--- a/e2e/deno/Dockerfile.test
+++ b/e2e/deno/Dockerfile.test
@@ -1,4 +1,4 @@
-FROM denoland/deno:1.43.1
+FROM denoland/deno:1.45.5
WORKDIR /app
RUN apt update && apt install -y socat
diff --git a/e2e/deno/README.md b/e2e/deno/README.md
index 5b579dc9..034bfa89 100644
--- a/e2e/deno/README.md
+++ b/e2e/deno/README.md
@@ -6,7 +6,7 @@ They are made for 2 purposes:
- Ensure published packages work as expected and can properly be imported
- Ensure that the library works with the actual Telegram API
-To achieve the first goal, we use a local JSR instance container where we publish the package,
+To achieve the first goal, we use a local JSR instance container where we publish the package,
and then install it from there in another container
## Setting up
@@ -27,4 +27,4 @@ Before running the tests, you need to copy `.env.example` to `.env` and fill in
./cli.sh run
# or in docker
./cli.sh run-docker
-```
\ No newline at end of file
+```
diff --git a/e2e/deno/deno.json b/e2e/deno/deno.json
index 71f4e17a..120e67e5 100644
--- a/e2e/deno/deno.json
+++ b/e2e/deno/deno.json
@@ -1,10 +1,10 @@
{
- "imports": {
- "@mtcute/web": "jsr:@mtcute/web@*",
- "@mtcute/wasm": "jsr:@mtcute/wasm@*",
- "@mtcute/tl": "jsr:@mtcute/tl@*",
- "@mtcute/tl-runtime": "jsr:@mtcute/tl-runtime@*",
- "@mtcute/core": "jsr:@mtcute/core@*",
- "@mtcute/deno": "jsr:@mtcute/deno@*"
- }
-}
\ No newline at end of file
+ "imports": {
+ "@mtcute/web": "jsr:@mtcute/web@*",
+ "@mtcute/wasm": "jsr:@mtcute/wasm@*",
+ "@mtcute/tl": "jsr:@mtcute/tl@*",
+ "@mtcute/tl-runtime": "jsr:@mtcute/tl-runtime@*",
+ "@mtcute/core": "jsr:@mtcute/core@*",
+ "@mtcute/deno": "jsr:@mtcute/deno@*"
+ }
+}
diff --git a/e2e/deno/init-server.js b/e2e/deno/init-server.js
index 429a2e9e..dc1152fd 100644
--- a/e2e/deno/init-server.js
+++ b/e2e/deno/init-server.js
@@ -1,5 +1,5 @@
/* eslint-disable no-console */
-const { execSync } = require('child_process')
+import { execSync } from 'node:child_process'
function getDockerContainerIp(name) {
const containerId = execSync(`docker compose ps -q ${name}`).toString().trim()
@@ -41,27 +41,25 @@ async function createBucket(name) {
}
}
-(async () => {
- for (const bucket of ['modules', 'docs', 'publishing', 'npm']) {
- const ok = await createBucket(bucket)
- console.log(`[i] Created bucket ${bucket}: ${ok}`)
- }
+for (const bucket of ['modules', 'docs', 'publishing', 'npm']) {
+ const ok = await createBucket(bucket)
+ console.log(`[i] Created bucket ${bucket}: ${ok}`)
+}
- // create @mtcute scope if it doesn't exist
- const resp = await fetch(`${API_URL}api/scopes`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Cookie: 'token=token',
- },
- body: JSON.stringify({ scope: 'mtcute' }),
- })
+// create @mtcute scope if it doesn't exist
+const resp = await fetch(`${API_URL}api/scopes`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Cookie': 'token=token',
+ },
+ body: JSON.stringify({ scope: 'mtcute' }),
+})
- if (resp.status !== 200 && resp.status !== 409) {
- throw new Error(`Failed to create scope: ${resp.statusText} ${await resp.text()}`)
- }
+if (resp.status !== 200 && resp.status !== 409) {
+ throw new Error(`Failed to create scope: ${resp.statusText} ${await resp.text()}`)
+}
- if (resp.status === 200) {
- console.log('[i] Created scope mtcute')
- }
-})()
+if (resp.status === 200) {
+ console.log('[i] Created scope mtcute')
+}
diff --git a/e2e/deno/tests/01.auth.ts b/e2e/deno/tests/01.auth.ts
index 5236b549..b728e7df 100644
--- a/e2e/deno/tests/01.auth.ts
+++ b/e2e/deno/tests/01.auth.ts
@@ -1,14 +1,14 @@
import { assertEquals } from 'https://deno.land/std@0.223.0/assert/mod.ts'
-
-import { tl, User } from '@mtcute/core'
+import { User, tl } from '@mtcute/core'
import { BaseTelegramClient, TelegramClient } from '@mtcute/core/client.js'
import { getApiParams } from '../utils.ts'
-const getAccountId = () =>
- Math.floor(Math.random() * 10000)
+function getAccountId() {
+ return Math.floor(Math.random() * 10000)
.toString()
.padStart(4, '0')
+}
async function authorizeInDc(dc: number, base: BaseTelegramClient) {
const tg = new TelegramClient({ client: base })
diff --git a/e2e/deno/tests/02.methods.ts b/e2e/deno/tests/02.methods.ts
index f62b9a13..e60e6841 100644
--- a/e2e/deno/tests/02.methods.ts
+++ b/e2e/deno/tests/02.methods.ts
@@ -1,5 +1,4 @@
import { assertEquals, assertNotEquals } from 'https://deno.land/std@0.223.0/assert/mod.ts'
-
import { MtPeerNotFoundError } from '@mtcute/core'
import { TelegramClient } from '@mtcute/core/client.js'
diff --git a/e2e/deno/tests/03.files.ts b/e2e/deno/tests/03.files.ts
index 3cbbbf5a..dee5d703 100644
--- a/e2e/deno/tests/03.files.ts
+++ b/e2e/deno/tests/03.files.ts
@@ -1,7 +1,8 @@
-import { assertEquals } from 'https://deno.land/std@0.223.0/assert/mod.ts'
import { createHash } from 'node:crypto'
-import { FileDownloadLocation, Thumbnail } from '@mtcute/core'
+import { assertEquals } from 'https://deno.land/std@0.223.0/assert/mod.ts'
+import type { FileDownloadLocation } from '@mtcute/core'
+import { Thumbnail } from '@mtcute/core'
import { TelegramClient } from '@mtcute/core/client.js'
import { sleep } from '@mtcute/core/utils.js'
diff --git a/e2e/deno/tests/04.updates.ts b/e2e/deno/tests/04.updates.ts
index 37bc49e1..f19d015f 100644
--- a/e2e/deno/tests/04.updates.ts
+++ b/e2e/deno/tests/04.updates.ts
@@ -1,6 +1,5 @@
import { assertEquals, assertNotEquals } from 'https://deno.land/std@0.223.0/assert/mod.ts'
-
-import { Message } from '@mtcute/core'
+import type { Message } from '@mtcute/core'
import { TelegramClient } from '@mtcute/core/client.js'
import { getApiParams, waitFor } from '../utils.ts'
@@ -18,7 +17,7 @@ Deno.test('4. handling updates', { sanitizeResources: false }, async (t) => {
await t.step('should send and receive messages', async () => {
const tg1Messages: Message[] = []
- tg1.on('new_message', (msg) => tg1Messages.push(msg))
+ tg1.on('new_message', msg => tg1Messages.push(msg))
const [tg1User] = await tg1.getUsers('self')
let username = tg1User!.username
@@ -36,7 +35,7 @@ Deno.test('4. handling updates', { sanitizeResources: false }, async (t) => {
await waitFor(() => {
assertNotEquals(
- tg1Messages.find((msg) => msg.text === messageText),
+ tg1Messages.find(msg => msg.text === messageText),
undefined,
)
})
diff --git a/e2e/deno/tests/05.worker.ts b/e2e/deno/tests/05.worker.ts
index d50bcf41..c4dd6480 100644
--- a/e2e/deno/tests/05.worker.ts
+++ b/e2e/deno/tests/05.worker.ts
@@ -1,9 +1,10 @@
import { assertEquals, assertGreater, assertInstanceOf } from 'https://deno.land/std@0.223.0/assert/mod.ts'
-
import { TelegramClient } from '@mtcute/core/client.js'
-import { Long, Message, TelegramWorkerPort, tl } from '@mtcute/deno'
+import type { Message } from '@mtcute/deno'
+import { Long, TelegramWorkerPort, tl } from '@mtcute/deno'
import { getApiParams, waitFor } from '../utils.ts'
+
import type { CustomMethods } from './_worker.ts'
Deno.test('5. worker', { sanitizeResources: false }, async (t) => {
@@ -16,7 +17,7 @@ Deno.test('5. worker', { sanitizeResources: false }, async (t) => {
})
const portClient = new TelegramClient({ client: port })
- await t.step('should make api calls', async function () {
+ await t.step('should make api calls', async () => {
const res = await port.call({ _: 'help.getConfig' })
assertEquals(res._, 'config')
@@ -25,7 +26,7 @@ Deno.test('5. worker', { sanitizeResources: false }, async (t) => {
assertEquals(Long.isLong((premiumPromo.users[0] as tl.RawUser).accessHash), true)
})
- await t.step('should call custom methods', async function () {
+ await t.step('should call custom methods', async () => {
const hello = await port.invokeCustom('hello')
assertEquals(hello, 'world')
@@ -33,7 +34,7 @@ Deno.test('5. worker', { sanitizeResources: false }, async (t) => {
assertEquals(sum, 5)
})
- await t.step('should throw errors', async function () {
+ await t.step('should throw errors', async () => {
try {
await port.call({ _: 'test.useConfigSimple' })
throw new Error('should have thrown')
@@ -42,7 +43,7 @@ Deno.test('5. worker', { sanitizeResources: false }, async (t) => {
}
})
- await t.step('should receive updates', async function () {
+ await t.step('should receive updates', async () => {
const client2 = new TelegramClient(getApiParams('dc2.session'))
try {
diff --git a/e2e/deno/tests/_worker.ts b/e2e/deno/tests/_worker.ts
index 1b5e3938..967cbd9a 100644
--- a/e2e/deno/tests/_worker.ts
+++ b/e2e/deno/tests/_worker.ts
@@ -1,4 +1,4 @@
-import { WorkerCustomMethods } from '@mtcute/core/worker.js'
+import type { WorkerCustomMethods } from '@mtcute/core/worker.js'
import { BaseTelegramClient, TelegramWorker } from '@mtcute/deno'
import { getApiParams } from '../utils.ts'
diff --git a/e2e/deno/tests/packaging/base-client.ts b/e2e/deno/tests/packaging/base-client.ts
index b752892a..f929853f 100644
--- a/e2e/deno/tests/packaging/base-client.ts
+++ b/e2e/deno/tests/packaging/base-client.ts
@@ -1,5 +1,4 @@
import { assertEquals } from 'https://deno.land/std@0.223.0/assert/mod.ts'
-
import { BaseTelegramClient } from '@mtcute/core/client.js'
import { getApiParams } from '../../utils.ts'
diff --git a/e2e/deno/tests/packaging/tl-runtime.ts b/e2e/deno/tests/packaging/tl-runtime.ts
index b00dbeb0..ec577252 100644
--- a/e2e/deno/tests/packaging/tl-runtime.ts
+++ b/e2e/deno/tests/packaging/tl-runtime.ts
@@ -1,6 +1,4 @@
-/* eslint-disable @typescript-eslint/no-explicit-any */
import { assertEquals } from 'https://deno.land/std@0.223.0/assert/mod.ts'
-
import { Long } from '@mtcute/core'
import { setPlatform } from '@mtcute/core/platform.js'
import { TlBinaryReader, TlBinaryWriter, TlSerializationCounter } from '@mtcute/tl-runtime'
@@ -19,7 +17,7 @@ Deno.test('encodings', () => {
Deno.test('TlBinaryReader', () => {
const map = {
- '85337187': function (r: any) {
+ 85337187(r: any) {
const ret: any = {}
ret._ = 'mt_resPQ'
ret.nonce = r.int128()
@@ -30,8 +28,8 @@ Deno.test('TlBinaryReader', () => {
return ret
},
}
- const data =
- '000000000000000001c8831ec97ae55140000000632416053e0549828cca27e966b301a48fece2fca5cf4d33f4a11ea877ba4aa5739073300817ed48941a08f98100000015c4b51c01000000216be86c022bb4c3'
+ const data
+ = '000000000000000001c8831ec97ae55140000000632416053e0549828cca27e966b301a48fece2fca5cf4d33f4a11ea877ba4aa5739073300817ed48941a08f98100000015c4b51c01000000216be86c022bb4c3'
const buf = p.hexDecode(data)
const r = new TlBinaryReader(map, buf, 8)
@@ -45,7 +43,7 @@ Deno.test('TlBinaryReader', () => {
Deno.test('TlBinaryWriter', () => {
const map = {
- mt_resPQ: function (w: any, obj: any) {
+ mt_resPQ(w: any, obj: any) {
w.uint(85337187)
w.bytes(obj.pq)
w.vector(w.long, obj.serverPublicKeyFingerprints)
diff --git a/e2e/deno/tests/packaging/tl-schema.ts b/e2e/deno/tests/packaging/tl-schema.ts
index 5514729e..348fa9c9 100644
--- a/e2e/deno/tests/packaging/tl-schema.ts
+++ b/e2e/deno/tests/packaging/tl-schema.ts
@@ -1,5 +1,4 @@
import { assertEquals } from 'https://deno.land/std@0.223.0/assert/mod.ts'
-
import { Long } from '@mtcute/core'
import { setPlatform } from '@mtcute/core/platform.js'
import { tl } from '@mtcute/tl'
@@ -29,7 +28,7 @@ Deno.test('@mtcute/tl', async (t) => {
await t.step('readers map works with TlBinaryReader', () => {
const buf = p.hexDecode('4ca5e8dd7b00000000000000c801000000000000')
- // eslint-disable-next-line
+
const obj = TlBinaryReader.deserializeObject(__tlReaderMap, buf)
assertEquals(obj._, 'inputPeerUser')
diff --git a/e2e/deno/tests/packaging/wasm.ts b/e2e/deno/tests/packaging/wasm.ts
index 865f670e..69a210ae 100644
--- a/e2e/deno/tests/packaging/wasm.ts
+++ b/e2e/deno/tests/packaging/wasm.ts
@@ -1,5 +1,4 @@
import { assertEquals } from 'https://deno.land/std@0.223.0/assert/mod.ts'
-
import { ige256Decrypt, ige256Encrypt } from '@mtcute/wasm'
import { WebCryptoProvider, WebPlatform } from '@mtcute/web'
diff --git a/e2e/deno/utils.ts b/e2e/deno/utils.ts
index dfba3630..86f0f183 100644
--- a/e2e/deno/utils.ts
+++ b/e2e/deno/utils.ts
@@ -1,9 +1,10 @@
-import { MaybePromise, MemoryStorage } from '@mtcute/core'
+import type { MaybePromise } from '@mtcute/core'
+import { MemoryStorage } from '@mtcute/core'
import { setPlatform } from '@mtcute/core/platform.js'
import { LogManager, sleep } from '@mtcute/core/utils.js'
import { DenoCryptoProvider, DenoPlatform, SqliteStorage, TcpTransport } from '@mtcute/deno'
-export const getApiParams = (storage?: string) => {
+export function getApiParams(storage?: string) {
if (!Deno.env.has('API_ID') || !Deno.env.has('API_HASH')) {
throw new Error('API_ID and API_HASH env variables must be set')
}
@@ -13,7 +14,7 @@ export const getApiParams = (storage?: string) => {
setPlatform(new DenoPlatform())
return {
- apiId: parseInt(Deno.env.get('API_ID')!),
+ apiId: Number.parseInt(Deno.env.get('API_ID')!),
apiHash: Deno.env.get('API_HASH')!,
testMode: true,
storage: storage ? new SqliteStorage(`.sessions/${storage}`) : new MemoryStorage(),
diff --git a/e2e/node/.mocharc.json b/e2e/node/.mocharc.json
index 1c46b480..04373577 100644
--- a/e2e/node/.mocharc.json
+++ b/e2e/node/.mocharc.json
@@ -1,3 +1,3 @@
{
- "node-option": []
+ "node-option": []
}
diff --git a/e2e/node/README.md b/e2e/node/README.md
index 842f184f..3733d8e4 100644
--- a/e2e/node/README.md
+++ b/e2e/node/README.md
@@ -6,7 +6,7 @@ They are made for 2 purposes:
- Ensure published packages work as expected and can properly be imported
- Ensure that the library works with the actual Telegram API (WIP)
-To achieve the first goal, we use a Verdaccio container to publish the package to,
+To achieve the first goal, we use a Verdaccio container to publish the package to,
and then install it from there in another container
## Setting up
@@ -45,4 +45,4 @@ npm config set -L project @mtcute:registry http://verdaccio.e2e.orb.local/
> Replace the URL above with the one generated with your Docker GUI of choice
> (e2e > verdaccio > RMB > Open in browser). Example above assumes OrbStack
-Then use `./cli.sh run` to run the tests
\ No newline at end of file
+Then use `./cli.sh run` to run the tests
diff --git a/e2e/node/cjs/package.json b/e2e/node/cjs/package.json
index 9e26dfee..0967ef42 100644
--- a/e2e/node/cjs/package.json
+++ b/e2e/node/cjs/package.json
@@ -1 +1 @@
-{}
\ No newline at end of file
+{}
diff --git a/e2e/node/cjs/tests/tl-runtime.js b/e2e/node/cjs/tests/tl-runtime.js
index 4e38b6ef..1799c80d 100644
--- a/e2e/node/cjs/tests/tl-runtime.js
+++ b/e2e/node/cjs/tests/tl-runtime.js
@@ -24,7 +24,7 @@ describe('@mtcute/tl-runtime', () => {
describe('TlBinaryReader', () => {
const map = {
- '85337187': function (r) {
+ 85337187(r) {
const ret = {}
ret._ = 'mt_resPQ'
ret.nonce = r.int128()
@@ -35,8 +35,8 @@ describe('@mtcute/tl-runtime', () => {
return ret
},
}
- const data =
- '000000000000000001c8831ec97ae55140000000632416053e0549828cca27e966b301a48fece2fca5cf4d33f4a11ea877ba4aa5739073300817ed48941a08f98100000015c4b51c01000000216be86c022bb4c3'
+ const data
+ = '000000000000000001c8831ec97ae55140000000632416053e0549828cca27e966b301a48fece2fca5cf4d33f4a11ea877ba4aa5739073300817ed48941a08f98100000015c4b51c01000000216be86c022bb4c3'
it('should work with Buffers', () => {
const buf = Buffer.from(data, 'hex')
@@ -64,7 +64,7 @@ describe('@mtcute/tl-runtime', () => {
describe('TlBinaryWriter', () => {
const map = {
- mt_resPQ: function (w, obj) {
+ mt_resPQ(w, obj) {
w.uint(85337187)
w.bytes(obj.pq)
w.vector(w.long, obj.serverPublicKeyFingerprints)
diff --git a/e2e/node/cjs/tests/tl-schema.js b/e2e/node/cjs/tests/tl-schema.js
index 43508e29..f84c8c9e 100644
--- a/e2e/node/cjs/tests/tl-schema.js
+++ b/e2e/node/cjs/tests/tl-schema.js
@@ -1,5 +1,4 @@
const Long = require('long')
-
const { TlBinaryReader, TlBinaryWriter } = require('@mtcute/tl-runtime')
const { tl } = require('@mtcute/tl')
const { __tlReaderMap } = require('@mtcute/tl/binary/reader')
@@ -35,6 +34,6 @@ describe('@mtcute/tl', () => {
})
it('correctly checks for combinator types', () => {
- expect(tl.isAnyInputUser({ _: 'inputUserEmpty' })).to.be.true
+ expect(tl.isAnyInputUser({ _: 'inputUserEmpty' })).to.eq(true)
})
})
diff --git a/e2e/node/cjs/utils.js b/e2e/node/cjs/utils.js
index a81c0027..be23b064 100644
--- a/e2e/node/cjs/utils.js
+++ b/e2e/node/cjs/utils.js
@@ -12,7 +12,7 @@ exports.getApiParams = () => {
setPlatform(new NodePlatform())
return {
- apiId: parseInt(process.env.API_ID),
+ apiId: Number.parseInt(process.env.API_ID),
apiHash: process.env.API_HASH,
testMode: true,
storage: new MemoryStorage(),
diff --git a/e2e/node/config.js b/e2e/node/config.js
index af1d6e14..1f7159fc 100644
--- a/e2e/node/config.js
+++ b/e2e/node/config.js
@@ -1,17 +1,17 @@
module.exports = {
cjs: {
getFiles: () => 'tests/**/*.js',
- runFile: (file) => `mocha ${file}`,
+ runFile: file => `mocha ${file}`,
},
esm: {
getFiles: () => 'tests/**/*.js',
- runFile: (file) => `mocha ${file}`,
+ runFile: file => `mocha ${file}`,
},
ts: {
getFiles: () => 'tests/**/*.ts',
beforeAll: () => ['tsc', 'node build-esm.cjs'],
runFile: (file) => {
- if (require('path').basename(file)[0] === '_') return null
+ if (require('node:path').basename(file)[0] === '_') return null
if (file.startsWith('tests/packaging/')) {
// packaging tests - we need to make sure everything imports and works
diff --git a/e2e/node/esm/package.json b/e2e/node/esm/package.json
index 7c34deb5..5ffd9800 100644
--- a/e2e/node/esm/package.json
+++ b/e2e/node/esm/package.json
@@ -1 +1 @@
-{"type":"module"}
\ No newline at end of file
+{ "type": "module" }
diff --git a/e2e/node/esm/tests/base-client.js b/e2e/node/esm/tests/base-client.js
index 818b5c97..855ddf90 100644
--- a/e2e/node/esm/tests/base-client.js
+++ b/e2e/node/esm/tests/base-client.js
@@ -1,6 +1,5 @@
import { expect } from 'chai'
import { describe, it } from 'mocha'
-
import { BaseTelegramClient } from '@mtcute/core/client.js'
import { getApiParams } from '../utils.js'
diff --git a/e2e/node/esm/tests/tl-runtime.js b/e2e/node/esm/tests/tl-runtime.js
index d5a4d3d8..43ce673a 100644
--- a/e2e/node/esm/tests/tl-runtime.js
+++ b/e2e/node/esm/tests/tl-runtime.js
@@ -1,7 +1,6 @@
import { expect } from 'chai'
import Long from 'long'
import { describe, it } from 'mocha'
-
import { NodePlatform } from '@mtcute/node'
import { TlBinaryReader, TlBinaryWriter, TlSerializationCounter } from '@mtcute/tl-runtime'
@@ -24,7 +23,7 @@ describe('encodings', () => {
describe('TlBinaryReader', () => {
const map = {
- '85337187': function (r) {
+ 85337187(r) {
const ret = {}
ret._ = 'mt_resPQ'
ret.nonce = r.int128()
@@ -35,8 +34,8 @@ describe('TlBinaryReader', () => {
return ret
},
}
- const data =
- '000000000000000001c8831ec97ae55140000000632416053e0549828cca27e966b301a48fece2fca5cf4d33f4a11ea877ba4aa5739073300817ed48941a08f98100000015c4b51c01000000216be86c022bb4c3'
+ const data
+ = '000000000000000001c8831ec97ae55140000000632416053e0549828cca27e966b301a48fece2fca5cf4d33f4a11ea877ba4aa5739073300817ed48941a08f98100000015c4b51c01000000216be86c022bb4c3'
it('should work with Buffers', () => {
const buf = Buffer.from(data, 'hex')
@@ -64,7 +63,7 @@ describe('TlBinaryReader', () => {
describe('TlBinaryWriter', () => {
const map = {
- mt_resPQ: function (w, obj) {
+ mt_resPQ(w, obj) {
w.uint(85337187)
w.bytes(obj.pq)
w.vector(w.long, obj.serverPublicKeyFingerprints)
diff --git a/e2e/node/esm/tests/tl-schema.js b/e2e/node/esm/tests/tl-schema.js
index ba4aab19..f83799f4 100644
--- a/e2e/node/esm/tests/tl-schema.js
+++ b/e2e/node/esm/tests/tl-schema.js
@@ -1,7 +1,6 @@
import { expect } from 'chai'
import Long from 'long'
import { describe, it } from 'mocha'
-
import { NodePlatform } from '@mtcute/node'
import { tl } from '@mtcute/tl'
import { __tlReaderMap } from '@mtcute/tl/binary/reader.js'
@@ -35,6 +34,6 @@ describe('@mtcute/tl', () => {
})
it('correctly checks for combinator types', () => {
- expect(tl.isAnyInputUser({ _: 'inputUserEmpty' })).to.be.true
+ expect(tl.isAnyInputUser({ _: 'inputUserEmpty' })).to.eq(true)
})
})
diff --git a/e2e/node/esm/tests/wasm.js b/e2e/node/esm/tests/wasm.js
index 27291ffa..1de0b398 100644
--- a/e2e/node/esm/tests/wasm.js
+++ b/e2e/node/esm/tests/wasm.js
@@ -1,6 +1,5 @@
import { expect } from 'chai'
import { before, describe, it } from 'mocha'
-
import { NodeCryptoProvider } from '@mtcute/node/utils.js'
import { ige256Decrypt, ige256Encrypt } from '@mtcute/wasm'
diff --git a/e2e/node/esm/utils.js b/e2e/node/esm/utils.js
index 938b6c7d..3b2b9aeb 100644
--- a/e2e/node/esm/utils.js
+++ b/e2e/node/esm/utils.js
@@ -4,7 +4,7 @@ import { LogManager } from '@mtcute/core/utils.js'
import { NodePlatform, TcpTransport } from '@mtcute/node'
import { NodeCryptoProvider } from '@mtcute/node/utils.js'
-export const getApiParams = () => {
+export function getApiParams() {
if (!process.env.API_ID || !process.env.API_HASH) {
throw new Error('API_ID and API_HASH env variables must be set')
}
@@ -12,7 +12,7 @@ export const getApiParams = () => {
setPlatform(new NodePlatform())
return {
- apiId: parseInt(process.env.API_ID),
+ apiId: Number.parseInt(process.env.API_ID),
apiHash: process.env.API_HASH,
testMode: true,
storage: new MemoryStorage(),
diff --git a/e2e/node/package.json b/e2e/node/package.json
index a94bfe9f..dd273173 100644
--- a/e2e/node/package.json
+++ b/e2e/node/package.json
@@ -1,35 +1,35 @@
{
- "name": "mtcute-e2e",
- "private": true,
- "dependencies": {
- "@mtcute/bun": "*",
- "@mtcute/core": "*",
- "@mtcute/crypto-node": "*",
- "@mtcute/dispatcher": "*",
- "@mtcute/file-id": "*",
- "@mtcute/html-parser": "*",
- "@mtcute/http-proxy": "*",
- "@mtcute/i18n": "*",
- "@mtcute/markdown-parser": "*",
- "@mtcute/mtproxy": "*",
- "@mtcute/node": "*",
- "@mtcute/socks-proxy": "*",
- "@mtcute/tl": "*",
- "@mtcute/tl-runtime": "*",
- "@mtcute/tl-utils": "*",
- "@mtcute/wasm": "*",
- "@mtcute/web": "*",
- "@types/chai": "^4.3.8",
- "@types/mocha": "^10.0.2",
- "chai": "^4.3.10",
- "dotenv": "16.3.1",
- "glob": "10.3.10",
- "long": "^5.2.3",
- "mocha": "^10.2.0",
- "ts-node": "^10.9.1",
- "typescript": "^5.2.2"
- },
- "devDependencies": {
- "@types/node": "^20.8.10"
- }
-}
\ No newline at end of file
+ "name": "mtcute-e2e",
+ "private": true,
+ "dependencies": {
+ "@mtcute/bun": "*",
+ "@mtcute/core": "*",
+ "@mtcute/crypto-node": "*",
+ "@mtcute/dispatcher": "*",
+ "@mtcute/file-id": "*",
+ "@mtcute/html-parser": "*",
+ "@mtcute/http-proxy": "*",
+ "@mtcute/i18n": "*",
+ "@mtcute/markdown-parser": "*",
+ "@mtcute/mtproxy": "*",
+ "@mtcute/node": "*",
+ "@mtcute/socks-proxy": "*",
+ "@mtcute/tl": "*",
+ "@mtcute/tl-runtime": "*",
+ "@mtcute/tl-utils": "*",
+ "@mtcute/wasm": "*",
+ "@mtcute/web": "*",
+ "@types/chai": "^4.3.8",
+ "@types/mocha": "^10.0.2",
+ "chai": "^4.3.10",
+ "dotenv": "16.3.1",
+ "glob": "10.3.10",
+ "long": "^5.2.3",
+ "mocha": "^10.2.0",
+ "ts-node": "^10.9.1",
+ "typescript": "^5.2.2"
+ },
+ "devDependencies": {
+ "@types/node": "^20.8.10"
+ }
+}
diff --git a/e2e/node/publish-canary.js b/e2e/node/publish-canary.js
index 59ca7257..9ed9273b 100644
--- a/e2e/node/publish-canary.js
+++ b/e2e/node/publish-canary.js
@@ -2,9 +2,9 @@
// at this point, we should have all our packages installed in node_modules
// so it should be safe to just cd into them and run `npm publish` on them
-const fs = require('fs')
-const path = require('path')
-const { execSync } = require('child_process')
+const fs = require('node:fs')
+const path = require('node:path')
+const { execSync } = require('node:child_process')
// setup tokenw
const { NPM_TOKEN, REGISTRY, CURRENT_COMMIT } = process.env
@@ -19,8 +19,8 @@ const commit = CURRENT_COMMIT.slice(0, 7)
const myPkgJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'))
const packages = Object.keys(myPkgJson.dependencies)
- .filter((x) => x.startsWith('@mtcute/'))
- .map((x) => x.slice('@mtcute/'.length))
+ .filter(x => x.startsWith('@mtcute/'))
+ .map(x => x.slice('@mtcute/'.length))
const workDir = path.join(__dirname, 'temp')
fs.mkdirSync(workDir, { recursive: true })
@@ -41,7 +41,7 @@ async function main() {
// prepare working directory
for (const pkg of packages) {
- const data = await fetch(`http://localhost:4873/@mtcute/${pkg}`).then((x) => x.json())
+ const data = await fetch(`http://localhost:4873/@mtcute/${pkg}`).then(x => x.json())
const version = data['dist-tags'].latest
const tarball = data.versions[version].dist.tarball
diff --git a/e2e/node/runner.js b/e2e/node/runner.js
index dd591f8f..95c9ad27 100644
--- a/e2e/node/runner.js
+++ b/e2e/node/runner.js
@@ -1,7 +1,8 @@
/* eslint-disable no-console */
+const cp = require('node:child_process')
+const path = require('node:path')
+
const glob = require('glob')
-const cp = require('child_process')
-const path = require('path')
const env = {}
require('dotenv').config({ processEnv: env })
@@ -44,7 +45,7 @@ function runForFile(dir, file, single = true) {
for (const c of cmds) {
console.log('%s $ %s', dir, c)
- cp.execSync('pnpm exec ' + c, options)
+ cp.execSync(`pnpm exec ${c}`, options)
}
}
@@ -69,7 +70,7 @@ function runForDir(dir) {
if (beforeAll) {
for (const c of beforeAll()) {
console.log('%s $ %s', dir, c)
- cp.execSync('pnpm exec ' + c, options)
+ cp.execSync(`pnpm exec ${c}`, options)
}
}
@@ -116,7 +117,7 @@ async function main() {
if (file) {
const files = glob.sync(config[dir].getFiles(), { cwd: path.join(__dirname, dir) })
- const matchingFile = files.find((f) => f.endsWith(file))
+ const matchingFile = files.find(f => f.endsWith(file))
if (!matchingFile) {
console.log("Can't find file %s", file)
diff --git a/e2e/node/ts/build-esm.cjs b/e2e/node/ts/build-esm.cjs
index 64d189ef..4835ead5 100644
--- a/e2e/node/ts/build-esm.cjs
+++ b/e2e/node/ts/build-esm.cjs
@@ -1,6 +1,7 @@
-const fs = require('fs')
-const path = require('path')
-const cp = require('child_process')
+const fs = require('node:fs')
+const path = require('node:path')
+const cp = require('node:child_process')
+
const glob = require('glob')
function fixForEsm() {
diff --git a/e2e/node/ts/mocha.esm.json b/e2e/node/ts/mocha.esm.json
index 95448eb3..72a03424 100644
--- a/e2e/node/ts/mocha.esm.json
+++ b/e2e/node/ts/mocha.esm.json
@@ -1,3 +1,3 @@
{
- "node-option": ["experimental-specifier-resolution=node", "loader=ts-node/esm"]
+ "node-option": ["experimental-specifier-resolution=node", "loader=ts-node/esm"]
}
diff --git a/e2e/node/ts/package.json b/e2e/node/ts/package.json
index 0292b995..a3c15a7a 100644
--- a/e2e/node/ts/package.json
+++ b/e2e/node/ts/package.json
@@ -1 +1 @@
-{"type":"commonjs"}
\ No newline at end of file
+{ "type": "commonjs" }
diff --git a/e2e/node/ts/run-esm.cjs b/e2e/node/ts/run-esm.cjs
index c00361e1..1ef05b1c 100644
--- a/e2e/node/ts/run-esm.cjs
+++ b/e2e/node/ts/run-esm.cjs
@@ -1,4 +1,4 @@
-const cp = require('child_process')
+const cp = require('node:child_process')
const { fixForEsm } = require('./build-esm.cjs')
diff --git a/e2e/node/ts/tests/01.auth.ts b/e2e/node/ts/tests/01.auth.ts
index aef3419f..386fc9d0 100644
--- a/e2e/node/ts/tests/01.auth.ts
+++ b/e2e/node/ts/tests/01.auth.ts
@@ -1,15 +1,15 @@
import { expect } from 'chai'
import { describe, it } from 'mocha'
-
-import { tl, User } from '@mtcute/core'
+import { User, tl } from '@mtcute/core'
import { BaseTelegramClient, TelegramClient } from '@mtcute/core/client.js'
import { getApiParams } from '../utils.js'
-const getAccountId = () =>
- Math.floor(Math.random() * 10000)
+function getAccountId() {
+ return Math.floor(Math.random() * 10000)
.toString()
.padStart(4, '0')
+}
async function authorizeInDc(dc: number, base: BaseTelegramClient) {
const tg = new TelegramClient({ client: base })
@@ -61,7 +61,7 @@ async function authorizeInDc(dc: number, base: BaseTelegramClient) {
await tg.close()
- expect(user.isSelf).to.be.true
+ expect(user.isSelf).to.eq(true)
expect(user.phoneNumber).to.equal(phone)
break
}
diff --git a/e2e/node/ts/tests/02.methods.ts b/e2e/node/ts/tests/02.methods.ts
index 1ad7ec03..5f5ef74c 100644
--- a/e2e/node/ts/tests/02.methods.ts
+++ b/e2e/node/ts/tests/02.methods.ts
@@ -1,6 +1,5 @@
import { expect } from 'chai'
import { describe, it } from 'mocha'
-
import { MtPeerNotFoundError } from '@mtcute/core'
import { TelegramClient } from '@mtcute/core/client.js'
@@ -16,14 +15,14 @@ describe('2. calling methods', function () {
it('getUsers(@BotFather)', async () => {
const [user] = await tg.getUsers('botfather')
- expect(user?.isBot).to.be.true
+ expect(user?.isBot).to.eq(true)
expect(user?.displayName).to.equal('BotFather')
})
it('getUsers(@BotFather) - cached', async () => {
const [user] = await tg.getUsers('botfather')
- expect(user?.isBot).to.be.true
+ expect(user?.isBot).to.eq(true)
expect(user?.displayName).to.equal('BotFather')
})
@@ -53,7 +52,7 @@ describe('2. calling methods', function () {
const res = await tg.updateProfile({ bio })
const newSelf = await tg.getFullChat('self')
- expect(res.isSelf).to.be.true
+ expect(res.isSelf).to.eq(true)
expect(oldSelf.bio).to.not.equal(newSelf.bio)
expect(newSelf.bio).to.equal(bio)
})
diff --git a/e2e/node/ts/tests/03.files.ts b/e2e/node/ts/tests/03.files.ts
index bbfc00b5..84df8bd6 100644
--- a/e2e/node/ts/tests/03.files.ts
+++ b/e2e/node/ts/tests/03.files.ts
@@ -1,9 +1,9 @@
-/* eslint-disable no-restricted-imports */
-import { expect } from 'chai'
-import { createHash } from 'crypto'
-import { describe, it } from 'mocha'
+import { createHash } from 'node:crypto'
-import { FileDownloadLocation, Thumbnail } from '@mtcute/core'
+import { expect } from 'chai'
+import { describe, it } from 'mocha'
+import type { FileDownloadLocation } from '@mtcute/core'
+import { Thumbnail } from '@mtcute/core'
import { TelegramClient } from '@mtcute/core/client.js'
import { sleep } from '@mtcute/core/utils.js'
diff --git a/e2e/node/ts/tests/04.updates.ts b/e2e/node/ts/tests/04.updates.ts
index a6349b34..7bd50023 100644
--- a/e2e/node/ts/tests/04.updates.ts
+++ b/e2e/node/ts/tests/04.updates.ts
@@ -1,12 +1,11 @@
import { expect } from 'chai'
import { describe, it } from 'mocha'
-
-import { Message } from '@mtcute/core'
+import type { Message } from '@mtcute/core'
import { TelegramClient } from '@mtcute/core/client.js'
import { getApiParams, waitFor } from '../utils.js'
-describe('4. handling updates', async function () {
+describe('4. handling updates', function () {
this.timeout(300_000)
const tg1 = new TelegramClient(getApiParams('dc1.session'))
@@ -27,7 +26,7 @@ describe('4. handling updates', async function () {
it('should send and receive messages', async () => {
const tg1Messages: Message[] = []
- tg1.on('new_message', (msg) => tg1Messages.push(msg))
+ tg1.on('new_message', msg => tg1Messages.push(msg))
const [tg1User] = await tg1.getUsers('self')
let username = tg1User!.username
@@ -44,7 +43,8 @@ describe('4. handling updates', async function () {
expect(sentMsg.chat.id).to.equal(tg1User!.id)
await waitFor(() => {
- expect(tg1Messages.find((msg) => msg.text === messageText)).to.exist
+ // eslint-disable-next-line ts/no-unused-expressions
+ expect(tg1Messages.find(msg => msg.text === messageText)).to.exist
})
})
})
diff --git a/e2e/node/ts/tests/05.worker.ts b/e2e/node/ts/tests/05.worker.ts
index b00cd4f8..bdb3d91c 100644
--- a/e2e/node/ts/tests/05.worker.ts
+++ b/e2e/node/ts/tests/05.worker.ts
@@ -1,16 +1,17 @@
-/* eslint-disable no-restricted-imports */
+import path from 'node:path'
+import { Worker } from 'node:worker_threads'
+
import { expect } from 'chai'
import { describe, it } from 'mocha'
-import path from 'path'
-import { Worker } from 'worker_threads'
-
import { TelegramClient } from '@mtcute/core/client.js'
-import { Long, Message, TelegramWorkerPort, tl } from '@mtcute/node'
+import type { Message } from '@mtcute/node'
+import { Long, TelegramWorkerPort, tl } from '@mtcute/node'
import { getApiParams, waitFor } from '../utils.js'
+
import type { CustomMethods } from './_worker.js'
-describe('5. worker', async function () {
+describe('5. worker', function () {
this.timeout(300_000)
const worker = new Worker(path.resolve(__dirname, '_worker.js'))
@@ -20,7 +21,7 @@ describe('5. worker', async function () {
})
const portClient = new TelegramClient({ client: port })
- it('should make api calls', async function () {
+ it('should make api calls', async () => {
const res = await port.call({ _: 'help.getConfig' })
expect(res._).to.equal('config')
@@ -29,7 +30,7 @@ describe('5. worker', async function () {
expect(Long.isLong((premiumPromo.users[0] as tl.RawUser).accessHash)).to.equal(true)
})
- it('should call custom methods', async function () {
+ it('should call custom methods', async () => {
const hello = await port.invokeCustom('hello')
expect(hello).to.equal('world')
@@ -37,7 +38,7 @@ describe('5. worker', async function () {
expect(sum).to.equal(5)
})
- it('should throw errors', async function () {
+ it('should throw errors', async () => {
try {
await port.call({ _: 'test.useConfigSimple' })
throw new Error('should have thrown')
@@ -46,7 +47,7 @@ describe('5. worker', async function () {
}
})
- it('should receive updates', async function () {
+ it('should receive updates', async () => {
const client2 = new TelegramClient(getApiParams('dc2.session'))
try {
@@ -86,6 +87,6 @@ describe('5. worker', async function () {
this.afterAll(async () => {
await port.close()
- worker.terminate()
+ void worker.terminate()
})
})
diff --git a/e2e/node/ts/tests/_worker.ts b/e2e/node/ts/tests/_worker.ts
index 7b0f43f1..03ea259d 100644
--- a/e2e/node/ts/tests/_worker.ts
+++ b/e2e/node/ts/tests/_worker.ts
@@ -1,4 +1,4 @@
-import { WorkerCustomMethods } from '@mtcute/core/worker.js'
+import type { WorkerCustomMethods } from '@mtcute/core/worker.js'
import { BaseTelegramClient, TelegramWorker } from '@mtcute/node'
import { getApiParams } from '../utils.js'
diff --git a/e2e/node/ts/tests/packaging/base-client.ts b/e2e/node/ts/tests/packaging/base-client.ts
index 665cbcef..a6d300f1 100644
--- a/e2e/node/ts/tests/packaging/base-client.ts
+++ b/e2e/node/ts/tests/packaging/base-client.ts
@@ -1,6 +1,5 @@
import { expect } from 'chai'
import { describe, it } from 'mocha'
-
import { BaseTelegramClient } from '@mtcute/core/client.js'
// @fix-import
diff --git a/e2e/node/ts/tests/packaging/tl-schema.ts b/e2e/node/ts/tests/packaging/tl-schema.ts
index 241fe134..529fa04b 100644
--- a/e2e/node/ts/tests/packaging/tl-schema.ts
+++ b/e2e/node/ts/tests/packaging/tl-schema.ts
@@ -1,7 +1,6 @@
import { expect } from 'chai'
import Long from 'long'
import { describe, it } from 'mocha'
-
import { setPlatform } from '@mtcute/core/platform.js'
import { NodePlatform } from '@mtcute/node'
import { tl } from '@mtcute/tl'
@@ -29,16 +28,14 @@ describe('@mtcute/tl', () => {
it('readers map works with TlBinaryReader', () => {
const buf = p.hexDecode('4ca5e8dd7b00000000000000c801000000000000')
- // eslint-disable-next-line
const obj = TlBinaryReader.deserializeObject(__tlReaderMap, buf)
expect(obj._).equal('inputPeerUser')
expect(obj.userId).equal(123)
- // eslint-disable-next-line
expect(obj.accessHash.toString()).equal('456')
})
it('correctly checks for combinator types', () => {
- expect(tl.isAnyInputUser({ _: 'inputUserEmpty' })).to.be.true
+ expect(tl.isAnyInputUser({ _: 'inputUserEmpty' })).to.eq(true)
})
})
diff --git a/e2e/node/ts/tests/packaging/wasm.ts b/e2e/node/ts/tests/packaging/wasm.ts
index 27291ffa..1de0b398 100644
--- a/e2e/node/ts/tests/packaging/wasm.ts
+++ b/e2e/node/ts/tests/packaging/wasm.ts
@@ -1,6 +1,5 @@
import { expect } from 'chai'
import { before, describe, it } from 'mocha'
-
import { NodeCryptoProvider } from '@mtcute/node/utils.js'
import { ige256Decrypt, ige256Encrypt } from '@mtcute/wasm'
diff --git a/e2e/node/ts/tsconfig.json b/e2e/node/ts/tsconfig.json
index deed9d5a..2cbc7b39 100644
--- a/e2e/node/ts/tsconfig.json
+++ b/e2e/node/ts/tsconfig.json
@@ -1,28 +1,28 @@
{
- "compilerOptions": {
- "outDir": "./dist",
- "module": "NodeNext",
- "moduleResolution": "NodeNext",
- "target": "es2020",
- "allowJs": true,
- "sourceMap": true,
- "inlineSources": true,
- "declaration": true,
- "esModuleInterop": true,
- "allowSyntheticDefaultImports": true,
- "strict": true,
- "noImplicitAny": true,
- "noImplicitThis": true,
- "incremental": true,
- "stripInternal": true,
- "skipLibCheck": true,
- "rootDir": "."
- },
- "exclude": [
- "**/node_modules",
- ],
- "include": [
- "./tests",
- "./utils.ts"
- ]
+ "compilerOptions": {
+ "incremental": true,
+ "target": "es2020",
+ "rootDir": ".",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "allowJs": true,
+ "strict": true,
+ "noImplicitAny": true,
+ "noImplicitThis": true,
+ "declaration": true,
+ "inlineSources": true,
+ "outDir": "./dist",
+ "sourceMap": true,
+ "stripInternal": true,
+ "allowSyntheticDefaultImports": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true
+ },
+ "include": [
+ "./tests",
+ "./utils.ts"
+ ],
+ "exclude": [
+ "**/node_modules"
+ ]
}
diff --git a/e2e/node/ts/utils.ts b/e2e/node/ts/utils.ts
index c39fa786..35472042 100644
--- a/e2e/node/ts/utils.ts
+++ b/e2e/node/ts/utils.ts
@@ -1,13 +1,13 @@
-// eslint-disable-next-line no-restricted-imports
-import { join } from 'path'
+import { join } from 'node:path'
-import { MaybePromise, MemoryStorage } from '@mtcute/core'
+import type { MaybePromise } from '@mtcute/core'
+import { MemoryStorage } from '@mtcute/core'
import { setPlatform } from '@mtcute/core/platform.js'
import { LogManager, sleep } from '@mtcute/core/utils.js'
import { NodePlatform, SqliteStorage, TcpTransport } from '@mtcute/node'
import { NodeCryptoProvider } from '@mtcute/node/utils.js'
-export const getApiParams = (storage?: string) => {
+export function getApiParams(storage?: string) {
if (!process.env.API_ID || !process.env.API_HASH) {
throw new Error('API_ID and API_HASH env variables must be set')
}
@@ -15,7 +15,7 @@ export const getApiParams = (storage?: string) => {
setPlatform(new NodePlatform())
return {
- apiId: parseInt(process.env.API_ID),
+ apiId: Number.parseInt(process.env.API_ID),
apiHash: process.env.API_HASH,
testMode: true,
storage: storage ? new SqliteStorage(join(__dirname, storage)) : new MemoryStorage(),
diff --git a/eslint.config.js b/eslint.config.js
new file mode 100644
index 00000000..efb0b8de
--- /dev/null
+++ b/eslint.config.js
@@ -0,0 +1,126 @@
+import antfu from '@antfu/eslint-config'
+
+export default antfu({
+ type: 'lib',
+ typescript: process.env.CI
+ ? {
+ tsconfigPath: 'tsconfig.json',
+ ignoresTypeAware: [
+ '.config/**/*',
+ 'e2e/**',
+ ],
+ overrides: {
+ 'ts/consistent-type-imports': 'off',
+ },
+ }
+ : true,
+ yaml: false,
+ markdown: false,
+ linterOptions: {
+ reportUnusedDisableDirectives: Boolean(process.env.CI),
+ },
+ rules: {
+ 'style/indent': ['error', 4, {
+ offsetTernaryExpressions: false,
+ // the rest is from default config: https://github.com/eslint-stylistic/eslint-stylistic/blob/main/packages/eslint-plugin/configs/customize.ts
+ ArrayExpression: 1,
+ CallExpression: { arguments: 1 },
+ flatTernaryExpressions: false,
+ FunctionDeclaration: { body: 1, parameters: 1 },
+ FunctionExpression: { body: 1, parameters: 1 },
+ ignoreComments: false,
+ ignoredNodes: [
+ 'TemplateLiteral *',
+ 'TSUnionType',
+ 'TSIntersectionType',
+ 'TSTypeParameterInstantiation',
+ 'FunctionExpression > .params[decorators.length > 0]',
+ 'FunctionExpression > .params > :matches(Decorator, :not(:first-child))',
+ ],
+ ImportDeclaration: 1,
+ MemberExpression: 1,
+ ObjectExpression: 1,
+ outerIIFEBody: 1,
+ SwitchCase: 1,
+ VariableDeclarator: 1,
+ }],
+ 'style/max-len': ['error', {
+ code: 120,
+ ignoreComments: true,
+ ignoreStrings: true,
+ ignoreTemplateLiterals: true,
+ }],
+ 'curly': ['error', 'multi-line'],
+ 'style/brace-style': ['error', '1tbs', { allowSingleLine: true }],
+ 'node/prefer-global/process': ['error', 'always'],
+ 'node/prefer-global/buffer': ['error', 'always'],
+ 'no-restricted-globals': ['error', 'Buffer', '__dirname', 'require'],
+ 'style/quotes': ['error', 'single', { avoidEscape: true }],
+ 'test/consistent-test-it': 'off',
+ 'test/prefer-lowercase-title': 'off',
+ 'test/no-identical-title': 'off',
+ 'import/order': ['error', { 'newlines-between': 'always' }],
+ 'antfu/if-newline': 'off',
+ 'import/no-relative-packages': 'error',
+ 'style/max-statements-per-line': ['error', { max: 2 }],
+ 'ts/no-redeclare': 'off',
+ 'eslint-comments/no-unlimited-disable': 'off',
+ 'no-cond-assign': 'off',
+ 'ts/explicit-function-return-type': 'off',
+ 'no-labels': 'off',
+ 'no-restricted-syntax': 'off',
+ 'unicorn/no-new-array': 'off',
+ 'jsdoc/check-param-names': 'off', // todo: will fix in another iteration
+ 'jsdoc/require-returns-description': 'off', // todo: will fix in another iteration
+ 'ts/no-unsafe-member-access': 'off',
+ 'ts/no-dynamic-delete': 'off',
+ 'ts/strict-boolean-expressions': 'off',
+ 'ts/unbound-method': 'off',
+ 'ts/no-invalid-void-type': 'off',
+ 'ts/no-unsafe-enum-comparison': 'off',
+ 'ts/promise-function-async': 'off',
+ 'dot-notation': 'off',
+ 'ts/dot-notation': 'off',
+ 'ts/switch-exhaustiveness-check': 'off',
+ 'ts/restrict-template-expressions': 'off',
+ 'ts/method-signature-style': 'off',
+ },
+}, {
+ ignores: [
+ // codegen
+ 'packages/tl/binary/rsa-keys.js',
+ 'packages/tl/binary/reader.js',
+ 'packages/tl/binary/writer.js',
+ 'packages/tl/index.js',
+ 'packages/tl/index.d.ts',
+ 'packages/tl/*.json',
+ 'packages/core/utils.ts',
+ 'e2e/deno/.jsr-data',
+ 'e2e/node/.verdaccio',
+ ],
+}, {
+ files: ['e2e/**', 'packages/node/**', 'packages/bun/**'],
+ rules: {
+ 'no-restricted-globals': 'off',
+ },
+}, {
+ files: ['packages/bun/**', 'packages/deno/**'],
+ rules: {
+ 'no-restricted-imports': 'off',
+ 'import/no-relative-packages': 'off', // common-internals is symlinked from node
+ },
+}, {
+ files: ['**/scripts/**', '**/*.cjs'],
+ rules: {
+ 'no-restricted-imports': 'off',
+ 'no-restricted-globals': 'off',
+ 'no-console': 'off',
+ },
+}, {
+ files: ['packages/create-*/**', 'packages/deno/**'],
+ rules: {
+ 'node/prefer-global/process': ['error', 'never'],
+ 'node/prefer-global/buffer': ['error', 'never'],
+ 'no-console': 'off',
+ },
+})
diff --git a/package.json b/package.json
index f58f944f..b6430160 100644
--- a/package.json
+++ b/package.json
@@ -1,87 +1,75 @@
{
- "name": "mtcute-workspace",
- "private": true,
- "version": "0.16.6",
- "description": "Type-safe library for MTProto (Telegram API) for browser and NodeJS",
- "license": "MIT",
- "author": "alina sireneva ",
- "keywords": [
- "telegram",
- "telegram-api",
- "telegram-bot",
- "telegram-library",
- "mtproto",
- "tgbot",
- "userbot",
- "api"
- ],
- "repository": {
- "type": "git",
- "url": "https://github.com/mtcute/mtcute"
- },
- "homepage": "https://mtcute.dev",
- "workspaces": [
- "packages/*"
- ],
- "scripts": {
- "postinstall": "node scripts/validate-deps-versions.mjs && node scripts/remove-jsr-sourcefiles.mjs",
- "test": "pnpm run -r test && vitest --config .config/vite.mts run",
- "test:dev": "vitest --config .config/vite.mts watch",
- "test:ui": "vitest --config .config/vite.mts --ui",
- "test:coverage": "vitest --config .config/vite.mts run --coverage",
- "test:ci": "vitest --config .config/vite.mts run --coverage.enabled --coverage.reporter=json",
- "test:browser": "vitest --config .config/vite.browser.mts run",
- "test:browser:dev": "vitest --config .config/vite.browser.mts watch",
- "lint": "eslint .",
- "lint:ci": "NODE_OPTIONS=\\\"--max_old_space_size=8192\\\" eslint --config .config/eslint.ci.js .",
- "lint:tsc": "rimraf packages/**/dist && pnpm -r --workspace-concurrency=4 exec tsc --build",
- "lint:tsc:ci": "pnpm -r exec tsc --build",
- "lint:dpdm": "dpdm -T --no-warning --no-tree --exit-code circular:1 packages/*",
- "lint:fix": "eslint --fix .",
- "format": "prettier --write \"packages/**/*.ts\"",
- "publish-all": "node scripts/publish.js all",
- "docs": "typedoc --options .config/typedoc/config.cjs",
- "build-package": "node scripts/build-package.js"
- },
- "devDependencies": {
- "@teidesu/slow-types-compiler": "1.1.0",
- "@types/node": "20.10.0",
- "@types/deno": "npm:@teidesu/deno-types@1.43.1",
- "@types/ws": "8.5.4",
- "@typescript-eslint/eslint-plugin": "6.4.0",
- "@typescript-eslint/parser": "6.4.0",
- "@vitest/browser": "1.4.0",
- "@vitest/coverage-v8": "1.4.0",
- "@vitest/expect": "1.4.0",
- "@vitest/spy": "1.4.0",
- "@vitest/ui": "1.4.0",
- "chai": "5.1.0",
- "cjs-module-lexer": "1.2.3",
- "dotenv-flow": "3.2.0",
- "dpdm": "3.14.0",
- "esbuild": "0.18.20",
- "eslint": "8.47.0",
- "eslint-config-prettier": "8.8.0",
- "eslint-import-resolver-typescript": "3.6.0",
- "eslint-plugin-ascii": "1.0.0",
- "eslint-plugin-import": "2.28.0",
- "eslint-plugin-simple-import-sort": "10.0.0",
- "glob": "10.2.6",
- "playwright": "1.42.1",
- "prettier": "3.0.3",
- "rimraf": "5.0.1",
- "semver": "7.5.1",
- "ts-node": "10.9.1",
- "tsconfig-paths": "4.2.0",
- "typedoc": "0.25.12",
- "typescript": "5.4.3",
- "vite": "5.1.6",
- "vite-plugin-node-polyfills": "0.21.0",
- "vitest": "1.4.0"
- },
- "packageManager": "pnpm@9.0.6",
- "prettier": "./.config/prettier.cjs",
- "eslintConfig": {
- "extends": "./.config/eslint.cjs"
- }
+ "name": "mtcute-workspace",
+ "type": "module",
+ "version": "0.16.6",
+ "private": true,
+ "packageManager": "pnpm@9.0.6",
+ "description": "Type-safe library for MTProto (Telegram API) for browser and NodeJS",
+ "author": "alina sireneva ",
+ "license": "MIT",
+ "homepage": "https://mtcute.dev",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/mtcute/mtcute"
+ },
+ "keywords": [
+ "telegram",
+ "telegram-api",
+ "telegram-bot",
+ "telegram-library",
+ "mtproto",
+ "tgbot",
+ "userbot",
+ "api"
+ ],
+ "workspaces": [
+ "packages/*"
+ ],
+ "scripts": {
+ "postinstall": "node scripts/validate-deps-versions.js && node scripts/remove-jsr-sourcefiles.js",
+ "test": "pnpm run -r test && vitest --config .config/vite.ts run",
+ "test:dev": "vitest --config .config/vite.ts watch",
+ "test:ui": "vitest --config .config/vite.ts --ui",
+ "test:coverage": "vitest --config .config/vite.ts run --coverage",
+ "test:ci": "vitest --config .config/vite.ts run --coverage.enabled --coverage.reporter=json",
+ "test:browser": "vitest --config .config/vite.browser.ts run",
+ "test:browser:dev": "vitest --config .config/vite.browser.ts watch",
+ "lint": "eslint",
+ "lint:ci": "CI=1 NODE_OPTIONS=\\\"--max_old_space_size=8192\\\" eslint",
+ "lint:tsc": "rimraf packages/**/dist packages/**/*.tsbuildinfo && pnpm -r --workspace-concurrency=4 exec tsc --build",
+ "lint:tsc:ci": "pnpm -r exec tsc --build",
+ "lint:dpdm": "dpdm -T --no-warning --no-tree --exit-code circular:1 packages/*",
+ "lint:fix": "eslint --fix .",
+ "publish-all": "node scripts/publish.js all",
+ "docs": "typedoc --options .config/typedoc/config.cjs",
+ "build-package": "node scripts/build-package.js"
+ },
+ "devDependencies": {
+ "@antfu/eslint-config": "2.26.0",
+ "@teidesu/slow-types-compiler": "1.1.0",
+ "@types/deno": "npm:@teidesu/deno-types@1.45.5",
+ "@types/node": "20.10.0",
+ "@types/ws": "8.5.4",
+ "@vitest/browser": "2.0.5",
+ "@vitest/coverage-v8": "2.0.5",
+ "@vitest/expect": "2.0.5",
+ "@vitest/spy": "2.0.5",
+ "@vitest/ui": "2.0.5",
+ "chai": "5.1.0",
+ "cjs-module-lexer": "1.2.3",
+ "dotenv-flow": "4.1.0",
+ "dpdm": "3.14.0",
+ "esbuild": "0.23.0",
+ "eslint": "9.9.0",
+ "glob": "11.0.0",
+ "playwright": "1.42.1",
+ "rimraf": "6.0.1",
+ "semver": "7.5.1",
+ "tsx": "4.17.0",
+ "typedoc": "0.26.5",
+ "typescript": "5.5.4",
+ "vite": "5.1.6",
+ "vite-plugin-node-polyfills": "0.22.0",
+ "vitest": "2.0.5"
+ }
}
diff --git a/packages/bun/package.json b/packages/bun/package.json
index af2a7a8f..f98784a0 100644
--- a/packages/bun/package.json
+++ b/packages/bun/package.json
@@ -1,29 +1,29 @@
{
- "name": "@mtcute/bun",
- "private": true,
- "version": "0.16.6",
- "description": "Meta-package for Bun",
- "author": "alina sireneva ",
- "license": "MIT",
- "type": "module",
- "sideEffects": false,
- "scripts": {
- "docs": "typedoc",
- "build": "pnpm run -w build-package bun"
- },
- "exports": {
- ".": "./src/index.ts",
- "./utils.js": "./src/utils.ts",
- "./methods.js": "./src/methods.ts"
- },
- "dependencies": {
- "@mtcute/core": "workspace:^",
- "@mtcute/wasm": "workspace:^",
- "@mtcute/markdown-parser": "workspace:^",
- "@mtcute/html-parser": "workspace:^"
- },
- "devDependencies": {
- "@mtcute/test": "workspace:^",
- "bun-types": "1.0.33"
- }
+ "name": "@mtcute/bun",
+ "type": "module",
+ "version": "0.16.6",
+ "private": true,
+ "description": "Meta-package for Bun",
+ "author": "alina sireneva ",
+ "license": "MIT",
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts",
+ "./utils.js": "./src/utils.ts",
+ "./methods.js": "./src/methods.ts"
+ },
+ "scripts": {
+ "docs": "typedoc",
+ "build": "pnpm run -w build-package bun"
+ },
+ "dependencies": {
+ "@mtcute/core": "workspace:^",
+ "@mtcute/html-parser": "workspace:^",
+ "@mtcute/markdown-parser": "workspace:^",
+ "@mtcute/wasm": "workspace:^"
+ },
+ "devDependencies": {
+ "@mtcute/test": "workspace:^",
+ "bun-types": "1.0.33"
+ }
}
diff --git a/packages/bun/src/client.ts b/packages/bun/src/client.ts
index 3baa53e3..2349b5f7 100644
--- a/packages/bun/src/client.ts
+++ b/packages/bun/src/client.ts
@@ -1,11 +1,15 @@
-import { createInterface, Interface as RlInterface } from 'readline'
+import type { Interface as RlInterface } from 'node:readline'
+import { createInterface } from 'node:readline'
+import type { Readable } from 'node:stream'
-import { FileDownloadLocation, FileDownloadParameters, ITelegramStorageProvider, PartialOnly, User } from '@mtcute/core'
+import type { FileDownloadLocation, FileDownloadParameters, ITelegramStorageProvider, PartialOnly, User } from '@mtcute/core'
+import type {
+ BaseTelegramClientOptions as BaseTelegramClientOptionsBase,
+ TelegramClientOptions,
+} from '@mtcute/core/client.js'
import {
BaseTelegramClient as BaseTelegramClientBase,
- BaseTelegramClientOptions as BaseTelegramClientOptionsBase,
TelegramClient as TelegramClientBase,
- TelegramClientOptions,
} from '@mtcute/core/client.js'
import { setPlatform } from '@mtcute/core/platform.js'
@@ -48,9 +52,9 @@ export class BaseTelegramClient extends BaseTelegramClientBase {
transport: () => new TcpTransport(),
...opts,
storage:
- typeof opts.storage === 'string' ?
- new SqliteStorage(opts.storage) :
- opts.storage ?? new SqliteStorage('client.session'),
+ typeof opts.storage === 'string'
+ ? new SqliteStorage(opts.storage)
+ : opts.storage ?? new SqliteStorage('client.session'),
})
}
}
@@ -91,7 +95,7 @@ export class TelegramClient extends TelegramClientBase {
})
}
- return new Promise((res) => this._rl?.question(text, res))
+ return new Promise(res => this._rl?.question(text, res))
}
close(): Promise {
@@ -131,7 +135,7 @@ export class TelegramClient extends TelegramClientBase {
this.start(params)
.then(then)
- .catch((err) => this.emitError(err))
+ .catch(err => this.emitError(err))
}
downloadToFile(
@@ -142,7 +146,7 @@ export class TelegramClient extends TelegramClientBase {
return downloadToFile(this, filename, location, params)
}
- downloadAsNodeStream(location: FileDownloadLocation, params?: FileDownloadParameters | undefined) {
+ downloadAsNodeStream(location: FileDownloadLocation, params?: FileDownloadParameters | undefined): Readable {
return downloadAsNodeStream(this, location, params)
}
}
diff --git a/packages/bun/src/methods/download-file.ts b/packages/bun/src/methods/download-file.ts
index f847b361..68523f16 100644
--- a/packages/bun/src/methods/download-file.ts
+++ b/packages/bun/src/methods/download-file.ts
@@ -1,6 +1,7 @@
import { unlinkSync } from 'node:fs'
-import { FileDownloadLocation, FileDownloadParameters, FileLocation, ITelegramClient } from '@mtcute/core'
+import type { FileDownloadLocation, FileDownloadParameters, ITelegramClient } from '@mtcute/core'
+import { FileLocation } from '@mtcute/core'
import { downloadAsIterable } from '@mtcute/core/methods.js'
/**
diff --git a/packages/bun/src/methods/download-node-stream.ts b/packages/bun/src/methods/download-node-stream.ts
index fa9874cd..5187640a 100644
--- a/packages/bun/src/methods/download-node-stream.ts
+++ b/packages/bun/src/methods/download-node-stream.ts
@@ -1,6 +1,6 @@
-import { Readable } from 'stream'
+import { Readable } from 'node:stream'
-import { FileDownloadLocation, FileDownloadParameters, ITelegramClient } from '@mtcute/core'
+import type { FileDownloadLocation, FileDownloadParameters, ITelegramClient } from '@mtcute/core'
import { downloadAsStream } from '@mtcute/core/methods.js'
/**
diff --git a/packages/bun/src/platform.ts b/packages/bun/src/platform.ts
index 39f8c937..60ff10ce 100644
--- a/packages/bun/src/platform.ts
+++ b/packages/bun/src/platform.ts
@@ -1,4 +1,4 @@
-import * as os from 'os'
+import * as os from 'node:os'
import { NodePlatform } from './common-internals-node/platform.js'
import { normalizeFile } from './utils/normalize-file.js'
diff --git a/packages/bun/src/sqlite/driver.ts b/packages/bun/src/sqlite/driver.ts
index 362e5f97..a9ce5c78 100644
--- a/packages/bun/src/sqlite/driver.ts
+++ b/packages/bun/src/sqlite/driver.ts
@@ -1,6 +1,6 @@
import { Database } from 'bun:sqlite'
-
-import { BaseSqliteStorageDriver, ISqliteDatabase } from '@mtcute/core'
+import type { ISqliteDatabase } from '@mtcute/core'
+import { BaseSqliteStorageDriver } from '@mtcute/core'
export interface SqliteStorageDriverOptions {
/**
@@ -19,7 +19,7 @@ export interface SqliteStorageDriverOptions {
export class SqliteStorageDriver extends BaseSqliteStorageDriver {
constructor(
readonly filename = ':memory:',
- readonly params?: SqliteStorageDriverOptions,
+ readonly params?: SqliteStorageDriverOptions | undefined,
) {
super()
}
diff --git a/packages/bun/src/sqlite/index.ts b/packages/bun/src/sqlite/index.ts
index 882b228d..f4fbb33c 100644
--- a/packages/bun/src/sqlite/index.ts
+++ b/packages/bun/src/sqlite/index.ts
@@ -1,13 +1,14 @@
import { BaseSqliteStorage } from '@mtcute/core'
-import { SqliteStorageDriver, SqliteStorageDriverOptions } from './driver.js'
+import type { SqliteStorageDriverOptions } from './driver.js'
+import { SqliteStorageDriver } from './driver.js'
export { SqliteStorageDriver } from './driver.js'
export class SqliteStorage extends BaseSqliteStorage {
constructor(
readonly filename = ':memory:',
- readonly params?: SqliteStorageDriverOptions,
+ readonly params?: SqliteStorageDriverOptions | undefined,
) {
super(new SqliteStorageDriver(filename, params))
}
diff --git a/packages/bun/src/sqlite/sqlite.test.ts b/packages/bun/src/sqlite/sqlite.test.ts
index 6810d931..bc6504a8 100644
--- a/packages/bun/src/sqlite/sqlite.test.ts
+++ b/packages/bun/src/sqlite/sqlite.test.ts
@@ -1,5 +1,4 @@
import { afterAll, beforeAll, describe } from 'vitest'
-
import { LogManager } from '@mtcute/core/utils.js'
import {
testAuthKeysRepository,
diff --git a/packages/bun/src/utils/crypto.test.ts b/packages/bun/src/utils/crypto.test.ts
index 17292c91..5bb77b50 100644
--- a/packages/bun/src/utils/crypto.test.ts
+++ b/packages/bun/src/utils/crypto.test.ts
@@ -1,5 +1,4 @@
import { describe } from 'vitest'
-
import { testCryptoProvider } from '@mtcute/test'
if (import.meta.env.TEST_ENV === 'bun') {
diff --git a/packages/bun/src/utils/crypto.ts b/packages/bun/src/utils/crypto.ts
index 02840d3f..7c79a07b 100644
--- a/packages/bun/src/utils/crypto.ts
+++ b/packages/bun/src/utils/crypto.ts
@@ -1,7 +1,7 @@
-// eslint-disable-next-line no-restricted-imports
-import { readFile } from 'fs/promises'
+import { readFile } from 'node:fs/promises'
-import { BaseCryptoProvider, IAesCtr, ICryptoProvider, IEncryptionScheme } from '@mtcute/core/utils.js'
+import type { IAesCtr, ICryptoProvider, IEncryptionScheme } from '@mtcute/core/utils.js'
+import { BaseCryptoProvider } from '@mtcute/core/utils.js'
import {
createCtr256,
ctr256,
@@ -28,7 +28,6 @@ const ALGO_TO_SUBTLE: Record = {
export class BunCryptoProvider extends BaseCryptoProvider implements ICryptoProvider {
async initialize(): Promise {
- // eslint-disable-next-line no-restricted-globals
const wasmFile = require.resolve('@mtcute/wasm/mtcute.wasm')
const wasm = await readFile(wasmFile)
initSync(wasm)
@@ -49,7 +48,7 @@ export class BunCryptoProvider extends BaseCryptoProvider implements ICryptoProv
const ctx = createCtr256(key, iv)
return {
- process: (data) => ctr256(ctx, data),
+ process: data => ctr256(ctx, data),
close: () => freeCtr256(ctx),
}
}
@@ -74,7 +73,7 @@ export class BunCryptoProvider extends BaseCryptoProvider implements ICryptoProv
keyMaterial,
(keylen || 64) * 8,
)
- .then((result) => new Uint8Array(result))
+ .then(result => new Uint8Array(result))
}
sha1(data: Uint8Array): Uint8Array {
@@ -113,7 +112,7 @@ export class BunCryptoProvider extends BaseCryptoProvider implements ICryptoProv
return gunzip(data)
}
- randomFill(buf: Uint8Array) {
+ randomFill(buf: Uint8Array): void {
crypto.getRandomValues(buf)
}
}
diff --git a/packages/bun/src/utils/normalize-file.ts b/packages/bun/src/utils/normalize-file.ts
index 49b00f75..540b6c15 100644
--- a/packages/bun/src/utils/normalize-file.ts
+++ b/packages/bun/src/utils/normalize-file.ts
@@ -1,24 +1,28 @@
-import { BunFile } from 'bun'
-import { ReadStream } from 'fs'
-import { stat } from 'fs/promises'
-import { basename } from 'path'
-import { Readable as NodeReadable } from 'stream'
+import { ReadStream } from 'node:fs'
+import { stat } from 'node:fs/promises'
+import { basename } from 'node:path'
+import { Readable as NodeReadable } from 'node:stream'
-import { UploadFileLike } from '@mtcute/core'
+import type { BunFile } from 'bun'
+import type { UploadFileLike } from '@mtcute/core'
// https://github.com/oven-sh/bun/issues/10481
function isBunFile(file: unknown): file is BunFile {
return file instanceof Blob && 'name' in file && file.name.length > 0
}
-export async function normalizeFile(file: UploadFileLike) {
+export async function normalizeFile(file: UploadFileLike): Promise<{
+ file: UploadFileLike
+ fileName?: string | undefined
+ fileSize?: number
+} | null> {
if (typeof file === 'string') {
file = Bun.file(file)
}
if (isBunFile(file)) {
return {
- file: file,
+ file,
fileName: file.name,
fileSize: file.size,
}
@@ -27,7 +31,7 @@ export async function normalizeFile(file: UploadFileLike) {
// while these are not Bun-specific, they still may happen
if (file instanceof ReadStream) {
const fileName = basename(file.path.toString())
- const fileSize = await stat(file.path.toString()).then((stat) => stat.size)
+ const fileSize = await stat(file.path.toString()).then(stat => stat.size)
return {
file: NodeReadable.toWeb(file) as unknown as ReadableStream,
diff --git a/packages/bun/src/utils/tcp.ts b/packages/bun/src/utils/tcp.ts
index e8141d8b..c0a6f6cd 100644
--- a/packages/bun/src/utils/tcp.ts
+++ b/packages/bun/src/utils/tcp.ts
@@ -1,8 +1,9 @@
-import { Socket } from 'bun'
-import EventEmitter from 'events'
+import EventEmitter from 'node:events'
-import { IntermediatePacketCodec, IPacketCodec, ITelegramTransport, MtcuteError, TransportState } from '@mtcute/core'
-import { BasicDcOption, ICryptoProvider, Logger } from '@mtcute/core/utils.js'
+import type { Socket } from 'bun'
+import type { IPacketCodec, ITelegramTransport } from '@mtcute/core'
+import { IntermediatePacketCodec, MtcuteError, TransportState } from '@mtcute/core'
+import type { BasicDcOption, ICryptoProvider, Logger } from '@mtcute/core/utils.js'
/**
* Base for TCP transports.
@@ -41,7 +42,7 @@ export abstract class BaseTcpTransport extends EventEmitter implements ITelegram
return this._currentDc
}
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ // eslint-disable-next-line unused-imports/no-unused-vars
connect(dc: BasicDcOption, testMode: boolean): void {
if (this._state !== TransportState.Idle) {
throw new MtcuteError('Transport is not IDLE')
@@ -49,8 +50,8 @@ export abstract class BaseTcpTransport extends EventEmitter implements ITelegram
if (!this.packetCodecInitialized) {
this._packetCodec.setup?.(this._crypto, this.log)
- this._packetCodec.on('error', (err) => this.emit('error', err))
- this._packetCodec.on('packet', (buf) => this.emit('message', buf))
+ this._packetCodec.on('error', err => this.emit('error', err))
+ this._packetCodec.on('packet', buf => this.emit('message', buf))
this.packetCodecInitialized = true
}
@@ -148,5 +149,5 @@ export abstract class BaseTcpTransport extends EventEmitter implements ITelegram
}
export class TcpTransport extends BaseTcpTransport {
- _packetCodec = new IntermediatePacketCodec()
+ _packetCodec: IntermediatePacketCodec = new IntermediatePacketCodec()
}
diff --git a/packages/bun/src/worker.ts b/packages/bun/src/worker.ts
index 877db612..477e87e0 100644
--- a/packages/bun/src/worker.ts
+++ b/packages/bun/src/worker.ts
@@ -1,18 +1,20 @@
-import { parentPort, Worker } from 'worker_threads'
+import { Worker, parentPort } from 'node:worker_threads'
import { setPlatform } from '@mtcute/core/platform.js'
-import {
+import type {
ClientMessageHandler,
RespondFn,
SendFn,
SomeWorker,
- TelegramWorker as TelegramWorkerBase,
TelegramWorkerOptions,
- TelegramWorkerPort as TelegramWorkerPortBase,
TelegramWorkerPortOptions,
WorkerCustomMethods,
WorkerMessageHandler,
} from '@mtcute/core/worker.js'
+import {
+ TelegramWorker as TelegramWorkerBase,
+ TelegramWorkerPort as TelegramWorkerPortBase,
+} from '@mtcute/core/worker.js'
import { BunPlatform } from './platform.js'
@@ -35,8 +37,8 @@ export class TelegramWorker extends TelegramWorke
const respond: RespondFn = port.postMessage.bind(port)
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
- parentPort.on('message', (message) => handler(message, respond))
+ // eslint-disable-next-line ts/no-unsafe-argument
+ parentPort.on('message', message => handler(message, respond))
return respond
}
@@ -50,7 +52,7 @@ export class TelegramWorkerPort extends TelegramW
connectToWorker(worker: SomeWorker, handler: ClientMessageHandler): [SendFn, () => void] {
if (!(worker instanceof Worker)) {
- throw new Error('Only worker_threads are supported')
+ throw new TypeError('Only worker_threads are supported')
}
const send: SendFn = worker.postMessage.bind(worker)
diff --git a/packages/bun/tsconfig.json b/packages/bun/tsconfig.json
index 9d487df1..30689cd4 100644
--- a/packages/bun/tsconfig.json
+++ b/packages/bun/tsconfig.json
@@ -1,20 +1,20 @@
{
- "extends": "../../tsconfig.json",
- "compilerOptions": {
- "outDir": "./dist",
- "rootDir": "./src",
- "types": [
- "bun-types",
- "vite/client"
- ]
- },
- "include": [
- "./src",
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "rootDir": "./src",
+ "types": [
+ "bun-types",
+ "vite/client"
],
- "references": [
- { "path": "../core" },
- { "path": "../dispatcher" },
- { "path": "../html-parser" },
- { "path": "../markdown-parser" }
- ]
+ "outDir": "./dist"
+ },
+ "references": [
+ { "path": "../core" },
+ { "path": "../dispatcher" },
+ { "path": "../html-parser" },
+ { "path": "../markdown-parser" }
+ ],
+ "include": [
+ "./src"
+ ]
}
diff --git a/packages/convert/README.md b/packages/convert/README.md
index 58360337..f9b580fd 100644
--- a/packages/convert/README.md
+++ b/packages/convert/README.md
@@ -8,7 +8,7 @@ Currently only the libraries that support exporting sessions to strings are supp
## [Telethon](https://github.com/LonamiWebs/Telethon)
-> Telethon v2 seems to have removed the ability to export sessions,
+> Telethon v2 seems to have removed the ability to export sessions,
> so it's currently not supported
```ts
diff --git a/packages/convert/package.json b/packages/convert/package.json
index 44096fea..92402ee6 100644
--- a/packages/convert/package.json
+++ b/packages/convert/package.json
@@ -1,20 +1,20 @@
{
- "name": "@mtcute/convert",
- "private": true,
- "version": "0.16.0",
- "description": "Cross-library session conversion utilities",
- "author": "alina sireneva ",
- "license": "MIT",
- "type": "module",
- "sideEffects": false,
- "scripts": {
- "build": "pnpm run -w build-package convert"
- },
- "exports": "./src/index.ts",
- "dependencies": {
- "@mtcute/core": "workspace:^"
- },
- "devDependencies": {
- "@mtcute/test": "workspace:^"
- }
+ "name": "@mtcute/convert",
+ "type": "module",
+ "version": "0.16.0",
+ "private": true,
+ "description": "Cross-library session conversion utilities",
+ "author": "alina sireneva ",
+ "license": "MIT",
+ "sideEffects": false,
+ "exports": "./src/index.ts",
+ "scripts": {
+ "build": "pnpm run -w build-package convert"
+ },
+ "dependencies": {
+ "@mtcute/core": "workspace:^"
+ },
+ "devDependencies": {
+ "@mtcute/test": "workspace:^"
+ }
}
diff --git a/packages/convert/src/dcs.ts b/packages/convert/src/dcs.ts
index a02f883b..d42afcad 100644
--- a/packages/convert/src/dcs.ts
+++ b/packages/convert/src/dcs.ts
@@ -1,4 +1,4 @@
-import { DcOptions } from '@mtcute/core/utils.js'
+import type { DcOptions } from '@mtcute/core/utils.js'
// some libraries only store the DCs in the source code, so we need to map them to the correct DCs
// this may not be very accurate, but it's better than nothing
@@ -7,7 +7,7 @@ import { DcOptions } from '@mtcute/core/utils.js'
// we'll also only map to ipv4 since that's more portable
export const DC_MAPPING_PROD: Record = {
- '1': {
+ 1: {
main: {
id: 1,
ipAddress: '149.154.175.56',
@@ -19,7 +19,7 @@ export const DC_MAPPING_PROD: Record = {
port: 443,
},
},
- '2': {
+ 2: {
main: {
id: 2,
ipAddress: '149.154.167.41',
@@ -31,7 +31,7 @@ export const DC_MAPPING_PROD: Record = {
port: 443,
},
},
- '3': {
+ 3: {
main: {
id: 3,
ipAddress: '149.154.175.100',
@@ -43,7 +43,7 @@ export const DC_MAPPING_PROD: Record = {
port: 443,
},
},
- '4': {
+ 4: {
main: {
id: 4,
ipAddress: '149.154.167.91',
@@ -55,7 +55,7 @@ export const DC_MAPPING_PROD: Record = {
port: 443,
},
},
- '5': {
+ 5: {
main: {
id: 5,
ipAddress: '91.108.56.179',
@@ -70,7 +70,7 @@ export const DC_MAPPING_PROD: Record = {
}
export const DC_MAPPING_TEST: Record = {
- '1': {
+ 1: {
main: {
id: 1,
ipAddress: '149.154.175.10',
@@ -82,7 +82,7 @@ export const DC_MAPPING_TEST: Record = {
port: 80,
},
},
- '2': {
+ 2: {
main: {
id: 2,
ipAddress: '149.154.167.40',
@@ -94,7 +94,7 @@ export const DC_MAPPING_TEST: Record = {
port: 443,
},
},
- '3': {
+ 3: {
main: {
id: 3,
ipAddress: '149.154.175.117',
@@ -109,5 +109,5 @@ export const DC_MAPPING_TEST: Record = {
}
export function isTestDc(ip: string): boolean {
- return Object.values(DC_MAPPING_TEST).some((dc) => dc.main.ipAddress === ip || dc.media.ipAddress === ip)
+ return Object.values(DC_MAPPING_TEST).some(dc => dc.main.ipAddress === ip || dc.media.ipAddress === ip)
}
diff --git a/packages/convert/src/gramjs/__fixtures__/generate.cjs b/packages/convert/src/gramjs/__fixtures__/generate.cjs
index 982fba2d..591a3c4a 100644
--- a/packages/convert/src/gramjs/__fixtures__/generate.cjs
+++ b/packages/convert/src/gramjs/__fixtures__/generate.cjs
@@ -1,6 +1,5 @@
-/* eslint-disable no-console */
-const { execSync } = require('child_process')
-const fs = require('fs')
+const { execSync } = require('node:child_process')
+const fs = require('node:fs')
const VERSION = '2.19.20'
const TMP_DIR = '/tmp/gramjs'
@@ -36,6 +35,7 @@ async function main() {
const session = stringSession.save()
fs.writeFileSync(
+ // eslint-disable-next-line node/no-path-concat
`${__dirname}/session.ts`,
`export const GRAMJS_SESSION = '${session}'\n`,
)
diff --git a/packages/convert/src/gramjs/__fixtures__/session.ts b/packages/convert/src/gramjs/__fixtures__/session.ts
index b05d3643..7a8433a5 100644
--- a/packages/convert/src/gramjs/__fixtures__/session.ts
+++ b/packages/convert/src/gramjs/__fixtures__/session.ts
@@ -1,2 +1,2 @@
-export const GRAMJS_SESSION =
- '1AgAOMTQ5LjE1NC4xNjcuNDABu60obcEYS8Yb/I7YlCwaLvW84dXCX2oGnBYG+zuMciJhHP99c8ZJvwxJgH8yU1QrqI+Gh0kK0JAuQucIpDfq/jJVLZ1ZRimq5yy1XbeEs65gtZA1+SUwZRXahh+NzGbPmOVUMCnCtRONo9GNvcx/QxSXRrh7T/K0YYN1iHsK1vJDk8/SUnthvTNmRycC+JLn4fMtctqP4Le2WPOH/deYbUF0BlwmR77M7fv1GZSInqCgWReaIl5nvn0IqA4mOCTkdOgcvwOiB2UmXwiyInxRuLdBIyLbBUDCuTlmL1m3FJqbuEpZEUJnoJf2YDFZ1wR6TfL0MUS1VwnjOcy3WIIFwwg='
+export const GRAMJS_SESSION
+ = '1AgAOMTQ5LjE1NC4xNjcuNDABu60obcEYS8Yb/I7YlCwaLvW84dXCX2oGnBYG+zuMciJhHP99c8ZJvwxJgH8yU1QrqI+Gh0kK0JAuQucIpDfq/jJVLZ1ZRimq5yy1XbeEs65gtZA1+SUwZRXahh+NzGbPmOVUMCnCtRONo9GNvcx/QxSXRrh7T/K0YYN1iHsK1vJDk8/SUnthvTNmRycC+JLn4fMtctqP4Le2WPOH/deYbUF0BlwmR77M7fv1GZSInqCgWReaIl5nvn0IqA4mOCTkdOgcvwOiB2UmXwiyInxRuLdBIyLbBUDCuTlmL1m3FJqbuEpZEUJnoJf2YDFZ1wR6TfL0MUS1VwnjOcy3WIIFwwg='
diff --git a/packages/convert/src/gramjs/convert.test.ts b/packages/convert/src/gramjs/convert.test.ts
index 1572fbf6..f18d5318 100644
--- a/packages/convert/src/gramjs/convert.test.ts
+++ b/packages/convert/src/gramjs/convert.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { getPlatform } from '@mtcute/core/platform.js'
import { GRAMJS_SESSION } from './__fixtures__/session.js'
@@ -9,14 +8,14 @@ describe('gramjs/convert', () => {
it('should correctly convert from gramjs sessions', () => {
expect(convertFromGramjsSession(GRAMJS_SESSION)).toEqual({
authKey: getPlatform().hexDecode(
- 'ad286dc1184bc61bfc8ed8942c1a2ef5bce1d5c25f6a069c1606fb3b8c722261' +
- '1cff7d73c649bf0c49807f3253542ba88f8687490ad0902e42e708a437eafe32' +
- '552d9d594629aae72cb55db784b3ae60b59035f925306515da861f8dcc66cf98' +
- 'e5543029c2b5138da3d18dbdcc7f43149746b87b4ff2b4618375887b0ad6f243' +
- '93cfd2527b61bd3366472702f892e7e1f32d72da8fe0b7b658f387fdd7986d41' +
- '74065c2647beccedfbf51994889ea0a059179a225e67be7d08a80e263824e474' +
- 'e81cbf03a20765265f08b2227c51b8b7412322db0540c2b939662f59b7149a9b' +
- 'b84a59114267a097f6603159d7047a4df2f43144b55709e339ccb7588205c308',
+ 'ad286dc1184bc61bfc8ed8942c1a2ef5bce1d5c25f6a069c1606fb3b8c722261'
+ + '1cff7d73c649bf0c49807f3253542ba88f8687490ad0902e42e708a437eafe32'
+ + '552d9d594629aae72cb55db784b3ae60b59035f925306515da861f8dcc66cf98'
+ + 'e5543029c2b5138da3d18dbdcc7f43149746b87b4ff2b4618375887b0ad6f243'
+ + '93cfd2527b61bd3366472702f892e7e1f32d72da8fe0b7b658f387fdd7986d41'
+ + '74065c2647beccedfbf51994889ea0a059179a225e67be7d08a80e263824e474'
+ + 'e81cbf03a20765265f08b2227c51b8b7412322db0540c2b939662f59b7149a9b'
+ + 'b84a59114267a097f6603159d7047a4df2f43144b55709e339ccb7588205c308',
),
primaryDcs: {
main: {
@@ -41,14 +40,14 @@ describe('gramjs/convert', () => {
expect(
convertToGramjsSession({
authKey: getPlatform().hexDecode(
- 'ad286dc1184bc61bfc8ed8942c1a2ef5bce1d5c25f6a069c1606fb3b8c722261' +
- '1cff7d73c649bf0c49807f3253542ba88f8687490ad0902e42e708a437eafe32' +
- '552d9d594629aae72cb55db784b3ae60b59035f925306515da861f8dcc66cf98' +
- 'e5543029c2b5138da3d18dbdcc7f43149746b87b4ff2b4618375887b0ad6f243' +
- '93cfd2527b61bd3366472702f892e7e1f32d72da8fe0b7b658f387fdd7986d41' +
- '74065c2647beccedfbf51994889ea0a059179a225e67be7d08a80e263824e474' +
- 'e81cbf03a20765265f08b2227c51b8b7412322db0540c2b939662f59b7149a9b' +
- 'b84a59114267a097f6603159d7047a4df2f43144b55709e339ccb7588205c308',
+ 'ad286dc1184bc61bfc8ed8942c1a2ef5bce1d5c25f6a069c1606fb3b8c722261'
+ + '1cff7d73c649bf0c49807f3253542ba88f8687490ad0902e42e708a437eafe32'
+ + '552d9d594629aae72cb55db784b3ae60b59035f925306515da861f8dcc66cf98'
+ + 'e5543029c2b5138da3d18dbdcc7f43149746b87b4ff2b4618375887b0ad6f243'
+ + '93cfd2527b61bd3366472702f892e7e1f32d72da8fe0b7b658f387fdd7986d41'
+ + '74065c2647beccedfbf51994889ea0a059179a225e67be7d08a80e263824e474'
+ + 'e81cbf03a20765265f08b2227c51b8b7412322db0540c2b939662f59b7149a9b'
+ + 'b84a59114267a097f6603159d7047a4df2f43144b55709e339ccb7588205c308',
),
primaryDcs: {
main: {
diff --git a/packages/convert/src/gramjs/convert.ts b/packages/convert/src/gramjs/convert.ts
index 05993b5a..60cc786c 100644
--- a/packages/convert/src/gramjs/convert.ts
+++ b/packages/convert/src/gramjs/convert.ts
@@ -1,7 +1,9 @@
-import { readStringSession, StringSessionData } from '@mtcute/core/utils.js'
+import type { StringSessionData } from '@mtcute/core/utils.js'
+import { readStringSession } from '@mtcute/core/utils.js'
import { convertFromTelethonSession } from '../telethon/convert.js'
-import { TelethonSession } from '../telethon/types.js'
+import type { TelethonSession } from '../telethon/types.js'
+
import { parseGramjsSession } from './parse.js'
import { serializeGramjsSession } from './serialize.js'
diff --git a/packages/convert/src/gramjs/parse.test.ts b/packages/convert/src/gramjs/parse.test.ts
index ec4dead1..8c944c08 100644
--- a/packages/convert/src/gramjs/parse.test.ts
+++ b/packages/convert/src/gramjs/parse.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { getPlatform } from '@mtcute/core/platform.js'
import { GRAMJS_SESSION } from './__fixtures__/session.js'
@@ -13,14 +12,14 @@ describe('gramjs/parse', () => {
port: 443,
ipv6: false,
authKey: getPlatform().hexDecode(
- 'ad286dc1184bc61bfc8ed8942c1a2ef5bce1d5c25f6a069c1606fb3b8c722261' +
- '1cff7d73c649bf0c49807f3253542ba88f8687490ad0902e42e708a437eafe32' +
- '552d9d594629aae72cb55db784b3ae60b59035f925306515da861f8dcc66cf98' +
- 'e5543029c2b5138da3d18dbdcc7f43149746b87b4ff2b4618375887b0ad6f243' +
- '93cfd2527b61bd3366472702f892e7e1f32d72da8fe0b7b658f387fdd7986d41' +
- '74065c2647beccedfbf51994889ea0a059179a225e67be7d08a80e263824e474' +
- 'e81cbf03a20765265f08b2227c51b8b7412322db0540c2b939662f59b7149a9b' +
- 'b84a59114267a097f6603159d7047a4df2f43144b55709e339ccb7588205c308',
+ 'ad286dc1184bc61bfc8ed8942c1a2ef5bce1d5c25f6a069c1606fb3b8c722261'
+ + '1cff7d73c649bf0c49807f3253542ba88f8687490ad0902e42e708a437eafe32'
+ + '552d9d594629aae72cb55db784b3ae60b59035f925306515da861f8dcc66cf98'
+ + 'e5543029c2b5138da3d18dbdcc7f43149746b87b4ff2b4618375887b0ad6f243'
+ + '93cfd2527b61bd3366472702f892e7e1f32d72da8fe0b7b658f387fdd7986d41'
+ + '74065c2647beccedfbf51994889ea0a059179a225e67be7d08a80e263824e474'
+ + 'e81cbf03a20765265f08b2227c51b8b7412322db0540c2b939662f59b7149a9b'
+ + 'b84a59114267a097f6603159d7047a4df2f43144b55709e339ccb7588205c308',
),
})
})
diff --git a/packages/convert/src/gramjs/parse.ts b/packages/convert/src/gramjs/parse.ts
index 950a975c..99623166 100644
--- a/packages/convert/src/gramjs/parse.ts
+++ b/packages/convert/src/gramjs/parse.ts
@@ -2,7 +2,7 @@ import { MtArgumentError } from '@mtcute/core'
import { getPlatform } from '@mtcute/core/platform.js'
import { dataViewFromBuffer } from '@mtcute/core/utils.js'
-import { TelethonSession } from '../telethon/types.js'
+import type { TelethonSession } from '../telethon/types.js'
export function parseGramjsSession(session: string): TelethonSession {
if (session[0] !== '1') {
diff --git a/packages/convert/src/gramjs/serialize.test.ts b/packages/convert/src/gramjs/serialize.test.ts
index 57936fe2..dd6a43d8 100644
--- a/packages/convert/src/gramjs/serialize.test.ts
+++ b/packages/convert/src/gramjs/serialize.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { getPlatform } from '@mtcute/core/platform.js'
import { GRAMJS_SESSION } from './__fixtures__/session.js'
@@ -14,14 +13,14 @@ describe('gramjs/serialize', () => {
port: 443,
ipv6: false,
authKey: getPlatform().hexDecode(
- 'ad286dc1184bc61bfc8ed8942c1a2ef5bce1d5c25f6a069c1606fb3b8c722261' +
- '1cff7d73c649bf0c49807f3253542ba88f8687490ad0902e42e708a437eafe32' +
- '552d9d594629aae72cb55db784b3ae60b59035f925306515da861f8dcc66cf98' +
- 'e5543029c2b5138da3d18dbdcc7f43149746b87b4ff2b4618375887b0ad6f243' +
- '93cfd2527b61bd3366472702f892e7e1f32d72da8fe0b7b658f387fdd7986d41' +
- '74065c2647beccedfbf51994889ea0a059179a225e67be7d08a80e263824e474' +
- 'e81cbf03a20765265f08b2227c51b8b7412322db0540c2b939662f59b7149a9b' +
- 'b84a59114267a097f6603159d7047a4df2f43144b55709e339ccb7588205c308',
+ 'ad286dc1184bc61bfc8ed8942c1a2ef5bce1d5c25f6a069c1606fb3b8c722261'
+ + '1cff7d73c649bf0c49807f3253542ba88f8687490ad0902e42e708a437eafe32'
+ + '552d9d594629aae72cb55db784b3ae60b59035f925306515da861f8dcc66cf98'
+ + 'e5543029c2b5138da3d18dbdcc7f43149746b87b4ff2b4618375887b0ad6f243'
+ + '93cfd2527b61bd3366472702f892e7e1f32d72da8fe0b7b658f387fdd7986d41'
+ + '74065c2647beccedfbf51994889ea0a059179a225e67be7d08a80e263824e474'
+ + 'e81cbf03a20765265f08b2227c51b8b7412322db0540c2b939662f59b7149a9b'
+ + 'b84a59114267a097f6603159d7047a4df2f43144b55709e339ccb7588205c308',
),
}),
).toEqual(GRAMJS_SESSION)
diff --git a/packages/convert/src/gramjs/serialize.ts b/packages/convert/src/gramjs/serialize.ts
index adaa0178..49fc155c 100644
--- a/packages/convert/src/gramjs/serialize.ts
+++ b/packages/convert/src/gramjs/serialize.ts
@@ -2,7 +2,7 @@ import { MtArgumentError } from '@mtcute/core'
import { getPlatform } from '@mtcute/core/platform.js'
import { dataViewFromBuffer } from '@mtcute/core/utils.js'
-import { TelethonSession } from '../telethon/types.js'
+import type { TelethonSession } from '../telethon/types.js'
export function serializeGramjsSession(session: TelethonSession) {
if (session.authKey.length !== 256) {
@@ -24,5 +24,5 @@ export function serializeGramjsSession(session: TelethonSession) {
pos += 2
u8.set(session.authKey, pos)
- return '1' + getPlatform().base64Encode(u8)
+ return `1${getPlatform().base64Encode(u8)}`
}
diff --git a/packages/convert/src/mtkruto/__fixtures__/generate.js b/packages/convert/src/mtkruto/__fixtures__/generate.js
index b0e353ab..3af29548 100644
--- a/packages/convert/src/mtkruto/__fixtures__/generate.js
+++ b/packages/convert/src/mtkruto/__fixtures__/generate.js
@@ -1,4 +1,4 @@
-/* eslint-disable import/no-unresolved, no-undef, no-console */
+/* eslint-disable no-undef, no-console */
import { Client, StorageMemory } from 'https://deno.land/x/mtkruto@0.1.157/mod.ts'
diff --git a/packages/convert/src/mtkruto/__fixtures__/session.ts b/packages/convert/src/mtkruto/__fixtures__/session.ts
index 348e0acd..c6c7b3d3 100644
--- a/packages/convert/src/mtkruto/__fixtures__/session.ts
+++ b/packages/convert/src/mtkruto/__fixtures__/session.ts
@@ -1,2 +1,2 @@
-export const MTKRUTO_SESSION =
- 'BjItdGVzdAAB_gABAQABWEIKa07Ch-9zoA024mDOpsv20TW4YwuoRRROqSi41YQCbD3c4nKnz7BcFIu1mfn6f6Xm3OTVqoT0zib4p_AuZD9H-t8j5AagecRg-oSpQlmjoiUazKQSxnxWotGWf1mPNntAeOvDNa5t1NjXUxmqdB3e2AjYLF_E2jDESVgUuDBQUMBHIDc_xFBAlz6kVxCZ6iINJHbnyJ2F19tbEPFJvSM999RKaFj5lUUVs0qKNXEUmsFYUuIdPBzjWilY8Uvf9nYU_xXd9CUAAXS5_i4aaWlHoTIf3zn8ZEINhDIU1DMauh5vhSWt7F0fkxODjtou-7PdIunuDtqyQm4steuNJc8'
+export const MTKRUTO_SESSION
+ = 'BjItdGVzdAAB_gABAQABWEIKa07Ch-9zoA024mDOpsv20TW4YwuoRRROqSi41YQCbD3c4nKnz7BcFIu1mfn6f6Xm3OTVqoT0zib4p_AuZD9H-t8j5AagecRg-oSpQlmjoiUazKQSxnxWotGWf1mPNntAeOvDNa5t1NjXUxmqdB3e2AjYLF_E2jDESVgUuDBQUMBHIDc_xFBAlz6kVxCZ6iINJHbnyJ2F19tbEPFJvSM999RKaFj5lUUVs0qKNXEUmsFYUuIdPBzjWilY8Uvf9nYU_xXd9CUAAXS5_i4aaWlHoTIf3zn8ZEINhDIU1DMauh5vhSWt7F0fkxODjtou-7PdIunuDtqyQm4steuNJc8'
diff --git a/packages/convert/src/mtkruto/convert.test.ts b/packages/convert/src/mtkruto/convert.test.ts
index 939f0699..3f123445 100644
--- a/packages/convert/src/mtkruto/convert.test.ts
+++ b/packages/convert/src/mtkruto/convert.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { u8HexDecode } from '@mtcute/test'
import { MTKRUTO_SESSION } from './__fixtures__/session.js'
@@ -9,14 +8,14 @@ describe('mtkruto/convert', () => {
it('should correctly convert from mtkruto sessions', () => {
expect(convertFromMtkrutoSession(MTKRUTO_SESSION)).toEqual({
authKey: u8HexDecode(
- '58420a6b4ec287ef73a00d36e260cea6cbf6d135b8630ba845144ea928b8d584' +
- '026c3ddce272a7cfb05c148bb599f9fa7fa5e6dce4d5aa84f4ce26f8a7f02e64' +
- '3f47fadf23e406a079c460fa84a94259a3a2251acca412c67c56a2d1967f598f' +
- '367b4078ebc335ae6dd4d8d75319aa741dded808d82c5fc4da30c4495814b830' +
- '5050c04720373fc45040973ea4571099ea220d2476e7c89d85d7db5b10f149bd' +
- '233df7d44a6858f9954515b34a8a3571149ac15852e21d3c1ce35a2958f14bdf' +
- 'f67614ff15ddf4250074b9fe2e1a696947a1321fdf39fc64420d843214d4331a' +
- 'ba1e6f8525adec5d1f9313838eda2efbb3dd22e9ee0edab2426e2cb5eb8d25cf',
+ '58420a6b4ec287ef73a00d36e260cea6cbf6d135b8630ba845144ea928b8d584'
+ + '026c3ddce272a7cfb05c148bb599f9fa7fa5e6dce4d5aa84f4ce26f8a7f02e64'
+ + '3f47fadf23e406a079c460fa84a94259a3a2251acca412c67c56a2d1967f598f'
+ + '367b4078ebc335ae6dd4d8d75319aa741dded808d82c5fc4da30c4495814b830'
+ + '5050c04720373fc45040973ea4571099ea220d2476e7c89d85d7db5b10f149bd'
+ + '233df7d44a6858f9954515b34a8a3571149ac15852e21d3c1ce35a2958f14bdf'
+ + 'f67614ff15ddf4250074b9fe2e1a696947a1321fdf39fc64420d843214d4331a'
+ + 'ba1e6f8525adec5d1f9313838eda2efbb3dd22e9ee0edab2426e2cb5eb8d25cf',
),
primaryDcs: {
main: {
@@ -39,14 +38,14 @@ describe('mtkruto/convert', () => {
expect(
convertToMtkrutoSession({
authKey: u8HexDecode(
- '58420a6b4ec287ef73a00d36e260cea6cbf6d135b8630ba845144ea928b8d584' +
- '026c3ddce272a7cfb05c148bb599f9fa7fa5e6dce4d5aa84f4ce26f8a7f02e64' +
- '3f47fadf23e406a079c460fa84a94259a3a2251acca412c67c56a2d1967f598f' +
- '367b4078ebc335ae6dd4d8d75319aa741dded808d82c5fc4da30c4495814b830' +
- '5050c04720373fc45040973ea4571099ea220d2476e7c89d85d7db5b10f149bd' +
- '233df7d44a6858f9954515b34a8a3571149ac15852e21d3c1ce35a2958f14bdf' +
- 'f67614ff15ddf4250074b9fe2e1a696947a1321fdf39fc64420d843214d4331a' +
- 'ba1e6f8525adec5d1f9313838eda2efbb3dd22e9ee0edab2426e2cb5eb8d25cf',
+ '58420a6b4ec287ef73a00d36e260cea6cbf6d135b8630ba845144ea928b8d584'
+ + '026c3ddce272a7cfb05c148bb599f9fa7fa5e6dce4d5aa84f4ce26f8a7f02e64'
+ + '3f47fadf23e406a079c460fa84a94259a3a2251acca412c67c56a2d1967f598f'
+ + '367b4078ebc335ae6dd4d8d75319aa741dded808d82c5fc4da30c4495814b830'
+ + '5050c04720373fc45040973ea4571099ea220d2476e7c89d85d7db5b10f149bd'
+ + '233df7d44a6858f9954515b34a8a3571149ac15852e21d3c1ce35a2958f14bdf'
+ + 'f67614ff15ddf4250074b9fe2e1a696947a1321fdf39fc64420d843214d4331a'
+ + 'ba1e6f8525adec5d1f9313838eda2efbb3dd22e9ee0edab2426e2cb5eb8d25cf',
),
primaryDcs: {
main: {
diff --git a/packages/convert/src/mtkruto/convert.ts b/packages/convert/src/mtkruto/convert.ts
index d3f15693..1fdcbdc8 100644
--- a/packages/convert/src/mtkruto/convert.ts
+++ b/packages/convert/src/mtkruto/convert.ts
@@ -1,9 +1,11 @@
-import { readStringSession, StringSessionData } from '@mtcute/core/utils.js'
+import type { StringSessionData } from '@mtcute/core/utils.js'
+import { readStringSession } from '@mtcute/core/utils.js'
import { DC_MAPPING_PROD, DC_MAPPING_TEST } from '../dcs.js'
+
import { parseMtkrutoSession } from './parse.js'
import { serializeMtkrutoSession } from './serialize.js'
-import { MtkrutoSession } from './types.js'
+import type { MtkrutoSession } from './types.js'
export function convertFromMtkrutoSession(session: MtkrutoSession | string): StringSessionData {
if (typeof session === 'string') {
diff --git a/packages/convert/src/mtkruto/parse.test.ts b/packages/convert/src/mtkruto/parse.test.ts
index 77aa19d4..46be4c2e 100644
--- a/packages/convert/src/mtkruto/parse.test.ts
+++ b/packages/convert/src/mtkruto/parse.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { u8HexDecode } from '@mtcute/test'
import { MTKRUTO_SESSION } from './__fixtures__/session.js'
@@ -11,14 +10,14 @@ describe('mtkruto/parse', () => {
dcId: 2,
isTest: true,
authKey: u8HexDecode(
- '58420a6b4ec287ef73a00d36e260cea6cbf6d135b8630ba845144ea928b8d584' +
- '026c3ddce272a7cfb05c148bb599f9fa7fa5e6dce4d5aa84f4ce26f8a7f02e64' +
- '3f47fadf23e406a079c460fa84a94259a3a2251acca412c67c56a2d1967f598f' +
- '367b4078ebc335ae6dd4d8d75319aa741dded808d82c5fc4da30c4495814b830' +
- '5050c04720373fc45040973ea4571099ea220d2476e7c89d85d7db5b10f149bd' +
- '233df7d44a6858f9954515b34a8a3571149ac15852e21d3c1ce35a2958f14bdf' +
- 'f67614ff15ddf4250074b9fe2e1a696947a1321fdf39fc64420d843214d4331a' +
- 'ba1e6f8525adec5d1f9313838eda2efbb3dd22e9ee0edab2426e2cb5eb8d25cf',
+ '58420a6b4ec287ef73a00d36e260cea6cbf6d135b8630ba845144ea928b8d584'
+ + '026c3ddce272a7cfb05c148bb599f9fa7fa5e6dce4d5aa84f4ce26f8a7f02e64'
+ + '3f47fadf23e406a079c460fa84a94259a3a2251acca412c67c56a2d1967f598f'
+ + '367b4078ebc335ae6dd4d8d75319aa741dded808d82c5fc4da30c4495814b830'
+ + '5050c04720373fc45040973ea4571099ea220d2476e7c89d85d7db5b10f149bd'
+ + '233df7d44a6858f9954515b34a8a3571149ac15852e21d3c1ce35a2958f14bdf'
+ + 'f67614ff15ddf4250074b9fe2e1a696947a1321fdf39fc64420d843214d4331a'
+ + 'ba1e6f8525adec5d1f9313838eda2efbb3dd22e9ee0edab2426e2cb5eb8d25cf',
),
})
})
diff --git a/packages/convert/src/mtkruto/parse.ts b/packages/convert/src/mtkruto/parse.ts
index 796e00e9..5afa35a9 100644
--- a/packages/convert/src/mtkruto/parse.ts
+++ b/packages/convert/src/mtkruto/parse.ts
@@ -3,7 +3,8 @@ import { getPlatform } from '@mtcute/core/platform.js'
import { TlBinaryReader } from '@mtcute/core/utils.js'
import { telegramRleDecode } from '../utils/rle.js'
-import { MtkrutoSession } from './types.js'
+
+import type { MtkrutoSession } from './types.js'
export function parseMtkrutoSession(session: string): MtkrutoSession {
const data = telegramRleDecode(getPlatform().base64Decode(session, true))
@@ -19,7 +20,7 @@ export function parseMtkrutoSession(session: string): MtkrutoSession {
}
const dcId = Number(dcIdStr)
- if (isNaN(dcId)) {
+ if (Number.isNaN(dcId)) {
throw new MtArgumentError(`Invalid DC ID: ${dcIdStr}`)
}
diff --git a/packages/convert/src/mtkruto/serialize.test.ts b/packages/convert/src/mtkruto/serialize.test.ts
index fa945c17..de8011bb 100644
--- a/packages/convert/src/mtkruto/serialize.test.ts
+++ b/packages/convert/src/mtkruto/serialize.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { u8HexDecode } from '@mtcute/test'
import { MTKRUTO_SESSION } from './__fixtures__/session.js'
@@ -12,14 +11,14 @@ describe('mtkruto/serialize', () => {
dcId: 2,
isTest: true,
authKey: u8HexDecode(
- '58420a6b4ec287ef73a00d36e260cea6cbf6d135b8630ba845144ea928b8d584' +
- '026c3ddce272a7cfb05c148bb599f9fa7fa5e6dce4d5aa84f4ce26f8a7f02e64' +
- '3f47fadf23e406a079c460fa84a94259a3a2251acca412c67c56a2d1967f598f' +
- '367b4078ebc335ae6dd4d8d75319aa741dded808d82c5fc4da30c4495814b830' +
- '5050c04720373fc45040973ea4571099ea220d2476e7c89d85d7db5b10f149bd' +
- '233df7d44a6858f9954515b34a8a3571149ac15852e21d3c1ce35a2958f14bdf' +
- 'f67614ff15ddf4250074b9fe2e1a696947a1321fdf39fc64420d843214d4331a' +
- 'ba1e6f8525adec5d1f9313838eda2efbb3dd22e9ee0edab2426e2cb5eb8d25cf',
+ '58420a6b4ec287ef73a00d36e260cea6cbf6d135b8630ba845144ea928b8d584'
+ + '026c3ddce272a7cfb05c148bb599f9fa7fa5e6dce4d5aa84f4ce26f8a7f02e64'
+ + '3f47fadf23e406a079c460fa84a94259a3a2251acca412c67c56a2d1967f598f'
+ + '367b4078ebc335ae6dd4d8d75319aa741dded808d82c5fc4da30c4495814b830'
+ + '5050c04720373fc45040973ea4571099ea220d2476e7c89d85d7db5b10f149bd'
+ + '233df7d44a6858f9954515b34a8a3571149ac15852e21d3c1ce35a2958f14bdf'
+ + 'f67614ff15ddf4250074b9fe2e1a696947a1321fdf39fc64420d843214d4331a'
+ + 'ba1e6f8525adec5d1f9313838eda2efbb3dd22e9ee0edab2426e2cb5eb8d25cf',
),
}),
).toEqual(MTKRUTO_SESSION)
diff --git a/packages/convert/src/mtkruto/serialize.ts b/packages/convert/src/mtkruto/serialize.ts
index 1e7986cc..1e2b6722 100644
--- a/packages/convert/src/mtkruto/serialize.ts
+++ b/packages/convert/src/mtkruto/serialize.ts
@@ -2,7 +2,8 @@ import { getPlatform } from '@mtcute/core/platform.js'
import { TlBinaryWriter } from '@mtcute/core/utils.js'
import { telegramRleEncode } from '../utils/rle.js'
-import { MtkrutoSession } from './types.js'
+
+import type { MtkrutoSession } from './types.js'
export function serializeMtkrutoSession(session: MtkrutoSession): string {
const dcIdStr = `${session.dcId}${session.isTest ? '-test' : ''}`
diff --git a/packages/convert/src/pyrogram/__fixtures__/session.ts b/packages/convert/src/pyrogram/__fixtures__/session.ts
index 58642802..51858e88 100644
--- a/packages/convert/src/pyrogram/__fixtures__/session.ts
+++ b/packages/convert/src/pyrogram/__fixtures__/session.ts
@@ -1,2 +1,2 @@
-export const PYROGRAM_TEST_SESSION =
- 'AgAyyvcBTk6KssqikKPxEhxfXJpkoFIgQ_o8VpCk_4g0tcHe0rVCXx34AaDKvaNOlbkJOZ4jA3AI8iDYkI2opuifbM_7S2u9MMdnrjfg5jpfkXfI9-wF8DK_UBGIe1zk_Ibn0IHLRz-lkb-QqZNhh8O8Ggb8cieamatEYwLrkjkZR7JG53q76F0ktUd22L6_bUlp9p_qgXqBg8vZdkIIs9T1OiShw2X6TNO0lYqfJVaczMVQcT9Zt0FiyrAMpovFuT7-96OFKWcQ9gzrs_SHfz9HrQgBwvNSdkVziXTtxLJXsaNz3smGeyh-CEuEgdF3enIECnzftlvvUClLN_ylcPir1bi4_wAAAAEqEi1JAA'
+export const PYROGRAM_TEST_SESSION
+ = 'AgAyyvcBTk6KssqikKPxEhxfXJpkoFIgQ_o8VpCk_4g0tcHe0rVCXx34AaDKvaNOlbkJOZ4jA3AI8iDYkI2opuifbM_7S2u9MMdnrjfg5jpfkXfI9-wF8DK_UBGIe1zk_Ibn0IHLRz-lkb-QqZNhh8O8Ggb8cieamatEYwLrkjkZR7JG53q76F0ktUd22L6_bUlp9p_qgXqBg8vZdkIIs9T1OiShw2X6TNO0lYqfJVaczMVQcT9Zt0FiyrAMpovFuT7-96OFKWcQ9gzrs_SHfz9HrQgBwvNSdkVziXTtxLJXsaNz3smGeyh-CEuEgdF3enIECnzftlvvUClLN_ylcPir1bi4_wAAAAEqEi1JAA'
diff --git a/packages/convert/src/pyrogram/__fixtures__/session_old.ts b/packages/convert/src/pyrogram/__fixtures__/session_old.ts
index 6951698f..85a6385c 100644
--- a/packages/convert/src/pyrogram/__fixtures__/session_old.ts
+++ b/packages/convert/src/pyrogram/__fixtures__/session_old.ts
@@ -1,2 +1,2 @@
-export const PYROGRAM_TEST_SESSION_OLD =
- 'AgEWdHMtuA1pC01YkNiHpL1bC0yBC3wzGZCwSRWKlA_a69RhePUN3M51NpnwSXrW3pZV9FS8WjAwUkA23uT_49t8c7Umw3ihhKD6-hTpZ5wXC2MuC0EsF0-Z6WshYhT3gmN6QhEt0jlXo5cW1BJ3MYmXtsTWNf_hJfd3_wF_ZFa58ntVV-3qd08wQRhiL_IxM7L5YazjPw0dg2z92CqRARku_oq5D29V6W6bo8T-SLzF_ujj5ZcAQL25mJtCcXfhhjp9atxcrqnKzEs05xyrehnlJZKoGmnX0mF2P_6wUHqZC9tcTBUV4AmFcbuy7m_4SYLnJ8MbftNs7aWHHNcB1R4fAAAAASoSLUkA'
+export const PYROGRAM_TEST_SESSION_OLD
+ = 'AgEWdHMtuA1pC01YkNiHpL1bC0yBC3wzGZCwSRWKlA_a69RhePUN3M51NpnwSXrW3pZV9FS8WjAwUkA23uT_49t8c7Umw3ihhKD6-hTpZ5wXC2MuC0EsF0-Z6WshYhT3gmN6QhEt0jlXo5cW1BJ3MYmXtsTWNf_hJfd3_wF_ZFa58ntVV-3qd08wQRhiL_IxM7L5YazjPw0dg2z92CqRARku_oq5D29V6W6bo8T-SLzF_ujj5ZcAQL25mJtCcXfhhjp9atxcrqnKzEs05xyrehnlJZKoGmnX0mF2P_6wUHqZC9tcTBUV4AmFcbuy7m_4SYLnJ8MbftNs7aWHHNcB1R4fAAAAASoSLUkA'
diff --git a/packages/convert/src/pyrogram/convert.test.ts b/packages/convert/src/pyrogram/convert.test.ts
index 547990ac..12d575a6 100644
--- a/packages/convert/src/pyrogram/convert.test.ts
+++ b/packages/convert/src/pyrogram/convert.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { getPlatform } from '@mtcute/core/platform.js'
import { PYROGRAM_TEST_SESSION_OLD } from './__fixtures__/session_old.js'
@@ -9,14 +8,14 @@ describe('pyrogram/convert', () => {
it('should correctly convert from pyrogram sessions', () => {
expect(convertFromPyrogramSession(PYROGRAM_TEST_SESSION_OLD)).toEqual({
authKey: getPlatform().hexDecode(
- '1674732db80d690b4d5890d887a4bd5b0b4c810b7c331990b049158a940fdaeb' +
- 'd46178f50ddcce753699f0497ad6de9655f454bc5a3030524036dee4ffe3db7c' +
- '73b526c378a184a0fafa14e9679c170b632e0b412c174f99e96b216214f78263' +
- '7a42112dd23957a39716d41277318997b6c4d635ffe125f777ff017f6456b9f2' +
- '7b5557edea774f304118622ff23133b2f961ace33f0d1d836cfdd82a9101192e' +
- 'fe8ab90f6f55e96e9ba3c4fe48bcc5fee8e3e5970040bdb9989b427177e1863a' +
- '7d6adc5caea9cacc4b34e71cab7a19e52592a81a69d7d261763ffeb0507a990b' +
- 'db5c4c1515e0098571bbb2ee6ff84982e727c31b7ed36ceda5871cd701d51e1f',
+ '1674732db80d690b4d5890d887a4bd5b0b4c810b7c331990b049158a940fdaeb'
+ + 'd46178f50ddcce753699f0497ad6de9655f454bc5a3030524036dee4ffe3db7c'
+ + '73b526c378a184a0fafa14e9679c170b632e0b412c174f99e96b216214f78263'
+ + '7a42112dd23957a39716d41277318997b6c4d635ffe125f777ff017f6456b9f2'
+ + '7b5557edea774f304118622ff23133b2f961ace33f0d1d836cfdd82a9101192e'
+ + 'fe8ab90f6f55e96e9ba3c4fe48bcc5fee8e3e5970040bdb9989b427177e1863a'
+ + '7d6adc5caea9cacc4b34e71cab7a19e52592a81a69d7d261763ffeb0507a990b'
+ + 'db5c4c1515e0098571bbb2ee6ff84982e727c31b7ed36ceda5871cd701d51e1f',
),
primaryDcs: {
main: {
@@ -45,14 +44,14 @@ describe('pyrogram/convert', () => {
expect(
convertToPyrogramSession({
authKey: getPlatform().hexDecode(
- '1674732db80d690b4d5890d887a4bd5b0b4c810b7c331990b049158a940fdaeb' +
- 'd46178f50ddcce753699f0497ad6de9655f454bc5a3030524036dee4ffe3db7c' +
- '73b526c378a184a0fafa14e9679c170b632e0b412c174f99e96b216214f78263' +
- '7a42112dd23957a39716d41277318997b6c4d635ffe125f777ff017f6456b9f2' +
- '7b5557edea774f304118622ff23133b2f961ace33f0d1d836cfdd82a9101192e' +
- 'fe8ab90f6f55e96e9ba3c4fe48bcc5fee8e3e5970040bdb9989b427177e1863a' +
- '7d6adc5caea9cacc4b34e71cab7a19e52592a81a69d7d261763ffeb0507a990b' +
- 'db5c4c1515e0098571bbb2ee6ff84982e727c31b7ed36ceda5871cd701d51e1f',
+ '1674732db80d690b4d5890d887a4bd5b0b4c810b7c331990b049158a940fdaeb'
+ + 'd46178f50ddcce753699f0497ad6de9655f454bc5a3030524036dee4ffe3db7c'
+ + '73b526c378a184a0fafa14e9679c170b632e0b412c174f99e96b216214f78263'
+ + '7a42112dd23957a39716d41277318997b6c4d635ffe125f777ff017f6456b9f2'
+ + '7b5557edea774f304118622ff23133b2f961ace33f0d1d836cfdd82a9101192e'
+ + 'fe8ab90f6f55e96e9ba3c4fe48bcc5fee8e3e5970040bdb9989b427177e1863a'
+ + '7d6adc5caea9cacc4b34e71cab7a19e52592a81a69d7d261763ffeb0507a990b'
+ + 'db5c4c1515e0098571bbb2ee6ff84982e727c31b7ed36ceda5871cd701d51e1f',
),
primaryDcs: {
main: {
diff --git a/packages/convert/src/pyrogram/convert.ts b/packages/convert/src/pyrogram/convert.ts
index d79b6a49..605e8a8b 100644
--- a/packages/convert/src/pyrogram/convert.ts
+++ b/packages/convert/src/pyrogram/convert.ts
@@ -1,9 +1,11 @@
-import { readStringSession, StringSessionData } from '@mtcute/core/utils.js'
+import type { StringSessionData } from '@mtcute/core/utils.js'
+import { readStringSession } from '@mtcute/core/utils.js'
import { DC_MAPPING_PROD, DC_MAPPING_TEST } from '../dcs.js'
+
import { parsePyrogramSession } from './parse.js'
import { serializePyrogramSession } from './serialize.js'
-import { PyrogramSession } from './types.js'
+import type { PyrogramSession } from './types.js'
export function convertFromPyrogramSession(session: PyrogramSession | string): StringSessionData {
if (typeof session === 'string') {
diff --git a/packages/convert/src/pyrogram/parse.test.ts b/packages/convert/src/pyrogram/parse.test.ts
index 69fb4a71..141b38da 100644
--- a/packages/convert/src/pyrogram/parse.test.ts
+++ b/packages/convert/src/pyrogram/parse.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { getPlatform } from '@mtcute/core/platform.js'
import { PYROGRAM_TEST_SESSION } from './__fixtures__/session.js'
@@ -14,14 +13,14 @@ describe('pyrogram/parse', () => {
userId: 5000801609,
dcId: 2,
authKey: getPlatform().hexDecode(
- '1674732db80d690b4d5890d887a4bd5b0b4c810b7c331990b049158a940fdaeb' +
- 'd46178f50ddcce753699f0497ad6de9655f454bc5a3030524036dee4ffe3db7c' +
- '73b526c378a184a0fafa14e9679c170b632e0b412c174f99e96b216214f78263' +
- '7a42112dd23957a39716d41277318997b6c4d635ffe125f777ff017f6456b9f2' +
- '7b5557edea774f304118622ff23133b2f961ace33f0d1d836cfdd82a9101192e' +
- 'fe8ab90f6f55e96e9ba3c4fe48bcc5fee8e3e5970040bdb9989b427177e1863a' +
- '7d6adc5caea9cacc4b34e71cab7a19e52592a81a69d7d261763ffeb0507a990b' +
- 'db5c4c1515e0098571bbb2ee6ff84982e727c31b7ed36ceda5871cd701d51e1f',
+ '1674732db80d690b4d5890d887a4bd5b0b4c810b7c331990b049158a940fdaeb'
+ + 'd46178f50ddcce753699f0497ad6de9655f454bc5a3030524036dee4ffe3db7c'
+ + '73b526c378a184a0fafa14e9679c170b632e0b412c174f99e96b216214f78263'
+ + '7a42112dd23957a39716d41277318997b6c4d635ffe125f777ff017f6456b9f2'
+ + '7b5557edea774f304118622ff23133b2f961ace33f0d1d836cfdd82a9101192e'
+ + 'fe8ab90f6f55e96e9ba3c4fe48bcc5fee8e3e5970040bdb9989b427177e1863a'
+ + '7d6adc5caea9cacc4b34e71cab7a19e52592a81a69d7d261763ffeb0507a990b'
+ + 'db5c4c1515e0098571bbb2ee6ff84982e727c31b7ed36ceda5871cd701d51e1f',
),
})
})
@@ -34,14 +33,14 @@ describe('pyrogram/parse', () => {
userId: 5000801609,
dcId: 2,
authKey: getPlatform().hexDecode(
- '4e4e8ab2caa290a3f1121c5f5c9a64a0522043fa3c5690a4ff8834b5c1ded2b5' +
- '425f1df801a0cabda34e95b909399e23037008f220d8908da8a6e89f6ccffb4b' +
- '6bbd30c767ae37e0e63a5f9177c8f7ec05f032bf5011887b5ce4fc86e7d081cb' +
- '473fa591bf90a9936187c3bc1a06fc72279a99ab446302eb92391947b246e77a' +
- 'bbe85d24b54776d8bebf6d4969f69fea817a8183cbd9764208b3d4f53a24a1c3' +
- '65fa4cd3b4958a9f25569cccc550713f59b74162cab00ca68bc5b93efef7a385' +
- '296710f60cebb3f4877f3f47ad0801c2f3527645738974edc4b257b1a373dec9' +
- '867b287e084b8481d1777a72040a7cdfb65bef50294b37fca570f8abd5b8b8ff',
+ '4e4e8ab2caa290a3f1121c5f5c9a64a0522043fa3c5690a4ff8834b5c1ded2b5'
+ + '425f1df801a0cabda34e95b909399e23037008f220d8908da8a6e89f6ccffb4b'
+ + '6bbd30c767ae37e0e63a5f9177c8f7ec05f032bf5011887b5ce4fc86e7d081cb'
+ + '473fa591bf90a9936187c3bc1a06fc72279a99ab446302eb92391947b246e77a'
+ + 'bbe85d24b54776d8bebf6d4969f69fea817a8183cbd9764208b3d4f53a24a1c3'
+ + '65fa4cd3b4958a9f25569cccc550713f59b74162cab00ca68bc5b93efef7a385'
+ + '296710f60cebb3f4877f3f47ad0801c2f3527645738974edc4b257b1a373dec9'
+ + '867b287e084b8481d1777a72040a7cdfb65bef50294b37fca570f8abd5b8b8ff',
),
})
})
diff --git a/packages/convert/src/pyrogram/parse.ts b/packages/convert/src/pyrogram/parse.ts
index 1363f893..6c6d7b67 100644
--- a/packages/convert/src/pyrogram/parse.ts
+++ b/packages/convert/src/pyrogram/parse.ts
@@ -4,7 +4,7 @@ import { Long } from '@mtcute/core'
import { getPlatform } from '@mtcute/core/platform.js'
import { dataViewFromBuffer, longFromBuffer } from '@mtcute/core/utils.js'
-import { PyrogramSession } from './types.js'
+import type { PyrogramSession } from './types.js'
const SESSION_STRING_SIZE = 351
const SESSION_STRING_SIZE_64 = 356
diff --git a/packages/convert/src/pyrogram/serialize.test.ts b/packages/convert/src/pyrogram/serialize.test.ts
index 3af64870..b9c4c0d1 100644
--- a/packages/convert/src/pyrogram/serialize.test.ts
+++ b/packages/convert/src/pyrogram/serialize.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { getPlatform } from '@mtcute/core/platform.js'
import { PYROGRAM_TEST_SESSION } from './__fixtures__/session.js'
@@ -15,14 +14,14 @@ describe('pyrogram/serialize', () => {
userId: 5000801609,
dcId: 2,
authKey: getPlatform().hexDecode(
- '1674732db80d690b4d5890d887a4bd5b0b4c810b7c331990b049158a940fdaeb' +
- 'd46178f50ddcce753699f0497ad6de9655f454bc5a3030524036dee4ffe3db7c' +
- '73b526c378a184a0fafa14e9679c170b632e0b412c174f99e96b216214f78263' +
- '7a42112dd23957a39716d41277318997b6c4d635ffe125f777ff017f6456b9f2' +
- '7b5557edea774f304118622ff23133b2f961ace33f0d1d836cfdd82a9101192e' +
- 'fe8ab90f6f55e96e9ba3c4fe48bcc5fee8e3e5970040bdb9989b427177e1863a' +
- '7d6adc5caea9cacc4b34e71cab7a19e52592a81a69d7d261763ffeb0507a990b' +
- 'db5c4c1515e0098571bbb2ee6ff84982e727c31b7ed36ceda5871cd701d51e1f',
+ '1674732db80d690b4d5890d887a4bd5b0b4c810b7c331990b049158a940fdaeb'
+ + 'd46178f50ddcce753699f0497ad6de9655f454bc5a3030524036dee4ffe3db7c'
+ + '73b526c378a184a0fafa14e9679c170b632e0b412c174f99e96b216214f78263'
+ + '7a42112dd23957a39716d41277318997b6c4d635ffe125f777ff017f6456b9f2'
+ + '7b5557edea774f304118622ff23133b2f961ace33f0d1d836cfdd82a9101192e'
+ + 'fe8ab90f6f55e96e9ba3c4fe48bcc5fee8e3e5970040bdb9989b427177e1863a'
+ + '7d6adc5caea9cacc4b34e71cab7a19e52592a81a69d7d261763ffeb0507a990b'
+ + 'db5c4c1515e0098571bbb2ee6ff84982e727c31b7ed36ceda5871cd701d51e1f',
),
}),
).toEqual(PYROGRAM_TEST_SESSION_OLD)
@@ -37,14 +36,14 @@ describe('pyrogram/serialize', () => {
userId: 5000801609,
dcId: 2,
authKey: getPlatform().hexDecode(
- '4e4e8ab2caa290a3f1121c5f5c9a64a0522043fa3c5690a4ff8834b5c1ded2b5' +
- '425f1df801a0cabda34e95b909399e23037008f220d8908da8a6e89f6ccffb4b' +
- '6bbd30c767ae37e0e63a5f9177c8f7ec05f032bf5011887b5ce4fc86e7d081cb' +
- '473fa591bf90a9936187c3bc1a06fc72279a99ab446302eb92391947b246e77a' +
- 'bbe85d24b54776d8bebf6d4969f69fea817a8183cbd9764208b3d4f53a24a1c3' +
- '65fa4cd3b4958a9f25569cccc550713f59b74162cab00ca68bc5b93efef7a385' +
- '296710f60cebb3f4877f3f47ad0801c2f3527645738974edc4b257b1a373dec9' +
- '867b287e084b8481d1777a72040a7cdfb65bef50294b37fca570f8abd5b8b8ff',
+ '4e4e8ab2caa290a3f1121c5f5c9a64a0522043fa3c5690a4ff8834b5c1ded2b5'
+ + '425f1df801a0cabda34e95b909399e23037008f220d8908da8a6e89f6ccffb4b'
+ + '6bbd30c767ae37e0e63a5f9177c8f7ec05f032bf5011887b5ce4fc86e7d081cb'
+ + '473fa591bf90a9936187c3bc1a06fc72279a99ab446302eb92391947b246e77a'
+ + 'bbe85d24b54776d8bebf6d4969f69fea817a8183cbd9764208b3d4f53a24a1c3'
+ + '65fa4cd3b4958a9f25569cccc550713f59b74162cab00ca68bc5b93efef7a385'
+ + '296710f60cebb3f4877f3f47ad0801c2f3527645738974edc4b257b1a373dec9'
+ + '867b287e084b8481d1777a72040a7cdfb65bef50294b37fca570f8abd5b8b8ff',
),
}),
).toEqual(PYROGRAM_TEST_SESSION)
diff --git a/packages/convert/src/pyrogram/serialize.ts b/packages/convert/src/pyrogram/serialize.ts
index 97f4c307..f6c74795 100644
--- a/packages/convert/src/pyrogram/serialize.ts
+++ b/packages/convert/src/pyrogram/serialize.ts
@@ -2,7 +2,7 @@ import { Long, MtArgumentError } from '@mtcute/core'
import { getPlatform } from '@mtcute/core/platform.js'
import { dataViewFromBuffer } from '@mtcute/core/utils.js'
-import { PyrogramSession } from './types.js'
+import type { PyrogramSession } from './types.js'
const SESSION_STRING_SIZE_OLD = 267
const SESSION_STRING_SIZE = 271
diff --git a/packages/convert/src/telethon/__fixtures__/session.ts b/packages/convert/src/telethon/__fixtures__/session.ts
index f53df8c3..c209e384 100644
--- a/packages/convert/src/telethon/__fixtures__/session.ts
+++ b/packages/convert/src/telethon/__fixtures__/session.ts
@@ -1,2 +1,2 @@
-export const TELETHON_TEST_SESSION =
- '1ApWapygAUChJS1_xwUK01Is4cOvQa1JKTn1POabdMUCfLmXNYFUyvG3v9Z_qbFNFp3zYP--3aVpTYI2DpB2Ib46p_bwSC0j1QEjvdQxJj26cVj8NfslrCkYrdV3glOhdczSq08kp31eqBGXMPhA7wy7DOcSLLAoy-Jf3Q_V_Q3y2a8_64ArFJe8PFfSqkdO56VQutajNLscFUtTQXUQFLJ7ft6vIl__UOc9tpQZEiFW7jWmID79WkfYLHFjuChTVKGMLDa8YcZj6z5Sq-pXPE9VbAbJ5L1JRqXOey3QGtZgJeIEww_WWD5nMMUfhLIydD2i7eDmVoUE5EIZPpsevJmjiGLw4vJk='
+export const TELETHON_TEST_SESSION
+ = '1ApWapygAUChJS1_xwUK01Is4cOvQa1JKTn1POabdMUCfLmXNYFUyvG3v9Z_qbFNFp3zYP--3aVpTYI2DpB2Ib46p_bwSC0j1QEjvdQxJj26cVj8NfslrCkYrdV3glOhdczSq08kp31eqBGXMPhA7wy7DOcSLLAoy-Jf3Q_V_Q3y2a8_64ArFJe8PFfSqkdO56VQutajNLscFUtTQXUQFLJ7ft6vIl__UOc9tpQZEiFW7jWmID79WkfYLHFjuChTVKGMLDa8YcZj6z5Sq-pXPE9VbAbJ5L1JRqXOey3QGtZgJeIEww_WWD5nMMUfhLIydD2i7eDmVoUE5EIZPpsevJmjiGLw4vJk='
diff --git a/packages/convert/src/telethon/__fixtures__/session_v6.ts b/packages/convert/src/telethon/__fixtures__/session_v6.ts
index 14495480..dc7bf5ba 100644
--- a/packages/convert/src/telethon/__fixtures__/session_v6.ts
+++ b/packages/convert/src/telethon/__fixtures__/session_v6.ts
@@ -1,2 +1,2 @@
-export const TELETHON_TEST_SESSION_V6 =
- '1ASABCyjyPfABAAAAAAAAAA4Bu4pveAFWSE51_trKsrRQeMvGXMl8fI6NsGaWqdrXXeqyaXne9qNthqnrBmH56kHfOhFUCPSoVzNNrGgnQr67AYQbkhpP_Yml2EDd8epdc6Gywh4q2NBgYyW6VBT8UKg89-FebYTO6n47I1cJMGsSZ1ddxEOpIpHXsSmPdGBSTz6uaHbLYo0jnxd59PQn4H4dKb8FxuOQsUVa3vY_o79HMVMQRVT1IksUKFg5gAe5ZJ0yx6W4pMviVbC-TYZC0HInmv2fFMv-S3rQyg1C7qpU-Gbo1P6UZC4KZGmu2pMJooFNyfRbFgl3BI5Z-FNx9TKu4UFrF9G6Q0l8PjPXOZm4j-c='
+export const TELETHON_TEST_SESSION_V6
+ = '1ASABCyjyPfABAAAAAAAAAA4Bu4pveAFWSE51_trKsrRQeMvGXMl8fI6NsGaWqdrXXeqyaXne9qNthqnrBmH56kHfOhFUCPSoVzNNrGgnQr67AYQbkhpP_Yml2EDd8epdc6Gywh4q2NBgYyW6VBT8UKg89-FebYTO6n47I1cJMGsSZ1ddxEOpIpHXsSmPdGBSTz6uaHbLYo0jnxd59PQn4H4dKb8FxuOQsUVa3vY_o79HMVMQRVT1IksUKFg5gAe5ZJ0yx6W4pMviVbC-TYZC0HInmv2fFMv-S3rQyg1C7qpU-Gbo1P6UZC4KZGmu2pMJooFNyfRbFgl3BI5Z-FNx9TKu4UFrF9G6Q0l8PjPXOZm4j-c='
diff --git a/packages/convert/src/telethon/convert.test.ts b/packages/convert/src/telethon/convert.test.ts
index 904ed375..d9d8867c 100644
--- a/packages/convert/src/telethon/convert.test.ts
+++ b/packages/convert/src/telethon/convert.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { getPlatform } from '@mtcute/core/platform.js'
import { TELETHON_TEST_SESSION } from './__fixtures__/session.js'
@@ -9,14 +8,14 @@ describe('telethon/convert', () => {
it('should correctly convert from telethon sessions', () => {
expect(convertFromTelethonSession(TELETHON_TEST_SESSION)).toEqual({
authKey: getPlatform().hexDecode(
- '28494b5ff1c142b4d48b3870ebd06b524a4e7d4f39a6dd31409f2e65cd605532' +
- 'bc6deff59fea6c5345a77cd83fefb7695a53608d83a41d886f8ea9fdbc120b48' +
- 'f54048ef750c498f6e9c563f0d7ec96b0a462b755de094e85d7334aad3c929df' +
- '57aa0465cc3e103bc32ec339c48b2c0a32f897f743f57f437cb66bcffae00ac5' +
- '25ef0f15f4aa91d3b9e9542eb5a8cd2ec70552d4d05d44052c9edfb7abc897ff' +
- 'd439cf6da506448855bb8d69880fbf5691f60b1c58ee0a14d528630b0daf1871' +
- '98facf94aafa95cf13d55b01b2792f5251a9739ecb7406b59809788130c3f596' +
- '0f99cc3147e12c8c9d0f68bb783995a1413910864fa6c7af2668e218bc38bc99',
+ '28494b5ff1c142b4d48b3870ebd06b524a4e7d4f39a6dd31409f2e65cd605532'
+ + 'bc6deff59fea6c5345a77cd83fefb7695a53608d83a41d886f8ea9fdbc120b48'
+ + 'f54048ef750c498f6e9c563f0d7ec96b0a462b755de094e85d7334aad3c929df'
+ + '57aa0465cc3e103bc32ec339c48b2c0a32f897f743f57f437cb66bcffae00ac5'
+ + '25ef0f15f4aa91d3b9e9542eb5a8cd2ec70552d4d05d44052c9edfb7abc897ff'
+ + 'd439cf6da506448855bb8d69880fbf5691f60b1c58ee0a14d528630b0daf1871'
+ + '98facf94aafa95cf13d55b01b2792f5251a9739ecb7406b59809788130c3f596'
+ + '0f99cc3147e12c8c9d0f68bb783995a1413910864fa6c7af2668e218bc38bc99',
),
primaryDcs: {
main: {
@@ -41,14 +40,14 @@ describe('telethon/convert', () => {
expect(
convertToTelethonSession({
authKey: getPlatform().hexDecode(
- '28494b5ff1c142b4d48b3870ebd06b524a4e7d4f39a6dd31409f2e65cd605532' +
- 'bc6deff59fea6c5345a77cd83fefb7695a53608d83a41d886f8ea9fdbc120b48' +
- 'f54048ef750c498f6e9c563f0d7ec96b0a462b755de094e85d7334aad3c929df' +
- '57aa0465cc3e103bc32ec339c48b2c0a32f897f743f57f437cb66bcffae00ac5' +
- '25ef0f15f4aa91d3b9e9542eb5a8cd2ec70552d4d05d44052c9edfb7abc897ff' +
- 'd439cf6da506448855bb8d69880fbf5691f60b1c58ee0a14d528630b0daf1871' +
- '98facf94aafa95cf13d55b01b2792f5251a9739ecb7406b59809788130c3f596' +
- '0f99cc3147e12c8c9d0f68bb783995a1413910864fa6c7af2668e218bc38bc99',
+ '28494b5ff1c142b4d48b3870ebd06b524a4e7d4f39a6dd31409f2e65cd605532'
+ + 'bc6deff59fea6c5345a77cd83fefb7695a53608d83a41d886f8ea9fdbc120b48'
+ + 'f54048ef750c498f6e9c563f0d7ec96b0a462b755de094e85d7334aad3c929df'
+ + '57aa0465cc3e103bc32ec339c48b2c0a32f897f743f57f437cb66bcffae00ac5'
+ + '25ef0f15f4aa91d3b9e9542eb5a8cd2ec70552d4d05d44052c9edfb7abc897ff'
+ + 'd439cf6da506448855bb8d69880fbf5691f60b1c58ee0a14d528630b0daf1871'
+ + '98facf94aafa95cf13d55b01b2792f5251a9739ecb7406b59809788130c3f596'
+ + '0f99cc3147e12c8c9d0f68bb783995a1413910864fa6c7af2668e218bc38bc99',
),
primaryDcs: {
main: {
diff --git a/packages/convert/src/telethon/convert.ts b/packages/convert/src/telethon/convert.ts
index 3e32e591..c14c49a2 100644
--- a/packages/convert/src/telethon/convert.ts
+++ b/packages/convert/src/telethon/convert.ts
@@ -1,9 +1,11 @@
-import { BasicDcOption, readStringSession, StringSessionData } from '@mtcute/core/utils.js'
+import type { BasicDcOption, StringSessionData } from '@mtcute/core/utils.js'
+import { readStringSession } from '@mtcute/core/utils.js'
import { isTestDc } from '../dcs.js'
+
import { parseTelethonSession } from './parse.js'
import { serializeTelethonSession } from './serialize.js'
-import { TelethonSession } from './types.js'
+import type { TelethonSession } from './types.js'
export function convertFromTelethonSession(session: TelethonSession | string): StringSessionData {
if (typeof session === 'string') {
diff --git a/packages/convert/src/telethon/parse.test.ts b/packages/convert/src/telethon/parse.test.ts
index 58a56e61..ca85915e 100644
--- a/packages/convert/src/telethon/parse.test.ts
+++ b/packages/convert/src/telethon/parse.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { getPlatform } from '@mtcute/core/platform.js'
import { TELETHON_TEST_SESSION } from './__fixtures__/session.js'
@@ -14,14 +13,14 @@ describe('telethon/parse', () => {
port: 80,
ipv6: false,
authKey: getPlatform().hexDecode(
- '28494b5ff1c142b4d48b3870ebd06b524a4e7d4f39a6dd31409f2e65cd605532' +
- 'bc6deff59fea6c5345a77cd83fefb7695a53608d83a41d886f8ea9fdbc120b48' +
- 'f54048ef750c498f6e9c563f0d7ec96b0a462b755de094e85d7334aad3c929df' +
- '57aa0465cc3e103bc32ec339c48b2c0a32f897f743f57f437cb66bcffae00ac5' +
- '25ef0f15f4aa91d3b9e9542eb5a8cd2ec70552d4d05d44052c9edfb7abc897ff' +
- 'd439cf6da506448855bb8d69880fbf5691f60b1c58ee0a14d528630b0daf1871' +
- '98facf94aafa95cf13d55b01b2792f5251a9739ecb7406b59809788130c3f596' +
- '0f99cc3147e12c8c9d0f68bb783995a1413910864fa6c7af2668e218bc38bc99',
+ '28494b5ff1c142b4d48b3870ebd06b524a4e7d4f39a6dd31409f2e65cd605532'
+ + 'bc6deff59fea6c5345a77cd83fefb7695a53608d83a41d886f8ea9fdbc120b48'
+ + 'f54048ef750c498f6e9c563f0d7ec96b0a462b755de094e85d7334aad3c929df'
+ + '57aa0465cc3e103bc32ec339c48b2c0a32f897f743f57f437cb66bcffae00ac5'
+ + '25ef0f15f4aa91d3b9e9542eb5a8cd2ec70552d4d05d44052c9edfb7abc897ff'
+ + 'd439cf6da506448855bb8d69880fbf5691f60b1c58ee0a14d528630b0daf1871'
+ + '98facf94aafa95cf13d55b01b2792f5251a9739ecb7406b59809788130c3f596'
+ + '0f99cc3147e12c8c9d0f68bb783995a1413910864fa6c7af2668e218bc38bc99',
),
})
})
@@ -33,14 +32,14 @@ describe('telethon/parse', () => {
port: 443,
ipv6: true,
authKey: getPlatform().hexDecode(
- '8a6f780156484e75fedacab2b45078cbc65cc97c7c8e8db06696a9dad75deab2' +
- '6979def6a36d86a9eb0661f9ea41df3a115408f4a857334dac682742bebb0184' +
- '1b921a4ffd89a5d840ddf1ea5d73a1b2c21e2ad8d0606325ba5414fc50a83cf7' +
- 'e15e6d84ceea7e3b235709306b1267575dc443a92291d7b1298f7460524f3eae' +
- '6876cb628d239f1779f4f427e07e1d29bf05c6e390b1455adef63fa3bf473153' +
- '104554f5224b142858398007b9649d32c7a5b8a4cbe255b0be4d8642d072279a' +
- 'fd9f14cbfe4b7ad0ca0d42eeaa54f866e8d4fe94642e0a6469aeda9309a2814d' +
- 'c9f45b160977048e59f85371f532aee1416b17d1ba43497c3e33d73999b88fe7',
+ '8a6f780156484e75fedacab2b45078cbc65cc97c7c8e8db06696a9dad75deab2'
+ + '6979def6a36d86a9eb0661f9ea41df3a115408f4a857334dac682742bebb0184'
+ + '1b921a4ffd89a5d840ddf1ea5d73a1b2c21e2ad8d0606325ba5414fc50a83cf7'
+ + 'e15e6d84ceea7e3b235709306b1267575dc443a92291d7b1298f7460524f3eae'
+ + '6876cb628d239f1779f4f427e07e1d29bf05c6e390b1455adef63fa3bf473153'
+ + '104554f5224b142858398007b9649d32c7a5b8a4cbe255b0be4d8642d072279a'
+ + 'fd9f14cbfe4b7ad0ca0d42eeaa54f866e8d4fe94642e0a6469aeda9309a2814d'
+ + 'c9f45b160977048e59f85371f532aee1416b17d1ba43497c3e33d73999b88fe7',
),
})
})
diff --git a/packages/convert/src/telethon/parse.ts b/packages/convert/src/telethon/parse.ts
index b630cd72..e366f5b7 100644
--- a/packages/convert/src/telethon/parse.ts
+++ b/packages/convert/src/telethon/parse.ts
@@ -3,7 +3,8 @@ import { getPlatform } from '@mtcute/core/platform.js'
import { dataViewFromBuffer } from '@mtcute/core/utils.js'
import { parseIpFromBytes } from '../utils/ip.js'
-import { TelethonSession } from './types.js'
+
+import type { TelethonSession } from './types.js'
export function parseTelethonSession(session: string): TelethonSession {
if (session[0] !== '1') {
diff --git a/packages/convert/src/telethon/serialize.test.ts b/packages/convert/src/telethon/serialize.test.ts
index 66ed90bc..ed9fcfc4 100644
--- a/packages/convert/src/telethon/serialize.test.ts
+++ b/packages/convert/src/telethon/serialize.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { getPlatform } from '@mtcute/core/platform.js'
import { TELETHON_TEST_SESSION } from './__fixtures__/session.js'
@@ -15,14 +14,14 @@ describe('telethon/serialize', () => {
port: 80,
ipv6: false,
authKey: getPlatform().hexDecode(
- '28494b5ff1c142b4d48b3870ebd06b524a4e7d4f39a6dd31409f2e65cd605532' +
- 'bc6deff59fea6c5345a77cd83fefb7695a53608d83a41d886f8ea9fdbc120b48' +
- 'f54048ef750c498f6e9c563f0d7ec96b0a462b755de094e85d7334aad3c929df' +
- '57aa0465cc3e103bc32ec339c48b2c0a32f897f743f57f437cb66bcffae00ac5' +
- '25ef0f15f4aa91d3b9e9542eb5a8cd2ec70552d4d05d44052c9edfb7abc897ff' +
- 'd439cf6da506448855bb8d69880fbf5691f60b1c58ee0a14d528630b0daf1871' +
- '98facf94aafa95cf13d55b01b2792f5251a9739ecb7406b59809788130c3f596' +
- '0f99cc3147e12c8c9d0f68bb783995a1413910864fa6c7af2668e218bc38bc99',
+ '28494b5ff1c142b4d48b3870ebd06b524a4e7d4f39a6dd31409f2e65cd605532'
+ + 'bc6deff59fea6c5345a77cd83fefb7695a53608d83a41d886f8ea9fdbc120b48'
+ + 'f54048ef750c498f6e9c563f0d7ec96b0a462b755de094e85d7334aad3c929df'
+ + '57aa0465cc3e103bc32ec339c48b2c0a32f897f743f57f437cb66bcffae00ac5'
+ + '25ef0f15f4aa91d3b9e9542eb5a8cd2ec70552d4d05d44052c9edfb7abc897ff'
+ + 'd439cf6da506448855bb8d69880fbf5691f60b1c58ee0a14d528630b0daf1871'
+ + '98facf94aafa95cf13d55b01b2792f5251a9739ecb7406b59809788130c3f596'
+ + '0f99cc3147e12c8c9d0f68bb783995a1413910864fa6c7af2668e218bc38bc99',
),
}),
).toEqual(TELETHON_TEST_SESSION)
@@ -36,14 +35,14 @@ describe('telethon/serialize', () => {
port: 443,
ipv6: true,
authKey: getPlatform().hexDecode(
- '8a6f780156484e75fedacab2b45078cbc65cc97c7c8e8db06696a9dad75deab2' +
- '6979def6a36d86a9eb0661f9ea41df3a115408f4a857334dac682742bebb0184' +
- '1b921a4ffd89a5d840ddf1ea5d73a1b2c21e2ad8d0606325ba5414fc50a83cf7' +
- 'e15e6d84ceea7e3b235709306b1267575dc443a92291d7b1298f7460524f3eae' +
- '6876cb628d239f1779f4f427e07e1d29bf05c6e390b1455adef63fa3bf473153' +
- '104554f5224b142858398007b9649d32c7a5b8a4cbe255b0be4d8642d072279a' +
- 'fd9f14cbfe4b7ad0ca0d42eeaa54f866e8d4fe94642e0a6469aeda9309a2814d' +
- 'c9f45b160977048e59f85371f532aee1416b17d1ba43497c3e33d73999b88fe7',
+ '8a6f780156484e75fedacab2b45078cbc65cc97c7c8e8db06696a9dad75deab2'
+ + '6979def6a36d86a9eb0661f9ea41df3a115408f4a857334dac682742bebb0184'
+ + '1b921a4ffd89a5d840ddf1ea5d73a1b2c21e2ad8d0606325ba5414fc50a83cf7'
+ + 'e15e6d84ceea7e3b235709306b1267575dc443a92291d7b1298f7460524f3eae'
+ + '6876cb628d239f1779f4f427e07e1d29bf05c6e390b1455adef63fa3bf473153'
+ + '104554f5224b142858398007b9649d32c7a5b8a4cbe255b0be4d8642d072279a'
+ + 'fd9f14cbfe4b7ad0ca0d42eeaa54f866e8d4fe94642e0a6469aeda9309a2814d'
+ + 'c9f45b160977048e59f85371f532aee1416b17d1ba43497c3e33d73999b88fe7',
),
}),
).toEqual(TELETHON_TEST_SESSION_V6)
diff --git a/packages/convert/src/telethon/serialize.ts b/packages/convert/src/telethon/serialize.ts
index 442612c7..bacd7a36 100644
--- a/packages/convert/src/telethon/serialize.ts
+++ b/packages/convert/src/telethon/serialize.ts
@@ -3,7 +3,8 @@ import { getPlatform } from '@mtcute/core/platform.js'
import { dataViewFromBuffer } from '@mtcute/core/utils.js'
import { serializeIpv4ToBytes, serializeIpv6ToBytes } from '../utils/ip.js'
-import { TelethonSession } from './types.js'
+
+import type { TelethonSession } from './types.js'
export function serializeTelethonSession(session: TelethonSession) {
if (session.authKey.length !== 256) {
@@ -33,5 +34,5 @@ export function serializeTelethonSession(session: TelethonSession) {
let b64 = getPlatform().base64Encode(u8, true)
while (b64.length % 4 !== 0) b64 += '=' // for some reason telethon uses padding
- return '1' + b64
+ return `1${b64}`
}
diff --git a/packages/convert/src/utils/ip.ts b/packages/convert/src/utils/ip.ts
index 8f01b386..e73b199b 100644
--- a/packages/convert/src/utils/ip.ts
+++ b/packages/convert/src/utils/ip.ts
@@ -20,7 +20,7 @@ export function parseIpFromBytes(data: Uint8Array): string {
throw new MtArgumentError('Invalid IP address length')
}
-export function serializeIpv4ToBytes(ip: string, buf: Uint8Array) {
+export function serializeIpv4ToBytes(ip: string, buf: Uint8Array): void {
const parts = ip.split('.')
if (parts.length !== 4) {
@@ -33,7 +33,7 @@ export function serializeIpv4ToBytes(ip: string, buf: Uint8Array) {
buf[3] = Number(parts[3])
}
-export function serializeIpv6ToBytes(ip: string, buf: Uint8Array) {
+export function serializeIpv6ToBytes(ip: string, buf: Uint8Array): void {
const parts = ip.split(':')
if (parts.length !== 8) {
@@ -41,8 +41,8 @@ export function serializeIpv6ToBytes(ip: string, buf: Uint8Array) {
}
for (let i = 0; i < 8; i++) {
- const val = parseInt(parts[i], 16)
+ const val = Number.parseInt(parts[i], 16)
buf[i * 2] = val >> 8
- buf[i * 2 + 1] = val & 0xff
+ buf[i * 2 + 1] = val & 0xFF
}
}
diff --git a/packages/convert/tsconfig.json b/packages/convert/tsconfig.json
index 798d46cb..3b5437ec 100644
--- a/packages/convert/tsconfig.json
+++ b/packages/convert/tsconfig.json
@@ -1,13 +1,13 @@
{
- "extends": "../../tsconfig.json",
- "compilerOptions": {
- "outDir": "./dist/esm",
- "rootDir": "./src",
- },
- "include": [
- "./src",
- ],
- "references": [
- { "path": "../core" },
- ],
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "rootDir": "./src",
+ "outDir": "./dist/esm"
+ },
+ "references": [
+ { "path": "../core" }
+ ],
+ "include": [
+ "./src"
+ ]
}
diff --git a/packages/core/README.md b/packages/core/README.md
index 407d500e..bd738bde 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -45,4 +45,4 @@ const self = await tg.start({
password: 'my-password',
})
console.log(`✨ logged in as ${self.displayName}`)
-```
\ No newline at end of file
+```
diff --git a/packages/core/build.config.cjs b/packages/core/build.config.cjs
index 631e06a0..cf790424 100644
--- a/packages/core/build.config.cjs
+++ b/packages/core/build.config.cjs
@@ -5,7 +5,7 @@ module.exports = ({ path, glob, transformFile, packageDir, outDir, jsr }) => ({
esmImportDirectives: true,
final() {
const version = require(path.join(packageDir, 'package.json')).version
- const replaceVersion = (content) => content.replace('%VERSION%', version)
+ const replaceVersion = content => content.replace('%VERSION%', version)
if (jsr) {
transformFile(path.join(outDir, 'network/network-manager.ts'), replaceVersion)
@@ -21,11 +21,11 @@ module.exports = ({ path, glob, transformFile, packageDir, outDir, jsr }) => ({
// skip for jsr for now because types aren't resolved correctly and it breaks everything (TODO: fix this)
const decoratorsRegex = new RegExp(
`(${KNOWN_DECORATORS.join('|')})\\((.+?)\\)(?:;|$)`,
- 'gsm',
+ 'gms',
)
const replaceDecorators = (content, file) => {
- if (!KNOWN_DECORATORS.some((d) => content.includes(d))) return null
+ if (!KNOWN_DECORATORS.some(d => content.includes(d))) return null
const countPerClass = new Map()
@@ -61,7 +61,7 @@ module.exports = ({ path, glob, transformFile, packageDir, outDir, jsr }) => ({
)
}
- return content + '\n' + customExports.join('\n') + '\n'
+ return `${content}\n${customExports.join('\n')}\n`
}
const globSrc = path.join(outDir, jsr ? 'highlevel/types/**/*.ts' : 'esm/highlevel/types/**/*.js')
diff --git a/packages/core/package.json b/packages/core/package.json
index 4868565e..664bf81c 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -1,36 +1,36 @@
{
- "name": "@mtcute/core",
- "private": true,
- "version": "0.16.6",
- "description": "Type-safe library for MTProto (Telegram API)",
- "author": "alina sireneva ",
- "license": "MIT",
- "type": "module",
- "sideEffects": false,
- "scripts": {
- "build": "pnpm run -w build-package core",
- "gen-client": "node ./scripts/generate-client.cjs",
- "gen-updates": "node ./scripts/generate-updates.cjs"
- },
- "exports": {
- ".": "./src/index.ts",
- "./utils.js": "./src/utils/index.ts",
- "./client.js": "./src/highlevel/client.ts",
- "./worker.js": "./src/highlevel/worker/index.ts",
- "./methods.js": "./src/highlevel/methods.ts",
- "./platform.js": "./src/platform.ts"
- },
- "dependencies": {
- "@mtcute/tl": "workspace:^",
- "@mtcute/tl-runtime": "workspace:^",
- "@mtcute/file-id": "workspace:^",
- "@types/events": "3.0.0",
- "events": "3.2.0",
- "long": "5.2.3"
- },
- "devDependencies": {
- "@types/ws": "8.5.4",
- "@mtcute/test": "workspace:^",
- "ws": "8.13.0"
- }
+ "name": "@mtcute/core",
+ "type": "module",
+ "version": "0.16.6",
+ "private": true,
+ "description": "Type-safe library for MTProto (Telegram API)",
+ "author": "alina sireneva ",
+ "license": "MIT",
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts",
+ "./utils.js": "./src/utils/index.ts",
+ "./client.js": "./src/highlevel/client.ts",
+ "./worker.js": "./src/highlevel/worker/index.ts",
+ "./methods.js": "./src/highlevel/methods.ts",
+ "./platform.js": "./src/platform.ts"
+ },
+ "scripts": {
+ "build": "pnpm run -w build-package core",
+ "gen-client": "node ./scripts/generate-client.cjs",
+ "gen-updates": "node ./scripts/generate-updates.cjs"
+ },
+ "dependencies": {
+ "@mtcute/file-id": "workspace:^",
+ "@mtcute/tl": "workspace:^",
+ "@mtcute/tl-runtime": "workspace:^",
+ "@types/events": "3.0.0",
+ "events": "3.2.0",
+ "long": "5.2.3"
+ },
+ "devDependencies": {
+ "@mtcute/test": "workspace:^",
+ "@types/ws": "8.5.4",
+ "ws": "8.13.0"
+ }
}
diff --git a/packages/core/scripts/generate-app-config.cjs b/packages/core/scripts/generate-app-config.cjs
index 807c3bc3..fffd2e7b 100644
--- a/packages/core/scripts/generate-app-config.cjs
+++ b/packages/core/scripts/generate-app-config.cjs
@@ -1,5 +1,5 @@
-const fs = require('fs')
-const path = require('path')
+const fs = require('node:fs')
+const path = require('node:path')
const spec = require('@mtcute/tl/app-config.json')
@@ -12,11 +12,11 @@ out.write(`// This file is generated automatically, do not modify!
export interface AppConfigSchema {
`)
-const indent = (str) => str.split('\n').map((x) => ' ' + x).join('\n')
+const indent = str => str.split('\n').map(x => ` ${x}`).join('\n')
for (const [key, { type, description }] of Object.entries(spec)) {
- out.write(indent(description) + '\n')
- out.write(indent(`${key}?: ${type}`) + '\n')
+ out.write(`${indent(description)}\n`)
+ out.write(`${indent(`${key}?: ${type}`)}\n`)
}
out.write(' [key: string]: unknown\n')
diff --git a/packages/core/scripts/generate-client.cjs b/packages/core/scripts/generate-client.cjs
index 670d2052..2119d348 100644
--- a/packages/core/scripts/generate-client.cjs
+++ b/packages/core/scripts/generate-client.cjs
@@ -1,13 +1,14 @@
+const path = require('node:path')
+const fs = require('node:fs')
+
const ts = require('typescript')
-const path = require('path')
-const fs = require('fs')
-const prettier = require('prettier')
-const updates = require('./generate-updates.cjs')
const schema = require('../../tl/api-schema.json')
+const updates = require('./generate-updates.cjs')
+
function findMethodAvailability(method) {
- const entry = schema.e.find((it) => it.kind === 'method' && it.name === method)
+ const entry = schema.e.find(it => it.kind === 'method' && it.name === method)
if (!entry) return null
return entry.available ?? null
@@ -22,7 +23,7 @@ async function* getFiles(dir) {
const res = path.resolve(dir, dirent.name)
if (dirent.isDirectory()) {
- yield* getFiles(res)
+ yield * getFiles(res)
} else {
yield res
}
@@ -74,15 +75,15 @@ function findRawApiUsages(ast, fileName) {
visitRecursively(
ast,
- (node) => node.kind === ts.SyntaxKind.CallExpression,
+ node => node.kind === ts.SyntaxKind.CallExpression,
(call) => {
if (call.expression.kind !== ts.SyntaxKind.PropertyAccessExpression) return
const prop = call.expression
if (
- prop.name.escapedText === 'call' &&
- prop.expression.kind === ts.SyntaxKind.Identifier &&
- prop.expression.escapedText === firstParamName
+ prop.name.escapedText === 'call'
+ && prop.expression.kind === ts.SyntaxKind.Identifier
+ && prop.expression.escapedText === firstParamName
) {
usages.push(call)
}
@@ -102,7 +103,7 @@ function findRawApiUsages(ast, fileName) {
)
}
- const method = arg.properties.find((it) => it.name.escapedText === '_')
+ const method = arg.properties.find(it => it.name.escapedText === '_')
if (!method || method.kind !== ts.SyntaxKind.PropertyAssignment) {
throwError(call, fileName, 'First argument to this.call() must have a _ property')
@@ -142,18 +143,18 @@ function findDependencies(ast) {
visitRecursively(
ast,
- (node) => node.kind === ts.SyntaxKind.CallExpression,
+ node => node.kind === ts.SyntaxKind.CallExpression,
(call) => {
if (call.expression.kind !== ts.SyntaxKind.PropertyAccessExpression) return
const prop = call.expression
if (
- prop.name.escapedText !== 'call' &&
- prop.name.escapedText !== '_emitError' &&
- prop.name.escapedText !== '_cachePeersFrom' &&
- prop.name.escapedText !== 'importSession' &&
- prop.name.escapedText !== 'emit' &&
- prop.expression.kind === ts.SyntaxKind.ThisKeyword
+ prop.name.escapedText !== 'call'
+ && prop.name.escapedText !== '_emitError'
+ && prop.name.escapedText !== '_cachePeersFrom'
+ && prop.name.escapedText !== 'importSession'
+ && prop.name.escapedText !== 'emit'
+ && prop.expression.kind === ts.SyntaxKind.ThisKeyword
) {
deps.add(prop.name.escapedText)
}
@@ -163,14 +164,14 @@ function findDependencies(ast) {
return [...deps]
}
-function determineCommonAvailability(methods, resolver = (v) => v) {
+function determineCommonAvailability(methods, resolver = v => v) {
let common = 'both'
for (const method of methods) {
const available = resolver(method)
if (available === null) {
- console.log('availability null for ' + method)
+ console.log(`availability null for ${method}`)
return null
}
@@ -185,18 +186,8 @@ function determineCommonAvailability(methods, resolver = (v) => v) {
return common
}
-async function runPrettier(targetFile) {
- const prettierConfig = await prettier.resolveConfig(targetFile)
- let fullSource = await fs.promises.readFile(targetFile, 'utf-8')
- fullSource = await prettier.format(fullSource, {
- ...(prettierConfig || {}),
- filepath: targetFile,
- })
- await fs.promises.writeFile(targetFile, fullSource)
-}
-
function runEslint(targetFile) {
- require('child_process').execSync(`pnpm exec eslint --fix ${targetFile}`, {
+ require('node:child_process').execSync(`pnpm exec eslint --fix ${targetFile}`, {
stdio: 'inherit',
})
}
@@ -211,15 +202,15 @@ async function addSingleMethod(state, fileName) {
function getLeadingComments(ast) {
return (ts.getLeadingCommentRanges(fileFullText, ast.pos) || [])
- .map((range) => fileFullText.substring(range.pos, range.end))
+ .map(range => fileFullText.substring(range.pos, range.end))
.join('\n')
}
function checkForFlag(ast, flag) {
return getLeadingComments(ast)
.split('\n')
- .map((i) => i.replace(/^(\/\/|\s*\*+|\/\*\*+\s*)/g, '').trim())
- .find((i) => i.startsWith(flag))
+ .map(i => i.replace(/^(\/\/|\s*\*+|\/\*{2,}\s*)/g, '').trim())
+ .find(i => i.startsWith(flag))
}
const hasOverloads = {}
@@ -232,8 +223,8 @@ async function addSingleMethod(state, fileName) {
if (!isCopy) continue
if (
- !stmt.importClause.namedBindings ||
- stmt.importClause.namedBindings.kind !== ts.SyntaxKind.NamedImports
+ !stmt.importClause.namedBindings
+ || stmt.importClause.namedBindings.kind !== ts.SyntaxKind.NamedImports
) {
throwError(stmt, fileName, 'Only named imports are supported!')
}
@@ -247,7 +238,7 @@ async function addSingleMethod(state, fileName) {
const modName = path.basename(modFullPath)
module = path.join(path.relative(targetDir, modPath), modName).replace(/\\/g, '/') // replace path delim to unix
- if (module[0] !== '.') module = './' + module
+ if (module[0] !== '.') module = `./${module}`
}
if (module === './client') {
@@ -274,8 +265,8 @@ async function addSingleMethod(state, fileName) {
)
}
- const isExported = (stmt.modifiers || []).find((mod) => mod.kind === ts.SyntaxKind.ExportKeyword)
- const isDeclare = (stmt.modifiers || []).find((mod) => mod.kind === ts.SyntaxKind.DeclareKeyword)
+ const isExported = (stmt.modifiers || []).find(mod => mod.kind === ts.SyntaxKind.ExportKeyword)
+ const isDeclare = (stmt.modifiers || []).find(mod => mod.kind === ts.SyntaxKind.DeclareKeyword)
const isInitialize = checkForFlag(stmt, '@initialize')
const isManualImpl = checkForFlag(stmt, '@manual-impl')
const isInitializeSuper = isInitialize === 'super'
@@ -302,7 +293,7 @@ async function addSingleMethod(state, fileName) {
return available
})()
const rawApiMethods = available === null && findRawApiUsages(stmt, fileName)
- const dependencies = findDependencies(stmt).filter((it) => it !== name)
+ const dependencies = findDependencies(stmt).filter(it => it !== name)
if (isInitialize && isExported) {
throwError(isExported, fileName, 'Initialization methods must not be exported')
@@ -391,7 +382,7 @@ async function addSingleMethod(state, fileName) {
continue
}
- const isExported = (stmt.modifiers || []).find((mod) => mod.kind === ts.SyntaxKind.ExportKeyword)
+ const isExported = (stmt.modifiers || []).find(mod => mod.kind === ts.SyntaxKind.ExportKeyword)
if (isTypeExported) {
if (!isExported) {
@@ -425,7 +416,7 @@ async function addSingleMethod(state, fileName) {
})
}
} else if (stmt.kind === ts.SyntaxKind.TypeAliasDeclaration && isTypeExported) {
- const isExported = (stmt.modifiers || []).find((mod) => mod.kind === ts.SyntaxKind.ExportKeyword)
+ const isExported = (stmt.modifiers || []).find(mod => mod.kind === ts.SyntaxKind.ExportKeyword)
if (!isExported) {
throwError(stmt, fileName, 'Exported type aliases must be exported')
@@ -471,11 +462,10 @@ async function main() {
}
output.write(
- '/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging, @typescript-eslint/unified-signatures */\n' +
- '/* eslint-disable @typescript-eslint/no-unsafe-argument */\n' +
- '/* THIS FILE WAS AUTO-GENERATED */\n' +
- "import EventEmitter from 'events'\n" +
- "import Long from 'long'\n",
+ '/* eslint-disable ts/no-unsafe-declaration-merging, ts/no-unsafe-argument */\n'
+ + '/* THIS FILE WAS AUTO-GENERATED */\n'
+ + "import EventEmitter from 'events'\n"
+ + "import Long from 'long'\n",
)
Object.entries(state.imports).forEach(([module, items]) => {
items = [...items]
@@ -518,7 +508,7 @@ on(name: '${type.typeName}', handler: ((upd: ${type.updateType}) => void)): this
})
output.write(`
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
+// eslint-disable-next-line ts/no-explicit-any
on(name: string, handler: (...args: any[]) => void): this\n
/**
@@ -554,7 +544,7 @@ withParams(params: RpcCallOptions): this\n`)
// try to determine it automatically
const checkDepsAvailability = (deps) => {
return determineCommonAvailability(deps, (name) => {
- const method = state.methods.list.find((it) => it.name === name && !it.overload)
+ const method = state.methods.list.find(it => it.name === name && !it.overload)
if (!method) {
throwError(
@@ -583,12 +573,12 @@ withParams(params: RpcCallOptions): this\n`)
// create method that calls that function and passes `this`
// first let's determine the signature
- const returnType = func.type ? ': ' + func.type.getText() : ''
- const generics = func.typeParameters ?
- `<${func.typeParameters.map((it) => it.getFullText()).join(', ')}>` :
- ''
+ const returnType = func.type ? `: ${func.type.getText()}` : ''
+ const generics = func.typeParameters
+ ? `<${func.typeParameters.map(it => it.getFullText()).join(', ')}>`
+ : ''
const rawParams = (func.parameters || []).filter(
- (it) => !it.type || it.type.getText() !== 'ITelegramClient',
+ it => !it.type || it.type.getText() !== 'ITelegramClient',
)
const parameters = rawParams
.map((it) => {
@@ -600,16 +590,16 @@ withParams(params: RpcCallOptions): this\n`)
// no explicit type.
// infer from initializer
if (
- it.initializer.kind === ts.SyntaxKind.TrueKeyword ||
- it.initializer.kind === ts.SyntaxKind.FalseKeyword
+ it.initializer.kind === ts.SyntaxKind.TrueKeyword
+ || it.initializer.kind === ts.SyntaxKind.FalseKeyword
) {
it.type = { kind: ts.SyntaxKind.BooleanKeyword }
} else if (it.initializer.kind === ts.SyntaxKind.StringLiteral) {
it.type = { kind: ts.SyntaxKind.StringKeyword }
} else if (
- it.initializer.kind === ts.SyntaxKind.NumericLiteral ||
- (it.initializer.kind === ts.SyntaxKind.Identifier &&
- (it.initializer.escapedText === 'NaN' || it.initializer.escapedText === 'Infinity'))
+ it.initializer.kind === ts.SyntaxKind.NumericLiteral
+ || (it.initializer.kind === ts.SyntaxKind.Identifier
+ && (it.initializer.escapedText === 'NaN' || it.initializer.escapedText === 'Infinity'))
) {
it.type = { kind: ts.SyntaxKind.NumberKeyword }
} else {
@@ -620,7 +610,7 @@ withParams(params: RpcCallOptions): this\n`)
const deleteParents = (obj) => {
if (Array.isArray(obj)) {
- return obj.forEach((it) => deleteParents(it))
+ return obj.forEach(it => deleteParents(it))
}
if (obj.parent) delete obj.parent
@@ -648,15 +638,16 @@ withParams(params: RpcCallOptions): this\n`)
// remove @internal mark and set default values for parameters
comment = comment
- .replace(/^\s*\/\/+\s*@(alias|available|manual).*$/gm, '')
- .replace(/(\n^|\/\*)\s*\*\s*@internal.*/m, '')
- .replace(/((?:\n^|\/\*)\s*\*\s*@param )([^\s]+?)($|\s+)/gm, (_, pref, arg, post) => {
- const param = rawParams.find((it) => it.name.escapedText === arg)
+ .replace(/^\s*\/{2,}\s*@(alias|available|manual).*$/gm, '')
+ .replace(/(\n|\/\*)\s*\*\s*@internal.*/, '')
+ .replace(/((?:\n|\/\*)\s*\*\s*@param )(\S+)($|\s+)/gm, (_, pref, arg, post) => {
+ const param = rawParams.find(it => it.name.escapedText === arg)
if (!param) return _
if (!param._savedDefault) return _
return `${pref}[${arg}=${param._savedDefault.trim()}]${post}`
})
+ // eslint-disable-next-line regexp/optimal-lookaround-quantifier
.replace(/(?<=\/\*.*)(?=\n\s*\*\s*(?:@[a-z]+|\/))/s, () => {
switch (available) {
case 'user':
@@ -674,7 +665,7 @@ withParams(params: RpcCallOptions): this\n`)
if (!hasOverloads) {
if (!comment.match(/\/\*\*?\s*\*\//)) {
// empty comment, no need to write it
- output.write(comment + '\n')
+ output.write(`${comment}\n`)
}
output.write(`${name}${generics}(${parameters})${returnType}\n`)
@@ -707,11 +698,11 @@ withParams(params: RpcCallOptions): this\n`)
output.write('constructor(opts: TelegramClientOptions) {\n')
output.write(' super()\n')
state.init.forEach((code) => {
- output.write(code + '\n')
+ output.write(`${code}\n`)
})
output.write('}\n')
- classContents.forEach((line) => output.write(line + '\n'))
+ classContents.forEach(line => output.write(`${line}\n`))
output.write(` withParams(params: RpcCallOptions): this {
return withParams(this, params)
@@ -719,7 +710,7 @@ withParams(params: RpcCallOptions): this\n`)
output.write('}\n')
- classProtoDecls.forEach((line) => output.write(line + '\n'))
+ classProtoDecls.forEach(line => output.write(`${line}\n`))
// proxied methods
;[
'prepare',
@@ -747,18 +738,18 @@ withParams(params: RpcCallOptions): this\n`)
'changePrimaryDc',
].forEach((name) => {
output.write(
- `TelegramClient.prototype.${name} = function(...args) {\n` +
- ` return this._client.${name}(...args)\n` +
- '}\n',
+ `TelegramClient.prototype.${name} = function(...args) {\n`
+ + ` return this._client.${name}(...args)\n`
+ + '}\n',
)
})
// disabled methods - they are used internally and we don't want to expose them
// if the user *really* needs them, they can use `client._client` to access the underlying client
;['onServerUpdate', 'onUpdate'].forEach((name) => {
output.write(
- `TelegramClient.prototype.${name} = function() {\n` +
- ` throw new Error('${name} is not available for TelegramClient, use .on() methods instead')\n` +
- '}\n',
+ `TelegramClient.prototype.${name} = function() {\n`
+ + ` throw new Error('${name} is not available for TelegramClient, use .on() methods instead')\n`
+ + '}\n',
)
})
state.impls.forEach(({ name, code }) => output.write(`TelegramClient.prototype.${name} = ${code}\n`))
@@ -781,10 +772,6 @@ withParams(params: RpcCallOptions): this\n`)
await new Promise((resolve) => { outputMethods.end(resolve) })
await new Promise((resolve) => { output.end(resolve) })
- // format the resulting files with prettier and eslint
- runPrettier(targetFile)
- runPrettier(targetFileMethods)
-
runEslint(targetFile)
runEslint(targetFileMethods)
}
diff --git a/packages/core/scripts/generate-updates.cjs b/packages/core/scripts/generate-updates.cjs
index c814655d..2e16ce70 100644
--- a/packages/core/scripts/generate-updates.cjs
+++ b/packages/core/scripts/generate-updates.cjs
@@ -1,18 +1,17 @@
-const fs = require('fs')
-const path = require('path')
-const prettier = require('prettier')
+const fs = require('node:fs')
+const path = require('node:path')
-const snakeToCamel = (s) => {
+function snakeToCamel(s) {
return s.replace(/(? {
return $1.substr(1).toUpperCase()
})
}
-const camelToPascal = (s) => s[0].toUpperCase() + s.substr(1)
+const camelToPascal = s => s[0].toUpperCase() + s.substr(1)
-const camelToSnake = (s) => {
+function camelToSnake(s) {
return s.replace(/(?<=[a-zA-Z0-9])([A-Z0-9]+(?=[A-Z]|$)|[A-Z0-9])/g, ($1) => {
- return '_' + $1.toLowerCase()
+ return `_${$1.toLowerCase()}`
})
}
@@ -20,8 +19,8 @@ function parseUpdateTypes() {
const lines = fs
.readFileSync(path.join(__dirname, 'update-types.txt'), 'utf-8')
.split('\n')
- .map((it) => it.trim())
- .filter((it) => it && it[0] !== '#')
+ .map(it => it.trim())
+ .filter(it => it && it[0] !== '#')
const ret = []
@@ -42,11 +41,11 @@ function parseUpdateTypes() {
}
function replaceSections(filename, sections, dir = __dirname) {
- let lines = fs.readFileSync(path.join(dir, '../src', filename), 'utf-8').split('\n')
+ const lines = fs.readFileSync(path.join(dir, '../src', filename), 'utf-8').split('\n')
const findMarker = (marker) => {
- const idx = lines.findIndex((line) => line.trim() === `// ${marker}`)
- if (idx === -1) throw new Error(marker + ' not found')
+ const idx = lines.findIndex(line => line.trim() === `// ${marker}`)
+ if (idx === -1) throw new Error(`${marker} not found`)
return idx
}
@@ -65,17 +64,6 @@ function replaceSections(filename, sections, dir = __dirname) {
const types = parseUpdateTypes()
-async function formatFile(filename, dir = __dirname) {
- const targetFile = path.join(dir, '../src/', filename)
- const prettierConfig = await prettier.resolveConfig(targetFile)
- let fullSource = await fs.promises.readFile(targetFile, 'utf-8')
- fullSource = await prettier.format(fullSource, {
- ...(prettierConfig || {}),
- filepath: targetFile,
- })
- await fs.promises.writeFile(targetFile, fullSource)
-}
-
function toSentence(type, stype = 'inline') {
const name = camelToSnake(type.handlerTypeName).toLowerCase().replace(/_/g, ' ')
@@ -91,8 +79,8 @@ function toSentence(type, stype = 'inline') {
function generateParsedUpdate() {
replaceSections('highlevel/types/updates/index.ts', {
codegen:
- 'export type ParsedUpdate =\n' +
- types.map((typ) => ` | { name: '${typ.typeName}'; data: ${typ.updateType} }\n`).join(''),
+ `export type ParsedUpdate =\n${
+ types.map(typ => ` | { name: '${typ.typeName}'; data: ${typ.updateType} }\n`).join('')}`,
})
}
@@ -100,7 +88,7 @@ async function main() {
generateParsedUpdate()
}
-module.exports = { types, toSentence, replaceSections, formatFile }
+module.exports = { types, toSentence, replaceSections }
if (require.main === module) {
main().catch(console.error)
diff --git a/packages/core/src/highlevel/base.test.ts b/packages/core/src/highlevel/base.test.ts
index 8447405a..4aeef310 100644
--- a/packages/core/src/highlevel/base.test.ts
+++ b/packages/core/src/highlevel/base.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
-
import { StubTelegramClient } from '@mtcute/test'
describe('BaseTelegramClient', () => {
diff --git a/packages/core/src/highlevel/base.ts b/packages/core/src/highlevel/base.ts
index f6708d9a..5ed8520e 100644
--- a/packages/core/src/highlevel/base.ts
+++ b/packages/core/src/highlevel/base.ts
@@ -1,30 +1,35 @@
-/* eslint-disable @typescript-eslint/require-await */
-import { mtp, tl } from '@mtcute/tl'
+import type { mtp } from '@mtcute/tl'
+import { tl } from '@mtcute/tl'
-import { MtClient, MtClientOptions } from '../network/client.js'
-import { ConnectionKind, RpcCallOptions } from '../network/network-manager.js'
-import { StorageManagerExtraOptions } from '../storage/storage.js'
+import type { MtClientOptions } from '../network/client.js'
+import { MtClient } from '../network/client.js'
+import type { ConnectionKind, RpcCallOptions } from '../network/network-manager.js'
+import type { StorageManagerExtraOptions } from '../storage/storage.js'
import { MtArgumentError } from '../types/errors.js'
-import { MustEqual } from '../types/utils.js'
+import type { MustEqual } from '../types/utils.js'
import { reportUnknownError } from '../utils/error-reporting.js'
+import type {
+ ICryptoProvider,
+ Logger,
+ StringSessionData,
+} from '../utils/index.js'
import {
asyncResettable,
computeNewPasswordHash,
computeSrpParams,
- ICryptoProvider,
isTlRpcError,
- Logger,
readStringSession,
- StringSessionData,
writeStringSession,
} from '../utils/index.js'
import { LogManager } from '../utils/logger.js'
-import { ConnectionState, ITelegramClient, ServerUpdateHandler } from './client.types.js'
+
+import type { ConnectionState, ITelegramClient, ServerUpdateHandler } from './client.types.js'
import { AppConfigManager } from './managers/app-config-manager.js'
-import { ITelegramStorageProvider } from './storage/provider.js'
-import { TelegramStorageManager, TelegramStorageManagerExtraOptions } from './storage/storage.js'
+import type { ITelegramStorageProvider } from './storage/provider.js'
+import type { TelegramStorageManagerExtraOptions } from './storage/storage.js'
+import { TelegramStorageManager } from './storage/storage.js'
import { UpdatesManager } from './updates/manager.js'
-import { RawUpdateHandler, UpdatesManagerParams } from './updates/types.js'
+import type { RawUpdateHandler, UpdatesManagerParams } from './updates/types.js'
export interface BaseTelegramClientOptions extends MtClientOptions {
storage: ITelegramStorageProvider
@@ -88,7 +93,8 @@ export class BaseTelegramClient implements ITelegramClient {
...this.params.storageOptions,
})
}
- readonly appConfig = new AppConfigManager(this)
+
+ readonly appConfig: AppConfigManager = new AppConfigManager(this)
private _prepare = asyncResettable(async () => {
await this.mt.prepare()
@@ -109,7 +115,7 @@ export class BaseTelegramClient implements ITelegramClient {
*
* Call {@link connect} to actually connect.
*/
- prepare() {
+ prepare(): Promise {
return this._prepare.run()
}
@@ -197,6 +203,7 @@ export class BaseTelegramClient implements ITelegramClient {
const res = await this.mt.call(message, params)
if (isTlRpcError(res)) {
+ // eslint-disable-next-line unicorn/error-message
const error = makeRpcError(res, new Error().stack ?? '', message._)
if (error.unknown && this.params.enableErrorReporting) {
@@ -208,7 +215,7 @@ export class BaseTelegramClient implements ITelegramClient {
await this.storage.peers.updatePeersFrom(res)
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
+ // eslint-disable-next-line ts/no-unsafe-return
return res
}
@@ -233,9 +240,9 @@ export class BaseTelegramClient implements ITelegramClient {
if (data.testMode && !this.params.testMode) {
throw new Error(
- 'This session string is not for the current backend. ' +
- `Session is ${data.testMode ? 'test' : 'prod'}, ` +
- `but the client is ${this.params.testMode ? 'test' : 'prod'}`,
+ 'This session string is not for the current backend. '
+ + `Session is ${data.testMode ? 'test' : 'prod'}, `
+ + `but the client is ${this.params.testMode ? 'test' : 'prod'}`,
)
}
@@ -320,7 +327,10 @@ export class BaseTelegramClient implements ITelegramClient {
this._connectionStateHandler = handler
}
- async getApiCrenetials() {
+ async getApiCrenetials(): Promise<{
+ id: number
+ hash: string
+ }> {
return {
id: this.params.apiId,
hash: this.params.apiHash,
@@ -346,6 +356,7 @@ export class BaseTelegramClient implements ITelegramClient {
computeSrpParams(request: tl.account.RawPassword, password: string): Promise {
return computeSrpParams(this.crypto, request, password)
}
+
computeNewPasswordHash(algo: tl.TypePasswordKdfAlgo, password: string): Promise {
return computeNewPasswordHash(this.crypto, algo, password)
}
diff --git a/packages/core/src/highlevel/client.ts b/packages/core/src/highlevel/client.ts
index fa5409b6..c4f43a21 100644
--- a/packages/core/src/highlevel/client.ts
+++ b/packages/core/src/highlevel/client.ts
@@ -1,29 +1,38 @@
-/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging, @typescript-eslint/unified-signatures */
-/* eslint-disable @typescript-eslint/no-unsafe-argument */
+/* eslint-disable ts/no-unsafe-declaration-merging, ts/no-unsafe-argument */
/* THIS FILE WAS AUTO-GENERATED */
-import EventEmitter from 'events'
-import Long from 'long'
+import EventEmitter from 'node:events'
-import { tdFileId } from '@mtcute/file-id'
-import { tl } from '@mtcute/tl'
+import type Long from 'long'
+import type { tdFileId } from '@mtcute/file-id'
+import type { tl } from '@mtcute/tl'
-import { RpcCallOptions } from '../network/index.js'
-import { MaybeArray, MaybePromise, MtUnsupportedError, PartialExcept, PartialOnly } from '../types/index.js'
-import { BaseTelegramClient, BaseTelegramClientOptions } from './base.js'
-import { ITelegramClient } from './client.types.js'
+import type { RpcCallOptions } from '../network/index.js'
+import type { MaybeArray, MaybePromise, PartialExcept, PartialOnly } from '../types/index.js'
+import { MtUnsupportedError } from '../types/index.js'
+
+import type { BaseTelegramClientOptions } from './base.js'
+import { BaseTelegramClient } from './base.js'
+import type { ITelegramClient } from './client.types.js'
+import type { AllStories, ArrayPaginated, ArrayWithTotal, Boost, BoostSlot, BoostStats, BotChatJoinRequestUpdate, BotCommands, BotReactionCountUpdate, BotReactionUpdate, BotStoppedUpdate, BusinessCallbackQuery, BusinessChatLink, BusinessConnection, BusinessMessage, BusinessWorkHoursDay, CallbackQuery, Chat, ChatEvent, ChatInviteLink, ChatInviteLinkMember, ChatJoinRequestUpdate, ChatMember, ChatMemberUpdate, ChatPreview, ChatlistPreview, ChosenInlineResult, CollectibleInfo, DeleteBusinessMessageUpdate, DeleteMessageUpdate, DeleteStoryUpdate, Dialog, FactCheck, FileDownloadLocation, FileDownloadParameters, ForumTopic, FullChat, GameHighScore, HistoryReadUpdate, InlineCallbackQuery, InlineQuery, InputChatEventFilters, InputDialogFolder, InputFileLike, InputInlineResult, InputMediaLike, InputMediaSticker, InputMessageId, InputPeerLike, InputPrivacyRule, InputReaction, InputStickerSet, InputStickerSetItem, InputText, MaybeDynamic, Message, MessageEffect, MessageMedia, MessageReactions, ParametersSkip2, ParsedUpdate, PeerReaction, PeerStories, PeersIndex, Photo, Poll, PollUpdate, PollVoteUpdate, PreCheckoutQuery, RawDocument, ReplyMarkup, SentCode, Sticker, StickerSet, StickerSourceType, StickerType, StoriesStealthMode, Story, StoryInteractions, StoryUpdate, StoryViewer, StoryViewersList, TakeoutSession, TextWithEntities, TypingStatus, UploadFileLike, UploadedFile, User, UserStatusUpdate, UserTypingUpdate } from './types/index.js'
+import type { StringSessionData } from './utils/string-session.js'
+import type { ITelegramStorageProvider } from './storage/provider.js'
+import { Conversation } from './types/conversation.js'
+import type { ParsedUpdateHandlerParams } from './updates/parsed.js'
+import { makeParsedUpdateHandler } from './updates/parsed.js'
import { checkPassword } from './methods/auth/check-password.js'
import { getPasswordHint } from './methods/auth/get-password-hint.js'
-import { logOut, LogOutResult } from './methods/auth/log-out.js'
+import type { LogOutResult } from './methods/auth/log-out.js'
+import { logOut } from './methods/auth/log-out.js'
import { recoverPassword } from './methods/auth/recover-password.js'
import { resendCode } from './methods/auth/resend-code.js'
import { run } from './methods/auth/run.js'
import { sendCode } from './methods/auth/send-code.js'
import { sendRecoveryCode } from './methods/auth/send-recovery-code.js'
-import { signIn } from './methods/auth/sign-in.js'
import { signInBot } from './methods/auth/sign-in-bot.js'
import { signInQr } from './methods/auth/sign-in-qr.js'
-import { start } from './methods/auth/start.js'
+import { signIn } from './methods/auth/sign-in.js'
import { startTest } from './methods/auth/start-test.js'
+import { start } from './methods/auth/start.js'
import { isSelfPeer } from './methods/auth/utils.js'
import { answerCallbackQuery } from './methods/bots/answer-callback-query.js'
import { answerInlineQuery } from './methods/bots/answer-inline-query.js'
@@ -43,7 +52,8 @@ import { addChatMembers } from './methods/chats/add-chat-members.js'
import { archiveChats } from './methods/chats/archive-chats.js'
import { banChatMember } from './methods/chats/ban-chat-member.js'
import { createChannel } from './methods/chats/create-channel.js'
-import { createGroup, CreateGroupResult } from './methods/chats/create-group.js'
+import type { CreateGroupResult } from './methods/chats/create-group.js'
+import { createGroup } from './methods/chats/create-group.js'
import { createSupergroup } from './methods/chats/create-supergroup.js'
import { deleteChannel } from './methods/chats/delete-channel.js'
import { deleteChatPhoto } from './methods/chats/delete-chat-photo.js'
@@ -51,11 +61,11 @@ import { deleteGroup } from './methods/chats/delete-group.js'
import { deleteHistory } from './methods/chats/delete-history.js'
import { deleteUserHistory } from './methods/chats/delete-user-history.js'
import { editAdminRights } from './methods/chats/edit-admin-rights.js'
-import { getChat } from './methods/chats/get-chat.js'
import { getChatEventLog } from './methods/chats/get-chat-event-log.js'
import { getChatMember } from './methods/chats/get-chat-member.js'
import { getChatMembers } from './methods/chats/get-chat-members.js'
import { getChatPreview } from './methods/chats/get-chat-preview.js'
+import { getChat } from './methods/chats/get-chat.js'
import { getFullChat } from './methods/chats/get-full-chat.js'
import { getNearbyChats } from './methods/chats/get-nearby-chats.js'
import { getSimilarChannels } from './methods/chats/get-similar-channels.js'
@@ -108,20 +118,22 @@ import { uploadMedia } from './methods/files/upload-media.js'
import { createForumTopic } from './methods/forums/create-forum-topic.js'
import { deleteForumTopicHistory } from './methods/forums/delete-forum-topic-history.js'
import { editForumTopic } from './methods/forums/edit-forum-topic.js'
-import { getForumTopics, GetForumTopicsOffset } from './methods/forums/get-forum-topics.js'
import { getForumTopicsById } from './methods/forums/get-forum-topics-by-id.js'
+import type { GetForumTopicsOffset } from './methods/forums/get-forum-topics.js'
+import { getForumTopics } from './methods/forums/get-forum-topics.js'
import { iterForumTopics } from './methods/forums/iter-forum-topics.js'
import { reorderPinnedForumTopics } from './methods/forums/reorder-pinned-forum-topics.js'
-import { toggleForum } from './methods/forums/toggle-forum.js'
import { toggleForumTopicClosed } from './methods/forums/toggle-forum-topic-closed.js'
import { toggleForumTopicPinned } from './methods/forums/toggle-forum-topic-pinned.js'
+import { toggleForum } from './methods/forums/toggle-forum.js'
import { toggleGeneralTopicHidden } from './methods/forums/toggle-general-topic-hidden.js'
import { createInviteLink } from './methods/invite-links/create-invite-link.js'
import { editInviteLink } from './methods/invite-links/edit-invite-link.js'
import { exportInviteLink } from './methods/invite-links/export-invite-link.js'
-import { getInviteLink } from './methods/invite-links/get-invite-link.js'
import { getInviteLinkMembers } from './methods/invite-links/get-invite-link-members.js'
-import { getInviteLinks, GetInviteLinksOffset } from './methods/invite-links/get-invite-links.js'
+import { getInviteLink } from './methods/invite-links/get-invite-link.js'
+import type { GetInviteLinksOffset } from './methods/invite-links/get-invite-links.js'
+import { getInviteLinks } from './methods/invite-links/get-invite-links.js'
import { getPrimaryInviteLink } from './methods/invite-links/get-primary-invite-link.js'
import { hideAllJoinRequests } from './methods/invite-links/hide-all-join-requests.js'
import { hideJoinRequest } from './methods/invite-links/hide-join-request.js'
@@ -129,23 +141,27 @@ import { iterInviteLinkMembers } from './methods/invite-links/iter-invite-link-m
import { iterInviteLinks } from './methods/invite-links/iter-invite-links.js'
import { revokeInviteLink } from './methods/invite-links/revoke-invite-link.js'
import { closePoll } from './methods/messages/close-poll.js'
-import { deleteMessages, deleteMessagesById, DeleteMessagesParams } from './methods/messages/delete-messages.js'
+import type { DeleteMessagesParams } from './methods/messages/delete-messages.js'
+import { deleteMessages, deleteMessagesById } from './methods/messages/delete-messages.js'
import { deleteScheduledMessages } from './methods/messages/delete-scheduled-messages.js'
import { editInlineMessage } from './methods/messages/edit-inline-message.js'
import { editMessage } from './methods/messages/edit-message.js'
-import { ForwardMessageOptions, forwardMessages, forwardMessagesById } from './methods/messages/forward-messages.js'
+import type { ForwardMessageOptions } from './methods/messages/forward-messages.js'
+import { forwardMessages, forwardMessagesById } from './methods/messages/forward-messages.js'
import { getAllScheduledMessages } from './methods/messages/get-all-scheduled-messages.js'
import { getAvailableMessageEffects } from './methods/messages/get-available-effects.js'
import { getCallbackQueryMessage } from './methods/messages/get-callback-query-message.js'
import { getDiscussionMessage } from './methods/messages/get-discussion-message.js'
import { getFactCheck } from './methods/messages/get-fact-check.js'
-import { getHistory, GetHistoryOffset } from './methods/messages/get-history.js'
+import type { GetHistoryOffset } from './methods/messages/get-history.js'
+import { getHistory } from './methods/messages/get-history.js'
import { getMessageByLink } from './methods/messages/get-message-by-link.js'
import { getMessageGroup } from './methods/messages/get-message-group.js'
import { getMessageReactions, getMessageReactionsById } from './methods/messages/get-message-reactions.js'
-import { getMessages } from './methods/messages/get-messages.js'
import { getMessagesUnsafe } from './methods/messages/get-messages-unsafe.js'
-import { getReactionUsers, GetReactionUsersOffset } from './methods/messages/get-reaction-users.js'
+import { getMessages } from './methods/messages/get-messages.js'
+import type { GetReactionUsersOffset } from './methods/messages/get-reaction-users.js'
+import { getReactionUsers } from './methods/messages/get-reaction-users.js'
import { getReplyTo } from './methods/messages/get-reply-to.js'
import { getScheduledMessages } from './methods/messages/get-scheduled-messages.js'
import { iterHistory } from './methods/messages/iter-history.js'
@@ -155,17 +171,23 @@ import { iterSearchMessages } from './methods/messages/iter-search-messages.js'
import { pinMessage } from './methods/messages/pin-message.js'
import { readHistory } from './methods/messages/read-history.js'
import { readReactions } from './methods/messages/read-reactions.js'
-import { searchGlobal, SearchGlobalOffset } from './methods/messages/search-global.js'
-import { iterSearchHashtag, searchHashtag, SearchHashtagOffset } from './methods/messages/search-hashtag.js'
-import { searchMessages, SearchMessagesOffset } from './methods/messages/search-messages.js'
+import type { SearchGlobalOffset } from './methods/messages/search-global.js'
+import { searchGlobal } from './methods/messages/search-global.js'
+import type { SearchHashtagOffset } from './methods/messages/search-hashtag.js'
+import { iterSearchHashtag, searchHashtag } from './methods/messages/search-hashtag.js'
+import type { SearchMessagesOffset } from './methods/messages/search-messages.js'
+import { searchMessages } from './methods/messages/search-messages.js'
import { answerMedia, answerMediaGroup, answerText } from './methods/messages/send-answer.js'
import { commentMedia, commentMediaGroup, commentText } from './methods/messages/send-comment.js'
-import { CommonSendParams } from './methods/messages/send-common.js'
-import { sendCopy, SendCopyParams } from './methods/messages/send-copy.js'
-import { sendCopyGroup, SendCopyGroupParams } from './methods/messages/send-copy-group.js'
-import { sendMedia } from './methods/messages/send-media.js'
+import type { CommonSendParams } from './methods/messages/send-common.js'
+import type { SendCopyGroupParams } from './methods/messages/send-copy-group.js'
+import { sendCopyGroup } from './methods/messages/send-copy-group.js'
+import type { SendCopyParams } from './methods/messages/send-copy.js'
+import { sendCopy } from './methods/messages/send-copy.js'
import { sendMediaGroup } from './methods/messages/send-media-group.js'
-import { QuoteParamsFrom, quoteWithMedia, quoteWithMediaGroup, quoteWithText } from './methods/messages/send-quote.js'
+import { sendMedia } from './methods/messages/send-media.js'
+import type { QuoteParamsFrom } from './methods/messages/send-quote.js'
+import { quoteWithMedia, quoteWithMediaGroup, quoteWithText } from './methods/messages/send-quote.js'
import { sendReaction } from './methods/messages/send-reaction.js'
import { replyMedia, replyMediaGroup, replyText } from './methods/messages/send-reply.js'
import { sendScheduled } from './methods/messages/send-scheduled.js'
@@ -179,13 +201,13 @@ import { unpinMessage } from './methods/messages/unpin-message.js'
import { getCollectibleInfo } from './methods/misc/get-collectible-info.js'
import { initTakeoutSession } from './methods/misc/init-takeout-session.js'
import { _normalizePrivacyRules } from './methods/misc/normalize-privacy-rules.js'
-import { withParams } from './methods/misc/with-params.js'
import { changeCloudPassword } from './methods/password/change-cloud-password.js'
import { enableCloudPassword } from './methods/password/enable-cloud-password.js'
import { cancelPasswordEmail, resendPasswordEmail, verifyPasswordEmail } from './methods/password/password-email.js'
import { removeCloudPassword } from './methods/password/remove-cloud-password.js'
import { applyBoost } from './methods/premium/apply-boost.js'
-import { canApplyBoost, CanApplyBoostResult } from './methods/premium/can-apply-boost.js'
+import type { CanApplyBoostResult } from './methods/premium/can-apply-boost.js'
+import { canApplyBoost } from './methods/premium/can-apply-boost.js'
import { createBusinessChatLink } from './methods/premium/create-business-chat-link.js'
import { deleteBusinessChatLink, editBusinessChatLink } from './methods/premium/edit-business-chat-link.js'
import { getBoostStats } from './methods/premium/get-boost-stats.js'
@@ -207,7 +229,8 @@ import { moveStickerInSet } from './methods/stickers/move-sticker-in-set.js'
import { replaceStickerInSet } from './methods/stickers/replace-sticker-in-set.js'
import { setChatStickerSet } from './methods/stickers/set-chat-sticker-set.js'
import { setStickerSetThumb } from './methods/stickers/set-sticker-set-thumb.js'
-import { canSendStory, CanSendStoryResult } from './methods/stories/can-send-story.js'
+import type { CanSendStoryResult } from './methods/stories/can-send-story.js'
+import { canSendStory } from './methods/stories/can-send-story.js'
import { deleteStories } from './methods/stories/delete-stories.js'
import { editStory } from './methods/stories/edit-story.js'
import { getAllStories } from './methods/stories/get-all-stories.js'
@@ -224,8 +247,8 @@ import { iterProfileStories } from './methods/stories/iter-profile-stories.js'
import { iterStoryViewers } from './methods/stories/iter-story-viewers.js'
import { readStories } from './methods/stories/read-stories.js'
import { reportStory } from './methods/stories/report-story.js'
-import { sendStory } from './methods/stories/send-story.js'
import { sendStoryReaction } from './methods/stories/send-story-reaction.js'
+import { sendStory } from './methods/stories/send-story.js'
import { togglePeerStoriesArchived } from './methods/stories/toggle-peer-stories-archived.js'
import { toggleStoriesPinned } from './methods/stories/toggle-stories-pinned.js'
import { blockUser } from './methods/users/block-user.js'
@@ -239,8 +262,8 @@ import { getProfilePhoto } from './methods/users/get-profile-photo.js'
import { getProfilePhotos } from './methods/users/get-profile-photos.js'
import { getUsers } from './methods/users/get-users.js'
import { iterProfilePhotos } from './methods/users/iter-profile-photos.js'
-import { resolveChannel, resolvePeer, resolveUser } from './methods/users/resolve-peer.js'
import { resolvePeerMany } from './methods/users/resolve-peer-many.js'
+import { resolveChannel, resolvePeer, resolveUser } from './methods/users/resolve-peer.js'
import { setGlobalTtl } from './methods/users/set-global-ttl.js'
import { setMyBirthday } from './methods/users/set-my-birthday.js'
import { setMyEmojiStatus } from './methods/users/set-my-emoji-status.js'
@@ -249,116 +272,21 @@ import { setMyUsername } from './methods/users/set-my-username.js'
import { setOffline } from './methods/users/set-offline.js'
import { unblockUser } from './methods/users/unblock-user.js'
import { updateProfile } from './methods/users/update-profile.js'
-import { ITelegramStorageProvider } from './storage/provider.js'
-import { Conversation } from './types/conversation.js'
-import {
- AllStories,
- ArrayPaginated,
- ArrayWithTotal,
- Boost,
- BoostSlot,
- BoostStats,
- BotChatJoinRequestUpdate,
- BotCommands,
- BotReactionCountUpdate,
- BotReactionUpdate,
- BotStoppedUpdate,
- BusinessCallbackQuery,
- BusinessChatLink,
- BusinessConnection,
- BusinessMessage,
- BusinessWorkHoursDay,
- CallbackQuery,
- Chat,
- ChatEvent,
- ChatInviteLink,
- ChatInviteLinkMember,
- ChatJoinRequestUpdate,
- ChatlistPreview,
- ChatMember,
- ChatMemberUpdate,
- ChatPreview,
- ChosenInlineResult,
- CollectibleInfo,
- DeleteBusinessMessageUpdate,
- DeleteMessageUpdate,
- DeleteStoryUpdate,
- Dialog,
- FactCheck,
- FileDownloadLocation,
- FileDownloadParameters,
- ForumTopic,
- FullChat,
- GameHighScore,
- HistoryReadUpdate,
- InlineCallbackQuery,
- InlineQuery,
- InputChatEventFilters,
- InputDialogFolder,
- InputFileLike,
- InputInlineResult,
- InputMediaLike,
- InputMediaSticker,
- InputMessageId,
- InputPeerLike,
- InputPrivacyRule,
- InputReaction,
- InputStickerSet,
- InputStickerSetItem,
- InputText,
- MaybeDynamic,
- Message,
- MessageEffect,
- MessageMedia,
- MessageReactions,
- ParametersSkip2,
- ParsedUpdate,
- PeerReaction,
- PeersIndex,
- PeerStories,
- Photo,
- Poll,
- PollUpdate,
- PollVoteUpdate,
- PreCheckoutQuery,
- RawDocument,
- ReplyMarkup,
- SentCode,
- Sticker,
- StickerSet,
- StickerSourceType,
- StickerType,
- StoriesStealthMode,
- Story,
- StoryInteractions,
- StoryUpdate,
- StoryViewer,
- StoryViewersList,
- TakeoutSession,
- TextWithEntities,
- TypingStatus,
- UploadedFile,
- UploadFileLike,
- User,
- UserStatusUpdate,
- UserTypingUpdate,
-} from './types/index.js'
-import { makeParsedUpdateHandler, ParsedUpdateHandlerParams } from './updates/parsed.js'
-import { StringSessionData } from './utils/string-session.js'
+import { withParams } from './methods/misc/with-params.js'
// from methods/_init.ts
// @copy
type TelegramClientOptions = (
| (PartialOnly, 'transport' | 'crypto'> & {
- /**
- * Storage to use for this client.
- *
- * If a string is passed, it will be used as
- * a name for the default platform-specific storage provider to use.
- *
- * @default `"client.session"`
- */
- storage?: string | ITelegramStorageProvider
- })
+ /**
+ * Storage to use for this client.
+ *
+ * If a string is passed, it will be used as
+ * a name for the default platform-specific storage provider to use.
+ *
+ * @default `"client.session"`
+ */
+ storage?: string | ITelegramStorageProvider
+ })
| { client: ITelegramClient }
) & {
/**
@@ -380,218 +308,217 @@ type TelegramClientOptions = (
}
export interface TelegramClient extends ITelegramClient {
- /**
- * Register a raw update handler
- *
- * @param name Event name
- * @param handler Raw update handler
- */
- on(name: 'raw_update', handler: (upd: tl.TypeUpdate | tl.TypeMessage, peers: PeersIndex) => void): this
+/**
+ * Register a raw update handler
+ *
+ * @param name Event name
+ * @param handler Raw update handler
+ */
+ on(name: 'raw_update', handler: ((upd: tl.TypeUpdate | tl.TypeMessage, peers: PeersIndex) => void)): this
/**
* Register a parsed update handler
*
* @param name Event name
* @param handler Raw update handler
*/
- on(name: 'update', handler: (upd: ParsedUpdate) => void): this
+ on(name: 'update', handler: ((upd: ParsedUpdate) => void)): this
/**
* Register a new message handler
*
* @param name Event name
* @param handler New message handler
*/
- on(name: 'new_message', handler: (upd: Message) => void): this
+ on(name: 'new_message', handler: ((upd: Message) => void)): this
/**
* Register an edit message handler
*
* @param name Event name
* @param handler Edit message handler
*/
- on(name: 'edit_message', handler: (upd: Message) => void): this
+ on(name: 'edit_message', handler: ((upd: Message) => void)): this
/**
* Register a message group handler
*
* @param name Event name
* @param handler Message group handler
*/
- on(name: 'message_group', handler: (upd: Message[]) => void): this
+ on(name: 'message_group', handler: ((upd: Message[]) => void)): this
/**
* Register a delete message handler
*
* @param name Event name
* @param handler Delete message handler
*/
- on(name: 'delete_message', handler: (upd: DeleteMessageUpdate) => void): this
+ on(name: 'delete_message', handler: ((upd: DeleteMessageUpdate) => void)): this
/**
* Register a chat member update handler
*
* @param name Event name
* @param handler Chat member update handler
*/
- on(name: 'chat_member', handler: (upd: ChatMemberUpdate) => void): this
+ on(name: 'chat_member', handler: ((upd: ChatMemberUpdate) => void)): this
/**
* Register an inline query handler
*
* @param name Event name
* @param handler Inline query handler
*/
- on(name: 'inline_query', handler: (upd: InlineQuery) => void): this
+ on(name: 'inline_query', handler: ((upd: InlineQuery) => void)): this
/**
* Register a chosen inline result handler
*
* @param name Event name
* @param handler Chosen inline result handler
*/
- on(name: 'chosen_inline_result', handler: (upd: ChosenInlineResult) => void): this
+ on(name: 'chosen_inline_result', handler: ((upd: ChosenInlineResult) => void)): this
/**
* Register a callback query handler
*
* @param name Event name
* @param handler Callback query handler
*/
- on(name: 'callback_query', handler: (upd: CallbackQuery) => void): this
+ on(name: 'callback_query', handler: ((upd: CallbackQuery) => void)): this
/**
* Register an inline callback query handler
*
* @param name Event name
* @param handler Inline callback query handler
*/
- on(name: 'inline_callback_query', handler: (upd: InlineCallbackQuery) => void): this
+ on(name: 'inline_callback_query', handler: ((upd: InlineCallbackQuery) => void)): this
/**
* Register a business callback query handler
*
* @param name Event name
* @param handler Business callback query handler
*/
- on(name: 'business_callback_query', handler: (upd: BusinessCallbackQuery) => void): this
+ on(name: 'business_callback_query', handler: ((upd: BusinessCallbackQuery) => void)): this
/**
* Register a poll update handler
*
* @param name Event name
* @param handler Poll update handler
*/
- on(name: 'poll', handler: (upd: PollUpdate) => void): this
+ on(name: 'poll', handler: ((upd: PollUpdate) => void)): this
/**
* Register a poll vote handler
*
* @param name Event name
* @param handler Poll vote handler
*/
- on(name: 'poll_vote', handler: (upd: PollVoteUpdate) => void): this
+ on(name: 'poll_vote', handler: ((upd: PollVoteUpdate) => void)): this
/**
* Register an user status update handler
*
* @param name Event name
* @param handler User status update handler
*/
- on(name: 'user_status', handler: (upd: UserStatusUpdate) => void): this
+ on(name: 'user_status', handler: ((upd: UserStatusUpdate) => void)): this
/**
* Register an user typing handler
*
* @param name Event name
* @param handler User typing handler
*/
- on(name: 'user_typing', handler: (upd: UserTypingUpdate) => void): this
+ on(name: 'user_typing', handler: ((upd: UserTypingUpdate) => void)): this
/**
* Register a history read handler
*
* @param name Event name
* @param handler History read handler
*/
- on(name: 'history_read', handler: (upd: HistoryReadUpdate) => void): this
+ on(name: 'history_read', handler: ((upd: HistoryReadUpdate) => void)): this
/**
* Register a bot stopped handler
*
* @param name Event name
* @param handler Bot stopped handler
*/
- on(name: 'bot_stopped', handler: (upd: BotStoppedUpdate) => void): this
+ on(name: 'bot_stopped', handler: ((upd: BotStoppedUpdate) => void)): this
/**
* Register a bot chat join request handler
*
* @param name Event name
* @param handler Bot chat join request handler
*/
- on(name: 'bot_chat_join_request', handler: (upd: BotChatJoinRequestUpdate) => void): this
+ on(name: 'bot_chat_join_request', handler: ((upd: BotChatJoinRequestUpdate) => void)): this
/**
* Register a chat join request handler
*
* @param name Event name
* @param handler Chat join request handler
*/
- on(name: 'chat_join_request', handler: (upd: ChatJoinRequestUpdate) => void): this
+ on(name: 'chat_join_request', handler: ((upd: ChatJoinRequestUpdate) => void)): this
/**
* Register a pre checkout query handler
*
* @param name Event name
* @param handler Pre checkout query handler
*/
- on(name: 'pre_checkout_query', handler: (upd: PreCheckoutQuery) => void): this
+ on(name: 'pre_checkout_query', handler: ((upd: PreCheckoutQuery) => void)): this
/**
* Register a story update handler
*
* @param name Event name
* @param handler Story update handler
*/
- on(name: 'story', handler: (upd: StoryUpdate) => void): this
+ on(name: 'story', handler: ((upd: StoryUpdate) => void)): this
/**
* Register a delete story handler
*
* @param name Event name
* @param handler Delete story handler
*/
- on(name: 'delete_story', handler: (upd: DeleteStoryUpdate) => void): this
+ on(name: 'delete_story', handler: ((upd: DeleteStoryUpdate) => void)): this
/**
* Register a bot reaction update handler
*
* @param name Event name
* @param handler Bot reaction update handler
*/
- on(name: 'bot_reaction', handler: (upd: BotReactionUpdate) => void): this
+ on(name: 'bot_reaction', handler: ((upd: BotReactionUpdate) => void)): this
/**
* Register a bot reaction count update handler
*
* @param name Event name
* @param handler Bot reaction count update handler
*/
- on(name: 'bot_reaction_count', handler: (upd: BotReactionCountUpdate) => void): this
+ on(name: 'bot_reaction_count', handler: ((upd: BotReactionCountUpdate) => void)): this
/**
* Register a business connection update handler
*
* @param name Event name
* @param handler Business connection update handler
*/
- on(name: 'business_connection', handler: (upd: BusinessConnection) => void): this
+ on(name: 'business_connection', handler: ((upd: BusinessConnection) => void)): this
/**
* Register a new business message handler
*
* @param name Event name
* @param handler New business message handler
*/
- on(name: 'new_business_message', handler: (upd: BusinessMessage) => void): this
+ on(name: 'new_business_message', handler: ((upd: BusinessMessage) => void)): this
/**
* Register an edit business message handler
*
* @param name Event name
* @param handler Edit business message handler
*/
- on(name: 'edit_business_message', handler: (upd: BusinessMessage) => void): this
+ on(name: 'edit_business_message', handler: ((upd: BusinessMessage) => void)): this
/**
* Register a business message group handler
*
* @param name Event name
* @param handler Business message group handler
*/
- on(name: 'business_message_group', handler: (upd: BusinessMessage[]) => void): this
+ on(name: 'business_message_group', handler: ((upd: BusinessMessage[]) => void)): this
/**
* Register a delete business message handler
*
* @param name Event name
* @param handler Delete business message handler
*/
- on(name: 'delete_business_message', handler: (upd: DeleteBusinessMessageUpdate) => void): this
+ on(name: 'delete_business_message', handler: ((upd: DeleteBusinessMessageUpdate) => void)): this
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
on(name: string, handler: (...args: any[]) => void): this
/**
@@ -638,10 +565,11 @@ export interface TelegramClient extends ITelegramClient {
* @returns The authorized user
* @throws BadRequestError In case the code is invalid
*/
- recoverPassword(params: {
+ recoverPassword(
+ params: {
/** The recovery code sent via email */
- recoveryCode: string
- }): Promise
+ recoveryCode: string
+ }): Promise
/**
* Re-send the confirmation code using a different type.
*
@@ -650,16 +578,17 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: 👤 users only
*
*/
- resendCode(params: {
+ resendCode(
+ params: {
/** Phone number in international format */
- phone: string
+ phone: string
- /** Confirmation code identifier from {@link SentCode} */
- phoneCodeHash: string
+ /** Confirmation code identifier from {@link SentCode} */
+ phoneCodeHash: string
- /** Abort signal */
- abortSignal?: AbortSignal
- }): Promise
+ /** Abort signal */
+ abortSignal?: AbortSignal
+ }): Promise
/**
* Simple wrapper that calls {@link start} and then
* provided callback function (if any) without the
@@ -674,7 +603,9 @@ export interface TelegramClient extends ITelegramClient {
* @param then Function to be called after {@link start} returns
* @deprecated This method provides no real value over {@link start}, please use it instead
*/
- run(params: Parameters[1], then?: (user: User) => void | Promise): void
+ run(
+ params: Parameters[1],
+ then?: (user: User) => void | Promise): void
/**
* Send the confirmation code to the given phone number
*
@@ -682,19 +613,20 @@ export interface TelegramClient extends ITelegramClient {
*
* @returns An object containing information about the sent confirmation code
*/
- sendCode(params: {
+ sendCode(
+ params: {
/** Phone number in international format */
- phone: string
+ phone: string
- /** Saved future auth tokens, if any */
- futureAuthTokens?: Uint8Array[]
+ /** Saved future auth tokens, if any */
+ futureAuthTokens?: Uint8Array[]
- /** Additional code settings to pass to the server */
- codeSettings?: Omit
+ /** Additional code settings to pass to the server */
+ codeSettings?: Omit
- /** Abort signal */
- abortSignal?: AbortSignal
- }): Promise
+ /** Abort signal */
+ abortSignal?: AbortSignal
+ }): Promise
/**
* Send a code to email needed to recover your password
*
@@ -722,34 +654,35 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: 👤 users only
*
*/
- signInQr(params: {
+ signInQr(
+ params: {
/**
* Function that will be called whenever the login URL is changed.
*
* The app is expected to display `url` as a QR code to the user
*/
- onUrlUpdated: (url: string, expires: Date) => void
+ onUrlUpdated: (url: string, expires: Date) => void
- /**
- * Function that will be called when the user has scanned the QR code
- * (i.e. when `updateLoginToken` is received), and the library is finalizing the auth
- */
- onQrScanned?: () => void
+ /**
+ * Function that will be called when the user has scanned the QR code
+ * (i.e. when `updateLoginToken` is received), and the library is finalizing the auth
+ */
+ onQrScanned?: () => void
- /** Password for 2FA */
- password?: MaybeDynamic
+ /** Password for 2FA */
+ password?: MaybeDynamic
- /**
- * Function that will be called after the server has rejected the password.
- *
- * Note that in case {@link password} is not a function,
- * this callback will never be called, and an error will be thrown instead.
- */
- invalidPasswordCallback?: () => MaybePromise
+ /**
+ * Function that will be called after the server has rejected the password.
+ *
+ * Note that in case {@link password} is not a function,
+ * this callback will never be called, and an error will be thrown instead.
+ */
+ invalidPasswordCallback?: () => MaybePromise
- /** Abort signal */
- abortSignal?: AbortSignal
- }): Promise
+ /** Abort signal */
+ abortSignal?: AbortSignal
+ }): Promise
/**
* Authorize a user in Telegram with a valid confirmation code.
*
@@ -759,16 +692,17 @@ export interface TelegramClient extends ITelegramClient {
* @throws BadRequestError In case the arguments are invalid
* @throws SessionPasswordNeededError In case a password is needed to sign in
*/
- signIn(params: {
+ signIn(
+ params: {
/** Phone number in international format */
- phone: string
- /** Code identifier from {@link sendCode} */
- phoneCodeHash: string
- /** The confirmation code that was received */
- phoneCode: string
- /** Abort signal */
- abortSignal?: AbortSignal
- }): Promise
+ phone: string
+ /** Code identifier from {@link sendCode} */
+ phoneCodeHash: string
+ /** The confirmation code that was received */
+ phoneCode: string
+ /** Abort signal */
+ abortSignal?: AbortSignal
+ }): Promise
/**
* Utility function to quickly authorize on test DC
* using a [Test phone number](https://core.telegram.org/api/auth#test-phone-numbers),
@@ -781,26 +715,27 @@ export interface TelegramClient extends ITelegramClient {
*
* @param params Additional parameters
*/
- startTest(params?: {
+ startTest(
+ params?: {
/**
* Whether to log out if current session is logged in.
*
* @default false.
*/
- logout?: boolean
+ logout?: boolean
- /**
- * Override phone number. Must be a valid Test phone number.
- *
- * By default is randomly generated.
- */
- phone?: string
+ /**
+ * Override phone number. Must be a valid Test phone number.
+ *
+ * By default is randomly generated.
+ */
+ phone?: string
- /**
- * Override user's DC. Must be a valid test DC.
- */
- dcId?: number
- }): Promise
+ /**
+ * Override user's DC. Must be a valid test DC.
+ */
+ dcId?: number
+ }): Promise
/**
* Start the client in an interactive and declarative manner,
@@ -817,7 +752,8 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: ✅ both users and bots
*
*/
- start(params: {
+ start(
+ params: {
/**
* String session exported using {@link TelegramClient.exportSession}.
*
@@ -826,84 +762,85 @@ export interface TelegramClient extends ITelegramClient {
* Note that passed session will be ignored in case storage already
* contains authorization.
*/
- session?: string | StringSessionData
+ session?: string | StringSessionData
- /**
- * Whether to overwrite existing session.
- */
- sessionForce?: boolean
+ /**
+ * Whether to overwrite existing session.
+ */
+ sessionForce?: boolean
- /**
- * When passed, [QR login flow](https://core.telegram.org/api/qr-login)
- * will be used instead of the regular login flow.
- *
- * This function will be called whenever the login URL is changed,
- * and the app is expected to display it as a QR code to the user.
- */
- qrCodeHandler?: (url: string, expires: Date) => void
+ /**
+ * When passed, [QR login flow](https://core.telegram.org/api/qr-login)
+ * will be used instead of the regular login flow.
+ *
+ * This function will be called whenever the login URL is changed,
+ * and the app is expected to display it as a QR code to the user.
+ */
+ qrCodeHandler?: (url: string, expires: Date) => void
- /**
- * Phone number of the account.
- * If account does not exist, it will be created
- */
- phone?: MaybeDynamic
+ /**
+ * Phone number of the account.
+ * If account does not exist, it will be created
+ */
+ phone?: MaybeDynamic
- /**
- * Bot token to use. Ignored if `phone` is supplied.
- */
- botToken?: MaybeDynamic
+ /**
+ * Bot token to use. Ignored if `phone` is supplied.
+ */
+ botToken?: MaybeDynamic
- /**
- * 2FA password. Ignored if `botToken` is supplied
- */
- password?: MaybeDynamic
+ /**
+ * 2FA password. Ignored if `botToken` is supplied
+ */
+ password?: MaybeDynamic
- /**
- * Code sent to the phone (either sms, call, flash call or other).
- * Ignored if `botToken` is supplied, must be present if `phone` is supplied.
- */
- code?: MaybeDynamic
+ /**
+ * Code sent to the phone (either sms, call, flash call or other).
+ * Ignored if `botToken` is supplied, must be present if `phone` is supplied.
+ */
+ code?: MaybeDynamic
- /**
- * If passed, this function will be called if provided code or 2FA password
- * was invalid. New code/password will be requested later.
- *
- * If provided `code`/`password` is a constant string, providing an
- * invalid one will interrupt authorization flow.
- */
- invalidCodeCallback?: (type: 'code' | 'password') => MaybePromise
+ /**
+ * If passed, this function will be called if provided code or 2FA password
+ * was invalid. New code/password will be requested later.
+ *
+ * If provided `code`/`password` is a constant string, providing an
+ * invalid one will interrupt authorization flow.
+ */
+ invalidCodeCallback?: (type: 'code' | 'password') => MaybePromise
- /**
- * Whether to force code delivery through SMS
- */
- forceSms?: boolean
+ /**
+ * Whether to force code delivery through SMS
+ */
+ forceSms?: boolean
- /**
- * Custom method that is called when a code is sent. Can be used
- * to show a GUI alert of some kind.
- *
- * This method is called *before* {@link start.params.code}.
- *
- * @param code
- * @default `console.log`.
- */
- codeSentCallback?: (code: SentCode) => MaybePromise
+ /**
+ * Custom method that is called when a code is sent. Can be used
+ * to show a GUI alert of some kind.
+ *
+ * This method is called *before* {@link start.params.code}.
+ *
+ * @param code
+ * @default `console.log`.
+ */
+ codeSentCallback?: (code: SentCode) => MaybePromise
- /** Saved future auth tokens, if any */
- futureAuthTokens?: Uint8Array[]
+ /** Saved future auth tokens, if any */
+ futureAuthTokens?: Uint8Array[]
- /** Additional code settings to pass to the server */
- codeSettings?: Omit
+ /** Additional code settings to pass to the server */
+ codeSettings?: Omit
- /** Abort signal */
- abortSignal?: AbortSignal
- }): Promise
+ /** Abort signal */
+ abortSignal?: AbortSignal
+ }): Promise
/**
* Check if the given peer/input peer is referring to the current user
* **Available**: ✅ both users and bots
*
*/
- isSelfPeer(peer: tl.TypeInputPeer | tl.TypePeer | tl.TypeInputUser): boolean
+ isSelfPeer(
+ peer: tl.TypeInputPeer | tl.TypePeer | tl.TypeInputUser): boolean
/**
* Send an answer to a callback query.
*
@@ -915,12 +852,12 @@ export interface TelegramClient extends ITelegramClient {
answerCallbackQuery(
queryId: Long | CallbackQuery,
params?: {
- /**
- * Maximum amount of time in seconds for which
- * this result can be cached by the client (not server!).
- *
- * @default 0
- */
+ /**
+ * Maximum amount of time in seconds for which
+ * this result can be cached by the client (not server!).
+ *
+ * @default 0
+ */
cacheTime?: number
/**
@@ -948,8 +885,7 @@ export interface TelegramClient extends ITelegramClient {
* with a deep-link parameter.
*/
url?: string
- },
- ): Promise
+ }): Promise
/**
* Answer an inline query.
*
@@ -963,12 +899,12 @@ export interface TelegramClient extends ITelegramClient {
queryId: tl.Long | InlineQuery,
results: InputInlineResult[],
params?: {
- /**
- * Maximum number of time in seconds that the results of the
- * query may be cached on the server for.
- *
- * @default 300
- */
+ /**
+ * Maximum number of time in seconds that the results of the
+ * query may be cached on the server for.
+ *
+ * @default 300
+ */
cacheTime?: number
/**
@@ -1019,9 +955,9 @@ export interface TelegramClient extends ITelegramClient {
* the chat where they wanted to use the bot's inline capabilities
*/
switchPm?: {
- /**
- * Text of the button
- */
+ /**
+ * Text of the button
+ */
text: string
/**
@@ -1035,9 +971,9 @@ export interface TelegramClient extends ITelegramClient {
* list with the specified text, that switches the user to the specified bot web app.
*/
switchWebview?: {
- /**
- * Text of the button
- */
+ /**
+ * Text of the button
+ */
text: string
/**
@@ -1045,62 +981,62 @@ export interface TelegramClient extends ITelegramClient {
*/
url: string
}
- },
- ): Promise
+ }): Promise
/**
* Answer a pre-checkout query.
*
- * **Available**: ✅ both users and bots
+ * **Available**: 🤖 bots only
*
* @param queryId Pre-checkout query ID
*/
answerPreCheckoutQuery(
queryId: tl.Long | PreCheckoutQuery,
params?: {
- /** If pre-checkout is rejected, error message to show to the user */
+ /** If pre-checkout is rejected, error message to show to the user */
error?: string
- },
- ): Promise
+ }): Promise
/**
* Delete commands for the current bot and the given scope.
*
* Does the same as passing `null` to {@link setMyCommands}
*
* Learn more about scopes in the [Bot API docs](https://core.telegram.org/bots/api#botcommandscope)
- * **Available**: ✅ both users and bots
+ * **Available**: 🤖 bots only
*
*/
- deleteMyCommands(params?: {
+ deleteMyCommands(
+ params?: {
/**
* Scope of the commands.
*
* @default `BotScope.default_` (i.e. `botCommandScopeDefault`)
*/
- scope?: tl.TypeBotCommandScope | BotCommands.IntermediateScope
+ scope?: tl.TypeBotCommandScope | BotCommands.IntermediateScope
- /**
- * User language applied to the scope.
- */
- langCode?: string
- }): Promise
+ /**
+ * User language applied to the scope.
+ */
+ langCode?: string
+ }): Promise
/**
* Gets information about a bot the current uzer owns (or the current bot)
* **Available**: ✅ both users and bots
*
*/
- getBotInfo(params: {
+ getBotInfo(
+ params: {
/**
* When called by a user, a bot the user owns must be specified.
* When called by a bot, must be empty
*/
- bot?: InputPeerLike
+ bot?: InputPeerLike
- /**
- * If passed, will retrieve the bot's description in the given language.
- * If left empty, will retrieve the fallback description.
- */
- langCode?: string
- }): Promise
+ /**
+ * If passed, will retrieve the bot's description in the given language.
+ * If left empty, will retrieve the fallback description.
+ */
+ langCode?: string
+ }): Promise
/**
* Fetches the menu button set for the given user.
* **Available**: 🤖 bots only
@@ -1117,7 +1053,7 @@ export interface TelegramClient extends ITelegramClient {
*/
getCallbackAnswer(
params: InputMessageId & {
- /** Data contained in the button */
+ /** Data contained in the button */
data: string | Uint8Array
/**
@@ -1151,8 +1087,7 @@ export interface TelegramClient extends ITelegramClient {
* it is checked by Telegram.
*/
password?: string
- },
- ): Promise
+ }): Promise
/**
* Get high scores of a game
* **Available**: 🤖 bots only
@@ -1160,10 +1095,9 @@ export interface TelegramClient extends ITelegramClient {
*/
getGameHighScores(
params: InputMessageId & {
- /** ID of the user to find high scores for */
+ /** ID of the user to find high scores for */
userId?: InputPeerLike
- },
- ): Promise
+ }): Promise
/**
* Get high scores of a game from an inline message
*
@@ -1174,62 +1108,65 @@ export interface TelegramClient extends ITelegramClient {
*/
getInlineGameHighScores(
messageId: string | tl.TypeInputBotInlineMessageID,
- userId?: InputPeerLike,
- ): Promise
+ userId?: InputPeerLike): Promise
/**
* Get a list of current bot's commands for the given command scope
* and user language. If they are not set, empty set is returned.
*
* Learn more about scopes in the [Bot API docs](https://core.telegram.org/bots/api#botcommandscope)
- * **Available**: ✅ both users and bots
+ * **Available**: 🤖 bots only
*
*/
- getMyCommands(params?: {
+ getMyCommands(
+ params?: {
/**
* Scope of the commands.
*
* @default `BotScope.default_` (i.e. `botCommandScopeDefault`)
*/
- scope?: tl.TypeBotCommandScope | BotCommands.IntermediateScope
+ scope?: tl.TypeBotCommandScope | BotCommands.IntermediateScope
- /**
- * User language applied to the scope.
- */
- langCode?: string
- }): Promise
+ /**
+ * User language applied to the scope.
+ */
+ langCode?: string
+ }): Promise
/**
* Sets information about a bot the current uzer owns (or the current bot)
* **Available**: ✅ both users and bots
*
*/
- setBotInfo(params: {
+ setBotInfo(
+ params: {
/**
* When called by a user, a bot the user owns must be specified.
* When called by a bot, must be empty
*/
- bot?: InputPeerLike
+ bot?: InputPeerLike
- /**
- * If passed, will update the bot's description in the given language.
- * If left empty, will change the fallback description.
- */
- langCode?: string
+ /**
+ * If passed, will update the bot's description in the given language.
+ * If left empty, will change the fallback description.
+ */
+ langCode?: string
- /** New bot name */
- name?: string
+ /** New bot name */
+ name?: string
- /** New bio text (displayed in the profile) */
- bio?: string
+ /** New bio text (displayed in the profile) */
+ bio?: string
- /** New description text (displayed when the chat is empty) */
- description?: string
- }): Promise
+ /** New description text (displayed when the chat is empty) */
+ description?: string
+ }): Promise
/**
* Sets a menu button for the given user.
- * **Available**: ✅ both users and bots
+ * **Available**: 🤖 bots only
*
*/
- setBotMenuButton(user: InputPeerLike, button: tl.TypeBotMenuButton): Promise
+ setBotMenuButton(
+ user: InputPeerLike,
+ button: tl.TypeBotMenuButton): Promise
/**
* Set a score of a user in a game
*
@@ -1240,7 +1177,7 @@ export interface TelegramClient extends ITelegramClient {
*/
setGameScore(
params: InputMessageId & {
- /** ID of the user who has scored */
+ /** ID of the user who has scored */
userId: InputPeerLike
/** The new score (must be >0) */
@@ -1263,8 +1200,7 @@ export interface TelegramClient extends ITelegramClient {
* to the client's update handler.
*/
shouldDispatch?: true
- },
- ): Promise
+ }): Promise
/**
* Set a score of a user in a game contained in
* an inline message
@@ -1273,25 +1209,26 @@ export interface TelegramClient extends ITelegramClient {
*
* @param params
*/
- setInlineGameScore(params: {
+ setInlineGameScore(
+ params: {
/** ID of the inline message */
- messageId: string | tl.TypeInputBotInlineMessageID
- /** ID of the user who has scored */
- userId: InputPeerLike
- /** The new score (must be >0) */
- score: number
- /**
- * When `true`, the game message will not be modified
- * to include the new score
- */
- noEdit?: boolean
+ messageId: string | tl.TypeInputBotInlineMessageID
+ /** ID of the user who has scored */
+ userId: InputPeerLike
+ /** The new score (must be >0) */
+ score: number
+ /**
+ * When `true`, the game message will not be modified
+ * to include the new score
+ */
+ noEdit?: boolean
- /**
- * Whether to allow user's score to decrease.
- * This can be useful when fixing mistakes or banning cheaters
- */
- force?: boolean
- }): Promise
+ /**
+ * Whether to allow user's score to decrease.
+ * This can be useful when fixing mistakes or banning cheaters
+ */
+ force?: boolean
+ }): Promise
/**
* Set or delete commands for the current bot and the given scope
*
@@ -1299,37 +1236,39 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: 🤖 bots only
*
*/
- setMyCommands(params: {
+ setMyCommands(
+ params: {
/**
* New list of bot commands for the given scope.
*
* Pass empty array or `null` to delete them.
*/
- commands: tl.RawBotCommand[] | null
+ commands: tl.RawBotCommand[] | null
- /**
- * Scope of the commands.
- *
- * @default `BotScope.default_` (i.e. `botCommandScopeDefault`)
- */
- scope?: tl.TypeBotCommandScope | BotCommands.IntermediateScope
+ /**
+ * Scope of the commands.
+ *
+ * @default `BotScope.default_` (i.e. `botCommandScopeDefault`)
+ */
+ scope?: tl.TypeBotCommandScope | BotCommands.IntermediateScope
- /**
- * User language applied to the scope.
- */
- langCode?: string
- }): Promise
+ /**
+ * User language applied to the scope.
+ */
+ langCode?: string
+ }): Promise
/**
* Sets the default chat permissions for the bot in the supergroup or channel.
* **Available**: 🤖 bots only
*
*/
- setMyDefaultRights(params: {
+ setMyDefaultRights(
+ params: {
/** Whether to target groups or channels. */
- target: 'channel' | 'group'
- /** The default chat permissions. */
- rights: Omit
- }): Promise
+ target: 'channel' | 'group'
+ /** The default chat permissions. */
+ rights: Omit
+ }): Promise
/**
* Add one or more new members to a group, supergroup or channel.
*
@@ -1343,15 +1282,14 @@ export interface TelegramClient extends ITelegramClient {
chatId: InputPeerLike,
users: MaybeArray,
params: {
- /**
- * Number of old messages to be forwarded (0-100).
- * Only applicable to legacy groups, ignored for supergroups and channels
- *
- * @default 100
- */
+ /**
+ * Number of old messages to be forwarded (0-100).
+ * Only applicable to legacy groups, ignored for supergroups and channels
+ *
+ * @default 100
+ */
forwardCount?: number
- },
- ): Promise
+ }): Promise
/**
* Archive one or more chats
*
@@ -1372,19 +1310,20 @@ export interface TelegramClient extends ITelegramClient {
*
* @returns Service message about removed user, if one was generated.
*/
- banChatMember(params: {
+ banChatMember(
+ params: {
/** Chat ID */
- chatId: InputPeerLike
+ chatId: InputPeerLike
- /** ID of the user/channel to ban */
- participantId: InputPeerLike
+ /** ID of the user/channel to ban */
+ participantId: InputPeerLike
- /**
- * Whether to dispatch the returned service message (if any)
- * to the client's update handler.
- */
- shouldDispatch?: true
- }): Promise
+ /**
+ * Whether to dispatch the returned service message (if any)
+ * to the client's update handler.
+ */
+ shouldDispatch?: true
+ }): Promise
/**
* Create a new broadcast channel
*
@@ -1392,17 +1331,18 @@ export interface TelegramClient extends ITelegramClient {
*
* @returns Newly created channel
*/
- createChannel(params: {
+ createChannel(
+ params: {
/**
* Channel title
*/
- title: string
+ title: string
- /**
- * Channel description
- */
- description?: string
- }): Promise
+ /**
+ * Channel description
+ */
+ description?: string
+ }): Promise
/**
* Create a legacy group chat
*
@@ -1411,25 +1351,26 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: 👤 users only
*
*/
- createGroup(params: {
+ createGroup(
+ params: {
/**
* Group title
*/
- title: string
+ title: string
- /**
- * User(s) to be invited in the group (ID(s), username(s) or phone number(s)).
- * Due to Telegram limitations, you can't create a legacy group with just yourself.
- */
- users: MaybeArray
+ /**
+ * User(s) to be invited in the group (ID(s), username(s) or phone number(s)).
+ * Due to Telegram limitations, you can't create a legacy group with just yourself.
+ */
+ users: MaybeArray
- /**
- * TTL period (in seconds) for the newly created chat
- *
- * @default 0 (i.e. messages don't expire)
- */
- ttlPeriod?: number
- }): Promise
+ /**
+ * TTL period (in seconds) for the newly created chat
+ *
+ * @default 0 (i.e. messages don't expire)
+ */
+ ttlPeriod?: number
+ }): Promise
/**
* Create a new supergroup
*
@@ -1437,29 +1378,30 @@ export interface TelegramClient extends ITelegramClient {
*
* @returns Newly created supergroup
*/
- createSupergroup(params: {
+ createSupergroup(
+ params: {
/**
* Supergroup title
*/
- title: string
+ title: string
- /**
- * Supergroup description
- */
- description?: string
+ /**
+ * Supergroup description
+ */
+ description?: string
- /**
- * Whether to create a forum
- */
- forum?: boolean
+ /**
+ * Whether to create a forum
+ */
+ forum?: boolean
- /**
- * TTL period (in seconds) for the newly created supergroup
- *
- * @default 0 (i.e. messages don't expire)
- */
- ttlPeriod?: number
- }): Promise
+ /**
+ * TTL period (in seconds) for the newly created supergroup
+ *
+ * @default 0 (i.e. messages don't expire)
+ */
+ ttlPeriod?: number
+ }): Promise
/**
* Delete a channel or a supergroup
@@ -1504,14 +1446,14 @@ export interface TelegramClient extends ITelegramClient {
deleteHistory(
chat: InputPeerLike,
params?: {
- /**
- * Deletion mode. Can be:
- * - `delete`: delete messages (only for yourself) AND the dialog itself
- * - `clear`: delete messages (only for yourself), but keep the dialog in the list
- * - `revoke`: delete messages for all users
- *
- * @default 'delete'
- */
+ /**
+ * Deletion mode. Can be:
+ * - `delete`: delete messages (only for yourself) AND the dialog itself
+ * - `clear`: delete messages (only for yourself), but keep the dialog in the list
+ * - `revoke`: delete messages for all users
+ *
+ * @default 'delete'
+ */
mode: 'delete' | 'clear' | 'revoke'
/**
@@ -1520,40 +1462,41 @@ export interface TelegramClient extends ITelegramClient {
* @default 0, i.e. remove all messages
*/
maxId?: number
- },
- ): Promise
+ }): Promise
/**
* Delete all messages of a user (or channel) in a supergroup
* **Available**: 👤 users only
*
*/
- deleteUserHistory(params: {
+ deleteUserHistory(
+ params: {
/** Chat ID */
- chatId: InputPeerLike
- /** User/channel ID whose messages to delete */
- participantId: InputPeerLike
+ chatId: InputPeerLike
+ /** User/channel ID whose messages to delete */
+ participantId: InputPeerLike
- /**
- * Whether to dispatch the updates that will be generated by this call.
- * Doesn't follow `disableNoDispatch`
- */
- shouldDispatch?: true
- }): Promise
+ /**
+ * Whether to dispatch the updates that will be generated by this call.
+ * Doesn't follow `disableNoDispatch`
+ */
+ shouldDispatch?: true
+ }): Promise
/**
* Edit supergroup/channel admin rights of a user.
* **Available**: ✅ both users and bots
*
*/
- editAdminRights(params: {
+ editAdminRights(
+ params: {
/** Chat ID */
- chatId: InputPeerLike
- /** User ID */
- userId: InputPeerLike
- /** New admin rights */
- rights: Omit
- /** Custom admin rank */
- rank?: string
- }): Promise
+ chatId: InputPeerLike
+ /** User ID */
+ userId: InputPeerLike
+ /** New admin rights */
+ rights: Omit
+ /** Custom admin rank */
+ rank?: string
+ }): Promise
/**
* Get chat event log ("Recent actions" in official clients).
*
@@ -1572,9 +1515,9 @@ export interface TelegramClient extends ITelegramClient {
getChatEventLog(
chatId: InputPeerLike,
params?: {
- /**
- * Search query
- */
+ /**
+ * Search query
+ */
query?: string
/**
@@ -1619,8 +1562,7 @@ export interface TelegramClient extends ITelegramClient {
* @default 100
*/
limit?: number
- },
- ): Promise
+ }): Promise
/**
* Get information about a single chat member
*
@@ -1630,12 +1572,13 @@ export interface TelegramClient extends ITelegramClient {
* @param userId User ID, username, phone number, `"me"` or `"self"`
* @returns Chat member, or `null` if user is not a member of the chat
*/
- getChatMember(params: {
+ getChatMember(
+ params: {
/** Chat ID or username */
- chatId: InputPeerLike
- /** User ID, username, phone number, `"me"` or `"self"` */
- userId: InputPeerLike
- }): Promise
+ chatId: InputPeerLike
+ /** User ID, username, phone number, `"me"` or `"self"` */
+ userId: InputPeerLike
+ }): Promise
/**
* Get a chunk of members of some chat.
*
@@ -1649,14 +1592,14 @@ export interface TelegramClient extends ITelegramClient {
getChatMembers(
chatId: InputPeerLike,
params?: {
- /**
- * Search query to filter members by their display names and usernames
- *
- * > **Note**: Only used for these values of `filter`:
- * > `all, banned, restricted, mention, contacts`
- *
- * @default `''` (empty string)
- */
+ /**
+ * Search query to filter members by their display names and usernames
+ *
+ * > **Note**: Only used for these values of `filter`:
+ * > `all, banned, restricted, mention, contacts`
+ *
+ * @default `''` (empty string)
+ */
query?: string
/**
@@ -1691,8 +1634,7 @@ export interface TelegramClient extends ITelegramClient {
* @default `recent`
*/
type?: 'all' | 'banned' | 'restricted' | 'bots' | 'recent' | 'admins' | 'contacts' | 'mention'
- },
- ): Promise>
+ }): Promise>
/**
* Get preview information about a private chat.
*
@@ -1750,7 +1692,8 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: 👤 users only
*
*/
- getSimilarChannels(channel: InputPeerLike): Promise>
+ getSimilarChannels(
+ channel: InputPeerLike): Promise>
/**
* Iterate over chat event log.
*
@@ -1764,11 +1707,11 @@ export interface TelegramClient extends ITelegramClient {
iterChatEventLog(
chatId: InputPeerLike,
params?: Parameters[2] & {
- /**
- * Total number of events to return.
- *
- * @default Infinity
- */
+ /**
+ * Total number of events to return.
+ *
+ * @default Infinity
+ */
limit?: number
/**
@@ -1778,8 +1721,7 @@ export interface TelegramClient extends ITelegramClient {
* @default 100
*/
chunkSize?: number
- },
- ): AsyncIterableIterator
+ }): AsyncIterableIterator
/**
* Iterate through chat members
*
@@ -1795,15 +1737,14 @@ export interface TelegramClient extends ITelegramClient {
iterChatMembers(
chatId: InputPeerLike,
params?: Parameters[2] & {
- /**
- * Chunk size, which will be passed as `limit` parameter
- * to {@link getChatMembers}. Usually you shouldn't care about this.
- *
- * @default `200`
- */
+ /**
+ * Chunk size, which will be passed as `limit` parameter
+ * to {@link getChatMembers}. Usually you shouldn't care about this.
+ *
+ * @default `200`
+ */
chunkSize?: number
- },
- ): AsyncIterableIterator
+ }): AsyncIterableIterator
/**
* Join a channel or supergroup
*
@@ -1827,12 +1768,13 @@ export interface TelegramClient extends ITelegramClient {
*
* @returns Service message about removed user, if one was generated.
*/
- kickChatMember(params: {
+ kickChatMember(
+ params: {
/** Chat ID */
- chatId: InputPeerLike
- /** User ID */
- userId: InputPeerLike
- }): Promise
+ chatId: InputPeerLike
+ /** User ID */
+ userId: InputPeerLike
+ }): Promise
/**
* Leave a group chat, supergroup or channel
*
@@ -1843,12 +1785,11 @@ export interface TelegramClient extends ITelegramClient {
leaveChat(
chatId: InputPeerLike,
params?: {
- /**
- * Whether to clear history after leaving (only for legacy group chats)
- */
+ /**
+ * Whether to clear history after leaving (only for legacy group chats)
+ */
clear?: boolean
- },
- ): Promise
+ }): Promise
/**
* Mark a chat as unread
*
@@ -1892,37 +1833,40 @@ export interface TelegramClient extends ITelegramClient {
*
* @param peerId Bot, channel or "me"/"self"
*/
- reorderUsernames(peerId: InputPeerLike, order: string[]): Promise
+ reorderUsernames(
+ peerId: InputPeerLike,
+ order: string[]): Promise
/**
* Restrict a user in a supergroup.
* **Available**: ✅ both users and bots
*
*/
- restrictChatMember(params: {
+ restrictChatMember(
+ params: {
/** Chat ID */
- chatId: InputPeerLike
+ chatId: InputPeerLike
- /** User ID */
- userId: InputPeerLike
+ /** User ID */
+ userId: InputPeerLike
- /**
- * Restrictions for the user. Note that unlike Bot API, this object contains
- * the restrictions, and not the permissions, i.e.
- * passing `sendMessages=true` will disallow the user to send messages,
- * and passing `{}` (empty object) will lift any restrictions
- */
- restrictions: Omit
+ /**
+ * Restrictions for the user. Note that unlike Bot API, this object contains
+ * the restrictions, and not the permissions, i.e.
+ * passing `sendMessages=true` will disallow the user to send messages,
+ * and passing `{}` (empty object) will lift any restrictions
+ */
+ restrictions: Omit
- /**
- * Date when the user will be unrestricted.
- * When `number` is passed, UNIX time in ms is expected.
- * If this value is less than 30 seconds or more than 366 days in
- * the future, user will be restricted forever.
- *
- * @default `0`, i.e. forever
- */
- until?: number | Date
- }): Promise
+ /**
+ * Date when the user will be unrestricted.
+ * When `number` is passed, UNIX time in ms is expected.
+ * If this value is less than 30 seconds or more than 366 days in
+ * the future, user will be restricted forever.
+ *
+ * @default `0`, i.e. forever
+ */
+ until?: number | Date
+ }): Promise
/**
* Save or delete a draft message associated with some chat
*
@@ -1931,48 +1875,51 @@ export interface TelegramClient extends ITelegramClient {
* @param chatId ID of the chat, its username, phone or `"me"` or `"self"`
* @param draft Draft message, or `null` to delete.
*/
- saveDraft(chatId: InputPeerLike, draft: null | Omit): Promise
+ saveDraft(
+ chatId: InputPeerLike,
+ draft: null | Omit): Promise
/**
* Set peer color and optionally background pattern
* **Available**: 👤 users only
*
*/
- setChatColor(params: {
+ setChatColor(
+ params: {
/**
* Peer where to update the color.
*
* By default will change the color for the current user
*/
- peer?: InputPeerLike
+ peer?: InputPeerLike
- /**
- * Color identificator
- *
- * Note that this value is **not** an RGB color representation. Instead, it is
- * a number which should be used to pick a color from a predefined
- * list of colors:
- * - `0-6` are the default colors used by Telegram clients:
- * `red, orange, purple, green, sea, blue, pink`
- * - `>= 7` are returned by `help.getAppConfig`.
- */
- color: number
+ /**
+ * Color identificator
+ *
+ * Note that this value is **not** an RGB color representation. Instead, it is
+ * a number which should be used to pick a color from a predefined
+ * list of colors:
+ * - `0-6` are the default colors used by Telegram clients:
+ * `red, orange, purple, green, sea, blue, pink`
+ * - `>= 7` are returned by `help.getAppConfig`.
+ */
+ color: number
- /**
- * Background pattern emoji ID.
- *
- * Must be an adaptive emoji, otherwise the request will fail.
- */
- backgroundEmojiId?: tl.Long
+ /**
+ * Background pattern emoji ID.
+ *
+ * Must be an adaptive emoji, otherwise the request will fail.
+ */
+ backgroundEmojiId?: tl.Long
- /**
- * Whether to set this color for the profile
- * header instead of chat name/replies.
- *
- * Currently only available for the current user.
- */
- forProfile?: boolean
- }): Promise
+ /**
+ * Whether to set this color for the profile
+ * header instead of chat name/replies.
+ *
+ * Currently only available for the current user.
+ */
+ forProfile?: boolean
+ }): Promise
/**
* Change default chat permissions for all members.
*
@@ -1989,8 +1936,7 @@ export interface TelegramClient extends ITelegramClient {
*/
setChatDefaultPermissions(
chatId: InputPeerLike,
- restrictions: Omit,
- ): Promise
+ restrictions: Omit): Promise
/**
* Change chat description
*
@@ -2001,7 +1947,9 @@ export interface TelegramClient extends ITelegramClient {
* @param chatId Chat ID or username
* @param description New chat description, 0-255 characters
*/
- setChatDescription(chatId: InputPeerLike, description: string): Promise
+ setChatDescription(
+ chatId: InputPeerLike,
+ description: string): Promise
/**
* Set a new chat photo or video.
*
@@ -2009,22 +1957,23 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: ✅ both users and bots
*
*/
- setChatPhoto(params: {
+ setChatPhoto(
+ params: {
/** Chat ID or username */
- chatId: InputPeerLike
+ chatId: InputPeerLike
- /** Media type (photo or video) */
+ /** Media type (photo or video) */
- type: 'photo' | 'video'
+ type: 'photo' | 'video'
- /** Input media file */
- media: InputFileLike
- /**
- * When `type = video`, timestamp in seconds which will be shown
- * as a static preview.
- */
- previewSec?: number
- }): Promise
+ /** Input media file */
+ media: InputFileLike
+ /**
+ * When `type = video`, timestamp in seconds which will be shown
+ * as a static preview.
+ */
+ previewSec?: number
+ }): Promise
/**
* Change chat title
*
@@ -2055,7 +2004,9 @@ export interface TelegramClient extends ITelegramClient {
* @param chatId Chat ID or current username
* @param username New username, or `null` to remove
*/
- setChatUsername(chatId: InputPeerLike, username: string | null): Promise
+ setChatUsername(
+ chatId: InputPeerLike,
+ username: string | null): Promise
/**
* Set supergroup's slow mode interval.
*
@@ -2076,7 +2027,8 @@ export interface TelegramClient extends ITelegramClient {
* @param chatId Chat ID or username
* @param [enabled=false] Whether content protection should be enabled
*/
- toggleContentProtection(chatId: InputPeerLike, enabled?: boolean): Promise
+ toggleContentProtection(
+ chatId: InputPeerLike, enabled?: boolean): Promise
/**
* Toggle a collectible (Fragment) username
*
@@ -2085,20 +2037,21 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: 👤 users only
*
*/
- toggleFragmentUsername(params: {
+ toggleFragmentUsername(
+ params: {
/** Peer ID whose username to toggle */
- peerId: InputPeerLike
+ peerId: InputPeerLike
- /**
- * Username to toggle
- */
- username: string
+ /**
+ * Username to toggle
+ */
+ username: string
- /**
- * Whether to enable or disable the username
- */
- active: boolean
- }): Promise
+ /**
+ * Whether to enable or disable the username
+ */
+ active: boolean
+ }): Promise
/**
* Set whether a channel/supergroup has join requests enabled.
*
@@ -2110,7 +2063,8 @@ export interface TelegramClient extends ITelegramClient {
* @param chatId Chat ID or username
* @param [enabled=false] Whether join requests should be enabled
*/
- toggleJoinRequests(chatId: InputPeerLike, enabled?: boolean): Promise
+ toggleJoinRequests(
+ chatId: InputPeerLike, enabled?: boolean): Promise
/**
* Set whether a channel/supergroup has join-to-send setting enabled.
*
@@ -2142,13 +2096,14 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: ✅ both users and bots
*
*/
- unbanChatMember(params: {
+ unbanChatMember(
+ params: {
/** Chat ID */
- chatId: InputPeerLike
+ chatId: InputPeerLike
- /** User/channel ID who should be unbanned */
- participantId: InputPeerLike
- }): Promise
+ /** User/channel ID who should be unbanned */
+ participantId: InputPeerLike
+ }): Promise
/**
* Unban a user/channel from a supergroup or a channel,
@@ -2160,45 +2115,47 @@ export interface TelegramClient extends ITelegramClient {
* **Available**: ✅ both users and bots
*
*/
- unrestrictChatMember(params: {
+ unrestrictChatMember(
+ params: {
/** Chat ID */
- chatId: InputPeerLike
+ chatId: InputPeerLike
- /** User/channel ID who should be unbanned */
- participantId: InputPeerLike
- }): Promise
+ /** User/channel ID who should be unbanned */
+ participantId: InputPeerLike
+ }): Promise
/**
* Add an existing Telegram user as a contact
* **Available**: 👤 users only
*
*/
- addContact(params: {
+ addContact(
+ params: {
/** User ID, username or phone number */
- userId: InputPeerLike
+ userId: InputPeerLike
- /**
- * First name of the contact
- */
- firstName: string
+ /**
+ * First name of the contact
+ */
+ firstName: string
- /**
- * Last name of the contact
- */
- lastName?: string
+ /**
+ * Last name of the contact
+ */
+ lastName?: string
- /**
- * Phone number of the contact, if available
- */
- phone?: string
+ /**
+ * Phone number of the contact, if available
+ */
+ phone?: string
- /**
- * Whether to share your own phone number
- * with the newly created contact
- *
- * @default false
- */
- sharePhone?: boolean
- }): Promise
+ /**
+ * Whether to share your own phone number
+ * with the newly created contact
+ *
+ * @default false
+ */
+ sharePhone?: boolean
+ }): Promise
/**
* Delete one or more contacts from your Telegram contacts list
*
@@ -2224,8 +2181,7 @@ export interface TelegramClient extends ITelegramClient {
* @param contacts List of contacts
*/
importContacts(
- contacts: PartialOnly, 'clientId'>[],
- ): Promise
+ contacts: PartialOnly, 'clientId'>[]): Promise
/**
* Create a folder from given parameters
*
@@ -2237,7 +2193,8 @@ export interface TelegramClient extends ITelegramClient {
* @param folder Parameters for the folder
* @returns Newly created folder
*/
- createFolder(folder: PartialExcept): Promise
+ createFolder(
+ folder: PartialExcept): Promise
/**
* Delete a folder by its ID
*
@@ -2253,18 +2210,19 @@ export interface TelegramClient extends ITelegramClient {
*
* @returns Modified folder
*/
- editFolder(params: {
+ editFolder(
+ params: {
/**
* Folder, folder ID or name.
* Note that passing an ID or name will require re-fetching all folders,
* and passing name might affect not the right folder if you have multiple
* with the same name.
*/
- folder: tl.RawDialogFilter | number | string
+ folder: tl.RawDialogFilter | number | string
- /** Modification to be applied to this folder */
- modification: Partial>
- }): Promise
+ /** Modification to be applied to this folder */
+ modification: Partial>
+ }): Promise
/**
* Try to find a dialog (dialogs) with a given peer (peers) by their ID, username or phone number.
@@ -2288,14 +2246,15 @@ export interface TelegramClient extends ITelegramClient {
*
* @param params Search parameters. At least one must be set.
*/
- findFolder(params: {
+ findFolder(
+ params: {
/** Folder title */
- title?: string
- /** Folder emoji */
- emoji?: string
- /** Folder ID */
- id?: number
- }): Promise
+ title?: string
+ /** Folder emoji */
+ emoji?: string
+ /** Folder ID */
+ id?: number
+ }): Promise
/**
* Get a preview of a chatlist by its invite link
*
@@ -2330,108 +2289,109 @@ export interface TelegramClient extends ITelegramClient {
*
* @param params Fetch parameters
*/
- iterDialogs(params?: {
+ iterDialogs(
+ params?: {
/**
* Offset message date used as an anchor for pagination.
*/
- offsetDate?: Date | number
+ offsetDate?: Date | number
- /**
- * Offset message ID used as an anchor for pagination
- */
- offsetId?: number
+ /**
+ * Offset message ID used as an anchor for pagination
+ */
+ offsetId?: number
- /**
- * Offset peer used as an anchor for pagination
- */
- offsetPeer?: tl.TypeInputPeer
+ /**
+ * Offset peer used as an anchor for pagination
+ */
+ offsetPeer?: tl.TypeInputPeer
- /**
- * Limits the number of dialogs to be received.
- *
- * @default `Infinity`, i.e. all dialogs are fetched
- */
- limit?: number
+ /**
+ * Limits the number of dialogs to be received.
+ *
+ * @default `Infinity`, i.e. all dialogs are fetched
+ */
+ limit?: number
- /**
- * Chunk size which will be passed to `messages.getDialogs`.
- * You shouldn't usually care about this.
- *
- * @default 100.
- */
- chunkSize?: number
+ /**
+ * Chunk size which will be passed to `messages.getDialogs`.
+ * You shouldn't usually care about this.
+ *
+ * @default 100.
+ */
+ chunkSize?: number
- /**
- * How to handle pinned dialogs?
- *
- * Whether to `include` them at the start of the list,
- * `exclude` them at all, or `only` return pinned dialogs.
- *
- * Additionally, for folders you can specify
- * `keep`, which will return pinned dialogs
- * ordered by date among other non-pinned dialogs.
- *
- * > **Note**: When using `include` mode with folders,
- * > pinned dialogs will only be fetched if all offset
- * > parameters are unset.
- *
- * @default `include`.
- */
- pinned?: 'include' | 'exclude' | 'only' | 'keep'
+ /**
+ * How to handle pinned dialogs?
+ *
+ * Whether to `include` them at the start of the list,
+ * `exclude` them at all, or `only` return pinned dialogs.
+ *
+ * Additionally, for folders you can specify
+ * `keep`, which will return pinned dialogs
+ * ordered by date among other non-pinned dialogs.
+ *
+ * > **Note**: When using `include` mode with folders,
+ * > pinned dialogs will only be fetched if all offset
+ * > parameters are unset.
+ *
+ * @default `include`.
+ */
+ pinned?: 'include' | 'exclude' | 'only' | 'keep'
- /**
- * How to handle archived chats?
- *
- * Whether to `keep` them among other dialogs,
- * `exclude` them from the list, or `only`
- * return archived dialogs
- *
- * Ignored for folders, since folders
- * themselves contain information about archived chats.
- *
- * > **Note**: when `pinned=only`, `archived=keep` will act as `only`
- * > because of Telegram API limitations.
- *
- * @default `exclude`
- */
- archived?: 'keep' | 'exclude' | 'only'
+ /**
+ * How to handle archived chats?
+ *
+ * Whether to `keep` them among other dialogs,
+ * `exclude` them from the list, or `only`
+ * return archived dialogs
+ *
+ * Ignored for folders, since folders
+ * themselves contain information about archived chats.
+ *
+ * > **Note**: when `pinned=only`, `archived=keep` will act as `only`
+ * > because of Telegram API limitations.
+ *
+ * @default `exclude`
+ */
+ archived?: 'keep' | 'exclude' | 'only'
- /**
- * Folder from which the dialogs will be fetched.
- *
- * You can pass folder object, id or title
- *
- * Note that passing anything except object will
- * cause the list of the folders to be fetched,
- * and passing a title may fetch from
- * a wrong folder if you have multiple with the same title.
- *
- * Also note that fetching dialogs in a folder is
- * *orders of magnitudes* slower than normal because
- * of Telegram API limitations - we have to fetch all dialogs
- * and filter the ones we need manually. If possible,
- * use {@link Dialog.filterFolder} instead.
- *
- * When a folder with given ID or title is not found,
- * {@link MtArgumentError} is thrown
- *
- * @default (fetches from "All" folder)
- */
- folder?: InputDialogFolder
+ /**
+ * Folder from which the dialogs will be fetched.
+ *
+ * You can pass folder object, id or title
+ *
+ * Note that passing anything except object will
+ * cause the list of the folders to be fetched,
+ * and passing a title may fetch from
+ * a wrong folder if you have multiple with the same title.
+ *
+ * Also note that fetching dialogs in a folder is
+ * orders of magnitudes* slower than normal because
+ * of Telegram API limitations - we have to fetch all dialogs
+ * and filter the ones we need manually. If possible,
+ * use {@link Dialog.filterFolder} instead.
+ *
+ * When a folder with given ID or title is not found,
+ * {@link MtArgumentError} is thrown
+ *
+ * @default (fetches from "All" folder)
+ */
+ folder?: InputDialogFolder
- /**
- * Additional filtering for the dialogs.
- *
- * If `folder` is not provided, this filter is used instead.
- * If `folder` is provided, fields from this object are used
- * to override filters inside the folder.
- */
- filter?: Partial>
- }): AsyncIterableIterator