style: 强类型大法

This commit is contained in:
手瓜一十雪
2025-02-02 23:22:21 +08:00
parent 76501bae34
commit 70945cf2d8
191 changed files with 923 additions and 806 deletions

View File

@@ -27,8 +27,7 @@ async function guessDuration(pttPath: string, logger: LogWrapper) {
async function handleWavFile(
file: Buffer,
filePath: string,
pcmPath: string,
_logger: LogWrapper
pcmPath: string
): Promise<{ input: Buffer; sampleRate: number }> {
const { fmt } = getWavFileInfo(file);
if (!ALLOW_SAMPLE_RATE.includes(fmt.sampleRate)) {
@@ -45,7 +44,7 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
logger.log(`语音文件${filePath}需要转换成silk`);
const pcmPath = `${pttPath}.pcm`;
const { input, sampleRate } = isWav(file)
? (await handleWavFile(file, filePath, pcmPath, logger))
? (await handleWavFile(file, filePath, pcmPath))
: { input: await FFmpegService.convert(filePath, pcmPath), sampleRate: 24000 };
const silk = await piscina.run({ input: input, sampleRate: sampleRate });
await fsPromise.writeFile(pttPath, Buffer.from(silk.data));
@@ -59,8 +58,8 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
let duration = 0;
try {
duration = getDuration(file) / 1000;
} catch (e: any) {
logger.log('获取语音文件时长失败, 使用文件大小推测时长', filePath, e.stack);
} catch (e: unknown) {
logger.log('获取语音文件时长失败, 使用文件大小推测时长', filePath, (e as Error).stack);
duration = await guessDuration(filePath, logger);
}
return {
@@ -69,8 +68,8 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
duration,
};
}
} catch (error: any) {
logger.logError('convert silk failed', error.stack);
} catch (error: unknown) {
logger.logError('convert silk failed', (error as Error).stack);
return {};
}
}

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
export type TaskExecutor<T> = (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void, onCancel: (callback: () => void) => void) => void | Promise<void>;
export class CancelableTask<T> {
@@ -7,30 +8,34 @@ export class CancelableTask<T> {
private cancelListeners: Array<() => void> = [];
constructor(executor: TaskExecutor<T>) {
this.promise = new Promise<T>(async (resolve, reject) => {
this.promise = new Promise<T>((resolve, reject) => {
const onCancel = (callback: () => void) => {
this.cancelCallback = callback;
};
try {
await executor(
(value) => {
if (!this.isCanceled) {
resolve(value);
}
},
(reason) => {
if (!this.isCanceled) {
reject(reason);
}
},
onCancel
);
} catch (error) {
if (!this.isCanceled) {
reject(error);
const execute = async () => {
try {
await executor(
(value) => {
if (!this.isCanceled) {
resolve(value);
}
},
(reason) => {
if (!this.isCanceled) {
reject(reason);
}
},
onCancel
);
} catch (error) {
if (!this.isCanceled) {
reject(error);
}
}
}
};
execute();
});
}
@@ -72,4 +77,4 @@ export class CancelableTask<T> {
next: () => this.promise.then(value => ({ value, done: true })),
};
}
}
}

View File

@@ -40,8 +40,8 @@ export abstract class ConfigBase<T> {
try {
fs.writeFileSync(configPath, fs.readFileSync(this.getConfigPath(undefined), 'utf-8'));
this.core.context.logger.log('[Core] [Config] 配置文件创建成功!\n');
} catch (e: any) {
this.core.context.logger.logError('[Core] [Config] 创建配置文件时发生错误:', e.message);
} catch (e: unknown) {
this.core.context.logger.logError('[Core] [Config] 创建配置文件时发生错误:', (e as Error).message);
}
} else if (!fs.existsSync(configPath) && !copy_default) {
fs.writeFileSync(configPath, '{}');
@@ -50,11 +50,11 @@ export abstract class ConfigBase<T> {
this.configData = json5.parse(fs.readFileSync(configPath, 'utf-8'));
this.core.context.logger.logDebug(`[Core] [Config] 配置文件${configPath}加载`, this.configData);
return this.configData;
} catch (e: any) {
} catch (e: unknown) {
if (e instanceof SyntaxError) {
this.core.context.logger.logError('[Core] [Config] 配置文件格式错误,请检查配置文件:', e.message);
} else {
this.core.context.logger.logError('[Core] [Config] 读取配置文件时发生错误:', e.message);
this.core.context.logger.logError('[Core] [Config] 读取配置文件时发生错误:', (e as Error).message);
}
return {} as T;
}
@@ -67,8 +67,8 @@ export abstract class ConfigBase<T> {
const configPath = this.getConfigPath(selfInfo.uin);
try {
fs.writeFileSync(configPath, JSON.stringify(newConfigData, this.getKeys(), 2));
} catch (e: any) {
this.core.context.logger.logError(`保存配置文件 ${configPath} 时发生错误:`, e.message);
} catch (e: unknown) {
this.core.context.logger.logError(`保存配置文件 ${configPath} 时发生错误:`, (e as Error).message);
}
}
}

View File

@@ -1,22 +0,0 @@
// decoratorAsyncMethod(this,function,wrapper)
async function decoratorMethod<T, R>(
target: T,
method: () => Promise<R>,
wrapper: (result: R) => Promise<any>,
executeImmediately: boolean = true
): Promise<any> {
const execute = async () => {
try {
const result = await method.call(target);
return wrapper(result);
} catch (error) {
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
}
};
if (executeImmediately) {
return execute();
} else {
return execute;
}
}

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { NodeIQQNTWrapperSession } from '@/core/wrapper';
import { randomUUID } from 'crypto';
import { ListenerNamingMapping, ServiceNamingMapping } from '@/core';
@@ -75,6 +76,7 @@ export class NTEventWrapper {
}
return undefined;
}
return undefined;
}
createListenerFunction<T>(listenerMainName: string, uniqueCode: string = ''): T {

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { FFmpeg } from '@ffmpeg.wasm/main';
import { randomUUID } from 'crypto';
import { readFileSync, statSync, writeFileSync } from 'fs';

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import Piscina from 'piscina';
import { VideoInfo } from './video';

View File

@@ -58,8 +58,8 @@ function timeoutPromise(timeout: number, errorMsg: string): Promise<void> {
async function checkFile(path: string): Promise<void> {
try {
await stat(path);
} catch (error: any) {
if (error.code === 'ENOENT') {
} catch (error: unknown) {
if ((error as Error & { code: string }).code === 'ENOENT') {
// 如果文件不存在,则抛出一个错误
throw new Error(`文件不存在: ${path}`);
} else {
@@ -169,6 +169,7 @@ export async function checkUriType(Uri: string) {
const data = uri.split(',')[1];
if (data) return { Uri: data, Type: FileUriType.Base64 };
}
return;
}, Uri);
if (OtherFileRet) return OtherFileRet;

View File

@@ -1,14 +1,16 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import path from 'node:path';
import fs from 'fs';
import os from 'node:os';
import { QQLevel } from '@/core';
import { QQVersionConfigType } from './types';
export async function solveProblem<T extends (...arg: any[]) => any>(func: T, ...args: Parameters<T>): Promise<ReturnType<T> | undefined> {
return new Promise<ReturnType<T> | undefined>((resolve) => {
try {
const result = func(...args);
resolve(result);
} catch (e) {
} catch {
resolve(undefined);
}
});
@@ -193,7 +195,7 @@ export function parseAppidFromMajor(nodeMajor: string): string | undefined {
if (!content.every(byte => byte === 0x00)) {
try {
return content.toString('utf-8');
} catch (error) {
} catch {
break;
}
}

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import winston, { format, transports } from 'winston';
import { truncateString } from '@/common/helper';
import path from 'node:path';
@@ -34,7 +35,7 @@ class Subscription {
for (const history of Subscription.history) {
try {
listener(history);
} catch (_) {
} catch {
// ignore
}
}
@@ -68,7 +69,7 @@ export class LogWrapper {
format: format.combine(
format.timestamp({ format: 'MM-DD HH:mm:ss' }),
format.printf(({ timestamp, level, message, ...meta }) => {
const userInfo = meta.userInfo ? `${meta.userInfo} | ` : '';
const userInfo = meta['userInfo'] ? `${meta['userInfo']} | ` : '';
return `${timestamp} [${level}] ${userInfo}${message}`;
})
),
@@ -83,7 +84,7 @@ export class LogWrapper {
format: format.combine(
format.colorize(),
format.printf(({ timestamp, level, message, ...meta }) => {
const userInfo = meta.userInfo ? `${meta.userInfo} | ` : '';
const userInfo = meta['userInfo'] ? `${meta['userInfo']} | ` : '';
return `${timestamp} [${level}] ${userInfo}${message}`;
})
),

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { LogWrapper } from '@/common/log';
export function proxyHandlerOf(logger: LogWrapper) {
@@ -5,6 +6,7 @@ export function proxyHandlerOf(logger: LogWrapper) {
get(target: any, prop: any, receiver: any) {
if (typeof target[prop] === 'undefined') {
// 如果方法不存在返回一个函数这个函数调用existentMethod
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return (..._args: unknown[]) => {
logger.logDebug(`${target.constructor.name} has no method ${prop}`);
};

View File

@@ -4,6 +4,7 @@ import { getDefaultQQVersionConfigInfo, getQQPackageInfoPath, getQQVersionConfig
import AppidTable from '@/core/external/appid.json';
import { LogWrapper } from '@/common/log';
import { getMajorPath } from '@/core';
import { QQAppidTableType, QQPackageInfoType, QQVersionConfigType } from './types';
export class QQBasicInfoWrapper {
QQMainPath: string | undefined;
@@ -89,7 +90,7 @@ export class QQBasicInfoWrapper {
this.context.logger.log('[QQ版本兼容性检测] 当前版本Appid未内置 通过Major获取 为了更好的性能请尝试更新NapCat');
return { appid: majorAppid, qua: this.getQUAFallback() };
}
} catch (error) {
} catch {
this.context.logger.log('[QQ版本兼容性检测] 通过Major 获取Appid异常 请检测NapCat/QQNT是否正常');
}
// 最终兜底为老版本

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import https from 'node:https';
import http from 'node:http';

View File

@@ -54,10 +54,10 @@ class Store {
// 分批次扫描
while (scanned < this.scanLimit && this.scanCursor < keys.length) {
const key = keys[this.scanCursor++];
const entry = this.store.get(key)!;
const entry = this.store.get(key!)!;
if (entry.expiresAt && entry.expiresAt < now) {
this.store.delete(key);
this.store.delete(key!);
}
scanned++;

View File

@@ -6,7 +6,7 @@ let osName: string;
try {
osName = os.hostname();
} catch (e) {
} catch {
osName = 'NapCat'; // + crypto.randomUUID().substring(0, 4);
}

View File

@@ -1,17 +1,17 @@
//QQVersionType
type QQPackageInfoType = {
export type QQPackageInfoType = {
version: string;
buildVersion: string;
platform: string;
eleArch: string;
}
type QQVersionConfigType = {
export type QQVersionConfigType = {
baseVersion: string;
curVersion: string;
prevVersion: string;
onErrorVersions: Array<any>;
onErrorVersions: Array<unknown>;
buildId: string;
}
type QQAppidTableType = {
export type QQAppidTableType = {
[key: string]: { appid: string, qua: string };
}