import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { getRecentLogs, clearLogFile } from './utils/logger.js';
import { info as log, error as logError } from './utils/logger.js';
import config from './config.js';
const app = new Hono();
// 静态文件服务 - 提供 screenshots 目录
app.use('/screenshots/*', serveStatic({ root: './' }));
// 静态 HTML 页面
const indexHTML = `
CloudStudio Runner - 日志查看器
准备就绪
📸 最新截图
截图文件不存在或无法加载
`;
// 路由定义
app.get('/', (c) => {
return c.html(indexHTML);
});
// API 路由 - 获取日志
app.get('/api/logs', (c) => {
try {
const lines = parseInt(c.req.query('lines') || '100');
const logs = getRecentLogs(lines);
return c.json({
success: true,
logs: logs,
count: logs.length,
timestamp: new Date().toISOString()
});
} catch (error) {
logError('获取日志API错误:', error);
return c.json({
success: false,
error: error.message
}, 500);
}
});
// API 路由 - 清空日志
app.post('/api/clear-logs', (c) => {
try {
const success = clearLogFile();
if (success) {
log('日志文件已通过Web界面清空');
return c.json({
success: true,
message: '日志文件已清空',
timestamp: new Date().toISOString()
});
} else {
return c.json({
success: false,
error: '清空日志文件失败'
}, 500);
}
} catch (error) {
logError('清空日志API错误:', error);
return c.json({
success: false,
error: error.message
}, 500);
}
});
// API 路由 - 系统状态
app.get('/api/status', (c) => {
return c.json({
success: true,
status: 'running',
uptime: process.uptime(),
memory: process.memoryUsage(),
timestamp: new Date().toISOString(),
config: {
webideUrl: config.webideUrl,
schedulerInterval: config.schedulerInterval,
headless: config.browserOptions.headless
}
});
});
// 健康检查
app.get('/health', (c) => {
return c.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// 启动服务器
const port = process.env.PORT || 7860;
async function startServer() {
try {
log(`启动 Web 服务器,端口: ${port}`);
log(`访问地址: http://localhost:${port}`);
serve({
fetch: app.fetch,
port: port,
});
log('Web 服务器启动成功');
} catch (error) {
logError('启动 Web 服务器失败:', error);
process.exit(1);
}
}
// 如果直接运行此文件,启动服务器
import { fileURLToPath } from 'url';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const scriptPath = path.resolve(process.argv[1]);
if (path.resolve(__filename) === scriptPath) {
startServer();
}
export { app, startServer };