"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const path_1 = require("../path");
// run a single unit inside a child process
class Runner {
    constructor(onMessage, onError) {
        this._handleError = (err) => {
            if (err) {
                this.kill();
                this._onError(err);
            }
        };
        this._handleMessage = (message) => {
            this._onMessage(message);
        };
        this._onMessage = onMessage;
        this._onError = onError;
    }
    kill() {
        if (this._childProcess !== null) {
            this._childProcess.kill();
            this._childProcess = null;
        }
    }
    start() {
        const system = path_1.PATH_SRC_SYSTEM;
        this._childProcess = (0, child_process_1.fork)(`${system}/debug/container.js`, [], {
            env: {
                NODE_ENV: 'development',
            },
            execArgv: [],
            silent: false,
        });
        this._childProcess.on('message', this._handleMessage);
        this._childProcess.on('error', this._handleError);
    }
    restart() {
        if (this._childProcess) {
            this.kill();
        }
        this.start();
    }
    alive() {
        return !!this._childProcess;
    }
    dead() {
        return !this.alive();
    }
    sendAction(action) {
        if (!this._childProcess) {
            throw new Error('cannot send action to dead container');
        }
        this._send(action);
    }
    _send(message) {
        this._childProcess.send(message, this._handleError.bind(this));
    }
}
exports.default = Runner;
//# sourceMappingURL=runner.js.map