<commit_before>/**
 * import(s)
 */

var debug = require('debug')('socket.io-rabbitmq-emitter');
var format = require('util').format;
var uid2 = require('uid2');
var parser = require('socket.io-parser');
var hasBin = require('has-binary-data');
var msgpack = require('msgpack-js');
var amqp = require('amqplib/callback_api');

/**
 * export(s)
 */

module.exports = Emitter;

var flags = [
    'json',
    'volatile',
    'broadcast'
];

function Emitter(opts) {
    if (!(this instanceof Emitter)) return new Emitter(opts);

    opts = opts || {};
    opts.port = opts.port || 5672;
    opts.host = opts.host || '127.0.0.1';
    opts.key = opts.key || 'socket.io-rabbitmq';

    this.url = opts.url ? opts.url : format('amqp://%s:%s', this.host, this.port);

    this.key = format('%s#emitter', opts.key);

    this._channel = null;

    this._rooms = {};
    this._flags = {};
}

flags.forEach(function (flag) {
    Emitter.prototype.__defineGetter__(flag, function () {
        debug('flag %s on', flag);
        this._flags[flag] = true;
        return this;
    });
});

Emitter.prototype.in =
    Emitter.prototype.to = function (room) {
        if (!~this._rooms.indexOf(room)) {
            debug('room %s', room);
            this._rooms.push(room);
        }
        return this;
    };

Emitter.prototype.of = function (nsp) {
    debug('nsp set to %s', nsp);
    this._flags.nsp = nsp;
    return this;
};

Emitter.prototype.emit = function () {
    // packet
    var args = Array.prototype.slice.call(arguments);
    var packet = {};
    packet.type = hasBin(args) ? parser.BINARY_EVENT : parser.EVENT;
    packet.data = args;
    // set namespace to packet
    if (this._flags.nsp) {
        packet.nsp = this._flags.nsp;
        delete this._flags.nsp;
    } else {
        packet.nsp = '/';
    }

    // publish
    var key = new Buffer(format('%s ', this.key), 'binary');
    var payload = msgpack.encode([packet, {
        rooms: this._rooms,
        flags: this._flags
    }]);
    var data = Buffer.concat([key, payload]);
    debug('send data length: key = %d, payload = %d, data = %d', key.length, payload.length, data.length);

    if (this._channel === null) {
        var _that = this;
        amqp.connect(_that.url, function (err, conn) {
            if (err) {
                console.error("[AMQP]", err.message);
                //TODO: Try to start
                return;
            }
            conn.on("error", function (err) {
                if (err.message !== "Connection closing") {
                    console.error("[AMQP] conn error", err.message);
                }
            });
            conn.on("close", function () {
                console.error("[AMQP] reconnecting");
                //TODO: restart
                return;
            });

            conn.createChannel(function on_open(err, ch) {
                if (err != null) bail(err);

                _that._channel = ch;
                _that._channel.assertQueue(_that.key);
                //_that._channel.sendToQueue(_that.key, data);
                _that._channel.publish("fanout", _that.key, data);
            });
        });

    } else {
        //this._channel.sendToQueue(this.key, data);
        this._channel.publish("fanout", _that.key, data);
    }

    // reset state
    this._rooms = [];
    this._flags = {};

    return this;
};
<commit_msg>code refactoring<commit_after>/**
 * import(s)
 */

var debug = require('debug')('socket.io-rabbitmq-emitter');
var format = require('util').format;
var uid2 = require('uid2');
var parser = require('socket.io-parser');
var hasBin = require('has-binary-data');
var msgpack = require('msgpack-js');
var amqp = require('amqplib/callback_api');

/**
 * export(s)
 */

module.exports = Emitter;

var flags = [
    'json',
    'volatile',
    'broadcast'
];

function Emitter(opts) {
    if (!(this instanceof Emitter)) return new Emitter(opts);

    opts = opts || {};
    opts.port = opts.port || 5672;
    opts.host = opts.host || '127.0.0.1';
    opts.key = opts.key || 'socket.io-rabbitmq';

    this.url = opts.url ? opts.url : format('amqp://%s:%s', this.host, this.port);

    this.key = format('%s#emitter', opts.key);

    this._channel = null;

    this._rooms = {};
    this._flags = {};
}

flags.forEach(function (flag) {
    Emitter.prototype.__defineGetter__(flag, function () {
        debug('flag %s on', flag);
        this._flags[flag] = true;
        return this;
    });
});

Emitter.prototype.in =
    Emitter.prototype.to = function (room) {
        if (!~this._rooms.indexOf(room)) {
            debug('room %s', room);
            this._rooms.push(room);
        }
        return this;
    };

Emitter.prototype.of = function (nsp) {
    debug('nsp set to %s', nsp);
    this._flags.nsp = nsp;
    return this;
};

Emitter.prototype.emit = function () {
    // packet
    var args = Array.prototype.slice.call(arguments);
    var packet = {};
    packet.type = hasBin(args) ? parser.BINARY_EVENT : parser.EVENT;
    packet.data = args;
    // set namespace to packet
    if (this._flags.nsp) {
        packet.nsp = this._flags.nsp;
        delete this._flags.nsp;
    } else {
        packet.nsp = '/';
    }

    // publish
    var key = new Buffer(format('%s ', this.key), 'binary');
    var payload = msgpack.encode([packet, {
        rooms: this._rooms,
        flags: this._flags
    }]);
    var data = Buffer.concat([key, payload]);
    debug('send data length: key = %d, payload = %d, data = %d', key.length, payload.length, data.length);

    if (this._channel === null) {
        var _that = this;
         _connect(_that.url, function cb(err, ch) {
            if (err) return console.error("[AMQP]", err.message);

            _that._channel = ch;
            _that._channel.assertQueue(_that.key);
            //_that._channel.sendToQueue(_that.key, data);
            _that._channel.publish("fanout", _that.key, data);
        });

    } else {
        //this._channel.sendToQueue(this.key, data);
        this._channel.publish("fanout", _that.key, data);
    }

    // reset state
    this._rooms = [];
    this._flags = {};

    return this;
};

function _connect(url, cb) {
    amqp.connect(url, function (err, conn) {
        if (err) {
            return console.error("[AMQP]", err.message);
        }
        conn.on("error", function (err) {
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err.message);
            }
        });
        conn.on("close", function () {
            return console.error("[AMQP] reconnecting");
        });

        conn.createChannel(function on_open(err, ch) {
            if (err != null) {
                console.error("[AMQP] create channel error", err.message);
                return cb(err);
            }

            cb(null, ch);
        });
    });
}
<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import 'current-input';

import App from './components/App';
import Home from './components/Home';
import PageNotFound from './components/PageNotFound';
import ExampleComponent from './components/ExampleComponent';
import ExampleTwoDeepComponent from './components/ExampleTwoDeepComponent';

const routes = (
  <Route path="/" mapMenuTitle="Home" component={App}>
    <IndexRoute component={Home} />

    <Route path="example" mapMenuTitle="Example" component={ExampleComponent}>
      <Route path="two-deep" mapMenuTitle="Two Deep" component={ExampleTwoDeepComponent} />
    </Route>

    <Route path="*" mapMenuTitle="Page Not Found" component={PageNotFound} />
  </Route>
);

render(
  <Router
    history={browserHistory}
    routes={routes}
  />,
  document.getElementById('root')
)
<commit_msg>Update index.js code style<commit_after>import React from 'react';
import { render } from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import 'current-input';

import App from './components/App';
import Home from './components/Home';
import PageNotFound from './components/PageNotFound';
import ExampleComponent from './components/ExampleComponent';
import ExampleTwoDeepComponent from './components/ExampleTwoDeepComponent';

const routes = (
  <Route path="/" mapMenuTitle="Home" component={App}>
    <IndexRoute component={Home} />

    <Route path="example" mapMenuTitle="Example" component={ExampleComponent}>
      <Route path="two-deep" mapMenuTitle="Two Deep" component={ExampleTwoDeepComponent} />
    </Route>

    <Route path="*" mapMenuTitle="Page Not Found" component={PageNotFound} />
  </Route>
);

