'use strict';

const memwatch = require('memwatch-next');
const cluster = require('cluster');
const path = require('path');

const logger = require('../logger.js');

module.exports = exports = {};

exports.clearConsole = function() {
    logger.debug('Function call. clearConsole()', {args: [].slice.call(arguments)});
    // console.log('\x1Bc');
    process.stdout.write('\x1Bc');
};

exports.getProcessLaunchDate = function() {
    logger.debug('Function call. getProcessLaunchDate()', {args: [].slice.call(arguments)});
    // The result is not absolutely precise.
    // Deviations of up to 2 seconds are to be expected
    const ms_in_second = 1000;
    const now = new Date().getTime();
    const uptime = process.uptime() * ms_in_second;
    return new Date(now - uptime);
};

exports.capitalize = function(str) {
    logger.debug('Function call. capitalize(str)', {args: [].slice.call(arguments)});
    if (!str.length || typeof str !== 'string') {
        return str;
    }

    str = str[0].toUpperCase() + str.substr(1);
    return str;
};

exports.monitorMemoryLeaks = function() {
    memwatch.on('leak', function(info) {
        logger.warn('Possible MEMORY LEAK detected', info);
    });
};

exports.spawnStalker = function(args, onMessage, onError=console.error) {
    cluster.setupMaster({
        exec: path.resolve(__dirname, '../../stalker/run'),
        args: args,
        silent: true
    });

    const worker = cluster.fork();
    worker.on('message', onMessageThunkify(onMessage));
    worker.on('error', onError);
};

function onMessageThunkify(fn) {
    return msg => {
        if (typeof msg.data === 'string') {
            console.log(msg.data);
        }

        if (msg.error) {
            console.log(msg.error);
        }

        return fn(msg);
    };
}

@@ -12,51 +12,8 @@
 ';%0A%0A
-const memwatch = require('memwatch-next');%0A
 cons
@@ -1007,163 +1007,8 @@
 %7D;%0A%0A
-exports.monitorMemoryLeaks = function() %7B%0A    memwatch.on('leak', function(info) %7B%0A        logger.warn('Possible MEMORY LEAK detected', info);%0A    %7D);%0A%7D;%0A%0A
 expo

Remove memory-leak detection helper from console interface.