import { Bert } from "./bert.js"; import { Duplex } from "node:stream"; const bert = new Bert(); const fakeWrite = () => undefined; process.stdout.write = fakeWrite; export class Port extends Duplex { constructor() { super({ objectMode: true }); } read() { const lenBytes = process.stdin.read(4); if (lenBytes) { const termLen = bert.bytesToInt(lenBytes, 4, true); const termBytes = process.stdin.read(termLen); if (termBytes) { return bert.decode(termBytes); } else { process.stderr.write(`Read should have gotten ${termLen} bytes.\n`); return null; } } else return null; } write(obj, encodingOrCallback, callback) { const actualCallback = callback || typeof encodingOrCallback === "function" ? encodingOrCallback : undefined; try { const term = bert.encode(obj, true); const len = Buffer.alloc(4); len.writeUInt32BE(term.length, 0); process.stdout.write(len); return process.stdout.write(term, actualCallback); } catch (error) { process.stderr.write(`Error writing: ${error}\n`); return false; } } // When all the data is done passing, it stops. _final() { this.push(null); } }