import { randomUUID } from "crypto"; import Logs from "./logs.js"; class ProcessData { #process; #name; #request = { callbacks: {}, functions: {} }; #response = { functions: {} }; constructor(processInstance = process, name = 'process', showStdout = false) { this.#process = processInstance; this.#name = name; this.#process.on('message', (message) => { this.#handleMessage(message); }); this.#process.stdout?.on('data', data => { if (showStdout) { Logs.out('%s stdout: ↩︎', name); console.log(data.toString()); } }); this.#process.stderr?.on('data', data => { Logs.out('%s stderr', name, data.toString()); }); } get(type, params) { const id = randomUUID(); this.#process.send({ method: 'get', type, id, params }); return new Promise(resolve => { this.#request.callbacks[id] = resolve; }); } registerResponse(type, func) { this.#response.functions[type] = func; } #responseData(type, params, id) { const func = this.#response.functions[type]; func?.(params).then(data => { this.#process.send({ type: 'response', data, id }); }); } post(type, data) { this.#process.send({ method: 'post', type, data }); } registerRequest(type, func) { this.#request.functions[type] = func; } #requestData(type, data) { const func = this.#request.functions[type]; func?.(data); } #handleMessage(message) { const { callbacks } = this.#request; const { method, type, data, error, id, params } = message; if (error) { console.error(error); } if (method == 'get' && id) { this.#responseData(type, params, id); } else if (type == 'response' && id && callbacks[id]) { callbacks[id](data); delete callbacks[id]; } else if (method == 'post' && type) { this.#requestData(type, data); } } } export default ProcessData;