render(
  <Router
    history={browserHistory}
    routes={routes}
  />,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>var bignum = require('bignum');
var prime_size = 128;
function pq() {
    var p = bignum.prime(prime_size);
    var q = bignum.prime(prime_size);
    this.p = p;
    this.q = q;
    this.pq = p.mul(q);
    this.t = p.sub(1).mul(q.sub(1));
}

var a = new pq();
var b = new pq();
var c = new pq();
var d = new pq();
var z = bignum.prime(prime_size);
var y = bignum.prime(prime_size * 2.5);

function make_key(a, others) {
    var product = a.pq;
    for (var i = 0; i < others.length; i++) product = product.mul(others[i].pq);
    var az_totient = a.t.mul(z.sub(1));
    var power_root = bignum(65537).invertm(az_totient);
    var root_lock = y.powm(power_root, a.pq.mul(z));
    return product.mul(root_lock).mod(product.mul(z));
}

console.log("----");
console.log( make_key(a, [b, c, d]));
console.log("----");
console.log( make_key(b, [a, c, d]));
console.log("----");
console.log( make_key(c, [a, b, d]));
console.log("----");
console.log( make_key(d, [a, b, c]));
console.log("----");
<commit_msg>cleanup?<commit_after>var bignum = require('bignum');
var prime_size = 128;
function pq() {
    var p = bignum.prime(prime_size);
    var q = bignum.prime(prime_size);
    this.p = p;
    this.q = q;
    this.pq = p.mul(q);
    this.t = p.sub(1).mul(q.sub(1));
}

var a = new pq();
var b = new pq();
var c = new pq();
var d = new pq();
var N = 65537;
var y = bignum.prime(prime_size);
var z = bignum.prime(prime_size * 3 - 1);

function make_key(a, others) {
    var product = a.pq;
    for (var i = 0; i < others.length; i++) product = product.mul(others[i].pq);

    var az_totient = a.t.mul(y.sub(1));
    var power_root = bignum(N).invertm(az_totient);
    var root_lock = z.powm(power_root, a.pq.mul(y));
    return product.mul(root_lock).mod(product.mul(y));
}

console.log("----");
console.log( make_key(a, [b, c, d]));
console.log("----");
console.log( make_key(b, [a, c, d]));
console.log("----");
console.log( make_key(c, [a, b, d]));
console.log("----");
console.log( make_key(d, [a, b, c]));
console.log("----");
<|endoftext|>


<commit_before>var bodyParser = require('body-parser');
var crypto = require('crypto');
var express = require('express');
var querystring = require('querystring');
var request = require('request');
var util = require('util');

(function() {
  'use strict';

  var app = express();

  var hostname = process.env.HOSTNAME || 'localhost';
  var port = process.env.PORT || 5000;

  var username = process.env.GITHUB_USERNAME || null;
  var token = process.env.ACCESS_TOKEN || null;
  var repo = process.env.GITHUB_REPO || null;
  var mdPath = process.env.CODEREVIEWMD || 'CODEREVIEW.md';

  function init(run_server) {
    // Validate Github config.
    if (!username) {
      var msg = 'Please specify Github %s via environment variable: %s';
      msg = util.format(msg, 'username', 'GITHUB_USERNAME');
      console.warn(msg);

      process.exit(1);
    }

    if (!token) {
      var msg = 'Please specify Github %s via environment variable: %s';
      msg = util.format(msg, 'access token', 'ACCESS_TOKEN');
      console.warn(msg);

      process.exit(1);
    }

    if (!repo) {
      var msg = 'Please specify Github %s via environment variable: %s';
      msg = util.format(msg, 'repository', 'GITHUB_REPO');
      console.warn(msg);

      process.exit(1);
    }

    // Prepare shared secret.
    var msg = username + repo + token;
    var secret = crypto.createHash('md5').update(msg)
                                         .digest('hex');

    // Setup webhook.
    var data = JSON.stringify({
      'name': 'web',
      'active': true,
      'events': [
        'pull_request'
      ],
      'config': {
        'url': util.format('https://%s/webhook/pullrequest/', hostname),
        'content_type': 'json',
        'secret': secret
      }
    });

    var url = util.format('https://api.github.com/repos/%s/%s/hooks',
                          username, repo);
    request({
      method: 'POST',
      url: url,
      auth: {'user': username, 'pass': token},
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length,
        'User-Agent': util.format('codereviewmd by %s', username)
      },
      body: data
    }, function(error, response, body) {
      if (error) {
        var msg = 'Failed to create webhook: HTTP%s - %s';
        console.error(util.format(msg, response.statusCode, body));

        process.exit(1);
        return;
      }

      var succeed = false;

      if (response.statusCode === 201) {
        succeed = true;
      } else if (response.statusCode === 422) {
        var msg = JSON.parse(body).errors[0].message;
        if (msg.toLowerCase().indexOf('already exists') > -1) {
          succeed = true;
        }
      }

      if (!succeed) {
        var msg = 'Failed to create webhook: HTTP%s - %s';
        console.error(util.format(msg, response.statusCode, body));

        process.exit(1);
        return;
      }

      // Run server now.
      run_server(username, token, repo, secret, mdPath);
    });
  }

  function runserver(username, token, repo, secret, mdPath) {
    app.set('port', port);

    var webhookParser = bodyParser.text({'type': 'application/json'});
    app.post('/webhook/pullrequest/', webhookParser, function(req, res) {
      var evt = req.header('X-Github-Event');
      var sign = req.header('X-Hub-Signature');
      var payload = req.body;

      if (evt !== 'ping' && evt !== 'pull_request') {
        return res.sendStatus(400);
      }

      // TODO: Use constant-time compare in Hmac verification
      var computed = crypto.createHmac('sha1', secret).update(payload)
                                                      .digest('hex');
      if ('sha1='+computed !== sign) {
        return res.sendStatus(403);
      }

      // TODO: Use async task to create a new checklist from CODEREVIEW.md
      var url = util.format('https://api.github.com/repos/%s/%s/contents/%s',
                            username, repo, mdPath);
      request({
        method: 'GET',
        url: url,
        auth: {'user': username, 'pass': token},
        headers: {
          'User-Agent': util.format('codereviewmd by %s', username)
        }
      }, function(error, response, body) {
        if (error) {
          var msg = 'Failed to read checklist: HTTP%s - %s';
          console.error(util.format(msg, response.statusCode, body));

          return;
        }

        var succeed = false;

        if (response.statusCode === 200) {
          succeed = true;
        }

        if (!succeed) {
          var msg = 'Failed to read checklist: HTTP%s - %s';
          console.error(util.format(msg, response.statusCode, body));

          return;
        }

        // TODO: HTTP-POST a new checklist onto the PR
        console.log(body);
        res.sendStatus(202);
      });
    });

    app.listen(app.get('port'), function() {
      console.log('Node app is running on port', app.get('port'));
    });
  }

  init(runserver);
}());
<commit_msg>Reply HTTP202 when failed to get checklist<commit_after>var bodyParser = require('body-parser');
var crypto = require('crypto');
var express = require('express');
var querystring = require('querystring');
var request = require('request');
var util = require('util');

(function() {
  'use strict';

  var app = express();

  var hostname = process.env.HOSTNAME || 'localhost';
  var port = process.env.PORT || 5000;

  var username = process.env.GITHUB_USERNAME || null;
  var token = process.env.ACCESS_TOKEN || null;
  var repo = process.env.GITHUB_REPO || null;
  var mdPath = process.env.CODEREVIEWMD || 'CODEREVIEW.md';

  function init(run_server) {
    // Validate Github config.
    if (!username) {
      var msg = 'Please specify Github %s via environment variable: %s';
      msg = util.format(msg, 'username', 'GITHUB_USERNAME');
      console.warn(msg);

      process.exit(1);
    }

    if (!token) {
      var msg = 'Please specify Github %s via environment variable: %s';
      msg = util.format(msg, 'access token', 'ACCESS_TOKEN');
      console.warn(msg);

      process.exit(1);
    }

    if (!repo) {
      var msg = 'Please specify Github %s via environment variable: %s';
      msg = util.format(msg, 'repository', 'GITHUB_REPO');
      console.warn(msg);

      process.exit(1);
    }

    // Prepare shared secret.
    var msg = username + repo + token;
    var secret = crypto.createHash('md5').update(msg)
                                         .digest('hex');

    // Setup webhook.
    var data = JSON.stringify({
      'name': 'web',
      'active': true,
      'events': [
        'pull_request'
      ],
      'config': {
        'url': util.format('https://%s/webhook/pullrequest/', hostname),
        'content_type': 'json',
        'secret': secret
      }
    });

    var url = util.format('https://api.github.com/repos/%s/%s/hooks',
                          username, repo);
    request({
      method: 'POST',
      url: url,
      auth: {'user': username, 'pass': token},
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length,
        'User-Agent': util.format('codereviewmd by %s', username)
      },
      body: data
    }, function(error, response, body) {
      if (error) {
        var msg = 'Failed to create webhook: HTTP%s - %s';
        console.error(util.format(msg, response.statusCode, body));

        process.exit(1);
        return;
      }

      var succeed = false;

      if (response.statusCode === 201) {
        succeed = true;
      } else if (response.statusCode === 422) {
        var msg = JSON.parse(body).errors[0].message;
        if (msg.toLowerCase().indexOf('already exists') > -1) {
          succeed = true;
        }
      }

      if (!succeed) {
        var msg = 'Failed to create webhook: HTTP%s - %s';
        console.error(util.format(msg, response.statusCode, body));

        process.exit(1);
        return;
      }

      // Run server now.
      run_server(username, token, repo, secret, mdPath);
    });
  }

  function runserver(username, token, repo, secret, mdPath) {
    app.set('port', port);

    var webhookParser = bodyParser.text({'type': 'application/json'});
    app.post('/webhook/pullrequest/', webhookParser, function(req, res) {
      var evt = req.header('X-Github-Event');
      var sign = req.header('X-Hub-Signature');
      var payload = req.body;

      if (evt !== 'ping' && evt !== 'pull_request') {
        return res.sendStatus(400);
      }

      // TODO: Use constant-time compare in Hmac verification
      var computed = crypto.createHmac('sha1', secret).update(payload)
                                                      .digest('hex');
      if ('sha1='+computed !== sign) {
        return res.sendStatus(403);
      }

      // TODO: Use async task to create a new checklist from CODEREVIEW.md
      var url = util.format('https://api.github.com/repos/%s/%s/contents/%s',
                            username, repo, mdPath);
      request({
        method: 'GET',
        url: url,
        auth: {'user': username, 'pass': token},
        headers: {
          'User-Agent': util.format('codereviewmd by %s', username)
        }
      }, function(error, response, body) {
        if (error) {
          var msg = 'Failed to read checklist: HTTP%s - %s';
          console.error(util.format(msg, response.statusCode, body));

          return res.sendStatus(202);
        }

        var succeed = false;

        if (response.statusCode === 200) {
          succeed = true;
        }

        if (!succeed) {
          var msg = 'Failed to read checklist: HTTP%s - %s';
          console.error(util.format(msg, response.statusCode, body));

          return res.sendStatus(202);
        }

        // TODO: HTTP-POST a new checklist onto the PR
        console.log(body);
        res.sendStatus(202);
      });
    });

    app.listen(app.get('port'), function() {
      console.log('Node app is running on port', app.get('port'));
    });
  }

  init(runserver);
}());
<|endoftext|>


