<commit_before>'use strict';

exports.init = function (app, config, auditLogger) {

    function log(context) {
        var auditLog = {};
        var method = context.method;

        auditLog.method = context.req.method;
        auditLog.url = context.req.originalUrl;
        auditLog.eventName = method.sharedClass.name;
        auditLog.subEventName = method.name;
        auditLog.arguments = context.args;
        auditLog.result = context.result || {};
        auditLog.error = context.error || {};
        auditLog.status = context.error ? (context.error.statusCode || context.error.status) : (Object.keys(context.result) > 0 ? 200 : 204);

        var user = {};
        auditLog.user = user;

        var loopback = app.loopback;
        var loopbackCtx = loopback.getCurrentContext();

        if (loopbackCtx) {

            var accessToken = loopback.getCurrentContext().get('accessToken');
            if (accessToken) {
                user = accessToken.user().toJSON();
            } else {
                user.name = 'ANONYMOUS';
            }
        } else {
            user.name = 'NO LOOPBACK CONTEXT';
        }

        user.ip = context.req.ip ||
            context.req._remoteAddress ||
            (context.req.connection && context.req.connection.remoteAddress) ||
            undefined;

        process.nextTick(function () {
            auditLogger.info({ 'log': auditLog });
        });
    }

    var models = app.models();
    models.forEach(function (Model) {

        Model.afterRemote('**', function (context, unused, next) {
            log(context);
            next();
        });
        Model.afterRemoteError('**', function (context, next) {
            log(context);
            next();
        });
    });
};
<commit_msg>Updated to log headers, query and params along with arguments body<commit_after>'use strict';

exports.init = function (app, config, auditLogger) {

    function log(context) {
        var auditLog = {};
        var method = context.method;

        auditLog.method = context.req.method;
        auditLog.url = context.req.originalUrl;
        auditLog.eventName = method.sharedClass.name;
        auditLog.subEventName = method.name;
        auditLog.arguments = {
            params: context.req.params,
            query: context.req.query,
            headers: context.req.headers,
            args: context.args
        };
        auditLog.result = context.result || {};
        auditLog.error = context.error || {};
        auditLog.status = context.error ? (context.error.statusCode || context.error.status) : (Object.keys(context.result) > 0 ? 200 : 204);

        var user = {};
        auditLog.user = user;

        var loopback = app.loopback;
        var loopbackCtx = loopback.getCurrentContext();

        if (loopbackCtx) {

            var accessToken = loopback.getCurrentContext().get('accessToken');
            if (accessToken) {
                user = accessToken.user().toJSON();
            } else {
                user.name = 'ANONYMOUS';
            }
        } else {
            user.name = 'NO LOOPBACK CONTEXT';
        }

        user.ip = context.req.ip ||
            context.req._remoteAddress ||
            (context.req.connection && context.req.connection.remoteAddress) ||
            undefined;

        process.nextTick(function () {
            auditLogger.info({ 'log': auditLog });
        });
    }

    var models = app.models();
    models.forEach(function (Model) {

        Model.afterRemote('**', function (context, unused, next) {
            log(context);
            next();
        });
        Model.afterRemoteError('**', function (context, next) {
            log(context);
            next();
        });
    });
};
<|endoftext|>


<commit_before>var newBlock = require('./new-block.js');

/**
 * Returns a sanitized three-number array representing RGB color values, with a safe default.
 * @param string
 * @returns {number[]}
 */
function getColorValue(string) {
  if (testRgb.test(string)) {
    return safeRgbToRgb(string);
  }
  if (testHex.test(string)) {
    return safeHexToRgb(string);
  }
  return [0, 0, 255];
}

var testRgb = new RegExp(/rgb/);
var matchRgb = new RegExp(/rgba?\(([^\)]+)\)/);
var testHex = new RegExp(/#\w+/);

/**
 * Extracts the comma-separated numbers from a rgb(a?) string.
 * @param string
 * @returns {string}
 */
function extractRgbSubstring(string) {
  var candidate = string.match(matchRgb);
  if (
    candidate &&
    candidate.length > 1 &&
    candidate[1].length > 0 &&
    typeof candidate[1] === 'string'
  ) {
    return candidate[1];
  }
  return '0,0,255';
}

/**
 * Returns a base10 number from one or two hex digits
 * @param h
 * @returns {number}
 */
function hToD(...h) {
  var hh = '00';
  if (h.length === 1) {
    hh = '' + h[0] + h[0];
  } else if (h.length === 2) {
    hh = '' + h[0] + h[1];
  }
  var d = parseInt(hh, 16);
  return !isNaN(d) ? d : 0;
}

/**
 * Returns a three-member number array from a rgb string
 * @param rgb
 * @returns {number[]}
 */
function safeRgbToRgb(rgb) {
  var value = extractRgbSubstring(rgb)
    .split(',')
    .map(function(a) {
      var b = parseInt(a, 10);
      return !isNaN(b) ? b : 0;
    });
  if (value.length >= 3) {
    return [value[0], value[1], value[2]];
  }
  return [0, 0, 255];
}

/**
 * Returns a three-member number array from a rgb string
 * @param hex
 * @returns {number[]}
 */
function safeHexToRgb(hex) {
  var value = hex.trim().split('#');
  var c = ['00', '00', '00'];
  if (value.length === 1) {
    c = value[0].split('');
  }
  if (value.length === 2) {
    c = value[1].split('');
  }
  switch (c.length) {
    case 3:
      return [hToD(c[0]), hToD(c[1]), hToD(c[2])];
    case 4:
      return [hToD(c[0]), hToD(c[1]), hToD(c[2])];
    case 6:
      return [hToD(c[0], c[1]), hToD(c[2], c[3]), hToD(c[4], c[5])];
    case 8:
      return [hToD(c[0], c[1]), hToD(c[2], c[3]), hToD(c[4], c[5])];
    default:
      return [0, 0, 255];
  }
}

function unitsMatch() {
  var args = Array.prototype.slice.call(arguments, 0);
  var re = /(px|%|em|rem|vh|vw)$/gi;
  var extension = args[0].match(re).toString();
  var matched = true;

  args.forEach(function compareExtension(arg) {
    if (arg.match(re).toString() !== extension) {
      matched = false;
    }
  });
  return matched;
}

module.exports = function lostUtilityDecl(css) {
  css.walkDecls('lost-utility', function lostUtilityDeclFunction(decl) {
    var utilityArray = decl.value.split(' ');
    var utility = utilityArray[0];
    var color;

    if (utility === 'edit') {
      if (utilityArray[1]) {
        color = getColorValue(decl.value);

        newBlock(
          decl,
          ' *:not(input):not(textarea):not(select)',
          ['background-color'],
          ['rgba(' + color[0] + ',' + color[1] + ',' + color[2] + ', 0.1)']
        );
      } else {
        newBlock(
          decl,
          ' *:not(input):not(textarea):not(select)',
          ['background-color'],
          ['rgba(0, 0, 255, 0.1)']
        );
      }
    }

    if (utility === 'clearfix') {
      newBlock(
        decl,
        ':after',
        ['content', 'display', 'clear'],
        ["''", 'table', 'both']
      );

      newBlock(decl, ':before', ['content', 'display'], ["''", 'table']);
    }

    if (utility === 'overlay') {
      var maxWidth = utilityArray[1] || '1024px',
        numCols = utilityArray[2] || 12,
        gutter = utilityArray[3] || '20px',
        totalGutter = parseFloat(gutter) * (numCols - 1),
        colWidth =
          ((parseFloat(maxWidth) - totalGutter) /
            numCols /
            parseFloat(maxWidth)) *
          100,
        gutterPercentage = (parseFloat(gutter) / parseFloat(maxWidth)) * 100,
        position = 0,
        gradient = 'to right, ';

      color = utilityArray[4] || '#e6f6ff';

      if (!unitsMatch(maxWidth, gutter)) {
        throw decl.error(
          'lost-utility: Please use the same units for width and gutter.',
          { plugin: 'lost', word: 'lost-utility' }
        );
      }

      for (var i = 1; i < numCols; i++) {
        // Start of color column
        gradient = gradient + color + ' ' + position + '%, ';

        // Move position to end of color column
        position = position + colWidth;

        // End of color column + Start of gutter column
        gradient =
          gradient +
          color +
          ' ' +
          position +
          '%, transparent ' +
          position +
          '%, ';

        // Move position to end of gutter column
        position = position + gutterPercentage;

        // End of gutter column
        gradient = gradient + 'transparent ' + position + '%, ';
      }

      gradient = gradient + color + ' ' + position + '%, ' + color + ' 100%';

      newBlock(
        decl,
        ':before',
        [
          'background-image',
          'content',
          'display',
          'height',
          'left',
          'margin',
          'max-width',
          'opacity',
          'pointer-events',
          'position',
          'right',
          'width',
          'z-index'
        ],
        [
          'linear-gradient(' + gradient + ')',
          "''",
          'inline-block',
          '100%',
          '0',
          '0 auto',
          maxWidth,
          '0.4',
          'none',
          'fixed',
          '0',
          '100%',
          '1'
        ]
      );
    }

    if (decl.parent.nodes.length === 1) {
      decl.parent.remove();
    } else {
      decl.remove();
    }
  });
};
<commit_msg>Switch statement seems to conflict with eslint & prettier, rewrite with short-circuit ifs<commit_after>var newBlock = require('./new-block.js');

/**
 * Returns a sanitized three-number array representing RGB color values, with a safe default.
 * @param string
 * @returns {number[]}
 */
function getColorValue(string) {
  if (testRgb.test(string)) {
    return safeRgbToRgb(string);
  }
  if (testHex.test(string)) {
    return safeHexToRgb(string);
  }
  return [0, 0, 255];
}

var testRgb = new RegExp(/rgb/);
var matchRgb = new RegExp(/rgba?\(([^\)]+)\)/);
var testHex = new RegExp(/#\w+/);

/**
 * Extracts the comma-separated numbers from a rgb(a?) string.
 * @param string
 * @returns {string}
 */
function extractRgbSubstring(string) {
  var candidate = string.match(matchRgb);
  if (
    candidate &&
    candidate.length > 1 &&
    candidate[1].length > 0 &&
    typeof candidate[1] === 'string'
  ) {
    return candidate[1];
  }
  return '0,0,255';
}

/**
 * Returns a base10 number from one or two hex digits
 * @param h
 * @returns {number}
 */
function hToD(...h) {
  var hh = '00';
  if (h.length === 1) {
    hh = '' + h[0] + h[0];
  } else if (h.length === 2) {
    hh = '' + h[0] + h[1];
  }
  var d = parseInt(hh, 16);
  return !isNaN(d) ? d : 0;
}

/**
 * Returns a three-member number array from a rgb string
 * @param rgb
 * @returns {number[]}
 */
function safeRgbToRgb(rgb) {
  var value = extractRgbSubstring(rgb)
    .split(',')
    .map(function(a) {
      var b = parseInt(a, 10);
      return !isNaN(b) ? b : 0;
    });
  if (value.length >= 3) {
    return [value[0], value[1], value[2]];
  }
  return [0, 0, 255];
}

/**
 * Returns a three-member number array from a rgb string
 * @param hex
 * @returns {number[]}
 */
function safeHexToRgb(hex) {
  var value = hex.trim().split('#');
  var c = ['00', '00', '00'];
  if (value.length === 1) {
    c = value[0].split('');
  }
  if (value.length === 2) {
    c = value[1].split('');
  }
  var l = c.length;
  if (l === 3) return [hToD(c[0]), hToD(c[1]), hToD(c[2])];
  if (l === 4) return [hToD(c[0]), hToD(c[1]), hToD(c[2])];
  if (l === 6) return [hToD(c[0], c[1]), hToD(c[2], c[3]), hToD(c[4], c[5])];
  if (l === 8) [hToD(c[0], c[1]), hToD(c[2], c[3]), hToD(c[4], c[5])];
  return [0, 0, 255];
}

function unitsMatch() {
  var args = Array.prototype.slice.call(arguments, 0);
  var re = /(px|%|em|rem|vh|vw)$/gi;
  var extension = args[0].match(re).toString();
  var matched = true;

  args.forEach(function compareExtension(arg) {
    if (arg.match(re).toString() !== extension) {
      matched = false;
    }
  });
  return matched;
}

module.exports = function lostUtilityDecl(css) {
  css.walkDecls('lost-utility', function lostUtilityDeclFunction(decl) {
    var utilityArray = decl.value.split(' ');
    var utility = utilityArray[0];
    var color;

    if (utility === 'edit') {
      if (utilityArray[1]) {
        color = getColorValue(decl.value);

        newBlock(
          decl,
          ' *:not(input):not(textarea):not(select)',
          ['background-color'],
          ['rgba(' + color[0] + ',' + color[1] + ',' + color[2] + ', 0.1)']
        );
      } else {
        newBlock(
          decl,
          ' *:not(input):not(textarea):not(select)',
          ['background-color'],
          ['rgba(0, 0, 255, 0.1)']
        );
      }
    }

    if (utility === 'clearfix') {
      newBlock(
        decl,
        ':after',
        ['content', 'display', 'clear'],
        ["''", 'table', 'both']
      );

      newBlock(decl, ':before', ['content', 'display'], ["''", 'table']);
    }

    if (utility === 'overlay') {
      var maxWidth = utilityArray[1] || '1024px',
        numCols = utilityArray[2] || 12,
        gutter = utilityArray[3] || '20px',
        totalGutter = parseFloat(gutter) * (numCols - 1),
        colWidth =
          ((parseFloat(maxWidth) - totalGutter) /
            numCols /
            parseFloat(maxWidth)) *
          100,
        gutterPercentage = (parseFloat(gutter) / parseFloat(maxWidth)) * 100,
        position = 0,
        gradient = 'to right, ';

      color = utilityArray[4] || '#e6f6ff';

      if (!unitsMatch(maxWidth, gutter)) {
        throw decl.error(
          'lost-utility: Please use the same units for width and gutter.',
          { plugin: 'lost', word: 'lost-utility' }
        );
      }

      for (var i = 1; i < numCols; i++) {
        // Start of color column
        gradient = gradient + color + ' ' + position + '%, ';

        // Move position to end of color column
        position = position + colWidth;

        // End of color column + Start of gutter column
        gradient =
          gradient +
          color +
          ' ' +
          position +
          '%, transparent ' +
          position +
          '%, ';

        // Move position to end of gutter column
        position = position + gutterPercentage;

        // End of gutter column
        gradient = gradient + 'transparent ' + position + '%, ';
      }

      gradient = gradient + color + ' ' + position + '%, ' + color + ' 100%';

      newBlock(
        decl,
        ':before',
        [
          'background-image',
          'content',
          'display',
          'height',
          'left',
          'margin',
          'max-width',
          'opacity',
          'pointer-events',
          'position',
          'right',
          'width',
          'z-index'
        ],
        [
          'linear-gradient(' + gradient + ')',
          "''",
          'inline-block',
          '100%',
          '0',
          '0 auto',
          maxWidth,
          '0.4',
          'none',
          'fixed',
          '0',
          '100%',
          '1'
        ]
      );
    }

    if (decl.parent.nodes.length === 1) {
      decl.parent.remove();
    } else {
      decl.remove();
    }
  });
};
<|endoftext|>


<commit_before>var Express = require('express');
var express = Express();
var http = require('http');
var server = http.Server(express);
var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var exec = require('child_process').exec;
var fs = require('fs');

var viewAccountName = "elijahparker";
var CLIENT_SERVER_PORT = 80;
var CLIENT_WS_PORT = 8101;

var wss = new WebSocketServer({
    port: CLIENT_WS_PORT
});

var EventEmitter = require("events").EventEmitter;

var app = new EventEmitter();

express.use(Express.static('/home/view/current/frontend/www'));

express.get('/socket/address', function(req, res) {
    var host = req.headers.host;
    var domain = host.split(':')[0];
    res.send({
        address: 'ws://' + domain + ':' + CLIENT_WS_PORT,
        server: 'local'
    });
});

var viewId = null;

wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
        //console.log("client:", client);
        try {
            if (client) client.send(data);
        } catch (err) {
            console.log("broadcast error:", err);
        }
    });
};

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        //console.log('received: %s', message);
        receive_message(message, ws);
    });
});

