chore(client): reworked codegen, use prototype methods instead of fields

This commit is contained in:
alina 🌸 2023-12-13 18:29:54 +03:00
parent 314bfa0fec
commit 1ce52d66ff
Signed by: teidesu
SSH key fingerprint: SHA256:uNeCpw6aTSU4aIObXLvHfLkDa82HWH9EiOj9AXOIRpI
5 changed files with 1018 additions and 278 deletions

View file

@ -258,6 +258,7 @@ async function addSingleMethod(state, fileName) {
const isExported = (stmt.modifiers || []).find((mod) => mod.kind === ts.SyntaxKind.ExportKeyword) const isExported = (stmt.modifiers || []).find((mod) => mod.kind === ts.SyntaxKind.ExportKeyword)
const isInitialize = checkForFlag(stmt, '@initialize') const isInitialize = checkForFlag(stmt, '@initialize')
const isManualImpl = checkForFlag(stmt, '@manual-impl')
const isInitializeSuper = isInitialize === 'super' const isInitializeSuper = isInitialize === 'super'
const aliases = (function () { const aliases = (function () {
const flag = checkForFlag(stmt, '@alias') const flag = checkForFlag(stmt, '@alias')
@ -303,6 +304,13 @@ async function addSingleMethod(state, fileName) {
} }
} }
if (isManualImpl) {
state.impls.push({
name: isManualImpl.split('=')[1],
code: stmt.getFullText(),
})
}
if (!isExported) continue if (!isExported) continue
const firstArg = stmt.parameters[0] const firstArg = stmt.parameters[0]
@ -348,7 +356,7 @@ async function addSingleMethod(state, fileName) {
state.imports[module] = new Set() state.imports[module] = new Set()
} }
if (!isManual) state.imports[module].add(name) state.imports[module].add(name)
} }
} }
} else if (stmt.kind === ts.SyntaxKind.InterfaceDeclaration) { } else if (stmt.kind === ts.SyntaxKind.InterfaceDeclaration) {
@ -420,6 +428,7 @@ async function main() {
used: {}, used: {},
list: [], list: [],
}, },
impls: [],
copy: [], copy: [],
files: {}, files: {},
} }
@ -432,7 +441,8 @@ async function main() {
output.write( output.write(
'/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging, @typescript-eslint/unified-signatures */\n' + '/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging, @typescript-eslint/unified-signatures */\n' +
'/* THIS FILE WAS AUTO-GENERATED */\n', '/* eslint-disable @typescript-eslint/no-unsafe-argument */\n' +
'/* THIS FILE WAS AUTO-GENERATED */\n',
) )
Object.entries(state.imports).forEach(([module, items]) => { Object.entries(state.imports).forEach(([module, items]) => {
items = [...items] items = [...items]
@ -480,6 +490,7 @@ on(name: string, handler: (...args: any[]) => void): this\n`)
const printer = ts.createPrinter() const printer = ts.createPrinter()
const classContents = [] const classContents = []
const classProtoDecls = []
state.methods.list.forEach( state.methods.list.forEach(
({ ({
@ -628,9 +639,15 @@ on(name: string, handler: (...args: any[]) => void): this\n`)
if (!overload && !isManual) { if (!overload && !isManual) {
if (hasOverloads) { if (hasOverloads) {
classContents.push('// @ts-expect-error .bind() kinda breaks typings for overloads') classProtoDecls.push('// @ts-expect-error this kinda breaks typings for overloads, idc')
} }
classContents.push(`${name} = ${origName}.bind(null, this)`) classProtoDecls.push(`TelegramClient.prototype.${name} = function(...args) {`)
if (hasOverloads) {
classProtoDecls.push('// @ts-expect-error this kinda breaks typings for overloads, idc')
}
classProtoDecls.push(` return ${origName}(this, ...args);`)
classProtoDecls.push('}\n')
} }
} }
}, },
@ -649,7 +666,9 @@ on(name: string, handler: (...args: any[]) => void): this\n`)
output.write('}\n') output.write('}\n')
classContents.forEach((line) => output.write(line + '\n')) classContents.forEach((line) => output.write(line + '\n'))
output.write('}') output.write('}\n')
classProtoDecls.forEach((line) => output.write(line + '\n'))
state.impls.forEach(({ name, code }) => output.write(`TelegramClient.prototype.${name} = ${code}\n`))
// format the resulting file with prettier // format the resulting file with prettier
const targetFile = path.join(__dirname, '../src/client.ts') const targetFile = path.join(__dirname, '../src/client.ts')

File diff suppressed because it is too large Load diff

View file

@ -10,8 +10,6 @@ import { Conversation } from '../types/conversation.js'
// @copy // @copy
import { _defaultStorageFactory } from '../utils/platform/storage.js' import { _defaultStorageFactory } from '../utils/platform/storage.js'
// @copy // @copy
import { start } from './auth/start.js'
// @copy
import { import {
enableUpdatesProcessing, enableUpdatesProcessing,
makeParsedUpdateHandler, makeParsedUpdateHandler,
@ -73,19 +71,5 @@ function _initializeClient(this: TelegramClient, opts: TelegramClientOptions) {
}, },
}), }),
}) })
this.start = async (params) => {
const user = await start(this, params)
await this.startUpdatesLoop()
return user
}
} else {
this.start = start.bind(null, this)
}
this.run = (params, then) => {
this.start(params)
.then(then)
.catch((err) => this._emitError(err))
} }
} }

View file

@ -13,7 +13,6 @@ import { start } from './start.js'
* *
* @param params Parameters to be passed to {@link start} * @param params Parameters to be passed to {@link start}
* @param then Function to be called after {@link start} returns * @param then Function to be called after {@link start} returns
* @manual
*/ */
export function run( export function run(
client: BaseTelegramClient, client: BaseTelegramClient,

View file

@ -1,6 +1,7 @@
/* eslint-disable no-console */ /* eslint-disable no-console */
import { BaseTelegramClient, MaybeAsync, MtArgumentError, tl } from '@mtcute/core' import { BaseTelegramClient, MaybeAsync, MtArgumentError, tl } from '@mtcute/core'
import type { TelegramClient } from '../../client.js'
import { MaybeDynamic, SentCode, User } from '../../types/index.js' import { MaybeDynamic, SentCode, User } from '../../types/index.js'
import { normalizePhoneNumber, resolveMaybeDynamic } from '../../utils/misc-utils.js' import { normalizePhoneNumber, resolveMaybeDynamic } from '../../utils/misc-utils.js'
import { getMe } from '../users/get-me.js' import { getMe } from '../users/get-me.js'
@ -210,3 +211,15 @@ export async function start(
throw new MtArgumentError('Failed to log in with provided credentials') throw new MtArgumentError('Failed to log in with provided credentials')
} }
// @manual-impl=start
/** @internal */
async function _start(this: TelegramClient, params: Parameters<typeof start>[1]) {
const user = await start(this, params)
if (!this.network.params.disableUpdates) {
await this.startUpdatesLoop()
}
return user
}