<commit_before>
define([
  'context',
  'ast',
  'templates',
], function (ctx, ast, t) {
  'use strict';

  var translators = Object.create(null);

  translators.AssignmentExpression = function (divAssignment, context) {
    return new ast.AssignmentExpression(
      translate(divAssignment.left, context),
      translate(divAssignment.right, context),

      // XXX: This is good luck. All assignment operators are equal!
      divAssignment.operator
    );
  };

  translators.BinaryExpression = function (divBinary, context) {
    return new ast.BinaryExpression(
      translate(divBinary.left, context),
      translate(divBinary.right, context),
      divBinary.operator
    );
  };

  translators.RelationalExpression = translators.BinaryExpression;

  translators.LogicalExpression = function (divLogical, context) {
    var logicalFunction;
    switch (divLogical.operator) {
      case '&':
      case '&&':
        logicalFunction = '__and';
        break;
      case '||':
        logicalFunction = '__or';
        break;
      case '^':
      case '^^':
        logicalFunction = '__xor';
        break;
      default:
        throw new Error('Logical operator unknown: ' + divLogical.operator);
    }
    return new t.callWith(logicalFunction, [
        translate(divLogical.left, context),
        translate(divLogical.right, context)
    ]);
  };

  translators.CallExpression = function (divCall, context) {
    var parameters = new ast.ArrayExpression(
      divCall.arguments.map(function (arg) {
        return translate(arg, context);
      })
    );
    var id = divCall.callee.name;
    var isProcess = context.isProcess(id);
    var afterCallLabel = context.newLabel();
    var callKind = isProcess ? 'newProcess' : 'callFunction';
    // Isolate as a subexpression (impicitely stored in the results queue)
    context[callKind](afterCallLabel, id, parameters);
    context.label(afterCallLabel);
    // Replace by the intermediate value (i.e. dequeue from the results queue)
    return t.dequeueReturnValue;
  };

  translators.CloneSentence = function (divClone, context) {
    var insideCloneLabel = context.newLabel();
    var afterCloneLabel = context.newLabel();
    context.clone(insideCloneLabel, afterCloneLabel);
    context.label(insideCloneLabel);
    translateBody(divClone, context);
    context.label(afterCloneLabel);
  };

  translators.Unit = function (divUnit, context) {
    var programFunction = translate(divUnit.program, context);
    var processesFunctions = divUnit.processes.map(function (divProcess) {
      return translate(divProcess, context);
    });
    var globals = translateGlobals(context);
    var locals = translateLocals(context);
    return new ast.Program(
      [globals, locals]
      .concat([programFunction])
      .concat(processesFunctions)
    );
  };

  function translateGlobals(context) {
    var globalBase = getGlobalBaseDeclaration(context);
    var globalDeclarations = translateSegment('globals', context);
    globalDeclarations.declarations.unshift(globalBase);
    return globalDeclarations;
  }

  function translateLocals(context) {
    return translateSegment('locals', context);
  }

  function getGlobalBaseDeclaration(context) {
    var offset = context.getMemoryMap().constructor.GLOBAL_OFFSET;
    return new ast.VariableDeclarator(
      t.globalBaseIdentifier,
      ast.Literal['for'](offset)
    );
  }

  function translateSegment(segment, context) {
    var mmap = context.getMemoryMap();
    var alignment = mmap.constructor.ALIGNMENT;

    var vars =
      getSegmentDeclarations(segment, [], mmap.cells[segment], alignment);

    return new ast.VariableDeclaration(vars);
  }

  function getSegmentDeclarations(segment, prefixes, cells, alignment) {
    var offset = 0;
    var definitions = [];
    for (var i = 0, cell; (cell = cells[i]); i++) {
      if (!cell.hidden) {
        var identifierFactory =
          'identifierFor' + { 'globals': 'Global', 'locals': 'Local' }[segment];
        prefixes.push(cell.name);
        definitions.push(new ast.VariableDeclarator(
          t[identifierFactory](prefixes),
          ast.Literal['for'](offset)
        ));
        if (cell.type === 'struct') {
          definitions = definitions.concat(
            getSegmentDeclarations(segment, prefixes, cell.fields, alignment)
          );
        }
        prefixes.pop();
      }
      offset += cell.size / alignment;
    }
    return flat(definitions);

    function flat(list) {
      return list.reduce(function (flat, item) {
        if (!Array.isArray(item)) {
          item = [item];
        }
        return flat.concat(item);
      }, []);
    }
  }

  translators.Program = function (divProgram, context) {
    var name = divProgram.name.name;
    var body = translate(divProgram.body, context);
    return t.programFunction(name, body);
  };

  translators.Process = function (divProgram, context) {
    var name = divProgram.name.name;
    var body = translate(divProgram.body, context);
    return t.processFunction(name, body);
  };

  translators.ProcessBody = function (divBody, context) {
    context.startLinearization();
    divBody.sentences.map(function (sentence) {
      translate(sentence, context);
    });
    context.end();
    var bodyCases = context.getLinearizationCases();
    return t.concurrentBody(bodyCases);
  };

  translators.Identifier = function (divIdentifier, context) {
    var name = divIdentifier.name;
    var scope = context.getScope(name);
    if (!scope) { throw new Error('Unknown name ' + name); }
    var scopeTranslator = 'memory' + scope[0].toUpperCase() + scope.substr(1);
    if (!(scopeTranslator in t)) { throw new Error('Unknown scope ' + scope); }
    return t[scopeTranslator](name);
  };

  translators.IfSentence = function (divIf, context) {
    var consequentLabel = context.newLabel();
    var alternateLabel = context.newLabel();

    var test = t.toBool(translate(divIf.test, context));
    context.goToIf(test, consequentLabel, alternateLabel);
    context.label(consequentLabel);
    translateBody(divIf, context, 'consequent');
    context.label(alternateLabel);
    if (divIf.alternate) {
      translateBody(divIf, context, 'alternate');
    }
  };

  translators.ExpressionSentence = function (divExpression, context) {
    var expression = translate(divExpression.expression, context);
    context.verbatim(new ast.ExpressionStatement(expression));
  };

  translators.Literal = function (divLiteral) {
    return ast.Literal.for(divLiteral.value);
  };

  translators.WhileSentence = function (divWhile, context) {
    var loopStartLabel = context.newLabel();
    var afterLoopLabel = context.newLabel();
    var testLabel = context.newLabel();

    context.label(testLabel);
    context.goToIf(
      translate(divWhile.test, context),
      loopStartLabel,
      afterLoopLabel
    );

    context.label(loopStartLabel);
    translateBody(divWhile, context);
    context.goTo(testLabel);

    context.label(afterLoopLabel);
  };

  translators.LoopSentence = function (divLoop, context) {
    var loopStartLabel = context.newLabel();
    var afterLoopLabel = context.newLabel();

    context.label(loopStartLabel);
    translateBody(divLoop, context);
    context.goTo(loopStartLabel);

    context.label(afterLoopLabel);
  };

  translators.RepeatSentence = function (divRepeat, context) {
    var loopStartLabel = context.newLabel();
    var afterLoopLabel = context.newLabel();

    context.label(loopStartLabel);
    translateBody(divRepeat, context);
    context.goToIf(
      translate(divRepeat.test, context),
      afterLoopLabel,
      loopStartLabel
    );

    context.label(afterLoopLabel);
  };

  translators.ReturnSentence = function (divReturn, context) {
    var returnArgument = divReturn.argument;
    if (!returnArgument) {
      returnArgument = t.defaultReturnArgument;
    }
    context.return(translate(returnArgument, context));
  };

  translators.SwitchSentence = function (divSwitch, context) {
    var afterSwitchLabel = context.newLabel();
    var defaultCaseLabel = context.newLabel();

    var cases = divSwitch.cases;
    var lastCase = cases[cases.length - 1];
    var hasDefault = lastCase && lastCase.tests === null;
    if (hasDefault) { cases.pop(); }

    var discriminant = translate(divSwitch.discriminant, context);
    var aux = context.newAux('_switch', discriminant);
    var choices = generateChoices(cases, context);

    context.verbatim(aux.declaration);
    context.select(
      aux.identifier, choices,
      hasDefault ? defaultCaseLabel : afterSwitchLabel
    );
    choices.forEach(function (choice) {
      context.label(choice.label);
      translateBody(choice.case, context, 'consequent');
      context.goTo(afterSwitchLabel);
    });
    if (hasDefault) {
      var defaultCase = lastCase;
      context.label(defaultCaseLabel);
      translateBody(defaultCase, context, 'consequent');
      context.goTo(afterSwitchLabel);
    }
    context.label(afterSwitchLabel);
  };

  function generateChoices(cases, context) {
    return cases.map(function (caseClause) {
      return {
        label: context.newLabel(),
        tests: caseClause.tests.map(function (test) {
          return translate(test, context);
        }),
        case: caseClause
      };
    });
  }

  translators.FrameSentence = function (divFrame, context) {
    var resumeLabel = context.newLabel();
    var argument = divFrame.argument || t.defaultFrameArgument;
    context.frame(resumeLabel, translate(argument, context));
    context.label(resumeLabel);
  };

  translators.DebugSentence = function (divDebug, context) {
    var resumeLabel = context.newLabel();
    context.debug(resumeLabel);
    context.label(resumeLabel);
  };

  translators.FromSentence = function (divFrom, context) {
    var initValue = divFrom.init.value;
    var limitValue = divFrom.limit.value;
    var isAscendant = initValue < limitValue;
    var defaultStep = isAscendant ? 1 : -1;
    var step = divFrom.step ? divFrom.step.value : defaultStep;
    var identifier = divFrom.identifier.name;

    var init = t.fromInitilizator(identifier, initValue);
    var test = t.fromTest(identifier, limitValue, isAscendant);
    var update = t.fromIncrement(identifier, step);

    translateForLikeLoop(divFrom, [init], [test], [update], context);
  };

  translators.ForSentence = function (divFor, context) {
    var inits = divFor.inits;
    var tests = divFor.tests;
    var updates = divFor.updates;
    translateForLikeLoop(divFor, inits, tests, updates, context);
  };

  translators.Range = function (divRange) {
    return t.newRange(divRange.min, divRange.max);
  };

  /**
   * All parameters here must be DIV2 AST.
   */
  function translateForLikeLoop(loop, inits, tests, updates, context) {
    var test = t.every(tests.map(function (test) {
      return t.toBool(translate(test, context));
    }));

    var testLabel = context.newLabel();
    var loopStartLabel = context.newLabel();
    var afterLoopLabel = context.newLabel();
    var updatesLabel = context.newLabel();

    inits.forEach(verbatim);

    context.label(testLabel);
    if (test) {
      context.goToIf(test, loopStartLabel, afterLoopLabel);
    }

    context.label(loopStartLabel);
    translateBody(loop, context);

    context.label(updatesLabel);
    updates.forEach(verbatim);
    context.goTo(testLabel);

    context.label(afterLoopLabel);

    function verbatim(divExpression) {
      context.verbatim(new ast.ExpressionStatement(
        translate(divExpression, context)
      ));
    }
  }

  function translate(divAst, context) {
    if (!divAst || !divAst.type) { throw new Error('Invalid DIV2 AST'); }
    if (!(divAst.type in translators)) {
      throw new Error('Translation unavailable for ' + divAst.type + ' AST');
    }
    return translators[divAst.type](divAst, context);
  }

  function translateBody(divBodySentence, context, bodyProperty) {
    bodyProperty = bodyProperty || 'body';
    return divBodySentence[bodyProperty].sentences.map(function (sentence) {
      return translate(sentence, context);
    });
  }

  return {
    translate: translate
  };
});
<commit_msg>Added TODO about MemoryBrowser-based variable assignments and reads.<commit_after>
define([
  'context',
  'ast',
  'templates',
], function (ctx, ast, t) {
  'use strict';

  var translators = Object.create(null);

  // TODO: Consider switching these to MemortBrowser-based assignment and read
  // so the JS code can be optimized and inlined later. This would decouple
  // translation from memory layout.
  translators.AssignmentExpression = function (divAssignment, context) {
    return new ast.AssignmentExpression(
      translate(divAssignment.left, context),
      translate(divAssignment.right, context),

      // XXX: This is good luck. All assignment operators are equal!
      divAssignment.operator
    );
  };

  translators.BinaryExpression = function (divBinary, context) {
    return new ast.BinaryExpression(
      translate(divBinary.left, context),
      translate(divBinary.right, context),
      divBinary.operator
    );
  };

  translators.RelationalExpression = translators.BinaryExpression;

  translators.LogicalExpression = function (divLogical, context) {
    var logicalFunction;
    switch (divLogical.operator) {
      case '&':
      case '&&':
        logicalFunction = '__and';
        break;
      case '||':
        logicalFunction = '__or';
        break;
      case '^':
      case '^^':
        logicalFunction = '__xor';
        break;
      default:
        throw new Error('Logical operator unknown: ' + divLogical.operator);
    }
    return new t.callWith(logicalFunction, [
        translate(divLogical.left, context),
        translate(divLogical.right, context)
    ]);
  };

  translators.CallExpression = function (divCall, context) {
    var parameters = new ast.ArrayExpression(
      divCall.arguments.map(function (arg) {
        return translate(arg, context);
      })
    );
    var id = divCall.callee.name;
    var isProcess = context.isProcess(id);
    var afterCallLabel = context.newLabel();
    var callKind = isProcess ? 'newProcess' : 'callFunction';
    // Isolate as a subexpression (impicitely stored in the results queue)
    context[callKind](afterCallLabel, id, parameters);
    context.label(afterCallLabel);
    // Replace by the intermediate value (i.e. dequeue from the results queue)
    return t.dequeueReturnValue;
  };

  translators.CloneSentence = function (divClone, context) {
    var insideCloneLabel = context.newLabel();
    var afterCloneLabel = context.newLabel();
    context.clone(insideCloneLabel, afterCloneLabel);
    context.label(insideCloneLabel);
    translateBody(divClone, context);
    context.label(afterCloneLabel);
  };

  translators.Unit = function (divUnit, context) {
    var programFunction = translate(divUnit.program, context);
    var processesFunctions = divUnit.processes.map(function (divProcess) {
      return translate(divProcess, context);
    });
    var globals = translateGlobals(context);
    var locals = translateLocals(context);
    return new ast.Program(
      [globals, locals]
      .concat([programFunction])
      .concat(processesFunctions)
    );
  };

  function translateGlobals(context) {
    var globalBase = getGlobalBaseDeclaration(context);
    var globalDeclarations = translateSegment('globals', context);
    globalDeclarations.declarations.unshift(globalBase);
    return globalDeclarations;
  }

  function translateLocals(context) {
    return translateSegment('locals', context);
  }

  function getGlobalBaseDeclaration(context) {
    var offset = context.getMemoryMap().constructor.GLOBAL_OFFSET;
    return new ast.VariableDeclarator(
      t.globalBaseIdentifier,
      ast.Literal['for'](offset)
    );
  }

  function translateSegment(segment, context) {
    var mmap = context.getMemoryMap();
    var alignment = mmap.constructor.ALIGNMENT;

    var vars =
      getSegmentDeclarations(segment, [], mmap.cells[segment], alignment);

    return new ast.VariableDeclaration(vars);
  }

  function getSegmentDeclarations(segment, prefixes, cells, alignment) {
    var offset = 0;
    var definitions = [];
    for (var i = 0, cell; (cell = cells[i]); i++) {
      if (!cell.hidden) {
        var identifierFactory =
          'identifierFor' + { 'globals': 'Global', 'locals': 'Local' }[segment];
        prefixes.push(cell.name);
        definitions.push(new ast.VariableDeclarator(
          t[identifierFactory](prefixes),
          ast.Literal['for'](offset)
        ));
        if (cell.type === 'struct') {
          definitions = definitions.concat(
            getSegmentDeclarations(segment, prefixes, cell.fields, alignment)
          );
        }
        prefixes.pop();
      }
      offset += cell.size / alignment;
    }
    return flat(definitions);

    function flat(list) {
      return list.reduce(function (flat, item) {
        if (!Array.isArray(item)) {
          item = [item];
        }
        return flat.concat(item);
      }, []);
    }
  }

  translators.Program = function (divProgram, context) {
    var name = divProgram.name.name;
    var body = translate(divProgram.body, context);
    return t.programFunction(name, body);
  };

  translators.Process = function (divProgram, context) {
    var name = divProgram.name.name;
    var body = translate(divProgram.body, context);
    return t.processFunction(name, body);
  };

  translators.ProcessBody = function (divBody, context) {
    context.startLinearization();
    divBody.sentences.map(function (sentence) {
      translate(sentence, context);
    });
    context.end();
    var bodyCases = context.getLinearizationCases();
    return t.concurrentBody(bodyCases);
  };

  translators.Identifier = function (divIdentifier, context) {
    var name = divIdentifier.name;
    var scope = context.getScope(name);
    if (!scope) { throw new Error('Unknown name ' + name); }
    var scopeTranslator = 'memory' + scope[0].toUpperCase() + scope.substr(1);
    if (!(scopeTranslator in t)) { throw new Error('Unknown scope ' + scope); }
    return t[scopeTranslator](name);
  };

  translators.IfSentence = function (divIf, context) {
    var consequentLabel = context.newLabel();
    var alternateLabel = context.newLabel();

    var test = t.toBool(translate(divIf.test, context));
    context.goToIf(test, consequentLabel, alternateLabel);
    context.label(consequentLabel);
    translateBody(divIf, context, 'consequent');
    context.label(alternateLabel);
    if (divIf.alternate) {
      translateBody(divIf, context, 'alternate');
    }
  };

  translators.ExpressionSentence = function (divExpression, context) {
    var expression = translate(divExpression.expression, context);
    context.verbatim(new ast.ExpressionStatement(expression));
  };

  translators.Literal = function (divLiteral) {
    return ast.Literal.for(divLiteral.value);
  };

  translators.WhileSentence = function (divWhile, context) {
    var loopStartLabel = context.newLabel();
    var afterLoopLabel = context.newLabel();
    var testLabel = context.newLabel();

    context.label(testLabel);
    context.goToIf(
      translate(divWhile.test, context),
      loopStartLabel,
      afterLoopLabel
    );

    context.label(loopStartLabel);
    translateBody(divWhile, context);
    context.goTo(testLabel);

    context.label(afterLoopLabel);
  };

  translators.LoopSentence = function (divLoop, context) {
    var loopStartLabel = context.newLabel();
    var afterLoopLabel = context.newLabel();

    context.label(loopStartLabel);
    translateBody(divLoop, context);
    context.goTo(loopStartLabel);

    context.label(afterLoopLabel);
  };

  translators.RepeatSentence = function (divRepeat, context) {
    var loopStartLabel = context.newLabel();
    var afterLoopLabel = context.newLabel();

    context.label(loopStartLabel);
    translateBody(divRepeat, context);
    context.goToIf(
      translate(divRepeat.test, context),
      afterLoopLabel,
      loopStartLabel
    );

    context.label(afterLoopLabel);
  };

  translators.ReturnSentence = function (divReturn, context) {
    var returnArgument = divReturn.argument;
    if (!returnArgument) {
      returnArgument = t.defaultReturnArgument;
    }
    context.return(translate(returnArgument, context));
  };

  translators.SwitchSentence = function (divSwitch, context) {
    var afterSwitchLabel = context.newLabel();
    var defaultCaseLabel = context.newLabel();

    var cases = divSwitch.cases;
    var lastCase = cases[cases.length - 1];
    var hasDefault = lastCase && lastCase.tests === null;
    if (hasDefault) { cases.pop(); }

    var discriminant = translate(divSwitch.discriminant, context);
    var aux = context.newAux('_switch', discriminant);
    var choices = generateChoices(cases, context);

    context.verbatim(aux.declaration);
    context.select(
      aux.identifier, choices,
      hasDefault ? defaultCaseLabel : afterSwitchLabel
    );
    choices.forEach(function (choice) {
      context.label(choice.label);
      translateBody(choice.case, context, 'consequent');
      context.goTo(afterSwitchLabel);
    });
    if (hasDefault) {
      var defaultCase = lastCase;
      context.label(defaultCaseLabel);
      translateBody(defaultCase, context, 'consequent');
      context.goTo(afterSwitchLabel);
    }
    context.label(afterSwitchLabel);
  };

  function generateChoices(cases, context) {
    return cases.map(function (caseClause) {
      return {
        label: context.newLabel(),
        tests: caseClause.tests.map(function (test) {
          return translate(test, context);
        }),
        case: caseClause
      };
    });
  }

  translators.FrameSentence = function (divFrame, context) {
    var resumeLabel = context.newLabel();
    var argument = divFrame.argument || t.defaultFrameArgument;
    context.frame(resumeLabel, translate(argument, context));
    context.label(resumeLabel);
  };

  translators.DebugSentence = function (divDebug, context) {
    var resumeLabel = context.newLabel();
    context.debug(resumeLabel);
    context.label(resumeLabel);
  };

  translators.FromSentence = function (divFrom, context) {
    var initValue = divFrom.init.value;
    var limitValue = divFrom.limit.value;
    var isAscendant = initValue < limitValue;
    var defaultStep = isAscendant ? 1 : -1;
    var step = divFrom.step ? divFrom.step.value : defaultStep;
    var identifier = divFrom.identifier.name;

    var init = t.fromInitilizator(identifier, initValue);
    var test = t.fromTest(identifier, limitValue, isAscendant);
    var update = t.fromIncrement(identifier, step);

    translateForLikeLoop(divFrom, [init], [test], [update], context);
  };

  translators.ForSentence = function (divFor, context) {
    var inits = divFor.inits;
    var tests = divFor.tests;
    var updates = divFor.updates;
    translateForLikeLoop(divFor, inits, tests, updates, context);
  };

  translators.Range = function (divRange) {
    return t.newRange(divRange.min, divRange.max);
  };

  /**
   * All parameters here must be DIV2 AST.
   */
  function translateForLikeLoop(loop, inits, tests, updates, context) {
    var test = t.every(tests.map(function (test) {
      return t.toBool(translate(test, context));
    }));

    var testLabel = context.newLabel();
    var loopStartLabel = context.newLabel();
    var afterLoopLabel = context.newLabel();
    var updatesLabel = context.newLabel();

    inits.forEach(verbatim);

    context.label(testLabel);
    if (test) {
      context.goToIf(test, loopStartLabel, afterLoopLabel);
    }

    context.label(loopStartLabel);
    translateBody(loop, context);

    context.label(updatesLabel);
    updates.forEach(verbatim);
    context.goTo(testLabel);

    context.label(afterLoopLabel);

    function verbatim(divExpression) {
      context.verbatim(new ast.ExpressionStatement(
        translate(divExpression, context)
      ));
    }
  }

  function translate(divAst, context) {
    if (!divAst || !divAst.type) { throw new Error('Invalid DIV2 AST'); }
    if (!(divAst.type in translators)) {
      throw new Error('Translation unavailable for ' + divAst.type + ' AST');
    }
    return translators[divAst.type](divAst, context);
  }

  function translateBody(divBodySentence, context, bodyProperty) {
    bodyProperty = bodyProperty || 'body';
    return divBodySentence[bodyProperty].sentences.map(function (sentence) {
      return translate(sentence, context);
    });
  }

  return {
    translate: translate
  };
});
<|endoftext|>