app.remote = false;
app.authCode = null;
var wsRemote;
var remotePingHandle = null;

function connectRemote() {
    if (app.remote) return;
    wsRemote = new WebSocket('ws://incoming.view.tl/socket/device', {
        headers: {
            'x-view-id': viewId
        }
    });

    wsRemote.on('message', function incoming(message) {
        //if (message.type != "pong") console.log('remote: %s', message);
        if(app.remote) {
            receive_message(message, wsRemote);
        } else {
            try {
                var msg = JSON.parse(message);
                if(msg.connected) {
                    app.remote = true;
                    app.authCode = null;
                    app.emit('auth-complete', app.authCode);
                    console.log("Connected to view.tl");
                    remotePingHandle = setInterval(function() {
                        send_message('ping', null, wsRemote);
                    }, 10000);
                    sendLogs();
                } else if(msg.code) {
                    app.authCode = msg.code;
                    app.emit('auth-required', app.authCode);
                }
            } catch (err) {
                console.log("Error while parsing message:", message, err);
                return;
            }
        }
    });

    wsRemote.once('open', function() {
    });

    wsRemote.once('close', function() {
        if (remotePingHandle) clearInterval(remotePingHandle);
        remotePingHandle = null;
        console.log("Disconnected from view.tl");
        app.remote = false;
        setTimeout(connectRemote);
    });

    wsRemote.once('error', function() {
        if (remotePingHandle) clearInterval(remotePingHandle);
        remotePingHandle = null;
        //console.log("Error connecting to view.tl");
        app.remote = false;
        setTimeout(connectRemote, 15000);
    });
}

// get cpu serial number as unique id for view device
exec('cat /proc/cpuinfo', function(error, stdout, stderr) {
    lines = stdout.split('\n');
    for(var i = 0; i < lines.length; i++) {
        if(lines[i].indexOf('Serial') === 0) {
            var matches = lines[i].match(/: ([0-9a-f]+)/i);
            if(matches.length > 1) {
                viewId = matches[1];
                console.log("VIEW_ID:", viewId);
                connectRemote();
            }
        }
    }
});

function sendLog(logfile, logname, callback) {
    if(app.remote) {
        fs.readFile(logfile, function(err, file) {
            if(!err && file) {
                console.log("sending log file to proxy: ", logfile);
                var obj = {
                    logname: logname,
                    bzip2: file.toString('base64')
                }
                send_message('log', obj, wsRemote);
                callback(null);
            } else {
                console.log("error sending log: ", err);
                callback(null);
            }
        });
    } else {
        callback(true);
    }
}

function sendLogs() {
    if(app.remote) {
        var logs = fs.readdirSync("/home/view/logsForUpload");
        logs = logs.filter(function(log) {
            return log.match(/^log/) ? true : false;
        });

        if(logs && logs.length > 0) {
            var nextLogName = logs.pop();
            var nextLog = "/home/view/logsForUpload/" + nextLogName;
            sendLog(nextLog, function(err) {
                if(!err) {
                    fs.unlink(nextLog, nextLogName, function() {
                        setTimeout(sendLogs, 120 * 1000);
                    });
                }
            });
        }
    }
}

function send_message(type, object, socket) {
    if (!object) object = {};
    if (typeof(type) === "string") {
        object.type = type;
    } else if (typeof(type) === "object" && type.type) {
        object = type;
    }

    var msg_string;
    try {
        msg_string = JSON.stringify(object);
    } catch (err) {
        console.log("Error encoding data to send:", err);
        return;
    }
    try {
        if (socket) {
            socket.send(msg_string);
        } else {
            wss.broadcast(msg_string);
            if (app.remote) wsRemote.send(msg_string);
        }
    } catch (err) {
        console.log("Error sending message:", err);
        return;
    }
}

function receive_message(msg_string, socket) {
    try {
    	var buildReply = function(nMsg, nSocket) {
    		return function(type, object) {
    			if(!object) object = {};
    			object.ack = nMsg.ack;
    			object._cbId = nMsg._cbId;

                send_message(type, object, nSocket);
    		}
    	}

        var msg = JSON.parse(msg_string);
        if (!msg || !msg.type) {
            throw "invalid message: no type set";
        } else if (msg.type == "ping") {
            send_message('pong', {}, socket);
        } else if (msg.type == "pong") {
            // ignoring...
        } else {
        	msg.reply = buildReply(msg, socket);
        	app.emit("message", msg);
        }
    } catch (err) {
        console.log("Error while parsing message:", msg_string, err);
        return;
    }
}

app.send = send_message;
app.sendLogs = sendLogs;

server.listen(CLIENT_SERVER_PORT, function() {
    console.log('listening on *:' + CLIENT_SERVER_PORT);
});

module.exports = app;<commit_msg>log upload fix<commit_after>var Express = require('express');
var express = Express();
var http = require('http');
var server = http.Server(express);
var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var exec = require('child_process').exec;
var fs = require('fs');

var viewAccountName = "elijahparker";
var CLIENT_SERVER_PORT = 80;
var CLIENT_WS_PORT = 8101;

var wss = new WebSocketServer({
    port: CLIENT_WS_PORT
});

var EventEmitter = require("events").EventEmitter;

var app = new EventEmitter();

express.use(Express.static('/home/view/current/frontend/www'));

express.get('/socket/address', function(req, res) {
    var host = req.headers.host;
    var domain = host.split(':')[0];
    res.send({
        address: 'ws://' + domain + ':' + CLIENT_WS_PORT,
        server: 'local'
    });
});

var viewId = null;

wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
        //console.log("client:", client);
        try {
            if (client) client.send(data);
        } catch (err) {
            console.log("broadcast error:", err);
        }
    });
};

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        //console.log('received: %s', message);
        receive_message(message, ws);
    });
});

app.remote = false;
app.authCode = null;
var wsRemote;
var remotePingHandle = null;

function connectRemote() {
    if (app.remote) return;
    wsRemote = new WebSocket('ws://incoming.view.tl/socket/device', {
        headers: {
            'x-view-id': viewId
        }
    });

    wsRemote.on('message', function incoming(message) {
        //if (message.type != "pong") console.log('remote: %s', message);
        if(app.remote) {
            receive_message(message, wsRemote);
        } else {
            try {
                var msg = JSON.parse(message);
                if(msg.connected) {
                    app.remote = true;
                    app.authCode = null;
                    app.emit('auth-complete', app.authCode);
                    console.log("Connected to view.tl");
                    remotePingHandle = setInterval(function() {
                        send_message('ping', null, wsRemote);
                    }, 10000);
                    sendLogs();
                } else if(msg.code) {
                    app.authCode = msg.code;
                    app.emit('auth-required', app.authCode);
                }
            } catch (err) {
                console.log("Error while parsing message:", message, err);
                return;
            }
        }
    });

    wsRemote.once('open', function() {
    });

    wsRemote.once('close', function() {
        if (remotePingHandle) clearInterval(remotePingHandle);
        remotePingHandle = null;
        console.log("Disconnected from view.tl");
        app.remote = false;
        setTimeout(connectRemote);
    });

    wsRemote.once('error', function() {
        if (remotePingHandle) clearInterval(remotePingHandle);
        remotePingHandle = null;
        //console.log("Error connecting to view.tl");
        app.remote = false;
        setTimeout(connectRemote, 15000);
    });
}

// get cpu serial number as unique id for view device
exec('cat /proc/cpuinfo', function(error, stdout, stderr) {
    lines = stdout.split('\n');
    for(var i = 0; i < lines.length; i++) {
        if(lines[i].indexOf('Serial') === 0) {
            var matches = lines[i].match(/: ([0-9a-f]+)/i);
            if(matches.length > 1) {
                viewId = matches[1];
                console.log("VIEW_ID:", viewId);
                connectRemote();
            }
        }
    }
});

