const http = require('http');
const fs = require('fs');
const path = require('path');
const port = Number(process.env.MYRAX_PLUGIN_PORT);
const dataDir = process.env.MYRAX_PLUGIN_DATA;
const statePath = path.join(dataDir, 'state.json');
function readState() {
try { return JSON.parse(fs.readFileSync(statePath, 'utf8')); }
catch { return {}; }
}
function writeState(state) {
fs.mkdirSync(dataDir, { recursive: true });
fs.writeFileSync(statePath, JSON.stringify(state), { mode: 0o600 });
}
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'content-type': 'application/json' });
return res.end('{"ok":true}');
}
if (req.method === 'GET' && req.url === '/api/state') {
res.writeHead(200, { 'content-type': 'application/json' });
return res.end(JSON.stringify(readState()));
}
res.writeHead(404, { 'content-type': 'application/json' });
res.end('{"error":"not found"}');
});
server.listen(port, '127.0.0.1', () => {
console.log(`listening on ${port}`); // goes to the plugin log
});
process.on('SIGINT', () => server.close(() => process.exit(0)));