"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RpcProcessor = void 0;
class RpcProcessor {
    constructor(child) {
        this.child = child;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        this.handlers = {};
        this.isClosed = false;
    }
    handler(method, handler) {
        this.handlers[method] = handler;
    }
    async handle(method, input) {
        const handler = this.handlers[method];
        if (!handler) {
            throw new Error(`Handler for method ${method} not found`);
        }
        return handler(input);
    }
    response(id, result, error) {
        if (id && !this.isClosed && this.child.connected && !this.child.killed) {
            this.child.send?.({ type: 'rpc_response', id, result, error });
        }
    }
    async init() {
        this.child.on('message', (msg) => {
            if (msg.type === 'rpc_request') {
                const { id, method, args } = msg;
                this.handle(method, args)
                    .then((result) => this.response(id, result, null))
                    .catch((error) => this.response(id, null, error));
            }
        });
        this.child.on('exit', () => {
            this.isClosed = true;
        });
        this.child.on('close', () => {
            this.isClosed = true;
        });
        this.child.on('disconnect', () => {
            this.isClosed = true;
        });
    }
}
exports.RpcProcessor = RpcProcessor;