function sendLog(logfile, logname, callback) {
    if(app.remote) {
        fs.readFile(logfile, function(err, file) {
            if(!err && file) {
                console.log("sending log file to proxy: ", logfile);
                var obj = {
                    logname: logname,
                    bzip2: file.toString('base64')
                }
                send_message('log', obj, wsRemote);
                callback(null);
            } else {
                console.log("error sending log: ", err);
                callback(null);
            }
        });
    } else {
        callback(true);
    }
}

function sendLogs() {
    if(app.remote) {
        var logs = fs.readdirSync("/home/view/logsForUpload");
        logs = logs.filter(function(log) {
            return log.match(/^log/) ? true : false;
        });

        if(logs && logs.length > 0) {
            var nextLogName = logs.pop();
            var nextLog = "/home/view/logsForUpload/" + nextLogName;
            sendLog(nextLog, nextLogName, function(err) {
                if(!err) {
                    fs.unlink(nextLog, function() {
                        setTimeout(sendLogs, 120 * 1000);
                    });
                }
            });
        }
    }
}

function send_message(type, object, socket) {
    if (!object) object = {};
    if (typeof(type) === "string") {
        object.type = type;
    } else if (typeof(type) === "object" && type.type) {
        object = type;
    }

    var msg_string;
    try {
        msg_string = JSON.stringify(object);
    } catch (err) {
        console.log("Error encoding data to send:", err);
        return;
    }
    try {
        if (socket) {
            socket.send(msg_string);
        } else {
            wss.broadcast(msg_string);
            if (app.remote) wsRemote.send(msg_string);
        }
    } catch (err) {
        console.log("Error sending message:", err);
        return;
    }
}

function receive_message(msg_string, socket) {
    try {
    	var buildReply = function(nMsg, nSocket) {
    		return function(type, object) {
    			if(!object) object = {};
    			object.ack = nMsg.ack;
    			object._cbId = nMsg._cbId;

                send_message(type, object, nSocket);
    		}
    	}

        var msg = JSON.parse(msg_string);
        if (!msg || !msg.type) {
            throw "invalid message: no type set";
        } else if (msg.type == "ping") {
            send_message('pong', {}, socket);
        } else if (msg.type == "pong") {
            // ignoring...
        } else {
        	msg.reply = buildReply(msg, socket);
        	app.emit("message", msg);
        }
    } catch (err) {
        console.log("Error while parsing message:", msg_string, err);
        return;
    }
}

app.send = send_message;
app.sendLogs = sendLogs;

server.listen(CLIENT_SERVER_PORT, function() {
    console.log('listening on *:' + CLIENT_SERVER_PORT);
});

module.exports = app;<|endoftext|>


<commit_before>var marked = require('marked'),
    promisify = require('vow-node').promisify,
    toc = promisify(require('toc-md').insert),
    renderer = require('./renderer'),
    defaultOptions = {
        renderer: renderer.getRenderer(),
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: false,
        smartLists: true,
        smartypants: false
    };

/**
 * Compile *.md files to html with marked module.
 *
 * @param {String} content content of *.md file
 * @returns {String} html string
 */
module.exports = function (content) {
    marked.setOptions(defaultOptions);

    return toc(content)
        .then(function (res) {
            // Bug in 'marked', invalid compile of markdown which is situated between HTML comments
            return marked(res.replace('<!-- TOC END -->', ''));
        });
};
<commit_msg>Fixed marked<commit_after>var marked = require('marked'),
    promisify = require('vow-node').promisify,
    toc = promisify(require('toc-md').insert),
    renderer = require('./renderer'),
    defaultOptions = {
        renderer: renderer.getRenderer(),
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: false,
        smartLists: true,
        smartypants: false
    };

/**
 * Compile *.md files to html with marked module.
 *
 * @param {String} content content of *.md file
 * @returns {String} html string
 */
module.exports = function (content) {
    marked.setOptions(defaultOptions);

    return toc(content)
        .then(function (res) {
            // Bug in 'marked', invalid compile of markdown which is situated between HTML comments
            return marked(res.replace('<!-- TOC -->', '').replace('<!-- TOC END -->', ''));
        });
};
<|endoftext|>


<commit_before>/*!
 * miner.js - inefficient miner for bcoin (because we can)
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
 * https://github.com/bcoin-org/bcoin
 */

'use strict';

var util = require('../utils/util');
var co = require('../utils/co');
var assert = require('assert');
var constants = require('../protocol/constants');
var AsyncObject = require('../utils/async');
var Address = require('../primitives/address');
var MinerBlock = require('./minerblock');
var BlockEntry = MinerBlock.BlockEntry;

/**
 * A bitcoin miner (supports mining witness blocks).
 * @exports Miner
 * @constructor
 * @param {Object} options
 * @param {Base58Address} options.address - Payout address.
 * @param {String?} [options.coinbaseFlags="mined by bcoin"]
 * @property {Boolean} running
 * @property {MinerBlock} attempt
 * @emits Miner#block
 * @emits Miner#status
 */

function Miner(options) {
  if (!(this instanceof Miner))
    return new Miner(options);

  AsyncObject.call(this);

  assert(options, 'Miner requires options.');
  assert(options.chain, 'Miner requires a blockchain.');

  this.chain = options.chain;
  this.mempool = options.mempool;
  this.network = this.chain.network;
  this.logger = options.logger || this.chain.logger;

  this.running = false;
  this.stopping = false;
  this.attempt = null;
  this.since = 0;

  this.version = -1;
  this.addresses = [];
  this.coinbaseFlags = new Buffer('mined by bcoin', 'ascii');

  this.minWeight = 0;
  this.maxWeight = 750000 * constants.WITNESS_SCALE_FACTOR;
  this.maxSigops = constants.block.MAX_SIGOPS_COST;
  this.priorityWeight = 50000 * constants.WITNESS_SCALE_FACTOR;
  this.minPriority = constants.tx.FREE_THRESHOLD;

  this._initOptions(options);
  this._init();
}

util.inherits(Miner, AsyncObject);

/**
 * Initialize the miner options.
 * @private
 */

Miner.prototype._initOptions = function _initOptions(options) {
  var i, flags;

  if (options.version != null) {
    assert(util.isNumber(options.version));
    this.version = options.version;
  }

  if (options.address)
    this.addAddress(options.address);

  if (options.addresses) {
    assert(Array.isArray(options.addresses));
    for (i = 0; i < options.addresses.length; i++)
      this.addAddress(options.addresses[i]);
  }

  if (options.coinbaseFlags) {
    flags = options.coinbaseFlags;
    if (typeof flags === 'string')
      flags = new Buffer(flags, 'utf8');
    assert(Buffer.isBuffer(flags));
    this.coinbaseFlags = flags;
  }

  if (options.minWeight != null) {
    assert(util.isNumber(options.minWeight));
    this.minWeight = options.minWeight;
  }

  if (options.maxWeight != null) {
    assert(util.isNumber(options.maxWeight));
    this.maxWeight = options.maxWeight;
  }

  if (options.maxSigops != null) {
    assert(util.isNumber(options.maxSigops));
    assert(options.maxSigops <= constants.block.MAX_SIGOPS_COST);
    this.maxSigops = options.maxSigops;
  }

  if (options.priorityWeight != null) {
    assert(util.isNumber(options.priorityWeight));
    this.priorityWeight = options.priorityWeight;
  }

  if (options.minPriority != null) {
    assert(util.isNumber(options.minPriority));
    this.minPriority = options.minPriority;
  }
};

/**
 * Initialize the miner.
 * @private
 */

Miner.prototype._init = function _init() {
  var self = this;

  this.chain.on('tip', function(tip) {
    if (!self.attempt)
      return;

    if (self.attempt.block.prevBlock === tip.prevBlock)
      self.attempt.destroy();
  });

  this.on('block', function(block, entry) {
    // Emit the block hex as a failsafe (in case we can't send it)
    self.logger.info('Found block: %d (%s).', entry.height, entry.rhash());
    self.logger.debug('Raw: %s', block.toRaw().toString('hex'));
  });

  this.on('status', function(stat) {
    self.logger.info(
      'Miner: hashrate=%dkhs hashes=%d target=%d height=%d best=%s',
      stat.hashrate / 1000 | 0,
      stat.hashes,
      stat.target,
      stat.height,
      stat.best);
  });
};

/**
 * Open the miner, wait for the chain and mempool to load.
 * @alias Miner#open
 * @returns {Promise}
 */

Miner.prototype._open = co(function* open() {
  yield this.chain.open();

  if (this.mempool)
    yield this.mempool.open();

  this.logger.info('Miner loaded (flags=%s).',
    this.coinbaseFlags.toString('utf8'));
});

/**
 * Close the miner.
 * @alias Miner#close
 * @returns {Promise}
 */

Miner.prototype._close = co(function* close() {
  if (!this.running)
    return;

  if (this.stopping) {
    yield this._onStop();
    return;
  }

  yield this.stop();
});

/**
 * Start mining.
 * @param {Number?} version - Custom block version.
 */

Miner.prototype.start = co(function* start() {
  var self = this;
  var block, entry;

  assert(!this.running, 'Miner is already running.');

  this.running = true;
  this.stopping = false;

  for (;;) {
    this.attempt = null;

    try {
      this.attempt = yield this.createBlock();
    } catch (e) {
      if (this.stopping)
        break;
      this.emit('error', e);
      continue;
    }

    if (this.stopping)
      break;

    this.attempt.on('status', function(status) {
      self.emit('status', status);
    });

    try {
      block = yield this.attempt.mineAsync();
    } catch (e) {
      if (this.stopping)
        break;
      this.emit('error', e);
      continue;
    }

    if (this.stopping)
      break;

    if (!block)
      continue;

    try {
      entry = yield this.chain.add(block);
    } catch (e) {
      if (this.stopping)
        break;
      this.emit('error', e);
      continue;
    }

    if (this.stopping)
      break;

    this.emit('block', block, entry);
  }

  this.emit('done');
});

/**
 * Stop mining.
 */

Miner.prototype.stop = co(function* stop() {
  assert(this.running, 'Miner is not running.');
  assert(!this.stopping, 'Miner is already stopping.');

  this.stopping = true;

  if (this.attempt)
    this.attempt.destroy();

  yield this._onDone();

  this.running = false;
  this.stopping = false;
  this.attempt = null;

  this.emit('stop');
});

/**
 * Wait for `done` event.
 */

Miner.prototype._onDone = function _onDone() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.once('done', resolve);
  });
};

/**
 * Wait for `stop` event.
 */

Miner.prototype._onStop = function _onStop() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.once('stop', resolve);
  });
};

/**
 * Create a block "attempt".
 * @param {ChainEntry} tip
 * @returns {Promise} - Returns {@link MinerBlock}.
 */

Miner.prototype.createBlock = co(function* createBlock(tip, address) {
  var version = this.version;
  var now = this.network.now();
  var ts, locktime, median, target, attempt;

  if (!tip)
    tip = this.chain.tip;

  assert(tip);

  ts = Math.max(now, tip.ts + 1);
  locktime = ts;

  if (version === -1)
    version = yield this.chain.computeBlockVersion(tip);

  // Cheat on testnet.
  // if (this.network.pow.difficultyReset) {
  //   median = yield tip.getMedianTimeAsync();
  //   ts = cheat(tip.ts, median, now, this.network.pow.targetSpacing);
  //   locktime = ts;
  // }

  target = yield this.chain.getTargetAsync(ts, tip);

  if (this.chain.state.hasMTP())
    locktime = yield tip.getMedianTimeAsync();

  if (!address)
    address = this.getAddress();

  attempt = new MinerBlock({
    tip: tip,
    version: version,
    bits: target,
    locktime: locktime,
    flags: this.chain.state.flags,
    address: address,
    coinbaseFlags: this.coinbaseFlags,
    witness: this.chain.state.hasWitness(),
    network: this.network
  });

  this.build(attempt);

  return attempt;
});

