Refactor CNB command to improve configuration handling and add default keep.json

- Changed import of 'path' module to use default import syntax.
- Updated 'live' command to accept a configuration file path with higher priority than JSON input.
- Removed stdin reading for JSON input; now reads directly from the specified config file.
- Simplified error handling for JSON parsing and configuration validation.
- Enhanced keepAlive creation by removing unnecessary callbacks and enabling debug mode.
- Added default keep.json file with example configuration.
This commit is contained in:
2026-02-15 23:52:32 +08:00
parent 786ee80839
commit 76aeb21a41
5 changed files with 390 additions and 518 deletions

View File

@@ -1,6 +1,6 @@
import { createKeepAlive } from '@kevisual/cnb/keep'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import path from 'node:path'
import { program, Command } from '@/program.ts';
@@ -16,25 +16,17 @@ const cnbCmd = new Command('cnb')
const liveCmd = new Command('live')
.description('启动 CNB Keep Alive 服务')
.option('-j, --json <string>', 'JSON数据 (不提供则从 stdin 读取)')
.option('-j, --json <string>', 'JSON数据')
.option('-c, --config <string>', '配置文件路径 (优先级高于 JSON 参数), 默认keep.json')
.action(async (opts) => {
let config: { wss: string; cookie: string; url?: string };
const configPath = path.join(process.cwd(), opts.config || 'keep.json');
try {
let jsonString = opts.json;
// 如果没有提供 json 参数,从 stdin 读取
if (!jsonString) {
const chunks: Buffer[] = [];
for await (const chunk of process.stdin) {
chunks.push(chunk);
}
jsonString = Buffer.concat(chunks).toString('utf-8').trim();
}
// 从文件读取
else if (jsonString.startsWith('@')) {
const filePath = resolve(jsonString.slice(1));
jsonString = readFileSync(filePath, 'utf-8').trim();
jsonString = readFileSync(configPath, 'utf-8').trim();
}
config = JSON.parse(jsonString);
@@ -42,30 +34,19 @@ const liveCmd = new Command('live')
console.error('JSON 解析错误: 请检查输入的 JSON 格式是否正确');
process.exit(1);
}
if (!config.wss || !config.cookie) {
console.error('配置错误: 必须包含 wss 和 cookie 字段');
process.exit(1);
}
const keepAlive = createKeepAlive({
createKeepAlive({
wsUrl: config.wss,
cookie: config.cookie,
onConnect: () => {
console.log('已连接到 CNB 服务器');
},
onDisconnect: (code) => {
console.log(`与 CNB 服务器断开连接,代码: ${code}`);
},
onError: (error) => {
console.error('CNB 连接错误:', error);
},
onMessage: (data) => {
console.log('收到 CNB 消息:', data.toString());
},
debug: true
});
keepAlive.connect();
});
cnbCmd.addCommand(liveCmd);