<commit_before>/*jshint node:true */

/* options
* --format=pretty|progress|html|failed
^ --ansi (default)
* --no-ansi  (uses ansi:false)
* --no-time  (uses time:true)
*/

'use strict';

var map   = require('map-stream'),
    gutil = require('gulp-util'),
    os    = require('os'),
    exec  = require('child_process').exec;

module.exports = function(command, opt){
	var counter = 0;
	var skipCmd = '';

	if (typeof command === 'object') {
		throw new Error('Invalid Behat Binary');
	}

	// if path to behat bin not supplied, use default vendor/bin path
	if(! command) {
		command = './vendor/bin/behat';
		if (os.platform() === 'win32') {
			command = '.\\vendor\\bin\\behat';
		}
	}

	// create default opt object if no options supplied
	if ( ! opt) { opt = {}; }

	// Global Options: not specific to Behat */
	if (typeof opt.debug === 'undefined') { opt.debug = false; }
	if (typeof opt.clear === 'undefined') { opt.clear = false; }
	if (typeof opt.flags === 'undefined') { opt.flags = ''; }
	if (typeof opt.silent === 'undefined') { opt.silent = false; }
	if (typeof opt.test === 'undefined') { opt.silent = true; option.debug = true}
	if (typeof opt.development === 'undefined') { opt.development = false; }

	// Behat Options: specific to Behat */
	if (typeof opt.format === 'undefined') { opt.format = ''; }       // --format='format'
	if (typeof opt.features === 'undefined') { opt.features = ''; }   // features='features'
	if (typeof opt.showTime === 'undefined') { opt.showTime = true; } // ==no-time
	if (typeof opt.ansi === 'undefined') { opt.ansi = true; }         // --no-ansi
	if (typeof opt.showPaths === 'undefined') { opt.showPaths = true; } // --no-paths
	if (typeof opt.multiline === 'undefined') { opt.multiline = true; } // ==multiline
	if (typeof opt.expand === 'undefined') { opt.expand = true; } // --no-expand
	if (typeof opt.definitions === 'undefined') { opt.definitions = '-d'; } // ==definitions="=d"
	if (typeof opt.name === 'undefined') { opt.name = ''; }  // --name
	if (typeof opt.tags === 'undefined') { opt.tags = ''; }  // --tags
	if (typeof opt.strict === 'undefined') { opt.strict = false; } // --strict
	if (typeof opt.stopOnFail === 'undefined') { opt.stopOnFail = false; } // =-stop-on-failure
	if (typeof opt.configFile === 'undefined') { opt.configFile = ''; } // ==config='file'
	if (typeof opt.profile === 'undefined') { opt.profile = ''; } // --profile='profile'

	return map(function (file, cb) {

		// construct command
		var cmd = opt.clear ? 'clear && ' + command : command;

		if(counter === 0) {
			counter++;

			cmd += skipCmd + ' ' + opt.flags;

			cmd.trim(); // clean up any space remnants

			if (opt.debug) {
				gutil.log(gutil.colors.yellow('\n       *** Debug Cmd: ' + cmd + '***\n'));
			}

			if ( ! opt.development) {
				exec(cmd, function (error, stdout, stderr) {

				if (!opt.silent && stderr) {
					gutil.log(stderr);
				}

				if (stdout) {
					stdout = stdout.trim(); // Trim trailing cr-lf
				}

				if (!opt.silent && stdout) {
					gutil.log(stdout);
				}

				if(opt.debug && error) {
					gutil.log(error);
				}

				if (opt.notify) {
					cb(error, file);
				}
			}
			});
		}
	});

};