/**
 * Mine a single block.
 * @param {ChainEntry} tip
 * @returns {Promise} - Returns [{@link Block}].
 */

Miner.prototype.mineBlock = co(function* mineBlock(tip, address) {
  var attempt = yield this.createBlock(tip, address);
  return yield attempt.mineAsync();
});

/**
 * Notify the miner that a new tx has entered the mempool.
 * @param {MempoolEntry} entry
 */

Miner.prototype.notifyEntry = function notifyEntry() {
  if (!this.running)
    return;

  if (!this.attempt)
    return;

  if (++this.since > 20) {
    this.since = 0;
    this.attempt.destroy();
  }
};

/**
 * Add an address to the address list.
 * @param {Address} address
 */

Miner.prototype.addAddress = function addAddress(address) {
  this.addresses.push(Address(address));
};

/**
 * Get a random address from the address list.
 * @returns {Address}
 */

Miner.prototype.getAddress = function getAddress() {
  assert(this.addresses.length !== 0, 'No address passed in for miner.');
  return this.addresses[Math.random() * this.addresses.length | 0];
};

/**
 * Get mempool entries, sort by dependency order.
 * Prioritize by priority and fee rates.
 * @returns {MempoolEntry[]}
 */

Miner.prototype.build = function build(attempt) {
  var depMap = {};
  var block = attempt.block;
  var queue = new Queue(cmpPriority);
  var priority = true;
  var i, j, entry, item, tx, hash, input;
  var prev, deps, hashes, weight, sigops;

  if (!this.mempool)
    return [];

  hashes = this.mempool.getSnapshot();

  for (i = 0; i < hashes.length; i++) {
    hash = hashes[i];
    entry = this.mempool.getEntry(hash);
    item = BlockEntry.fromEntry(entry, attempt);
    tx = item.tx;

    if (tx.isCoinbase())
      throw new Error('Cannot add coinbase to block.');

    if (!tx.isFinal(attempt.height, attempt.locktime))
      continue;

    for (j = 0; j < tx.inputs.length; j++) {
      input = tx.inputs[j];
      prev = input.prevout.hash;

      if (!this.mempool.hasTX(prev))
        continue;

      item.depCount += 1;

      if (!depMap[prev])
        depMap[prev] = [];

      depMap[prev].push(item);
    }

    if (item.depCount > 0)
      continue;

    queue.push(item);
  }

  while (queue.size() > 0) {
    item = queue.pop();
    tx = item.tx;
    hash = item.hash;
    weight = attempt.weight;
    sigops = attempt.sigops;

    if (!attempt.witness && tx.hasWitness())
      continue;

    weight += tx.getWeight();

    if (weight > this.maxWeight)
      continue;

    sigops += item.sigops;

    // If we had a view we could do:
    // sigops += tx.getSigopsCost(view, attempt.flags);

    if (sigops > this.maxSigops)
      continue;

    if (priority) {
      if (weight > this.priorityWeight || item.priority < this.minPriority) {
        // Todo: Compare descendant rate with
        // cumulative fees and cumulative vsize.
        queue.cmp = cmpRate;
        priority = false;
        queue.push(item);
        continue;
      }
    } else {
      if (item.free && weight >= this.minWeight)
        continue;
    }

    attempt.weight = weight;
    attempt.sigops = sigops;
    attempt.fees += item.fee;
    attempt.items.push(item);

    block.txs.push(tx);

    deps = depMap[hash];

    if (!deps)
      continue;

    for (j = 0; j < deps.length; j++) {
      item = deps[j];
      if (--item.depCount === 0)
        queue.push(item);
    }
  }

  attempt.updateCoinbase();
  attempt.updateMerkle();

  assert(block.getWeight() <= attempt.weight);
};

/**
 * Queue
 * @constructor
 */

function Queue(cmp) {
  this.cmp = cmp;
  this.items = [];
}

Queue.prototype.size = function size() {
  return this.items.length;
};

Queue.prototype.push = function push(item) {
  util.binaryInsert(this.items, item, this.cmp);
};

Queue.prototype.pop = function pop() {
  return this.items.pop();
};

/*
 * Helpers
 */

function cmpPriority(a, b) {
  return a.priority - b.priority;
}

function cmpRate(a, b) {
  return a.rate - b.rate;
}

function cheat(prevTime, medianTime, now, targetSpacing) {
  var resetTime = prevTime + (targetSpacing * 2) + 1;

  // Already easy.
  if (now <= resetTime)
    return medianTime + 1;

  // time-too-new - 30 min
  if (resetTime > now + (1.5 * 60 * 60))
    return medianTime + 1;

  // time-too-old
  if (resetTime <= medianTime)
    return medianTime + 1;

  return resetTime;
}

/*
 * Expose
 */

module.exports = Miner;
<commit_msg>miner: better cheating.<commit_after>/*!
 * miner.js - inefficient miner for bcoin (because we can)
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
 * https://github.com/bcoin-org/bcoin
 */

'use strict';

var util = require('../utils/util');
var co = require('../utils/co');
var assert = require('assert');
var constants = require('../protocol/constants');
var AsyncObject = require('../utils/async');
var Address = require('../primitives/address');
var MinerBlock = require('./minerblock');
var BlockEntry = MinerBlock.BlockEntry;

/**
 * A bitcoin miner (supports mining witness blocks).
 * @exports Miner
 * @constructor
 * @param {Object} options
 * @param {Base58Address} options.address - Payout address.
 * @param {String?} [options.coinbaseFlags="mined by bcoin"]
 * @property {Boolean} running
 * @property {MinerBlock} attempt
 * @emits Miner#block
 * @emits Miner#status
 */

function Miner(options) {
  if (!(this instanceof Miner))
    return new Miner(options);

  AsyncObject.call(this);

  assert(options, 'Miner requires options.');
  assert(options.chain, 'Miner requires a blockchain.');

  this.chain = options.chain;
  this.mempool = options.mempool;
  this.network = this.chain.network;
  this.logger = options.logger || this.chain.logger;

  this.running = false;
  this.stopping = false;
  this.attempt = null;
  this.since = 0;

  this.version = -1;
  this.addresses = [];
  this.coinbaseFlags = new Buffer('mined by bcoin', 'ascii');

  this.minWeight = 0;
  this.maxWeight = 750000 * constants.WITNESS_SCALE_FACTOR;
  this.maxSigops = constants.block.MAX_SIGOPS_COST;
  this.priorityWeight = 50000 * constants.WITNESS_SCALE_FACTOR;
  this.minPriority = constants.tx.FREE_THRESHOLD;

  this._initOptions(options);
  this._init();
}

util.inherits(Miner, AsyncObject);

/**
 * Initialize the miner options.
 * @private
 */

Miner.prototype._initOptions = function _initOptions(options) {
  var i, flags;

  if (options.version != null) {
    assert(util.isNumber(options.version));
    this.version = options.version;
  }

  if (options.address)
    this.addAddress(options.address);

  if (options.addresses) {
    assert(Array.isArray(options.addresses));
    for (i = 0; i < options.addresses.length; i++)
      this.addAddress(options.addresses[i]);
  }

  if (options.coinbaseFlags) {
    flags = options.coinbaseFlags;
    if (typeof flags === 'string')
      flags = new Buffer(flags, 'utf8');
    assert(Buffer.isBuffer(flags));
    this.coinbaseFlags = flags;
  }

  if (options.minWeight != null) {
    assert(util.isNumber(options.minWeight));
    this.minWeight = options.minWeight;
  }

  if (options.maxWeight != null) {
    assert(util.isNumber(options.maxWeight));
    this.maxWeight = options.maxWeight;
  }

  if (options.maxSigops != null) {
    assert(util.isNumber(options.maxSigops));
    assert(options.maxSigops <= constants.block.MAX_SIGOPS_COST);
    this.maxSigops = options.maxSigops;
  }

  if (options.priorityWeight != null) {
    assert(util.isNumber(options.priorityWeight));
    this.priorityWeight = options.priorityWeight;
  }

  if (options.minPriority != null) {
    assert(util.isNumber(options.minPriority));
    this.minPriority = options.minPriority;
  }
};

/**
 * Initialize the miner.
 * @private
 */

Miner.prototype._init = function _init() {
  var self = this;

  this.chain.on('tip', function(tip) {
    if (!self.attempt)
      return;

    if (self.attempt.block.prevBlock === tip.prevBlock)
      self.attempt.destroy();
  });

  this.on('block', function(block, entry) {
    // Emit the block hex as a failsafe (in case we can't send it)
    self.logger.info('Found block: %d (%s).', entry.height, entry.rhash());
    self.logger.debug('Raw: %s', block.toRaw().toString('hex'));
  });

  this.on('status', function(stat) {
    self.logger.info(
      'Miner: hashrate=%dkhs hashes=%d target=%d height=%d best=%s',
      stat.hashrate / 1000 | 0,
      stat.hashes,
      stat.target,
      stat.height,
      stat.best);
  });
};

/**
 * Open the miner, wait for the chain and mempool to load.
 * @alias Miner#open
 * @returns {Promise}
 */

Miner.prototype._open = co(function* open() {
  yield this.chain.open();

  if (this.mempool)
    yield this.mempool.open();

  this.logger.info('Miner loaded (flags=%s).',
    this.coinbaseFlags.toString('utf8'));
});

/**
 * Close the miner.
 * @alias Miner#close
 * @returns {Promise}
 */

Miner.prototype._close = co(function* close() {
  if (!this.running)
    return;

  if (this.stopping) {
    yield this._onStop();
    return;
  }

  yield this.stop();
});

/**
 * Start mining.
 * @param {Number?} version - Custom block version.
 */

Miner.prototype.start = co(function* start() {
  var self = this;
  var block, entry;

  assert(!this.running, 'Miner is already running.');

  this.running = true;
  this.stopping = false;

  for (;;) {
    this.attempt = null;

    try {
      this.attempt = yield this.createBlock();
    } catch (e) {
      if (this.stopping)
        break;
      this.emit('error', e);
      continue;
    }

    if (this.stopping)
      break;

    this.attempt.on('status', function(status) {
      self.emit('status', status);
    });

    try {
      block = yield this.attempt.mineAsync();
    } catch (e) {
      if (this.stopping)
        break;
      this.emit('error', e);
      continue;
    }

    if (this.stopping)
      break;

    if (!block)
      continue;

    try {
      entry = yield this.chain.add(block);
    } catch (e) {
      if (this.stopping)
        break;
      this.emit('error', e);
      continue;
    }

    if (this.stopping)
      break;

    this.emit('block', block, entry);
  }

  this.emit('done');
});

/**
 * Stop mining.
 */

Miner.prototype.stop = co(function* stop() {
  assert(this.running, 'Miner is not running.');
  assert(!this.stopping, 'Miner is already stopping.');

  this.stopping = true;

  if (this.attempt)
    this.attempt.destroy();

  yield this._onDone();

  this.running = false;
  this.stopping = false;
  this.attempt = null;

  this.emit('stop');
});

/**
 * Wait for `done` event.
 */

Miner.prototype._onDone = function _onDone() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.once('done', resolve);
  });
};

/**
 * Wait for `stop` event.
 */

Miner.prototype._onStop = function _onStop() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.once('stop', resolve);
  });
};

/**
 * Create a block "attempt".
 * @param {ChainEntry} tip
 * @returns {Promise} - Returns {@link MinerBlock}.
 */

