Files
cli/assistant/src/server.ts
2025-05-17 03:32:38 +08:00

79 lines
2.3 KiB
TypeScript

import { app, assistantConfig } from './app.ts';
import { proxyRoute, proxyWs } from './services/proxy/proxy-page-index.ts';
import './routes/index.ts';
import getPort, { portNumbers } from 'get-port';
import { program } from 'commander';
import { spawnSync } from 'child_process';
import chalk from 'chalk';
export const runServer = async (port?: number) => {
let _port: number | undefined;
if (port) {
_port = await getPort({ port });
if (_port !== port) {
console.log(`Port ${port} is not available`);
_port = undefined;
}
}
if (!_port) {
// 检车端口可用性
const isPortAvailable = await getPort({ port: portNumbers(51015, 52000) });
if (!isPortAvailable) {
console.log(`Port ${isPortAvailable} is not available`);
process.exit(1);
}
_port = isPortAvailable;
}
app.listen(_port, () => {
console.log(`Server is running on https://localhost:${_port}`);
});
app.server.on(proxyRoute);
proxyWs();
return {
app,
port: _port,
};
};
program
.description('启动服务')
.option('-d, --daemon', '是否以守护进程方式运行')
.option('-n, --name <name>', '服务名称', 'assistant-server')
.option('-p, --port <port>', '服务端口')
.option('-s, --start', '是否启动服务')
.option('-i, --home', 'home目录')
.action(async (options) => {
// console.log('当前执行路径:', execPath, inte);
if (options.daemon) {
const [_interpreter, execPath] = process.argv;
const name = options.name;
const port = options.port;
let pm2Command = `pm2 start ${execPath} --name ${name} -- -s `;
if (port) {
pm2Command += ` -p ${port}`;
}
if (options.home) {
pm2Command += ` --home`;
}
const result = spawnSync(pm2Command, {
shell: true,
stdio: 'inherit',
});
if (result.error) {
console.error('Error starting server:', result.error);
process.exit(1);
}
console.log('以守护进程方式运行');
} else if (options.start) {
console.log('启动服务', chalk.green(assistantConfig.configDir));
const server = await runServer(options.port);
}
});
export const runParser = async (argv: string[]) => {
try {
program.parse(argv);
} catch (error) {
console.error('执行错误:', error.message);
}
};