<commit_msg>integrated behat options<commit_after>/*jshint node:true */

/* options
 * --format=pretty|progress|html|failed
 ^ --ansi (default)
 * --no-ansi  (uses ansi:false)
 * --no-time  (uses time:true)
 */

'use strict';

var map   = require('map-stream'),
	gutil = require('gulp-util'),
	os    = require('os'),
	exec  = require('child_process').exec;

module.exports = function(command, opt){
	var counter = 0;
	var skipCmd = '';

	if (typeof command === 'object') {
		throw new Error('Invalid Behat Binary');
	}

	// if path to behat bin not supplied, use default vendor/bin path
	if(! command) {
		var ansi = '--ansi';

		command = './vendor/bin/behat';
		if (os.platform() === 'win32') {
			command = '.\\vendor\\bin\\behat';
		}
	}

	// create default opt object if no options supplied
	if ( ! opt) { opt = {}; }

	// Global Options: not specific to Behat */
	if (typeof opt.debug === 'undefined') { opt.debug = false; }
	if (typeof opt.clear === 'undefined') { opt.clear = false; }
	if (typeof opt.flags === 'undefined') { opt.flags = ''; }
	if (typeof opt.silent === 'undefined') { opt.silent = false; }
	if (typeof opt.test === 'undefined') { opt.silent = true; opt.debug = true}
	if (typeof opt.development === 'undefined') { opt.development = false; }

	// Behat Options: specific to Behat */
	if (typeof opt.format === 'undefined') { opt.format = ''; }             // --format='format'
	if (typeof opt.features === 'undefined') { opt.features = ''; }         // features='features'
	if (typeof opt.showTime === 'undefined') { opt.showTime = true; }       // --no-time
	if (typeof opt.ansi === 'undefined') { opt.ansi = true; }               // --no-ansi
	if (typeof opt.showPaths === 'undefined') { opt.showPaths = true; }     // --no-paths
	if (typeof opt.multiline === 'undefined') { opt.multiline = true; }     // --multiline
	if (typeof opt.expand === 'undefined') { opt.expand = true; }           // --no-expand
	if (typeof opt.definitions === 'undefined') { opt.definitions = '-d'; } // --definitions="=d"
	if (typeof opt.name === 'undefined') { opt.name = ''; }                 // --name
	if (typeof opt.tags === 'undefined') { opt.tags = ''; }                 // --tags
	if (typeof opt.strict === 'undefined') { opt.strict = false; }          // --strict
	if (typeof opt.stopOnFail === 'undefined') { opt.stopOnFail = false; }  // --stop-on-failure
	if (typeof opt.configFile === 'undefined') { opt.configFile = ''; }     // --config='file'
	if (typeof opt.profile === 'undefined') { opt.profile = ''; }           // --profile='profile'

	return map(function (file, cb) {

		// construct command
		var cmd = opt.clear ? 'clear && ' + command : command;

		// integrate options
		cmd = opt.ansi ? cmd += ' --ansi' : cmd += ' --no-ansi';
		cmd = opt.expand ? cmd += ' --expand' : cmd += ' --no-expand';
		cmd = opt.showTime ? cmd += ' --time' : cmd += ' --no-time';
		cmd = opt.showPaths ? cmd += ' --paths' : cmd += ' --no-paths';
		if(opt.strict) { cmd += '--strict' }
		if(opt.stopOnFail) { cmd += '--stop-on-failure' }
		if(opt.configFile != '') { cmd += '--config=' + opt.configFile }
		if(opt.profile != '') { cmd += '--config=' + opt.profile }

		if(counter === 0) {
			counter++;

			cmd += skipCmd + ' ' + opt.flags;

			cmd.trim(); // clean up any space remnants

			if (opt.debug) {
				gutil.log(gutil.colors.yellow('\n       *** Debug Cmd: ' + cmd + '***\n'));
			}

			if ( ! opt.development) {
				exec(cmd, function (error, stdout, stderr) {

					console.log(stdout);

					if (!opt.silent && stderr) {
						gutil.log(stderr);
					}

					if (stdout) {
						stdout = stdout.trim(); // Trim trailing cr-lf
					}

					if (!opt.silent && stdout) {
						gutil.log(stdout);
					}

					if (opt.debug && error) {
						gutil.log(error);
					}

					if (opt.notify) {
						cb(error, file);
					}

				});
			}
		}
	});

};

<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var Q = require('q');

var util = require('./lib/utility');
var Process = require('./lib/process');
var models = require('./lib/models');

/*globals */

/**
 * Kwantu workflow engine
 *
 * @constructor
 * @param {string} profile - Profile UUID
 * @param {Object} [config] - Workflow configuration
 * 	@param {string} config._id
 *	Workflow configuration / definition ID
 * @param {Object} [instance] - Workflow instance
 * 	@param {string} instance._id
 *	Workflow instance ID
 * @author Brent Gordon
 * @version 0.1.0
 *
 * @example new Workflow('1234', {})
 *
 *
 * @return {Object} new Workflow object
 *
 * @throws "ERROR: Message"
 *
 */

function Workflow(profile, app, config, instance){
	//
	var _this = this;
	// Profile ID validation checks
	if (profile === '' || profile === undefined) {
        throw new Error('A profile id is required.');
    } else if (typeof(profile) !== 'string') {
    	throw new Error('The profile id must be a javascript string.');
    } else {
    	_this.profile = profile || '';
    }
    // App ID validation checks
	if (app === '' || app === undefined) {
        throw new Error('A app id is required.');
    } else if (typeof(app) !== 'string') {
    	throw new Error('The app id must be a javascript string.');
    } else {
    	_this.app = app || '';
    }
    // Workflow configuration validation checks
    if (config === '' || config === undefined) {
    	throw new Error('A workflow configuration is required.');
    } else if (typeof(config) !== 'object') {
        _this.config = JSON.parse(config);
    } else {
    	_this.config = config;
    }
    // Workflow instance validation checks
    _this.instance = instance;
}

/**
 * Create a new workflow process.
 *
 * @example
 * Workflow.create();
 *
 * @return Success / error message with the newly created workflow processes
 * instance data.
 *
 */
Workflow.prototype.create = function(){
	//
	var _this = this;
	var deferred = Q.defer();
	if (_this.instance !== undefined) {
		var warn = util.warn('Instance already exists.', _this.instance)
		deferred.resolve(warn);
	} else {
		// Create the workflow processes instance object
		var model = models.instance();
		model._id = _this.profile + ':processes';
		model.version = _this.config.version;
		// Update the processes and subProcesses sections with defaults
		// model.processes[0].id = _this.config.processes[0]._id;
		// model.processes[0].seq = 1;
		_this.instance = model;
		var success = util.success('Workflow processes instance created successfully.', _this.instance);
		deferred.resolve(success);
	}
	return deferred.promise;
};

/**
 * Workflow process, this function executes and process within a workflow
 * configuration.
 *
 * @param {object} processId - the process id to process
 *
 * @example
 * Workflow.process();
 *
 * @return ''
 *
 */
Workflow.prototype.initialize = function(processId, inputData){
	// Re-assign this
	var _this = this;
	// Create the deffered object
	var deferred = Q.defer();
	var configProcess = [];
	// Check the passed in parameters
	if (processId !== '' && processId !== undefined) {
		// Get the current process config
		configProcess = _this.config.processes.filter(function(objProcess){
			if (objProcess._id === processId) {
				return objProcess;
			}
		});
		if (configProcess[0]._id === undefined) {
			var error = util.error('WF001', err);
			deferred.reject(error);
		}
	} else {
		configProcess.push(_this.config.processes[0]);
		processId = _this.config.processes[0]._id;
	}
	// Get the seq and array index for the process and sub-process
	var state = Process.state(_this, processId);
	var processIndex = state.processIndex;
	var processSeq = state.processSeq;
	var subProcessId = state.subProcessId;
	var subProcessIndex = state.subProcessIndex;
	var subProcessSeq = state.subProcessSeq;
	// Push the process object into the array
	var processModel = {
		"id": "",
      	"seq": 1,
      	"subProcesses": []
	}
	// 1. Update the process id and seq
	processModel.id = processId;
	processModel.seq = processSeq;
	_this.instance.processes.push(processModel);
	// 2. Complete all the process prerequisites
	Process.preRequisites(configProcess[0].prerequisites, _this).then(function(result){
		// Check if all pre-requisites were met
		if (result.complete === true) {
			// 3. Complete all the process pre-actions
			Process.preActions(configProcess[0].preActions, _this).then(function(result){
				// Check if all pre-actions were met
				if (result.complete) {
					// 4. Initialise the first sub-process
					Process.subProcess(processId, configProcess[0].subProcesses[0], inputData, _this).then(function(result){
						// Check if sub-process initialisation was successfull
						if (result.complete) {
							// 5. Update the subProcess section details in the processes model
							var subProcessModel = result.res;
							// _this.instance.processes[processIndex].subProcesses.push(subProcessModel);
							_this.instance.processes.filter(function(objProcess){
								if (objProcess.id === processId) {
									objProcess.subProcesses.push(subProcessModel);
								}
							});
							var success = util.success('Process: ' + _this.config.processes[0]._id + ' initialized successfully.');
							deferred.resolve(success);
						} else {
							var error = util.error('WF008');
							deferred.reject(error);
						}
					}).fail(function(err){
						var error = util.error('WF007', err);
						console.log(err);
						deferred.reject(error);
					});
				} else {
					var error = util.error('WF006');
					deferred.reject(error);
				}
			}).fail(function(err){
				var error = util.error('WF005', err);
				console.log(err);
				deferred.reject(error);
			});
		} else {
			var error = util.error('WF004');
			deferred.reject(error);
		}
	}).fail(function(err){
		var error = util.error('WF003', err);
		console.log(err);
		deferred.reject(error);
	});
	// Return the deffered promise object
	return deferred.promise;
};

Workflow.prototype.saveIndicator = function(){
	return 'Implementation pending..';
};