Miner.prototype.createBlock = co(function* createBlock(tip, address) {
  var version = this.version;
  var now = this.network.now();
  var ts, locktime, median, target, attempt;

  if (!tip)
    tip = this.chain.tip;

  assert(tip);

  ts = Math.max(now, tip.ts + 1);
  locktime = ts;

  if (version === -1)
    version = yield this.chain.computeBlockVersion(tip);

  // Cheat on testnet.
  // if (this.network.pow.difficultyReset) {
  //   median = yield tip.getMedianTimeAsync();
  //   ts = cheat(tip.ts, median, now, this.network.pow.targetSpacing);
  //   locktime = ts;
  // }

  target = yield this.chain.getTargetAsync(ts, tip);

  if (this.chain.state.hasMTP())
    locktime = yield tip.getMedianTimeAsync();

  if (!address)
    address = this.getAddress();

  attempt = new MinerBlock({
    tip: tip,
    version: version,
    bits: target,
    locktime: locktime,
    flags: this.chain.state.flags,
    address: address,
    coinbaseFlags: this.coinbaseFlags,
    witness: this.chain.state.hasWitness(),
    network: this.network
  });

  this.build(attempt);

  return attempt;
});

/**
 * Mine a single block.
 * @param {ChainEntry} tip
 * @returns {Promise} - Returns [{@link Block}].
 */

Miner.prototype.mineBlock = co(function* mineBlock(tip, address) {
  var attempt = yield this.createBlock(tip, address);
  return yield attempt.mineAsync();
});

/**
 * Notify the miner that a new tx has entered the mempool.
 * @param {MempoolEntry} entry
 */

Miner.prototype.notifyEntry = function notifyEntry() {
  if (!this.running)
    return;

  if (!this.attempt)
    return;

  if (++this.since > 20) {
    this.since = 0;
    this.attempt.destroy();
  }
};

/**
 * Add an address to the address list.
 * @param {Address} address
 */

Miner.prototype.addAddress = function addAddress(address) {
  this.addresses.push(Address(address));
};

/**
 * Get a random address from the address list.
 * @returns {Address}
 */

Miner.prototype.getAddress = function getAddress() {
  assert(this.addresses.length !== 0, 'No address passed in for miner.');
  return this.addresses[Math.random() * this.addresses.length | 0];
};

/**
 * Get mempool entries, sort by dependency order.
 * Prioritize by priority and fee rates.
 * @returns {MempoolEntry[]}
 */

Miner.prototype.build = function build(attempt) {
  var depMap = {};
  var block = attempt.block;
  var queue = new Queue(cmpPriority);
  var priority = true;
  var i, j, entry, item, tx, hash, input;
  var prev, deps, hashes, weight, sigops;

  if (!this.mempool)
    return [];

  hashes = this.mempool.getSnapshot();

  for (i = 0; i < hashes.length; i++) {
    hash = hashes[i];
    entry = this.mempool.getEntry(hash);
    item = BlockEntry.fromEntry(entry, attempt);
    tx = item.tx;

    if (tx.isCoinbase())
      throw new Error('Cannot add coinbase to block.');

    if (!tx.isFinal(attempt.height, attempt.locktime))
      continue;

    for (j = 0; j < tx.inputs.length; j++) {
      input = tx.inputs[j];
      prev = input.prevout.hash;

      if (!this.mempool.hasTX(prev))
        continue;

      item.depCount += 1;

      if (!depMap[prev])
        depMap[prev] = [];

      depMap[prev].push(item);
    }

    if (item.depCount > 0)
      continue;

    queue.push(item);
  }

  while (queue.size() > 0) {
    item = queue.pop();
    tx = item.tx;
    hash = item.hash;
    weight = attempt.weight;
    sigops = attempt.sigops;

    if (!attempt.witness && tx.hasWitness())
      continue;

    weight += tx.getWeight();

    if (weight > this.maxWeight)
      continue;

    sigops += item.sigops;

    // If we had a view we could do:
    // sigops += tx.getSigopsCost(view, attempt.flags);

    if (sigops > this.maxSigops)
      continue;

    if (priority) {
      if (weight > this.priorityWeight || item.priority < this.minPriority) {
        // Todo: Compare descendant rate with
        // cumulative fees and cumulative vsize.
        queue.cmp = cmpRate;
        priority = false;
        queue.push(item);
        continue;
      }
    } else {
      if (item.free && weight >= this.minWeight)
        continue;
    }

    attempt.weight = weight;
    attempt.sigops = sigops;
    attempt.fees += item.fee;
    attempt.items.push(item);

    block.txs.push(tx);

    deps = depMap[hash];

    if (!deps)
      continue;

    for (j = 0; j < deps.length; j++) {
      item = deps[j];
      if (--item.depCount === 0)
        queue.push(item);
    }
  }

  attempt.updateCoinbase();
  attempt.updateMerkle();

  assert(block.getWeight() <= attempt.weight);
};

/**
 * Queue
 * @constructor
 */

function Queue(cmp) {
  this.cmp = cmp;
  this.items = [];
}

Queue.prototype.size = function size() {
  return this.items.length;
};

Queue.prototype.push = function push(item) {
  util.binaryInsert(this.items, item, this.cmp);
};

Queue.prototype.pop = function pop() {
  return this.items.pop();
};

/*
 * Helpers
 */

function cmpPriority(a, b) {
  return a.priority - b.priority;
}

function cmpRate(a, b) {
  return a.rate - b.rate;
}

function cheat(prevTime, medianTime, now, targetSpacing) {
  var resetTime = prevTime + (targetSpacing * 3);

  // Already easy.
  if (now >= resetTime)
    return now;

  // time-too-new - 30 min
  if (resetTime > now + (1.5 * 60 * 60))
    return medianTime + 1;

  // time-too-old
  if (resetTime <= medianTime)
    return medianTime + 1;

  return resetTime;
}

/*
 * Expose
 */

module.exports = Miner;
<|endoftext|>


<commit_before>"use strict";

// external modules
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");

// core
var config = require('../config.js');
var logger = require("../logger.js");

var dbconfig = config.db;
dbconfig.logging = config.debug ? logger.info : false;

var sequelize;
if (typeof dbconfig.username === 'undefined' && typeof dbconfig.password === 'undefined') {
    sequelize = new Sequelize(dbconfig.database, dbconfig);
} else {
    sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password, dbconfig);
}

var db = {};

fs
    .readdirSync(__dirname)
    .filter(function (file) {
        return (file.indexOf(".") !== 0) && (file !== "index.js");
    })
    .forEach(function (file) {
        var model = sequelize.import(path.join(__dirname, file));
        db[model.name] = model;
    });

