Apply formatting and minor style fixes across repo

Normalize code style across multiple packages: whitespace cleanup, consistent commas and trailing commas in arrays/enums/objects, fix table markdown lines in CI comment template, ensure newline at EOF, normalize header/object property quoting and spacing, remove stray blank lines and minor non-functional comment tweaks. These are formatting-only changes and small type/annotation spacing adjustments; no functional behavior changes intended.
This commit is contained in:
手瓜一十雪 committed 2026-03-05 18:45:50 +08:00
1 parent d2d0b258bc
commit 974528fe7e
186 files changed
+1367 -1233

No files matched your search

@@ -52,7 +52,6 @@ export const BackupExportConfigHandler: RequestHandler = async (_req, res) => {
sendError(res, '流式压缩失败');
}
});
} catch (error) {
const msg = (error as Error).message;
console.error('导出配置失败:', error);
@@ -140,9 +139,8 @@ export const BackupImportConfigHandler: RequestHandler = async (req, res) => {
return sendSuccess(res, {
message: '配置导入成功,重启后生效~',
filesImported: extractedFiles.size,
filesBackedUp: backupFiles.size
filesBackedUp: backupFiles.size,
});
} catch (error) {
console.error('导入配置失败:', error);
const msg = (error as Error).message;
@@ -154,7 +154,7 @@ export const getAllReleasesHandler: RequestHandler = async (req, res) => {
total,
totalPages,
},
mirror: usedMirror
mirror: usedMirror,
});
} catch (error) {
res.status(500).json({ error: 'Failed to fetch releases' });
@@ -3,7 +3,7 @@ import { WebSocket, WebSocketServer, RawData } from 'ws';
import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response';
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { IncomingMessage } from 'http';
import { OB11Response } from '@/napcat-onebot/action/OneBotAction';
import { OB11Response, OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { OB11LifeCycleEvent, LifeCycleSubType } from '@/napcat-onebot/event/meta/OB11LifeCycleEvent';
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
@@ -12,7 +12,7 @@ import { ActionMap } from '@/napcat-onebot/action';
import { NapCatCore } from '@/napcat-core/index';
import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
import { OB11EmitEventContent, OB11NetworkReloadType } from '@/napcat-onebot/network/index';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import json5 from 'json5';
type ActionNameType = typeof ActionName[keyof typeof ActionName];
@@ -82,7 +82,7 @@ class DebugAdapter extends IOB11NetworkAdapter<WebsocketServerConfig> {
token: '',
enableForcePushEvent: true,
debug: true,
heartInterval: 0
heartInterval: 0,
};
super(`debug-${sessionId}`, config, core, obContext, actions);
@@ -161,9 +161,9 @@ class DebugAdapter extends IOB11NetworkAdapter<WebsocketServerConfig> {
this.updateActivity();
let receiveData: { action: ActionNameType, params?: Record<string, unknown>, echo?: unknown; } = {
action: ActionName.Unknown,
params: {}
params: {},
};
let echo: unknown = undefined;
let echo: unknown;
try {
receiveData = json5.parse(message.toString());
@@ -332,7 +332,7 @@ router.post('/create', async (_req: Request, res: Response) => {
*/
const handleCallApi = async (req: Request, res: Response) => {
try {
let adapterName = req.params['adapterName'] || req.body.adapterName || DEFAULT_ADAPTER_NAME;
const adapterName = req.params['adapterName'] || req.body.adapterName || DEFAULT_ADAPTER_NAME;
let adapter = debugAdapterManager.getAdapter(adapterName);
@@ -6,7 +6,7 @@ import {
buildMirrorUrl,
getMirrorConfig,
setCustomMirror,
clearMirrorCache
clearMirrorCache,
} from 'napcat-common/src/mirror';
import https from 'https';
import http from 'http';
+11 -12
View File
@@ -121,7 +121,7 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
homepage?: string;
repository?: string;
icon?: string;
}> = new Array();
}> = [];
// 收集所有插件的扩展页面
const extensionPages: Array<{
@@ -175,13 +175,12 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
path: page.path,
title: page.title,
icon: page.icon,
description: page.description
description: page.description,
});
}
}
}
return sendSuccess(res, { plugins: AllPlugins, pluginManagerNotFound: false, extensionPages });
};
@@ -342,7 +341,7 @@ export const PluginConfigSSEHandler: RequestHandler = (req, res): void => {
hideField: (key: string) => {
sendSSE('schema', { type: 'hideField', key });
},
getCurrentConfig: () => currentConfig
getCurrentConfig: () => currentConfig,
};
// 存储会话
@@ -423,30 +422,30 @@ export const PluginConfigChangeHandler: RequestHandler = async (req, res) => {
if (plugin.runtime.module?.plugin_on_config_change) {
const uiController = {
updateSchema: (schema: any[]) => {
session.res.write(`event: schema\n`);
session.res.write('event: schema\n');
session.res.write(`data: ${JSON.stringify({ type: 'full', schema })}\n\n`);
},
updateField: (fieldKey: string, field: any) => {
session.res.write(`event: schema\n`);
session.res.write('event: schema\n');
session.res.write(`data: ${JSON.stringify({ type: 'updateField', key: fieldKey, field })}\n\n`);
},
removeField: (fieldKey: string) => {
session.res.write(`event: schema\n`);
session.res.write('event: schema\n');
session.res.write(`data: ${JSON.stringify({ type: 'removeField', key: fieldKey })}\n\n`);
},
addField: (field: any, afterKey?: string) => {
session.res.write(`event: schema\n`);
session.res.write('event: schema\n');
session.res.write(`data: ${JSON.stringify({ type: 'addField', field, afterKey })}\n\n`);
},
showField: (fieldKey: string) => {
session.res.write(`event: schema\n`);
session.res.write('event: schema\n');
session.res.write(`data: ${JSON.stringify({ type: 'showField', key: fieldKey })}\n\n`);
},
hideField: (fieldKey: string) => {
session.res.write(`event: schema\n`);
session.res.write('event: schema\n');
session.res.write(`data: ${JSON.stringify({ type: 'hideField', key: fieldKey })}\n\n`);
},
getCurrentConfig: () => session.currentConfig
getCurrentConfig: () => session.currentConfig,
};
try {
@@ -460,7 +459,7 @@ export const PluginConfigChangeHandler: RequestHandler = async (req, res) => {
);
}
} catch (e: any) {
session.res.write(`event: error\n`);
session.res.write('event: error\n');
session.res.write(`data: ${JSON.stringify({ message: e.message })}\n\n`);
}
}
@@ -20,7 +20,7 @@ function oidbRequest (uid: string, body: Record<string, unknown>): Promise<Recor
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
Accept: 'application/json, text/plain, */*',
},
}, (res) => {
let data = '';
@@ -554,5 +554,3 @@ export const QQPollNewDeviceQRHandler: RequestHandler = async (req, res) => {
return sendError(res, `Failed to poll QR status: ${(e as Error).message}`);
}
};
@@ -10,7 +10,7 @@ import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { NapCatCoreWorkingEnv } from '@/napcat-webui-backend/src/types';
import {
getGitHubRelease,
findAvailableDownloadUrl
findAvailableDownloadUrl,
} from '@/napcat-common/src/mirror';
import { ILogWrapper } from '@/napcat-common/src/log-interface';
@@ -39,7 +39,7 @@ interface UpdateConfig {
// 需要跳过更新的文件
const SKIP_UPDATE_FILES = [
'NapCatWinBootMain.exe',
'NapCatWinBootHook.dll'
'NapCatWinBootHook.dll',
];
/**
@@ -67,7 +67,7 @@ function scanFilesRecursively (dirPath: string, basePath: string = dirPath): Arr
} else if (stat.isFile()) {
files.push({
sourcePath: fullPath,
relativePath: relativePath
relativePath,
});
}
}
@@ -86,7 +86,7 @@ async function downloadFile (url: string, dest: string): Promise<void> {
return new Promise((resolve, reject) => {
const request = https.get(url, {
headers: { 'User-Agent': 'NapCat-WebUI' }
headers: { 'User-Agent': 'NapCat-WebUI' },
}, (res) => {
webUiLogger?.log('[NapCat Update] Response status:', res.statusCode);
webUiLogger?.log('[NapCat Update] Content-Type:', res.headers['content-type']);
@@ -171,7 +171,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
webUiLogger?.log(`[NapCat Update] Using download URL: ${downloadUrl}`);
} catch (error) {
// 如果镜像都不可用,直接使用原始 URL
webUiLogger?.logWarn(`[NapCat Update] All nightly.link mirrors failed, using original URL`);
webUiLogger?.logWarn('[NapCat Update] All nightly.link mirrors failed, using original URL');
downloadUrl = baseUrl;
}
} else {
@@ -289,7 +289,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
webUiLogger?.logError(`[NapCat Update] Failed to update ${targetFilePath}, will retry on next startup:`, error);
failedFiles.push({
sourcePath: fileInfo.sourcePath,
targetPath: targetFilePath
targetPath: targetFilePath,
});
}
}
@@ -300,7 +300,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
version: actualVersion,
updateTime: new Date().toISOString(),
files: failedFiles,
changelog: ''
changelog: '',
};
// 保存更新配置文件
@@ -317,14 +317,12 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
status: 'completed',
message,
newVersion: actualVersion,
failedFilesCount: failedFiles.length
failedFilesCount: failedFiles.length,
});
} catch (error) {
webUiLogger?.logError('[NapCat Update] 更新失败:', error);
sendError(res, '更新失败: ' + (error instanceof Error ? error.message : '未知错误'));
}
} catch (error: any) {
webUiLogger?.logError('[NapCat Update] 更新失败:', error);
sendError(res, '更新失败: ' + error.message);
@@ -340,7 +338,7 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper,
const configPath = path.join(webUiPathWrapper.configPath, 'napcat-update.json');
if (!fs.existsSync(configPath)) {
//logger.log('[NapCat Update] No pending updates found');
// logger.log('[NapCat Update] No pending updates found');
return;
}
@@ -373,7 +371,6 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper,
}
fs.copyFileSync(file.sourcePath, file.targetPath);
logger.log(`[NapCat Update] Updated ${path.basename(file.targetPath)} on startup`);
} catch (error) {
logger.logError(`[NapCat Update] Failed to update ${file.targetPath} on startup:`, error);
// 如果仍然失败,保留在列表中
@@ -385,7 +382,7 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper,
if (remainingFiles.length > 0) {
const updatedConfig: UpdateConfig = {
...updateConfig,
files: remainingFiles
files: remainingFiles,
};
fs.writeFileSync(configPath, JSON.stringify(updatedConfig, null, 2));
logger.log(`[NapCat Update] ${remainingFiles.length} files still pending update`);
@@ -1,26 +1,26 @@
/**
* NapCat WebUI Service Worker
*
*
* 路由缓存策略设计:
*
*
* 【永不缓存 - Network Only】
* - /api/* WebUI API
* - /plugin/:id/api/* 插件 API
* - /files/theme.css 动态主题 CSS
* - /webui/fonts/CustomFont.woff 用户自定义字体
* - WebSocket / SSE 连接
*
*
* 【强缓存 - Cache First】
* - /webui/assets/* 前端静态资源(带 hash)
* - /webui/fonts/* 内置字体(排除 CustomFont)
* - q1.qlogo.cn QQ 头像
*
*
* 【网络优先 - Network First】
* - /webui/* (HTML 导航) SPA 页面
* - /plugin/:id/page/* 插件页面
* - /plugin/:id/files/* 插件文件系统静态资源
*
* 【后台更新 - Stale-While-Revalidate】
*
* 【后台更新 - Stale-While-Revalidate】
* - /plugin/:id/mem/* 插件内存静态资源
*/
@@ -216,11 +216,10 @@ self.addEventListener('fetch', (event) => {
// 8. 其他同源请求 - Network Only(避免意外缓存)
if (url.origin === self.location.origin) {
// 不缓存,直接穿透
return;
}
// 9. 其他外部请求 - Network Only
return;
});
// ============ 缓存策略实现 ============
@@ -32,7 +32,7 @@ export async function auth (req: Request, res: Response, next: NextFunction) {
}
// 判断是否有Authorization头
if (hash) {
//if (!hash) return sendError(res, 'Unauthorized');
// if (!hash) return sendError(res, 'Unauthorized');
// 解析token
let Credential: WebUiCredentialJson;
try {
@@ -3,7 +3,7 @@ import {
GetMirrorListHandler,
SetCustomMirrorHandler,
TestMirrorsSSEHandler,
TestSingleMirrorHandler
TestSingleMirrorHandler,
} from '@/napcat-webui-backend/src/api/Mirror';
const router: Router = Router();
@@ -8,7 +8,7 @@ const router: Router = Router();
// 使用内存存储,配合流式处理
const upload = multer({
storage: multer.memoryStorage()
storage: multer.memoryStorage(),
});
// router:读取配置
@@ -21,4 +21,3 @@ router.get('/ExportConfig', BackupExportConfigHandler);
router.post('/ImportConfig', upload.single('configFile'), BackupImportConfigHandler);
export { router as OB11ConfigRouter };
@@ -13,13 +13,13 @@ import {
PluginConfigSSEHandler,
PluginConfigChangeHandler,
// ImportLocalPluginHandler,
GetPluginIconHandler
GetPluginIconHandler,
} from '@/napcat-webui-backend/src/api/Plugin';
import {
GetPluginStoreListHandler,
GetPluginStoreDetailHandler,
InstallPluginFromStoreHandler,
InstallPluginFromStoreSSEHandler
InstallPluginFromStoreSSEHandler,
} from '@/napcat-webui-backend/src/api/PluginStore';
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
@@ -10,4 +10,4 @@ const router: Router = Router();
// POST /api/UpdateNapCat/update - 更新NapCat
router.post('/update', UpdateNapCatHandler);
export { router as UpdateNapCatRouter };
export { router as UpdateNapCatRouter };