Workflow.prototype.transition = function(processId, subProcessId, stepId, transitionId, subProcessModel, nextStep, workflow){
	// Re-assign this
	var _this = this;
	// Create the deffered object
	var deferred = Q.defer();
	Process.transition(processId, subProcessId, stepId, transitionId, subProcessModel, nextStep, workflow).then(function(result){
		var success = util.success('Workflow transitioned to the next step successfully.', subProcessModel);
		deferred.resolve(success);
	}).fail(function(err){
		var error = util.error('WF003', err);
		console.log(err);
		deferred.reject(error);
	});
	// Return the deffered promise object
	return deferred.promise;
};

module.exports = Workflow;

<commit_msg>Updated to use native es6 promises<commit_after>'use strict';

var Promise = require('es6-promise').Promise;

var util = require('./lib/utility');
var Process = require('./lib/process');
var models = require('./lib/models');

/*globals */

/**
 * Kwantu workflow engine
 *
 * @constructor
 * @param {string} profile - Profile UUID
 * @param {Object} [config] - Workflow configuration
 * 	@param {string} config._id
 *	Workflow configuration / definition ID
 * @param {Object} [instance] - Workflow instance
 * 	@param {string} instance._id
 *	Workflow instance ID
 * @author Brent Gordon
 * @version 0.1.0
 *
 * @example new Workflow('1234', {})
 *
 *
 * @return {Object} new Workflow object
 *
 * @throws "ERROR: Message"
 *
 */

function Workflow(profile, app, config, instance){
	//
	var _this = this;
	// Profile ID validation checks
	if (profile === '' || profile === undefined) {
        throw new Error('A profile id is required.');
    } else if (typeof(profile) !== 'string') {
    	throw new Error('The profile id must be a javascript string.');
    } else {
    	_this.profile = profile || '';
    }
    // App ID validation checks
	if (app === '' || app === undefined) {
        throw new Error('An app id is required.');
    } else if (typeof(app) !== 'string') {
    	throw new Error('The app id must be a javascript string.');
    } else {
    	_this.app = app || '';
    }
    // Workflow configuration validation checks
    if (config === '' || config === undefined) {
    	throw new Error('A workflow configuration is required.');
    } else if (typeof(config) !== 'object') {
        _this.config = JSON.parse(config);
    } else {
    	_this.config = config;
    }
    // Workflow instance validation checks
    _this.instance = instance;
}

/**
 * Create a new workflow process.
 *
 * @example
 * Workflow.create();
 *
 * @return Success / error message with the newly created workflow processes
 * instance data.
 *
 */
Workflow.prototype.create = function(){
	//
	var _this = this;
	// Use the native es6 Promise constructor
	return new Promise(function(resolve, reject) {
		if (_this.instance !== undefined) {
			var warn = util.warn('Instance already exists.', _this.instance)
			resolve(warn);
		} else {
			// Create the workflow processes instance object
			var model = models.instance();
			model._id = _this.profile + ':processes';
			model.version = _this.config.version;
			// Update the processes and subProcesses sections with defaults
			// model.processes[0].id = _this.config.processes[0]._id;
			// model.processes[0].seq = 1;
			_this.instance = model;
			var success = util.success('Workflow processes instance created successfully.', _this.instance);
			resolve(success);
		}
	});
};

/**
 * Workflow initialize, this function executes a process within a workflow
 * configuration.
 *
 * @param {string} processId - the process id to process
 * @param {object} inputData - the input data to process
 *
 * @example
 * Workflow.initialize('processId', { validDate: 'date' });
 *
 * @return
 * { complete: true, message: 'Process: 'processId' initialized successfully.', res: undefined }
 *
 */
Workflow.prototype.initialize = function(processId, inputData){
	// Re-assign this
	var _this = this;
	// Use the native es6 Promise constructor
	return new Promise(function(resolve, reject) {
		var configProcess = [];
		// Check the passed in parameters
		if (processId !== '' && processId !== undefined) {
			// Get the current process config
			configProcess = _this.config.processes.filter(function(objProcess){
				if (objProcess._id === processId) {
					return objProcess;
				}
			});
			if (configProcess[0]._id === undefined) {
				var error = util.error('WF001', err);
				reject(error);
			}
		} else {
			configProcess.push(_this.config.processes[0]);
			processId = _this.config.processes[0]._id;
		}
		// Get the current list of process instances
		var processSeq = 1;
		var currentProcess = [];
		currentProcess = _this.instance.processes.filter(function(objProcess){
			if (objProcess.id === processId) {
				return objProcess;
			}
		});
		var currentSeq = currentProcess.length;
		var nextSeq = currentSeq + 1;
		// Push the process object into the array
		var processModel = {
			"id": "",
	      	"seq": nextSeq,
	      	"subProcesses": []
		}
		// 1. Update the process id and seq
		processModel.id = processId;
		processModel.seq = processSeq;
		_this.instance.processes.push(processModel);
		// 2. Complete all the process prerequisites
		Process.preRequisites(configProcess[0].prerequisites, _this).then(function(result){
			// Check if all pre-requisites were met
			if (result.complete === true) {
				// 3. Complete all the process pre-actions
				Process.preActions(configProcess[0].preActions, _this).then(function(result){
					// Check if all pre-actions were met
					if (result.complete) {
						// 4. Initialise the first sub-process
						Process.subProcess(processId, configProcess[0].subProcesses[0], 1, inputData, _this).then(function(result){
							// Check if sub-process initialisation was successfull
							if (result.complete) {
								// 5. Update the subProcess section details in the processes model
								var subProcessModel = result.res;
								// _this.instance.processes[processIndex].subProcesses.push(subProcessModel);
								_this.instance.processes.filter(function(objProcess){
									if (objProcess.id === processId) {
										objProcess.subProcesses.push(subProcessModel);
									}
								});
								var success = util.success('Process: ' + _this.config.processes[0]._id + ' initialized successfully.');
								resolve(success);
							} else {
								var error = util.error('WF008');
								reject(error);
							}
						}).fail(function(err){
							reject(err);
						});
					} else {
						var error = util.error('WF006');
						reject(error);
					}
				}).fail(function(err){
					reject(err);
				});
			} else {
				var error = util.error('WF004');
				reject(error);
			}
		}).fail(function(err){
			reject(err);
		});
	});
};

Workflow.prototype.task = function(type, params){
	// Re-assign this
	var _this = this;
	// Use the native es6 Promise constructor
	return new Promise(function(resolve, reject) {
		if (type === 'indicator.markComplete') {
			resolve('Success');
		} else {
			reject('Error');
		}
	});
};

Workflow.prototype.transition = function(processId, subProcessId, stepId, transitionId, subProcessModel, workflow){
	// Re-assign this
	var _this = this;
	// Use the native es6 Promise constructor
	return new Promise(function(resolve, reject) {
		Process.transition(processId, subProcessId, stepId, transitionId, subProcessModel, workflow).then(function(result){
			var success = util.success('Workflow transitioned to the next step successfully.', subProcessModel);
			resolve(success);
		}).fail(function(err){
			reject(err);
		});
	});
};

module.exports = Workflow;

<|endoftext|>


<commit_before>var path  = require('path');
var fs    = require('fs');
var EOL   = require('os').EOL;
var async = require('async');

var through = require('through2');
var gutil   = require('gulp-util');

module.exports = function (options) {
  options = options || {};

  var SECTION_START_REGEX = /<!--\s*build:(css|js)(?:\(([^\)]+?)\))?\s+(\/?([^\s]+?))\s*-->/gim;
  var SECTION_END_REGEX   = /<!--\s*endbuild\s*-->/gim;
  var SECTION_JS_REGEX    = /<\s*script\s+.*?src\s*=\s*"([^"]+?)".*?><\s*\/\s*script\s*>/gi;
  var SECTION_CSS_REGEX   = /<\s*link\s+.*?href\s*=\s*"([^"]+)".*?>/gi;

  var fileRegex = {
    js : SECTION_JS_REGEX,
    css: SECTION_CSS_REGEX
  }

  if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(searchString, position) {
        var subjectString = this.toString();
        if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
          position = subjectString.length;
        }
        position -= searchString.length;
        var lastIndex = subjectString.indexOf(searchString, position);
        return lastIndex !== -1 && lastIndex === position;
    };
  }

  function createSection(section) {
    return {
      name         : section[4],
      original     : section[0],
      fileType     : section[1],
      alternatePath: section[2],
      outName      : section[3],
      content      : section[5]
    }
  }

  function fileToRef(file) {
    if(file.path.endsWith('.js')) {
      return '<script src="' + file.path + '"></script>';
    }
    else if(file.path.endsWith('.css')) {
      return '<link rel="stylesheet" href="' + file.path + '"/>';
    }
    throw 'File type not supported for ' + file.path
  }

  function parseSectionFiles(section, reg, pathInfo) {
    var files = [];

    processFilePath = function(a, b) {
      filePath    = path.join(pathInfo.alternatePath || pathInfo.mainPath, b)
      fileContent = new Buffer(fs.readFileSync(filePath));

      files.push(new gutil.File({
        path    : b,
        contents: fileContent
      }));
    }

    section.content
      .replace(/<!--(?:(?:.|\r|\n)*?)-->/gim, '')
      .replace(reg, processFilePath)

    return files
  }

  function transformSectionFiles(section, files, onTaskDone) {
    var processor = options[section.name]
    var result    = []

    if (!processor) {
      onTaskDone(null, [section.content])
      return
    }

    function onData(file) {
      result.push(fileToRef(file))
    }

    function onEnd() {
      processor.removeListener('on', onData)
      onTaskDone(null, section.original + result.join('\n'))
    }

    processor.on('data', onData)
    processor.on('end', onEnd)
    files.forEach(processor.write.bind(processor))
    processor.end();
  }

  function processHtml(file, pathInfo, onDone) {

    var sectionsRaw = String(file.contents).split(SECTION_END_REGEX);
    var resultTasks    = [];

    sectionsRaw.forEach(function(sectionRaw) {
      resultTasks.push(function(onTaskDone) {

        // Not a valid section, append to result
        if (!sectionRaw.match(SECTION_START_REGEX)) {
          onTaskDone(null, sectionRaw)
          return
        }

        var section      = createSection(sectionRaw.split(SECTION_START_REGEX));
        var sectionFiles = parseSectionFiles(section, fileRegex[section.fileType], pathInfo);
        transformSectionFiles(section, sectionFiles, onTaskDone);
      });
    });

    async.parallel(resultTasks, function(err, results) {
      onDone(results.join(''))
    });
  }

  return through.obj(function (file, enc, callback) {

    if (file.isNull()) {
      this.push(file);
      callback();
      return;
    }

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-indexpipe', 'Streams are not supported!'));
      callback();
      return
    }

    var pathInfo = {
      basePath: file.base,
      mainPath: path.dirname(file.path),
      mainName: path.basename(file.path),
    }

    function onDone(content) {
      var file = new gutil.File({
        path    : path.join(path.relative(pathInfo.basePath, pathInfo.mainPath), pathInfo.mainName),
        contents: new Buffer(content)
      })

      this.push(file)
      callback();
    }

    processHtml(file, pathInfo, onDone.bind(this));
  });
};
<commit_msg>Respect relative paths<commit_after>var path  = require('path');
var fs    = require('fs');
var EOL   = require('os').EOL;
var async = require('async');

var through = require('through2');
var gutil   = require('gulp-util');

