|
| 1 | +#!/usr/bin/env node |
| 2 | +import fs from 'fs/promises'; |
| 3 | +import express from 'express'; |
| 4 | +import path from 'path'; |
| 5 | +import { fileURLToPath } from 'url'; |
| 6 | + |
| 7 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 8 | + |
| 9 | +const app = express(); |
| 10 | +app.use(express.json()); |
| 11 | + |
| 12 | +// Simple in-memory workflows |
| 13 | +const workflows = new Map(); |
| 14 | + |
| 15 | +app.post('/workflow/:name', async (req, res) => { |
| 16 | + workflows.set(req.params.name, req.body); |
| 17 | + res.json({ status: 'saved', workflow: req.params.name }); |
| 18 | +}); |
| 19 | + |
| 20 | +app.post('/run/:name', async (_req, res) => { |
| 21 | + const flow = workflows.get(_req.params.name); |
| 22 | + if (!flow) return res.status(404).json({ error: 'Workflow not found' }); |
| 23 | + await runWorkflow(flow); |
| 24 | + res.json({ status: 'executed', workflow: _req.params.name }); |
| 25 | +}); |
| 26 | + |
| 27 | +async function runWorkflow(steps) { |
| 28 | + for (const step of steps) { |
| 29 | + switch (step.type) { |
| 30 | + case 'log': |
| 31 | + console.log(step.message); |
| 32 | + break; |
| 33 | + case 'delay': |
| 34 | + await new Promise(resolve => setTimeout(resolve, step.ms || 0)); |
| 35 | + break; |
| 36 | + case 'http': |
| 37 | + try { |
| 38 | + const res = await fetch(step.url, { method: step.method || 'GET' }); |
| 39 | + console.log('HTTP', res.status, step.url); |
| 40 | + } catch (err) { |
| 41 | + console.error('HTTP error', err.message); |
| 42 | + } |
| 43 | + break; |
| 44 | + default: |
| 45 | + console.warn('Unknown step', step); |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +const PORT = process.env.PORT || 3000; |
| 51 | +app.listen(PORT, () => { |
| 52 | + console.log(`p8p listening on port ${PORT}`); |
| 53 | +}); |
| 54 | + |
| 55 | +// CLI usage: load workflow from file and run |
| 56 | +if (process.argv[2]) { |
| 57 | + const filePath = path.resolve(process.cwd(), process.argv[2]); |
| 58 | + fs.readFile(filePath, 'utf8').then(data => { |
| 59 | + const flow = JSON.parse(data); |
| 60 | + runWorkflow(flow); |
| 61 | + }); |
| 62 | +} |
0 commit comments