Object.keys(db).forEach(function (modelName) {
    if ("associate" in db[modelName]) {
        db[modelName].associate(db);
    }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<commit_msg>Update sequelize init condition<commit_after>"use strict";

// external modules
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");

// core
var config = require('../config.js');
var logger = require("../logger.js");

var dbconfig = config.db;
dbconfig.logging = config.debug ? logger.info : false;

var sequelize = null;
if (dbconfig.hasOwnProperty('username') || dbconfig.hasOwnProperty('password'))
    sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password, dbconfig);
else
    sequelize = new Sequelize(dbconfig.database, dbconfig);

var db = {};

fs
    .readdirSync(__dirname)
    .filter(function (file) {
        return (file.indexOf(".") !== 0) && (file !== "index.js");
    })
    .forEach(function (file) {
        var model = sequelize.import(path.join(__dirname, file));
        db[model.name] = model;
    });

Object.keys(db).forEach(function (modelName) {
    if ("associate" in db[modelName]) {
        db[modelName].associate(db);
    }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<|endoftext|>


<commit_before>const WebSocket = require('ws');

// Should have musicService which creates server and on success returns result, as promise?
// Then musicService.prototype.listen which has all the events? call this after Main service returns success?
// Finally can call musicService.prototype.nextSong from API request?

function musicService(server, path) {
  this.wss = new WebSocket.Server({ server: server, path: path });

  var Mopidy = require('mopidy');
  this.mopidy = new Mopidy({
    webSocketUrl: "ws://localhost:6680/mopidy/ws/"
  });

  // Log all activity and interaction with Mopidy to console
  // mopidy.on(console.log.bind(console));

  this.mopidy.on("state:online", () => {
    console.log("Music Service is Online");
    this._handleEvents();
  });

  this.wss.on('connection', (ws) => {
    ws.on('message', (message) => {
      console.log('received: %s', message);
    });

    let con = { "connected": "true" };
    ws.send(JSON.stringify(con));

    var trackresultcb = function(response) {
      console.log(response);
      // ws.send(JSON.stringify(response));
    };
//    this.track('current', trackresultcb);
  });
}

musicService.prototype._handleEvents = function () {

  this.mopidy.on("event:playbackStateChanged", (response) => {
    console.log("New State: " + JSON.stringify(response));
    console.log("State is " + response.new_state);

    this.wss.clients.forEach(function each(client) {
      client.send(JSON.stringify(response));
    });
  });

  this.mopidy.on("event:trackPlaybackStarted", (response) => {
    let album = response.tl_track.track.album;
    let track = response.tl_track.track;

    console.log("Album: " + album.name + ", Album Artist(s): " + album.artists[0].name + ", Song: " + track.name);

    this.wss.clients.forEach(function each(client) {
      client.send(JSON.stringify(track));
    });
  });
}

musicService.prototype.playback = function(action, responsecb) {

  console.log("Recieved Mopidy Request for playback change: " + action);

  // Most of these actions are missing a response in the promise from Mopidy
  switch (action) {
    case 'play':
      this.mopidy.playback.play()
        .then( () => responsecb.status(200).json({ "message": "success" }))
        .catch( () => responsecb.status(400).json({ "error": "unknown" }))
        .done();
      break;
    case 'next':
      this.mopidy.playback.next()
        .then( () => responsecb.status(200).json({ "message": "success" }))
        .catch( () => responsecb.status(400).json({ "error": "unknown" }))
        .done();
      break;
    default:
      console.log("Missing playback action");
      responsecb.status(400).json({ "error": "no action specified" });
  }

}

musicService.prototype.playlists = function(responsecb) {

  console.log("Recieved Mopidy Request for playlists");

  this.mopidy.playlists.getPlaylists().then( (playlists) => {
    if (playlists) {
      responsecb.json(playlists);
    } else {
      responsecb.status(400).json({ "error": "no playlists available" });
    }
  })
  .catch( () => res.status(400).json({ "error": "unknown" }))
  .done();
}

musicService.prototype.load = function(playlisturi, responsecb) {
  // We're expecting a playlist URI vs a list of tracks

  console.log("Recieved Mopidy Request to Load playlist URI:: " + playlisturi);

  // Clear the current playlist, this could be made optional
  this.mopidy.tracklist.clear();

  // .add(tracks, position, uri)
  this.mopidy.tracklist.add(null, null, playlisturi)
    .then( () => responsecb.status(200).json({ "message": "success" }))
    .catch( () => responsecb.status(400).json({ "error": "unknown" }))
    .done();
}

musicService.prototype.track = function(type, responsecb) {
  // Accept current, next, prev as type

  console.log("Recieved Mopidy Request for " + type + " track");

  this.mopidy.playback.getCurrentTrack().then( (track) => {
    if (track) {
      responsecb.json(track);
    } else {
      responsecb.status(400).json({ "error": "no track available" });
    }
  })
  .catch( () => res.status(400).json({ "error": "unknown" }))
  .done();
}

module.exports.musicService = musicService;
<commit_msg>Changes for other status<commit_after>const WebSocket = require('ws');

// Should have musicService which creates server and on success returns result, as promise?
// Then musicService.prototype.listen which has all the events? call this after Main service returns success?
// Finally can call musicService.prototype.nextSong from API request?

function musicService(server, path) {
  this.wss = new WebSocket.Server({ server: server, path: path });

  var Mopidy = require('mopidy');
  this.mopidy = new Mopidy({
    webSocketUrl: "ws://localhost:6680/mopidy/ws/"
  });

  // Log all activity and interaction with Mopidy to console
  // mopidy.on(console.log.bind(console));

  this.mopidy.on("state:online", () => {
    console.log("Music Service is Online");
    this._handleEvents();
  });

  this.wss.on('connection', (ws) => {
    ws.on('message', (message) => {
      console.log('received: %s', message);
    });

    let con = { "connected": "true" };
    ws.send(JSON.stringify(con));

    var trackresultcb = function(response) {
      console.log(response);
      // ws.send(JSON.stringify(response));
    };
//    this.track('current', trackresultcb);
  });
}

musicService.prototype._handleEvents = function () {

  this.mopidy.on("event:playbackStateChanged", (response) => {
    console.log("New State: " + JSON.stringify(response));
    console.log("State is " + response.new_state);

    this.wss.clients.forEach(function each(client) {
      client.send(JSON.stringify(response));
    });
  });

  this.mopidy.on("event:trackPlaybackStarted", (response) => {
    let album = response.tl_track.track.album;
    let track = response.tl_track.track;

    console.log("Album: " + album.name + ", Album Artist(s): " + album.artists[0].name + ", Song: " + track.name);

    this.wss.clients.forEach(function each(client) {
      client.send(JSON.stringify(track));
    });
  });
}

musicService.prototype.playback = function(action, responsecb) {

  console.log("Recieved Mopidy Request for playback change: " + action);

  // Most of these actions are missing a response in the promise from Mopidy
  switch (action) {
    case 'play':
      this.mopidy.playback.play()
        .then( () => responsecb.status(200).json({ "message": "success" }))
        .catch( () => responsecb.status(400).json({ "error": "unknown" }))
        .done();
      break;
    case 'next':
      this.mopidy.playback.next()
        .then( () => responsecb.status(200).json({ "message": "success" }))
        .catch( () => responsecb.status(400).json({ "error": "unknown" }))
        .done();
      break;
    case 'stop':
      this.mopidy.playback.stop()
        .then( () => responsecb.status(200).json({ "message": "success" }))
        .catch( () => responsecb.status(400).json({ "error": "unknown" }))
        .done();
      break;
    default:
      console.log("Missing playback action");
      responsecb.status(400).json({ "error": "no action specified" });
  }

}

musicService.prototype.playlists = function(responsecb) {

  console.log("Recieved Mopidy Request for playlists");

  this.mopidy.playlists.getPlaylists().then( (playlists) => {
    if (playlists) {
      responsecb.json(playlists);
    } else {
      responsecb.status(400).json({ "error": "no playlists available" });
    }
  })
  .catch( () => res.status(400).json({ "error": "unknown" }))
  .done();
}

musicService.prototype.load = function(playlisturi, responsecb) {
  // We're expecting a playlist URI vs a list of tracks

  console.log("Recieved Mopidy Request to Load playlist URI:: " + playlisturi);

  // Clear the current playlist, this could be made optional
  this.mopidy.tracklist.clear();

  // .add(tracks, position, uri)
  this.mopidy.tracklist.add(null, null, playlisturi)
    .then( () => responsecb.status(200).json({ "message": "success" }))
    .catch( () => responsecb.status(400).json({ "error": "unknown" }))
    .done();
}

musicService.prototype.track = function(type, responsecb) {
  // Accept current, next, prev as type

  console.log("Recieved Mopidy Request for " + type + " track");

  this.mopidy.playback.getCurrentTrack().then( (track) => {
    if (track) {
      responsecb.json(track);
    } else {
      responsecb.status(400).json({ "error": "no track available" });
    }
  })
  .catch( () => res.status(400).json({ "error": "unknown" }))
  .done();
}

module.exports.musicService = musicService;
<|endoftext|>


<commit_before>var babel = require('../../lib/babel');
var camelcase = require('camelcase');
var del = require('del');
var fs = require('fs');
var gat = require('gulp-auto-task');
var gulp = require('gulp');
var gulpRename = require('gulp-rename');
var gulpSourcemaps = require('gulp-sourcemaps');
var gulpUglify = require('gulp-uglify');
var path = require('path');
var report = require('../lib/report');
var resolve = require('../lib/resolve');
var rollup = require('rollup');
var rollupBabel = require('rollup-plugin-babel');
var rollupCommonjs = require('rollup-plugin-commonjs');
var rollupNpm = require('rollup-plugin-npm');

var opts = gat.opts();
var tmpFile = 'src/global.js';
var package = require(path.join(process.cwd(), 'package.json'));
var packageMain = package['jsnext:main'] || package.main;
var packageName = package.name;
var packageNameVar = camelcase(packageName);
var noConflictAndGlobal = `
  import main from '../${packageMain}';

  const previousGlobal = window.${packageNameVar};
  main.noConflict = function noConflict () {
    window.${packageNameVar} = previousGlobal;
    return this;
  };
  window.${packageNameVar} = main;

  export default main;
`;

function log (e) {
  console.log(e);
}

function noop (done) {
  done();
}

module.exports = gulp.series(
  function cleanBefore () {
    return del(['dist', 'lib', tmpFile]);
  },
  gulp.parallel(
    gulp.series(
      function tmp (done) {
        fs.writeFile(tmpFile, new Buffer(noConflictAndGlobal, 'utf-8').toString(), done);
      },
      function dist (done) {
        rollup.rollup({
          entry: tmpFile,
          plugins: [
            rollupBabel({
              presets: [resolve('babel-preset-es2015-rollup')]
            }),
            rollupCommonjs(),
            rollupNpm()
          ]
        }).catch(log).then(function (bundle) {
          bundle.write({
            dest: 'dist/index.js',
            format: 'umd',
            globals: opts.globals,
            moduleName: packageName,
            sourceMap: true,
            useStrict: false
          }).catch(log).then(function () {
            done();
          });
        });
      },
      opts.max ? noop : function uglify () {
        return gulp.src('dist/index.js')
          .pipe(gulpRename({ basename: 'index.min' }))
          .pipe(gulpSourcemaps.init())
          .pipe(report(gulpUglify()))
          .pipe(gulpSourcemaps.write('.'))
          .pipe(gulp.dest('dist'));
      },
      function cleanTmp () {
        return del([tmpFile]);
      }
    ),
    function lib () {
      return gulp.src(['src/**/*.js'])
        .pipe(babel())
        .pipe(gulp.dest('lib'));
    }
  )
);
<commit_msg>Fix path.<commit_after>var babel = require('../lib/babel');
var camelcase = require('camelcase');
var del = require('del');
var fs = require('fs');
var gat = require('gulp-auto-task');
var gulp = require('gulp');
var gulpRename = require('gulp-rename');
var gulpSourcemaps = require('gulp-sourcemaps');
var gulpUglify = require('gulp-uglify');
var path = require('path');
var report = require('../lib/report');
var resolve = require('../lib/resolve');
var rollup = require('rollup');
var rollupBabel = require('rollup-plugin-babel');
var rollupCommonjs = require('rollup-plugin-commonjs');
var rollupNpm = require('rollup-plugin-npm');

var opts = gat.opts();
var tmpFile = 'src/global.js';
var package = require(path.join(process.cwd(), 'package.json'));
var packageMain = package['jsnext:main'] || package.main;
var packageName = package.name;
var packageNameVar = camelcase(packageName);
var noConflictAndGlobal = `
  import main from '../${packageMain}';

  const previousGlobal = window.${packageNameVar};
  main.noConflict = function noConflict () {
    window.${packageNameVar} = previousGlobal;
    return this;
  };
  window.${packageNameVar} = main;

  export default main;
`;

function log (e) {
  console.log(e);
}

function noop (done) {
  done();
}

module.exports = gulp.series(
  function cleanBefore () {
    return del(['dist', 'lib', tmpFile]);
  },
  gulp.parallel(
    gulp.series(
      function tmp (done) {
        fs.writeFile(tmpFile, new Buffer(noConflictAndGlobal, 'utf-8').toString(), done);
      },
      function dist (done) {
        rollup.rollup({
          entry: tmpFile,
          plugins: [
            rollupBabel({
              presets: [resolve('babel-preset-es2015-rollup')]
            }),
            rollupCommonjs(),
            rollupNpm()
          ]
        }).catch(log).then(function (bundle) {
          bundle.write({
            dest: 'dist/index.js',
            format: 'umd',
            globals: opts.globals,
            moduleName: packageName,
            sourceMap: true,
            useStrict: false
          }).catch(log).then(function () {
            done();
          });
        });
      },
      opts.max ? noop : function uglify () {
        return gulp.src('dist/index.js')
          .pipe(gulpRename({ basename: 'index.min' }))
          .pipe(gulpSourcemaps.init())
          .pipe(report(gulpUglify()))
          .pipe(gulpSourcemaps.write('.'))
          .pipe(gulp.dest('dist'));
      },
      function cleanTmp () {
        return del([tmpFile]);
      }
    ),
    function lib () {
      return gulp.src(['src/**/*.js'])
        .pipe(babel())
        .pipe(gulp.dest('lib'));
    }
  )
);
<|endoftext|>


<commit_before>
/**
 * @fileoverview This does 3 tasks.  It firstly detects sets up 2 interception
 * points intended for goog.js (or anyone else) to be notified of scripts
 * loaded or to veto the loading of a certain script.  Then it checks if we
 * are trying to run a closure jsunit test.  If we are then it kills the
 * current process and starts a new instance of nctest <filename>.
 *
 * If this is NOT a test then we minimaly initialise the closure framework.
 * This means that we just load the base.js file as specified in the
 * closureBasePath
 *
 * @author guido@tapia.com.au (Guido Tapia)
 * @suppress {checkTypes}
 */

if (typeof(goog) !== 'undefined') {
  goog.provide('nclosure.base');

  goog.require('nclosure.opts');
  goog.require('nclosure.settingsLoader');
} else {
  global['nclosure'] = global['nclosure'] || {};
}

/**
 * @constructor
 */
nclosure.base = function() {
  /**
   * The settings loaded in the current context.
   * @type {nclosure.opts}
   */
  this.globalClosureSettings;

  /**
   * The path to closure library's goog directory where deps.js and base.js
   * reside
   * @type {string}
   */
  this.closureBasePath;

  /**
   * Stores a reference to the name of all the scripts loaded so we don't load
   * things twice.
   *
   * @private
   * @type {Object.<boolean>}
   */
  this.scriptsWritten_ = {};

  /**
   * @private
   * @type {nclosure.settingsLoader}
   */
  this.settingsLoader_ = require('./settingsloader').settingsLoader;

  /*
   * This snippet is the main 'brains' of this entire module.
   *
   * If the currently executing file (being interpreted by Node.js) is a test
   * file, we stop current execution and run the file using nctest.
   */
  if (this.isRunningTestingFile_()) {
    this.runCurrentFileInGoogTest_();
    this.killCurrentThread_();
  } else {
    this.loadBaseScript_();
    this.loadGoogDeps_();
    this.loadAllDependencies(this.globalClosureSettings);
    this.interceptGoogRequires_();
  }
};

/**
  * If this method returns false then the loadScript funciton above will abort
  * the loading of a specified script. Intended to be shadowed by goog.js
  * @param {string} dir The directory where the file resides.
  * @param {string} file The file to load.
  * @return {boolean} Wether to continue loading the script.
  */
nclosure.base.prototype.closureScriptLoading = function(dir, file) {
  return true;
};

/**
  * Notification after a script is loaded. Intended to be shadowed by goog.js
  * @param {string} dir The directory where the file resides.
  * @param {string} file The file to load.
  */
nclosure.base.prototype.closureScriptLoaded = function(dir, file) { };

/**
  * @param {nclosure.opts} opts The settings object passed in to goog()
  *    call which may contain some dependencies.
  */
nclosure.base.prototype.loadAllDependencies = function(opts) {
  this.loadAdditionalDepsInSettingsObject_(opts);
  this.loadCurrentScriptDeps_();
};

/**
 * @private
 * This function allows other classes to use goog.require and pass in Node
 * modules that will be pumped into the global scope of the executing module.
 */
nclosure.base.prototype.interceptGoogRequires_ = function() {
  var nodeRequire = require;
  var googRequire = goog.require;
  var that = this;
  goog.require = function intercept(namespace) {
    // If tests are requiring 'nclosure' then lets load the test
    // additionalDeps if any specified.  Otherwise ignore the call
    // to require('nclosure') as we are already initialised
    if (namespace === 'node.process') { return { goog: that }; }
    // Ignore these 'herlper' classes which are not infact proper closure
    // classes as they exists before closure (base.js) has been loaded.
    // This means they must be called manually using node's require().
    // If anyone is the using goog.require() for these types its only
    // to get a bit of compiler support
    else if (namespace.indexOf('nclosure_') === 0) { return; }
    // Assume no namespace == node.js core libs
    else if (namespace.indexOf('.') < 0) {
      global[namespace] = nodeRequire(namespace);
    } else {
      googRequire(namespace);
    }
  };
};

/**
  * Determines wether the currently running file, i.e. The file that is being
  * executed by the node.js interpreter is a test file or not.
  *
  * TODO [GT]: Is there a better way to determine if this is a test file, this
  * regex seems a little fragile?
  *
  * @return {boolean} Wether the currently running file is a testing file
  *     or not.
  * @private
  */
nclosure.base.prototype.isRunningTestingFile_ = function() {
  var contents = require('fs').
      readFileSync(process.argv[1]).toString();
  return contents.toString().search(
      /\s*goog\s*\.\s*require\(\s*['"]goog\.testing\.jsunit['"]\)/g) >= 0;
};

/**
  * If the current file being executed is a test we actually stop processing and
  * start a new child process that runs this file using nctest
  * @private
  */
nclosure.base.prototype.runCurrentFileInGoogTest_ = function() {
  var command = 'nctest';
  var args = process.argv.splice(1);
  var test = require('child_process').spawn(command, args);
  var printMsg = function(data) {
    data = data.toString();
    if (data.charAt(data.length - 1) === '\n') {
      data = data.substring(0, data.length - 1);
    }
    console.error(data);
  };
  test.stdout.on('data', printMsg);
  test.stderr.on('data', printMsg);
  test.on('uncaughtException', function(err) {
    console.error(err.stack);
  });
};

/**
  * Kills the current thread (stops the Node session)
  * @private
  */
nclosure.base.prototype.killCurrentThread_ = function() {
  process.once('uncaughtException', function(ex) {});
  throw new Error();
};

/**
  * Loads the base script
  * @private
  */
nclosure.base.prototype.loadBaseScript_ = function() {
  this.globalClosureSettings = this.settingsLoader_.readSettingsObject();
  this.closureBasePath = this.resolveClosureBasePath_();
  this.loadBaseScriptImpl_();
};

/**
  * We can now load the Closure dependency tree.
  * @private
  */
nclosure.base.prototype.loadGoogDeps_ = function() {
  this.loadDependenciesFile(this.closureBasePath, 'deps.js');
};

/**
  * Resolves the path to the goog directory in the closure library.  This
  * directory holds the deps.js and base.js file.
  * @return {string} The goog directory in the closure library.  This
  *    directory holds the deps.js and base.js file.
  * @private
  */
nclosure.base.prototype.resolveClosureBasePath_ = function() {
  return require('path').resolve(
      this.globalClosureSettings.closureBasePath, 'closure/goog');
};

/**
  * Loads the closure's base.js file which gets the running context into a
  * minimally initiated closure state.  We also update the following references:
  *
  * goog.global points to the 'window' object in a browser environment. We
  * replace that with our own global context.  We also set window and top which
  * are used by various different portions of the closure library and testing
  * code.
  *
  * Closure loads files by writing out <script> tags. This is fine in a browser
  * but obviously we need to replace this behaviour to make things work on Node.
  * @private
  */
nclosure.base.prototype.loadBaseScriptImpl_ = function() {
  this.loadScript(this.closureBasePath, 'base.js');
  goog.global = goog.window = global.window = global.top = global;
  var that = this;

  global.goog.writeScriptTag_ = function(filename) {
    that.loadScript(that.closureBasePath, filename);
    return false;
  };
};

/**
  * Loads a script into the current global context.
  *
  * TODO: This is how we will load and execute JavaScript files. The
  * synchronous implementation seems to be appropriate for loading modules,
  * but one could think about asynchronous loading anyway (especially for
  * later calls to goog.require(...)).
  *
  * TODO: We need to ensure that no script is loaded
  * twice because this would lead to an exception when
  * a Closure namespace is declared more than once.
  * Not sure how Closure handles this, or whether the
  * problem is only circumvented by their compiler.
  *
  * @param {string} dir The directory where the file resides.
  * @param {string} file The file to load.
  */
nclosure.base.prototype.loadScript = function(dir, file) {
  // Give goog.js a chance to stop the loading of certain scripts
  if (!this.closureScriptLoading(dir, file)) { return; }

  // TODO: Do we need absolute file support?
  var path = (file.indexOf('/') === 0 ? file :
      require('path').resolve(dir, file));

  if (this.scriptsWritten_[path]) { return; }
  this.scriptsWritten_[path] = true;

  var contents = require('fs').readFileSync(path).toString();
  contents = this.settingsLoader_.removeShebang(contents);
  try {
    process.binding('evals').Script.
        runInThisContext.call(global, contents, file);
  } catch (ex) {
    console.error('Could not goog.require("' + path + '")\n' + ex.stack);
    process.exit(1);
  }
  this.closureScriptLoaded(dir, file);
};

/**
  * This can be called by any 'nclosure' initiaised system to load
  * additional deps files dynamically.  This is safe to be called even if
  * you are not sure wether the file exists as it will be ignored if the file
  * does not exist.  It is also safe to be called multiple times for the
  * same file as multiple requests are ignored.
  *
  * @param {string} dir The directory with the specified file.
  * @param {string} file The dependencies file to load.
  */
nclosure.base.prototype.loadDependenciesFile = function(dir, file) {
  var path = this.settingsLoader_.getPath(dir, file);
  if (!require('path').existsSync(path)) { return; }
  this.loadScript(dir, file);
};

/**
  * If the currently executed script has deps.js in its directory also load it
  * as it will contain some additional dependencies which may not be in the
  * additionalDeps declaration of the settings file.
  *
  * @private
  */
nclosure.base.prototype.loadCurrentScriptDeps_ = function() {
  var file = process.argv[process.argv.length - 1];
  if (require('path').existsSync(file)) {
    var depsPath = !file ? null : this.settingsLoader_.getFileDirectory(file);
    if (depsPath) this.loadDependenciesFile(depsPath, 'deps.js');
  }
  this.loadDependenciesFile(__dirname, 'deps.js');
  this.loadDependenciesFile(__dirname, '../bin/deps.js');

};

/**
  * @private
  * @param {nclosure.opts} opts The options object which we will parse for
  *    additional deps.
  */
nclosure.base.prototype.loadAdditionalDepsInSettingsObject_ =
    function(opts) {
  if (!opts || !opts.additionalDeps) { return; }

  for (var i = 0, len = opts.additionalDeps.length; i < len; i++) {
    var fileName = opts.additionalDeps[i];
    var idx = fileName.lastIndexOf('/');
    this.loadScript(fileName.substring(0, idx + 1),
        fileName.substring(idx + 1));
  }
};

/**
 * @type {nclosure.base}
 */
exports.nclosurebase = new nclosure.base();
<commit_msg>Fixes the entire library.<commit_after>/**
 * @fileoverview This does 3 tasks.  It firstly detects sets up 2 interception
 * points intended for goog.js (or anyone else) to be notified of scripts
 * loaded or to veto the loading of a certain script.  Then it checks if we
 * are trying to run a closure jsunit test.  If we are then it kills the
 * current process and starts a new instance of nctest <filename>.
 *
 * If this is NOT a test then we minimaly initialise the closure framework.
 * This means that we just load the base.js file as specified in the
 * closureBasePath
 *
 * @author guido@tapia.com.au (Guido Tapia)
 * @suppress {checkTypes}
 */

if (typeof(goog) !== 'undefined') {
  goog.provide('nclosure.base');

  goog.require('nclosure.opts');
  goog.require('nclosure.settingsLoader');
} else {
  global['nclosure'] = global['nclosure'] || {};
}

/**
 * @constructor
 */
nclosure.base = function() {
  /**
   * The settings loaded in the current context.
   * @type {nclosure.opts}
   */
  this.globalClosureSettings;

  /**
   * The path to closure library's goog directory where deps.js and base.js
   * reside
   * @type {string}
   */
  this.closureBasePath;

  /**
   * Stores a reference to the name of all the scripts loaded so we don't load
   * things twice.
   *
   * @private
   * @type {Object.<boolean>}
   */
  this.scriptsWritten_ = {};

  /**
   * @private
   * @type {nclosure.settingsLoader}
   */
  this.settingsLoader_ = require('./settingsloader').settingsLoader;

  /*
   * This snippet is the main 'brains' of this entire module.
   *
   * If the currently executing file (being interpreted by Node.js) is a test
   * file, we stop current execution and run the file using nctest.
   */
  if (this.isRunningTestingFile_()) {
    this.runCurrentFileInGoogTest_();
    this.killCurrentThread_();
  } else {
    this.loadBaseScript_();
    this.loadGoogDeps_();
    this.loadAllDependencies(this.globalClosureSettings);
    this.interceptGoogRequires_();
  }
};

/**
  * If this method returns false then the loadScript funciton above will abort
  * the loading of a specified script. Intended to be shadowed by goog.js
  * @param {string} dir The directory where the file resides.
  * @param {string} file The file to load.
  * @return {boolean} Wether to continue loading the script.
  */
nclosure.base.prototype.closureScriptLoading = function(dir, file) {
  return true;
};

/**
  * Notification after a script is loaded. Intended to be shadowed by goog.js
  * @param {string} dir The directory where the file resides.
  * @param {string} file The file to load.
  */
nclosure.base.prototype.closureScriptLoaded = function(dir, file) { };

/**
  * @param {nclosure.opts} opts The settings object passed in to goog()
  *    call which may contain some dependencies.
  */
nclosure.base.prototype.loadAllDependencies = function(opts) {
  this.loadAdditionalDepsInSettingsObject_(opts);
  this.loadCurrentScriptDeps_();
};

/**
 * @private
 * This function allows other classes to use goog.require and pass in Node
 * modules that will be pumped into the global scope of the executing module.
 */
nclosure.base.prototype.interceptGoogRequires_ = function() {
  var nodeRequire = require;
  var googRequire = goog.require;
  var that = this;
  goog.require = function intercept(namespace) {
    // If tests are requiring 'nclosure' then lets load the test
    // additionalDeps if any specified.  Otherwise ignore the call
    // to require('nclosure') as we are already initialised
    if (namespace === 'node.process') { return { goog: that }; }
    // Ignore these 'herlper' classes which are not infact proper closure
    // classes as they exists before closure (base.js) has been loaded.
    // This means they must be called manually using node's require().
    // If anyone is the using goog.require() for these types its only
    // to get a bit of compiler support
    else if (namespace.indexOf('nclosure_') === 0) { return; }
    // Assume no namespace == node.js core libs
    else if (namespace.indexOf('.') < 0) {
      global[namespace] = nodeRequire(namespace);
    } else {
      googRequire(namespace);
    }
  };
};

/**
  * Determines wether the currently running file, i.e. The file that is being
  * executed by the node.js interpreter is a test file or not.
  *
  * TODO [GT]: Is there a better way to determine if this is a test file, this
  * regex seems a little fragile?
  *
  * @return {boolean} Wether the currently running file is a testing file
  *     or not.
  * @private
  */
nclosure.base.prototype.isRunningTestingFile_ = function() {
  var contents = require('fs').
      readFileSync(process.argv[1]).toString();
  return contents.toString().search(
      /\s*goog\s*\.\s*require\(\s*['"]goog\.testing\.jsunit['"]\)/g) >= 0;
};

/**
  * If the current file being executed is a test we actually stop processing and
  * start a new child process that runs this file using nctest
  * @private
  */
nclosure.base.prototype.runCurrentFileInGoogTest_ = function() {
  var command = 'nctest';
  var args = process.argv.splice(1);
  var test = require('child_process').spawn(command, args);
  var printMsg = function(data) {
    data = data.toString();
    if (data.charAt(data.length - 1) === '\n') {
      data = data.substring(0, data.length - 1);
    }
    console.error(data);
  };
  test.stdout.on('data', printMsg);
  test.stderr.on('data', printMsg);
  test.on('uncaughtException', function(err) {
    console.error(err.stack);
  });
};

/**
  * Kills the current thread (stops the Node session)
  * @private
  */
nclosure.base.prototype.killCurrentThread_ = function() {
  process.once('uncaughtException', function(ex) {});
  throw new Error();
};

/**
  * Loads the base script
  * @private
  */
nclosure.base.prototype.loadBaseScript_ = function() {
  this.globalClosureSettings = this.settingsLoader_.readSettingsObject();
  this.closureBasePath = this.resolveClosureBasePath_();
  this.loadBaseScriptImpl_();
};

/**
  * We can now load the Closure dependency tree.
  * @private
  */
nclosure.base.prototype.loadGoogDeps_ = function() {
  this.loadDependenciesFile(this.closureBasePath, 'deps.js');
};

/**
  * Resolves the path to the goog directory in the closure library.  This
  * directory holds the deps.js and base.js file.
  * @return {string} The goog directory in the closure library.  This
  *    directory holds the deps.js and base.js file.
  * @private
  */
nclosure.base.prototype.resolveClosureBasePath_ = function() {
  return require('path').resolve(
      this.globalClosureSettings.closureBasePath, 'closure/goog');
};

/**
  * Loads the closure's base.js file which gets the running context into a
  * minimally initiated closure state.  We also update the following references:
  *
  * goog.global points to the 'window' object in a browser environment. We
  * replace that with our own global context.  We also set window and top which
  * are used by various different portions of the closure library and testing
  * code.
  *
  * Closure loads files by writing out <script> tags. This is fine in a browser
  * but obviously we need to replace this behaviour to make things work on Node.
  * @private
  */
nclosure.base.prototype.loadBaseScriptImpl_ = function() {
  this.loadScript(this.closureBasePath, 'base.js');
  goog.global = goog.window = global.window = global.top = global;
  var that = this;

  global.goog.writeScriptTag_ = function(filename) {
    that.loadScript(that.closureBasePath, filename);
    return false;
  };
};

/**
  * Loads a script into the current global context.
  *
  * TODO: This is how we will load and execute JavaScript files. The
  * synchronous implementation seems to be appropriate for loading modules,
  * but one could think about asynchronous loading anyway (especially for
  * later calls to goog.require(...)).
  *
  * TODO: We need to ensure that no script is loaded
  * twice because this would lead to an exception when
  * a Closure namespace is declared more than once.
  * Not sure how Closure handles this, or whether the
  * problem is only circumvented by their compiler.
  *
  * @param {string} dir The directory where the file resides.
  * @param {string} file The file to load.
  */
nclosure.base.prototype.loadScript = function(dir, file) {
  // Give goog.js a chance to stop the loading of certain scripts
  if (!this.closureScriptLoading(dir, file)) { return; }

  // TODO: Do we need absolute file support?
  var path = (file.indexOf('/') === 0 ? file :
      require('path').resolve(dir, file));

  if (this.scriptsWritten_[path]) { return; }
  this.scriptsWritten_[path] = true;

  var contents = require('fs').readFileSync(path).toString();
  contents = this.settingsLoader_.removeShebang(contents);
  try {
    process.binding('evals').NodeScript.
        runInThisContext.call(global, contents, file);
  } catch (ex) {
    console.error('Could not goog.require("' + path + '")\n' + ex.stack);
    process.exit(1);
  }
  this.closureScriptLoaded(dir, file);
};

/**
  * This can be called by any 'nclosure' initiaised system to load
  * additional deps files dynamically.  This is safe to be called even if
  * you are not sure wether the file exists as it will be ignored if the file
  * does not exist.  It is also safe to be called multiple times for the
  * same file as multiple requests are ignored.
  *
  * @param {string} dir The directory with the specified file.
  * @param {string} file The dependencies file to load.
  */
nclosure.base.prototype.loadDependenciesFile = function(dir, file) {
  var path = this.settingsLoader_.getPath(dir, file);
  if (!require('path').existsSync(path)) { return; }
  this.loadScript(dir, file);
};

/**
  * If the currently executed script has deps.js in its directory also load it
  * as it will contain some additional dependencies which may not be in the
  * additionalDeps declaration of the settings file.
  *
  * @private
  */
nclosure.base.prototype.loadCurrentScriptDeps_ = function() {
  var file = process.argv[process.argv.length - 1];
  if (require('path').existsSync(file)) {
    var depsPath = !file ? null : this.settingsLoader_.getFileDirectory(file);
    if (depsPath) this.loadDependenciesFile(depsPath, 'deps.js');
  }
  this.loadDependenciesFile(__dirname, 'deps.js');
  this.loadDependenciesFile(__dirname, '../bin/deps.js');

};

/**
  * @private
  * @param {nclosure.opts} opts The options object which we will parse for
  *    additional deps.
  */
nclosure.base.prototype.loadAdditionalDepsInSettingsObject_ =
    function(opts) {
  if (!opts || !opts.additionalDeps) { return; }

  for (var i = 0, len = opts.additionalDeps.length; i < len; i++) {
    var fileName = opts.additionalDeps[i];
    var idx = fileName.lastIndexOf('/');
    this.loadScript(fileName.substring(0, idx + 1),
        fileName.substring(idx + 1));
  }
};

/**
 * @type {nclosure.base}
 */
exports.nclosurebase = new nclosure.base();
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  var exec = require('child_process').exec;
  var changelog = require('./lib/changelog');

  /**
   * Bump version
   *  - increase version
   *  - generate changelog
   *  - create tag
   *  - push to github
   *
   *
   * grunt bump
   * grunt bump:patch
   * grunt bump:minor
   * grunt bump:major
   */
  var DESC = 'Increment version, generate changelog, create tag and push to github.';
  grunt.registerTask('bump', DESC, function(type) {

    var finish = this.async();
    var queue = [];
    var next = function() {
      var cmd = queue.shift();

      if (!cmd) {
        return finish();
      }

      exec(cmd[0], function(err, output) {
        if (err) {
          return grunt.fail.fatal(err.message.replace(/\n$/, '.'));
        }
        if (cmd[1]) {
          grunt.log.ok(cmd[1]);
        }
        if (cmd[2]) {
          cmd[2](output);
        }
        next();
      });
    };

    var run = function(cmd, msg, fn) {
      queue.push([cmd, msg, fn]);
    };

    // increment the version
    var pkg = grunt.file.readJSON(grunt.config('pkgFile'));
    var previousVersion = pkg.version;
    var newVersion = pkg.version = bumpVersion(previousVersion, type);

    // write updated package.json
    grunt.file.write(grunt.config('pkgFile'), JSON.stringify(pkg, null, '  ') + '\n');
    grunt.log.ok('Version bumped to ' + newVersion);

    // generate changelog
    changelog.generate('v' + newVersion).then(function(data) {
      grunt.file.write('CHANGELOG.md', data + grunt.file.read('CHANGELOG.md'));
      next();
    });

    run('sublime -w CHANGELOG.md', 'CHANGELOG.md updated');
    run('git commit package.json CHANGELOG.md -m "chore: release v' + newVersion + '"',
        'Changes committed');
    run('git tag -a v' + newVersion + ' -m "Version ' + newVersion + '"', 'New tag "v' +
        newVersion + '" created');
    run('git push upstream master --tags', 'Pushed to github');
  });

  var bumpVersion = function(version, versionType) {
    var type = {
      patch: 2,
      minor: 1,
      major: 0
    };

    var parts = version.split('.');
    var idx = type[versionType || 'patch'];

    parts[idx] = parseInt(parts[idx], 10) + 1;
    while(++idx < parts.length) {
      parts[idx] = 0;
    }
    return parts.join('.');
  };
};
<commit_msg>chore(release): push to correct branch (master/stable)<commit_after>module.exports = function(grunt) {

  var exec = require('child_process').exec;
  var changelog = require('./lib/changelog');

  /**
   * Bump version
   *  - increase version
   *  - generate changelog
   *  - create tag
   *  - push to github
   *
   *
   * grunt bump
   * grunt bump:patch
   * grunt bump:minor
   * grunt bump:major
   */
  var DESC = 'Increment version, generate changelog, create tag and push to github.';
  grunt.registerTask('bump', DESC, function(type) {

    var finish = this.async();
    var queue = [];
    var next = function() {
      var cmd = queue.shift();

      if (!cmd) {
        return finish();
      }

      exec(cmd[0], function(err, output) {
        if (err) {
          return grunt.fail.fatal(err.message.replace(/\n$/, '.'));
        }
        if (cmd[1]) {
          grunt.log.ok(cmd[1]);
        }
        if (cmd[2]) {
          cmd[2](output);
        }
        next();
      });
    };

    var run = function(cmd, msg, fn) {
      queue.push([cmd, msg, fn]);
    };

    // increment the version
    var pkg = grunt.file.readJSON(grunt.config('pkgFile'));
    var previousVersion = pkg.version;
    var minor = parseInt(previousVersion.split('.')[1], 10);
    var branch = (minor % 2) ? 'master' : 'stable';
    var newVersion = pkg.version = bumpVersion(previousVersion, type);

    // write updated package.json
    grunt.file.write(grunt.config('pkgFile'), JSON.stringify(pkg, null, '  ') + '\n');
    grunt.log.ok('Version bumped to ' + newVersion);

    // generate changelog
    changelog.generate('v' + newVersion).then(function(data) {
      grunt.file.write('CHANGELOG.md', data + grunt.file.read('CHANGELOG.md'));
      next();
    });

    run('sublime -w CHANGELOG.md', 'CHANGELOG.md updated');
    run('git commit package.json CHANGELOG.md -m "chore: release v' + newVersion + '"',
        'Changes committed');
    run('git tag -a v' + newVersion + ' -m "Version ' + newVersion + '"', 'New tag "v' +
        newVersion + '" created');
    run('git push upstream ' + branch + ' --tags', 'Pushed to github');
  });

  var bumpVersion = function(version, versionType) {
    var type = {
      patch: 2,
      minor: 1,
      major: 0
    };

    var parts = version.split('.');
    var idx = type[versionType || 'patch'];

    parts[idx] = parseInt(parts[idx], 10) + 1;
    while(++idx < parts.length) {
      parts[idx] = 0;
    }
    return parts.join('.');
  };
};
<|endoftext|>


<commit_before>var Promise = require('es6-promise').Promise;
var log = require('./utils/log');
var helper = require('./utils/config-helper');
var config, paths, pkg;

function run(type){
    config = helper.getConfig();
    if (type == 'current') return Promise.resolve(config.pkg.version);
    log.info("\nBumping version");
    var build = require('./build');
    var Bump = require('./utils/bump');
    var newVersion;
    return new Bump(['./package.json','./README.md', config.paths.source + '/**/version.js'], {type: type }).run()
        .then(function(version){
            log.info(" * Now on " + version);
            log.info("Rebuilding HTML");
            newVersion = version;
            return build.html({version:version});
        }).then(function(){
            return newVersion;
        }).catch(log.onError);
}

module.exports = {
    run: run,
    all: run,
    adhoc: run
};
<commit_msg>v11.11.11<commit_after>var Promise = require('es6-promise').Promise;
var log = require('./utils/log');
var helper = require('./utils/config-helper');
var config;

function all(type){
    if (type == 'current') return Promise.resolve(config.pkg.version);

    var build = require('./build');
    var Bump = require('./utils/bump');
    var newVersion;
    return new Bump(['./package.json','./README.md', config.paths.source + '/**/version.js'], {type: type }).run()
        .then(function(version){
            log.info(" * Now on " + version);
            newVersion = version;
            return build.html({version:version});
        }).then(function(){
            return newVersion;
        }).catch(log.onError);
}

function exec(task, options){
    config = helper.getConfig();
    log.info('Bumping :');
    switch (task){
        case 'all': all(options); break;
        //default: help(task); break; //todo: help
    }
}

module.exports = {
    all:  function(options){ exec('all', options); }
};<|endoftext|>