module.exports = function (options) {
  options = options || {};

  var SECTION_START_REGEX = /<!--\s*build:(css|js)(?:\(([^\)]+?)\))?\s+(\/?([^\s]+?))\s*-->/gim;
  var SECTION_END_REGEX   = /<!--\s*endbuild\s*-->/gim;
  var SECTION_JS_REGEX    = /<\s*script\s+.*?src\s*=\s*"([^"]+?)".*?><\s*\/\s*script\s*>/gi;
  var SECTION_CSS_REGEX   = /<\s*link\s+.*?href\s*=\s*"([^"]+)".*?>/gi;

  var fileRegex = {
    js : SECTION_JS_REGEX,
    css: SECTION_CSS_REGEX
  }

  if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(searchString, position) {
        var subjectString = this.toString();
        if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
          position = subjectString.length;
        }
        position -= searchString.length;
        var lastIndex = subjectString.indexOf(searchString, position);
        return lastIndex !== -1 && lastIndex === position;
    };
  }

  function createSection(section) {
    return {
      name         : section[4],
      original     : section[0],
      fileType     : section[1],
      alternatePath: section[2],
      outName      : section[3],
      content      : section[5]
    }
  }

  function fileToRef(file) {
    if(file.path.endsWith('.js')) {
      return '<script src="' + file.relative + '"></script>';
    }
    else if(file.path.endsWith('.css')) {
      return '<link rel="stylesheet" href="' + file.relative + '"/>';
    }
    throw 'File type not supported for ' + file.relative
  }

  function parseSectionFiles(section, reg, pathInfo) {
    var files = [];

    processFilePath = function(a, b) {
      filePath    = path.join(pathInfo.alternatePath || pathInfo.mainPath, b)
      fileContent = new Buffer(fs.readFileSync(filePath));

      files.push(new gutil.File({
        path    : b,
        contents: fileContent
      }));
    }

    section.content
      .replace(/<!--(?:(?:.|\r|\n)*?)-->/gim, '')
      .replace(reg, processFilePath)

    return files
  }

  function transformSectionFiles(section, files, onTaskDone) {
    var processor = options[section.name]
    var result    = []

    if (!processor) {
      onTaskDone(null, [section.content])
      return
    }

    function onData(file) {
      result.push(fileToRef(file))
    }

    function onEnd() {
      processor.removeListener('on', onData)
      onTaskDone(null, section.original + result.join('\n'))
    }

    processor.on('data', onData)
    processor.on('end', onEnd)
    files.forEach(processor.write.bind(processor))
    processor.end();
  }

  function processHtml(file, pathInfo, onDone) {

    var sectionsRaw = String(file.contents).split(SECTION_END_REGEX);
    var resultTasks    = [];

    sectionsRaw.forEach(function(sectionRaw) {
      resultTasks.push(function(onTaskDone) {

        // Not a valid section, append to result
        if (!sectionRaw.match(SECTION_START_REGEX)) {
          onTaskDone(null, sectionRaw)
          return
        }

        var section      = createSection(sectionRaw.split(SECTION_START_REGEX));
        var sectionFiles = parseSectionFiles(section, fileRegex[section.fileType], pathInfo);
        transformSectionFiles(section, sectionFiles, onTaskDone);
      });
    });

    async.parallel(resultTasks, function(err, results) {
      onDone(results.join(''))
    });
  }

  return through.obj(function (file, enc, callback) {

    if (file.isNull()) {
      this.push(file);
      callback();
      return;
    }

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-indexpipe', 'Streams are not supported!'));
      callback();
      return
    }

    var pathInfo = {
      basePath: file.base,
      mainPath: path.dirname(file.path),
      mainName: path.basename(file.path),
    }

    function onDone(content) {
      var file = new gutil.File({
        path    : path.join(path.relative(pathInfo.basePath, pathInfo.mainPath), pathInfo.mainName),
        contents: new Buffer(content)
      })

      this.push(file)
      callback();
    }

    processHtml(file, pathInfo, onDone.bind(this));
  });
};
<|endoftext|>


<commit_before>'use strict';

console.log('Loading function');

const doc = require('dynamodb-doc');
const crypto = require('crypto');
const Q = require('q');
const Entities = require('html-entities').XmlEntities;

const entities = new Entities();
const dynamo = new doc.DynamoDB();

exports.handler = (event, context, callback) => {
	//console.log('Received event:', JSON.stringify(event, null, 2));
	if (process.env.ignoreSecurity || validate(event)) {

		var body = JSON.parse(event.body),
			bodyText = entities.decode(body.text),
			actionsRe = /<at>([^<]+)<\/at>\s{0,2}([+-]{2})|!(\w+)(?:\s+(\w+)="(.+?)")?/g,
			actions = [], action, reResult,
			resultPromisesArray = [];

		console.log('Parsed text:', bodyText);
		while((reResult = actionsRe.exec(bodyText)) !== null) {
            let action = { type: reResult[0] || '', teamid: body.channelData.teamsTeamId, caller: body.from };

			if (action.type.startsWith('<at>')) {
				let name = reResult[1];
				let op = reResult[2];
				let mention = body.entities.find(entity => { return entity.mentioned && entity.mentioned.name === name });

				if (mention) {
                    action.type = op || action.type;
                    action.userid = mention.mentioned.id;
                    action.name = mention.mentioned.name;
				}
			} else if (action.type.startsWith('!set')) {
                action.type = 'set';
                action.key = reResult[4];
                action.value = reResult[5];
                if (!action.key || !action.value) {
                    action.type = 'error'
                }
            } else if (action.type.startsWith('!')) {
                action.type = '!';
                action.key = reResult[3];
            }

            actions.push(action);
		}

		//console.log("Submitted actions:", actions);

		if (actions.length == 0) {
			sendHelp(context, callback);
			return;
		}

		actions.forEach(action => {
            logAction(action)
			switch (action.type) {
                case "set":
					resultPromisesArray.push(setBangAction(action));
					break;
				case "!":
					resultPromisesArray.push(bangAction(action));
					break;
				case "++":
					resultPromisesArray.push(increment(action));
					break;
				case "--":
					resultPromisesArray.push(increment(action));
			}
		}, this);

		Q.all(resultPromisesArray).fail(error => { console.error(error) }).done(results => {
			//console.log("final result: ", results);
			let response = results.join('
');

			callback(null, {
				statusCode: 200,
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ type: 'message', text: response })
			});
		});

	} else {
		callback(null, {
			statusCode: '401'
		});
	}

};

function bangAction(action) {
    let emoticon = '';

    switch(action.key) {
        case 'list':
            return getScoreList(action);
        case 'flip':
            emoticon = '(╯°Д°）╯︵ ┻━┻';
            break;
        case 'unflip':
            emoticon = '┬──┬ ノ( ゜-゜ノ)';
            break;
        case 'shrug':
            emoticon = '¯\\\\_(ツ)_/¯';
            break;
        case 'disapprove':
            emoticon = 'ಠ_ಠ';
            break;
        default:
            return getBangAction(action);
    }

    return Q(emoticon);
}

function getBangAction(action) {
	let params = {
		TableName: 'BangActions',
        Key: { "key": action.key, "teamid": action.teamid }
	};
	return Q.ninvoke(dynamo, "getItem", params)
		.then(data => {
			//console.log("Getting user for inc:", data);
			if (data.Item) {
                return data.Item.value;
            } else {
                return "Action not found.";
            }
		}).fail(error => {
			console.error('Error getting bang action:', error);
		});
}

function setBangAction(action) {
    let params = {
        TableName: 'BangActions',
        Item: {
            "creator": action.caller.id,
            "key": action.key,
            "value": action.value,
            "createtime": Date.now(),
            "teamid": action.teamid
        }
    };
    return Q.ninvoke(dynamo, "putItem", params)
        .then(data => {
            console.log("after put", data);
            return '!' + action.key + " is now \"" + action.value + "\"."
		}).fail(error => {
			console.error('Error setting bang action:', error);
		});
}

function getScoreList(action) {
	let params = {
		TableName: 'KarmaBot',
        KeyConditionExpression: "#t = :tid",
        ExpressionAttributeNames:{
            "#t": "teamid"
        },
        ExpressionAttributeValues: {
            ":tid":action.teamid
        }
	}

    //console.log("scan params:",params)

	return Q.ninvoke(dynamo, "query", params)
		.then(data => {
			//console.log("scan data:",data)
            let res = '';

            if (data.Items.length) {
                res += "
";

                // sorting by score
                data.Items.sort((a, b) => b.score - a.score);

                res += data.Items.reduce((acc, user) => {
                    return  acc += "
" + user.name + ": " + user.score + "
";
                }, '');

                res += "
";

            } else { res = "No one has karma :(" }
			//console.log("score list result:", res);
			return res;
		}).fail(error => {
			console.error('Error getting score list:', error);
		});
}

function increment(action) {
	let params = {
		TableName: 'KarmaBot',
        Key: { "userid": action.userid, "teamid": action.teamid }
	};

	return Q.ninvoke(dynamo, "getItem", params)
		.then(data => {
			//console.log("Getting user for inc:", data);
			if (data.Item) {
				let params = {
					TableName: 'KarmaBot',
					Key: { "userid": data.Item.userid, "teamid": data.Item.teamid },
					ExpressionAttributeNames: { "#S": "score", "#LS": "lastscore" },
					ExpressionAttributeValues: { ":s": action.type === "++" ? data.Item.score + 1 : data.Item.score - 1 , ":ls": Date.now() },
					ReturnValues: "ALL_NEW",
					UpdateExpression: "SET #S = :s, #LS = :ls"
				}

				//console.log("update params:", params);

				return Q.ninvoke(dynamo, "updateItem", params)
					.then(data => {
						//console.log("after update", data);
						return "<at>" + data.Attributes.name + "</at> has " + data.Attributes.score + " karma."
					});
			} else {
				let score = action.type === "++" ? 1 : -1;
                let friendlyName = action.name.split(', ').reverse().join(' ');
				let params = {
					TableName: 'KarmaBot',
					Item: {
						"userid": action.userid,
						"name": friendlyName,
						"score": score,
						"lastscore": Date.now(),
                        "teamid": action.teamid
					}
				};
				return Q.ninvoke(dynamo, "putItem", params)
					.then(data => {
						console.log("after put", data);
						return "<at>" + friendlyName + "</at> has " + score + " karma."
					});
			}
		}).fail(error => {
			console.error('Error updating:', error);
		});
}

function logAction(action) {
    let params = {
        TableName: 'KarmaBotActions',
        Item: {
            'userid': action.caller.id,
            'actiontime': Date.now(),
            'action': JSON.stringify(action)
        }
    };
    dynamo.putItem(params).send();
}

function sendHelp(context, callback) {
	let response = ["You can use the following commands: ",
					"
@user++ : to add a point to a user
",
					"
@user-- : to remove a point from a user
",
					"
!list    : to list the current score board
"
				   ].join('');

	callback(null, {
		statusCode: 200,
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ type: 'message', text: response })
	});
}

