const express = require('express'); const { exec } = require('child_process'); const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.json({ limit: '10mb' })); const AUTH_TOKEN = process.env.API_TOKEN; // 🔐 鉴权中间件 app.use((req, res, next) => { const auth = req.headers.authorization; if (!auth || !auth.startsWith('Bearer ')) { return res.status(401).send('Unauthorized'); } const token = auth.slice(7); if (token !== AUTH_TOKEN) { return res.status(401).send('Unauthorized'); } next(); }); const safeUnlink = (file) => { try { if (fs.existsSync(file)) fs.unlinkSync(file); } catch (e) { console.error('Cleanup failed:', file, e.message); } }; /** * 核心引擎:将所有图形转为路径并执行布尔运算 */ const runInkscape = (svg, mode) => { return new Promise((resolve, reject) => { const id = crypto.randomUUID(); const inputFile = path.join('/tmp', `${id}_in.svg`); const outputFile = path.join('/tmp', `${id}_out.svg`); const cleanup = () => { safeUnlink(inputFile); safeUnlink(outputFile); }; try { // 预处理 const processedSvg = svg.replace(/currentColor/g, '#000000'); fs.writeFileSync(inputFile, processedSvg); } catch (err) { cleanup(); return reject(err); } let coreActions = ['object-to-path']; if (mode === 'stroke') { coreActions.push('object-stroke-to-path', 'path-union'); } else if (mode === 'fill') { coreActions.push('object-set-property:fill,#000000', 'path-union'); } else if (mode === 'stroke-fill') { coreActions.push( 'object-set-property:fill,#000000', 'object-stroke-to-path', 'select-all', 'path-union' ); } const actions = [ `file-open:${inputFile}`, 'select-all', ...coreActions, `export-filename:${outputFile}`, 'export-plain-svg', 'export-do', 'file-close' ].join(';'); const command = `xvfb-run -a inkscape --actions="${actions}"`; exec(command, (error, stdout, stderr) => { if (error) { cleanup(); return reject(new Error(stderr || error.message)); } if (!fs.existsSync(outputFile)) { cleanup(); return reject(new Error('Output SVG not generated')); } try { const result = fs.readFileSync(outputFile, 'utf8'); const dValues = []; const pathMatch = /]+d="([^"]+)"/g; let match; while ((match = pathMatch.exec(result)) !== null) { dValues.push(match[1]); } cleanup(); resolve(dValues.join(' ')); } catch (err) { cleanup(); reject(err); } }); }); }; app.post('/convert/:mode', async (req, res) => { try { const d = await runInkscape(req.body.svg, req.params.mode); res.send(d); } catch (err) { res.status(500).send(err.message); } }); app.listen(7860);