import { spawn } from 'node:child_process'; import path from 'node:path'; export class PortalScreenshot { constructor({ helper = path.resolve(new URL('./py/portal_screenshot.py', import.meta.url).pathname), python = 'python3', spawnImpl = spawn, tmpDir = '/tmp/jarvis-cu', timeoutMs = 8000 } = {}) { this.helper = helper; this.python = python; this.spawnImpl = spawnImpl; this.tmpDir = tmpDir; this.timeoutMs = timeoutMs; } async capture(output = path.join(this.tmpDir, `portal-${Date.now()}.png`)) { return new Promise((resolve, reject) => { const child = this.spawnImpl(this.python, [this.helper, output], { stdio: ['ignore', 'pipe', 'pipe'] }); let out = ''; let err = ''; let settled = false; const timer = setTimeout(() => { if (settled) return; settled = true; child.kill('SIGTERM'); reject(new Error('screenshot portal timed out')); }, this.timeoutMs); const done = (fn) => (value) => { if (settled) return; settled = true; clearTimeout(timer); fn(value); }; child.stdout.on('data', (d) => { out += d; }); child.stderr.on('data', (d) => { err += d; }); child.on('error', done(reject)); child.on('close', (code) => done(code === 0 ? resolve : reject)(code === 0 ? (out.trim() || output) : new Error(err || `Screenshot portal exited ${code}`))); }); } }