function stringToUtf8ByteArray(str) {
	 let out = [], p = 0;

	for (var i = 0; i < str.length; i++) {
		let c = str.charCodeAt(i);
		if (c < 128) {
			out[p++] = c;
		} else if (c < 2048) {
			out[p++] = (c >> 6) | 192;
			out[p++] = (c & 63) | 128;
		} else if (
			((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&
			((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {
			// Surrogate Pair
			c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
			out[p++] = (c >> 18) | 240;
			out[p++] = ((c >> 12) & 63) | 128;
			out[p++] = ((c >> 6) & 63) | 128;
			out[p++] = (c & 63) | 128;
		} else {
			out[p++] = (c >> 12) | 224;
			out[p++] = ((c >> 6) & 63) | 128;
			out[p++] = (c & 63) | 128;
		}
	}
	return out;
}

function validate(request) {
	let messageContent = request.body,
		authHeader = request.headers && request.headers.Authorization,
		claimedSenderId = request.queryStringParameters.id,
		signature, hash;

	if (!claimedSenderId) {
		console.log('Id not present on request', request);
		return false;
	}

	if (!authHeader) {
		console.log('Authentication header not provided', request);
		return false;
	}

	if (!authHeader.startsWith("HMAC ")) {
		console.log('Incorrect auth scheme', request);
		return false;
	}

	if (!messageContent) {
		console.log('Unable to validate authentication header for messages with empty body', request);
		return false;
	}

	signature = authHeader.substring(5);

	const secret = new Buffer(process.env[claimedSenderId], 'base64');
	const contentBytes = new Buffer(stringToUtf8ByteArray(messageContent));
	const hmac = crypto.createHmac('SHA256', secret);

	hmac.update(contentBytes);
	hash = hmac.digest('base64');

	if (hash == signature) {
		console.log("Authenticated!");
		return true;
	}

	console.log('AuthHeaderValueMismatch', "Expected:'" + hash + "' Provided:'" + signature + "'");
	return false;
}
<commit_msg>no more mixed tabs/spaces<commit_after>'use strict';

console.log('Loading function');

const doc = require('dynamodb-doc');
const crypto = require('crypto');
const Q = require('q');
const Entities = require('html-entities').XmlEntities;

const entities = new Entities();
const dynamo = new doc.DynamoDB();

exports.handler = (event, context, callback) => {
	//console.log('Received event:', JSON.stringify(event, null, 2));
	if (process.env.ignoreSecurity || validate(event)) {

		var body = JSON.parse(event.body),
			bodyText = entities.decode(body.text),
			actionsRe = /<at>([^<]+)<\/at>\s{0,2}([+-]{2})|!(\w+)(?:\s+(\w+)="(.+?)")?/g,
			actions = [], action, reResult,
			resultPromisesArray = [];

		console.log('Parsed text:', bodyText);
		while((reResult = actionsRe.exec(bodyText)) !== null) {
            let action = { type: reResult[0] || '', teamid: body.channelData.teamsTeamId, caller: body.from };

			if (action.type.startsWith('<at>')) {
				let name = reResult[1];
				let op = reResult[2];
				let mention = body.entities.find(entity => { return entity.mentioned && entity.mentioned.name === name });

				if (mention) {
					action.type = op || action.type;
					action.userid = mention.mentioned.id;
					action.name = mention.mentioned.name;
				}
			} else if (action.type.startsWith('!set')) {
				action.type = 'set';
				action.key = reResult[4];
				action.value = reResult[5];
				if (!action.key || !action.value) {
					action.type = 'error'
				}
			} else if (action.type.startsWith('!')) {
				action.type = '!';
				action.key = reResult[3];
			}

			actions.push(action);
		}

		//console.log("Submitted actions:", actions);

		if (actions.length == 0) {
			sendHelp(context, callback);
			return;
		}

		actions.forEach(action => {
			logAction(action)
			switch (action.type) {
				case "set":
					resultPromisesArray.push(setBangAction(action));
					break;
				case "!":
					resultPromisesArray.push(bangAction(action));
					break;
				case "++":
					resultPromisesArray.push(increment(action));
					break;
				case "--":
					resultPromisesArray.push(increment(action));
			}
		}, this);

		Q.all(resultPromisesArray).fail(error => { console.error(error) }).done(results => {
			//console.log("final result: ", results);
			let response = results.join('
');

			callback(null, {
				statusCode: 200,
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ type: 'message', text: response })
			});
		});

	} else {
		callback(null, {
			statusCode: '401'
		});
	}

};

function bangAction(action) {
	let emoticon = '';

	switch(action.key) {
		case 'list':
			return getScoreList(action);
		case 'flip':
			emoticon = '(╯°Д°）╯︵ ┻━┻';
			break;
		case 'unflip':
			emoticon = '┬──┬ ノ( ゜-゜ノ)';
			break;
		case 'shrug':
			emoticon = '¯\\\\_(ツ)_/¯';
			break;
		case 'disapprove':
			emoticon = 'ಠ_ಠ';
			break;
		default:
			return getBangAction(action);
	}

	return Q(emoticon);
}

function getBangAction(action) {
	let params = {
		TableName: 'BangActions',
		Key: { "key": action.key, "teamid": action.teamid }
	};
	return Q.ninvoke(dynamo, "getItem", params)
		.then(data => {
			//console.log("Getting user for inc:", data);
			if (data.Item) {
				return data.Item.value;
			} else {
				return "Action not found.";
			}
		}).fail(error => {
			console.error('Error getting bang action:', error);
		});
}

function setBangAction(action) {
	let params = {
		TableName: 'BangActions',
		Item: {
			"creator": action.caller.id,
			"key": action.key,
			"value": action.value,
			"createtime": Date.now(),
			"teamid": action.teamid
		}
	};
	return Q.ninvoke(dynamo, "putItem", params)
		.then(data => {
			console.log("after put", data);
			return '!' + action.key + " is now \"" + action.value + "\"."
		}).fail(error => {
			console.error('Error setting bang action:', error);
		});
}

function getScoreList(action) {
	let params = {
		TableName: 'KarmaBot',
		KeyConditionExpression: "#t = :tid",
		ExpressionAttributeNames:{
			"#t": "teamid"
		},
		ExpressionAttributeValues: {
			":tid":action.teamid
		}
	}

    //console.log("scan params:",params)

	return Q.ninvoke(dynamo, "query", params)
		.then(data => {
			//console.log("scan data:",data)
			let res = '';

			if (data.Items.length) {
				res += "
";

				// sorting by score
				data.Items.sort((a, b) => b.score - a.score);

				res += data.Items.reduce((acc, user) => {
					return  acc += "
" + user.name + ": " + user.score + "
";
				}, '');

				res += "
";

			} else { res = "No one has karma :(" }
			//console.log("score list result:", res);
			return res;
		}).fail(error => {
			console.error('Error getting score list:', error);
		});
}

function increment(action) {
	let params = {
		TableName: 'KarmaBot',
		Key: { "userid": action.userid, "teamid": action.teamid }
	};

	return Q.ninvoke(dynamo, "getItem", params)
		.then(data => {
			//console.log("Getting user for inc:", data);
			if (data.Item) {
				let params = {
					TableName: 'KarmaBot',
					Key: { "userid": data.Item.userid, "teamid": data.Item.teamid },
					ExpressionAttributeNames: { "#S": "score", "#LS": "lastscore" },
					ExpressionAttributeValues: { ":s": action.type === "++" ? data.Item.score + 1 : data.Item.score - 1 , ":ls": Date.now() },
					ReturnValues: "ALL_NEW",
					UpdateExpression: "SET #S = :s, #LS = :ls"
				}

				//console.log("update params:", params);

				return Q.ninvoke(dynamo, "updateItem", params)
					.then(data => {
						//console.log("after update", data);
						return "<at>" + data.Attributes.name + "</at> has " + data.Attributes.score + " karma."
					});
			} else {
				let score = action.type === "++" ? 1 : -1;
				let friendlyName = action.name.split(', ').reverse().join(' ');
				let params = {
					TableName: 'KarmaBot',
					Item: {
						"userid": action.userid,
						"name": friendlyName,
						"score": score,
						"lastscore": Date.now(),
						"teamid": action.teamid
					}
				};
				return Q.ninvoke(dynamo, "putItem", params)
					.then(data => {
						console.log("after put", data);
						return "<at>" + friendlyName + "</at> has " + score + " karma."
					});
			}
		}).fail(error => {
			console.error('Error updating:', error);
		});
}

function logAction(action) {
	let params = {
		TableName: 'KarmaBotActions',
		Item: {
			'userid': action.caller.id,
			'actiontime': Date.now(),
			'action': JSON.stringify(action)
		}
	};
	dynamo.putItem(params).send();
}

function sendHelp(context, callback) {
	let response = ["You can use the following commands: ",
					"
@user++ : to add a point to a user
",
					"
@user-- : to remove a point from a user
",
					"
!list    : to list the current score board
"
				   ].join('');

	callback(null, {
		statusCode: 200,
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ type: 'message', text: response })
	});
}

function stringToUtf8ByteArray(str) {
	let out = [], p = 0;

	for (var i = 0; i < str.length; i++) {
		let c = str.charCodeAt(i);
		if (c < 128) {
			out[p++] = c;
		} else if (c < 2048) {
			out[p++] = (c >> 6) | 192;
			out[p++] = (c & 63) | 128;
		} else if (
			((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&
			((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {
			// Surrogate Pair
			c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
			out[p++] = (c >> 18) | 240;
			out[p++] = ((c >> 12) & 63) | 128;
			out[p++] = ((c >> 6) & 63) | 128;
			out[p++] = (c & 63) | 128;
		} else {
			out[p++] = (c >> 12) | 224;
			out[p++] = ((c >> 6) & 63) | 128;
			out[p++] = (c & 63) | 128;
		}
	}
	return out;
}

function validate(request) {
	let messageContent = request.body,
		authHeader = request.headers && request.headers.Authorization,
		claimedSenderId = request.queryStringParameters.id,
		signature, hash;

	if (!claimedSenderId) {
		console.log('Id not present on request', request);
		return false;
	}

	if (!authHeader) {
		console.log('Authentication header not provided', request);
		return false;
	}

	if (!authHeader.startsWith("HMAC ")) {
		console.log('Incorrect auth scheme', request);
		return false;
	}

	if (!messageContent) {
		console.log('Unable to validate authentication header for messages with empty body', request);
		return false;
	}

	signature = authHeader.substring(5);

	const secret = new Buffer(process.env[claimedSenderId], 'base64');
	const contentBytes = new Buffer(stringToUtf8ByteArray(messageContent));
	const hmac = crypto.createHmac('SHA256', secret);

	hmac.update(contentBytes);
	hash = hmac.digest('base64');

	if (hash == signature) {
		console.log("Authenticated!");
		return true;
	}

	console.log('AuthHeaderValueMismatch', "Expected:'" + hash + "' Provided:'" + signature + "'");
	return false;
}
<|endoftext|>


<commit_before>var config = require(__dirname + '/config/config.js');
var data   = require("ripple-gateway-data-sequelize");
var ripple = require(__dirname +'/lib/ripple/');

/** @module Api */
var api = require('require-all-to-camel')(__dirname+'/lib/api/');

module.exports = {
  config: config,
  ripple: ripple,
  data: data,
  api: api
};

<commit_msg>[CHORE] update the sequelize adapter dependency location<commit_after>var config = require(__dirname + '/config/config.js');
var data   = require(__dirname +'/lib/data/');
var ripple = require(__dirname +'/lib/ripple/');

/** @module Api */
var api = require('require-all-to-camel')(__dirname+'/lib/api/');

module.exports = {
  config: config,
  ripple: ripple,
  data: data,
  api: api
};

<|endoftext|>


<commit_before>module.exports = require('../lib');<commit_msg>Oops :p<commit_after>module.exports = require('./lib');<|endoftext|>