// 开发桥接服务:以 HTTP 形式暴露与 Tauri IPC 相同的命令契约 // 浏览器预览模式使用;打包为桌面应用后由 Rust 后端接管同一契约 import http from 'node:http'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { handleCommand, DATA_DIR } from './db.mjs'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const DIST = path.join(__dirname, '..', 'dist'); const PORT = Number(process.env.FP_PORT || process.env.PORT || 8787); const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.json': 'application/json' }; const server = http.createServer(async (req, res) => { const url = new URL(req.url, 'http://localhost'); res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS'); if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; } if (req.method === 'POST' && url.pathname.startsWith('/api/')) { const cmd = url.pathname.slice(5); let body = ''; let size = 0; req.on('data', chunk => { size += chunk.length; if (size > 160 * 1024 * 1024) { req.destroy(); } // 与 sync-server 对齐 else body += chunk; }); req.on('end', () => { let payload = {}; try { payload = body ? JSON.parse(body) : {}; } catch {} try { const data = handleCommand(cmd, payload); res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify({ ok: true, data })); } catch (e) { res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify({ ok: false, error: e.message || String(e) })); } }); return; } // 静态托管 dist(若已构建),便于纯浏览器验收 if (req.method === 'GET' && fs.existsSync(DIST)) { let p = url.pathname === '/' ? '/index.html' : url.pathname; const abs = path.join(DIST, p); if (fs.existsSync(abs) && fs.statSync(abs).isFile()) { res.writeHead(200, { 'Content-Type': MIME[path.extname(abs)] ?? 'application/octet-stream' }); res.end(fs.readFileSync(abs)); return; } const indexHtml = path.join(DIST, 'index.html'); if (fs.existsSync(indexHtml)) { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(fs.readFileSync(indexHtml)); return; } } res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify({ ok: false, error: 'not found' })); }); server.listen(PORT, '127.0.0.1', () => { console.log('[footprints-bridge] listening on http://127.0.0.1:' + PORT); console.log('[footprints-bridge] data dir:', DATA_DIR); });