<commit_before>const telegraf = require('telegraf');
const fs = require('fs');
const cd = require('./cdHomeFunction.js');
const ls = require('./lsFunction.js');
const cdReturnBack = require('./cdReturnBack.js');
const cdRute = require('./cdRute.js');
const getFile = require('./getFile');
const situation = require('./situation.js');

const TOKEN = process.env.TOKEN;
const bot = new telegraf(TOKEN);

let situationsValue = ' ';
let aux = ' ';
let cd_aux;
let count;
let countGet;

bot.on('text', function (ctx) {
  const instruction = ctx.update.message.text;
  count = instruction.split('cd /');
  countGet = instruction.split('get ');

  if(count[0] === '') {
    cd_aux = count[1];
    console.log(cd_aux);
  }else if(countGet[0] === '') {
    cd_aux = 'get';
    console.log(cd_aux);
  }else {
    cd_aux = instruction;
  }
  console.log(ctx.update.message.text);
  console.log(cd_aux);

  if(countGet[0] === '') {
    situationsValue = situation(ctx.update.message.text, aux);
  }else {
    situationsValue = situation(cd_aux, aux);
  }
  aux = situationsValue;
  console.log(aux);

  switch(cd_aux) {
    case 'cd':
      ctx.reply(situationsValue);
      cd(function (error, data){
        if(error){
          console.error('error', error);
        }else {
          data.forEach(function (file){
            ctx.reply(file);
          });
        }
      });
    break;

    case 'cd ..':
      ctx.reply(situationsValue);
      cdReturnBack(situationsValue, function(error, data) {
        if(error) {
          console.error('error', error);
        }else {
          data.forEach(function (file) {
            ctx.reply(file);
          });
        }
      });
    break;

    case 'get':
      ctx.reply(situationsValue);
      bot.telegram.sendDocument('11150012', {
        source: fs.createReadStream(getFile(situationsValue))
      });

    break;

    case 'ls':
      ctx.reply(situationsValue);
      ls(situationsValue, function (error, data) {
        if(error){
          console.error('error', error);
          ctx.reply('Path:' + situationsValue + ' incorrecto, introduzca cd u otra ruta para seguir');
        }else {
          data.forEach(function (file) {
            ctx.reply(file);
          });
        }
      });
    break;

    default:
      ctx.reply(situationsValue);
      cdRute(situationsValue, function (error, data) {
        if(error){
          console.error('error', error);
          ctx.reply('Path:' + ctx.update.message.text + ' no existe');
        }else{
          data.forEach(function (file){
            ctx.reply(file);
          });
        }
      });
    break;
  }
})

bot.startPolling();
<commit_msg>getFile ya devuelve fichero en su formato correcto sin .dat<commit_after>const telegraf = require('telegraf');
const fs = require('fs');
const cd = require('./cdHomeFunction.js');
const ls = require('./lsFunction.js');
const cdReturnBack = require('./cdReturnBack.js');
const cdRute = require('./cdRute.js');
const getFile = require('./getFile');
const situation = require('./situation.js');

const TOKEN = process.env.TOKEN;
const bot = new telegraf(TOKEN);

let situationsValue = ' ';
let aux = ' ';
let cd_aux;
let count;
let countGet;

bot.on('text', function (ctx) {
  const instruction = ctx.update.message.text;
  count = instruction.split('cd /');
  countGet = instruction.split('get ');

  if(count[0] === '') {
    cd_aux = count[1];
    console.log(cd_aux);
  }else if(countGet[0] === '') {
    cd_aux = 'get';
    console.log(cd_aux);
  }else {
    cd_aux = instruction;
  }
  console.log(ctx.update.message.text);
  console.log(cd_aux);

  if(countGet[0] === '') {
    situationsValue = situation(ctx.update.message.text, aux);
  }else {
    situationsValue = situation(cd_aux, aux);
  }
  aux = situationsValue;
  console.log(aux);

  switch(cd_aux) {
    case 'cd':
      ctx.reply(situationsValue);
      cd(function (error, data){
        if(error){
          console.error('error', error);
        }else {
          data.forEach(function (file){
            ctx.reply(file);
          });
        }
      });
    break;

    case 'cd ..':
      ctx.reply(situationsValue);
      cdReturnBack(situationsValue, function(error, data) {
        if(error) {
          console.error('error', error);
        }else {
          data.forEach(function (file) {
            ctx.reply(file);
          });
        }
      });
    break;

    case 'get':
      ctx.reply(situationsValue);
      bot.telegram.sendDocument('11150012', {
        source: getFile(situationsValue)
      });

    break;

    case 'ls':
      ctx.reply(situationsValue);
      ls(situationsValue, function (error, data) {
        if(error){
          console.error('error', error);
          ctx.reply('Path:' + situationsValue + ' incorrecto, introduzca cd u otra ruta para seguir');
        }else {
          data.forEach(function (file) {
            ctx.reply(file);
          });
        }
      });
    break;

    default:
      ctx.reply(situationsValue);
      cdRute(situationsValue, function (error, data) {
        if(error){
          console.error('error', error);
          ctx.reply('Path:' + ctx.update.message.text + ' no existe');
        }else{
          data.forEach(function (file){
            ctx.reply(file);
          });
        }
      });
    break;
  }
})

bot.startPolling();
<|endoftext|>


<commit_before>var url = require('url');

/**
 * Github image tag
 *
 * Syntax:
 *   {% img_p slug [title]%}
 */
hexo.extend.tag.register('img_p', function(args){
    var classes = args[1] || "";
    var imgAttr = args[2] || "{}";
    var slug = args[0] || "";

    var PostAsset = ctx.model('PostAsset');

    var asset = PostAsset.findOne({post: this._id, slug: slug});

    classes = classes.split(',');
    imgAttr = JSON.parse(imgAttr);

    imgAttr.src   = githubResourceUrl + imageId;
    imgAttr.class = classes.join(' ');

    return '';

});<commit_msg>updates<commit_after>var url = require('url');

/**
 * Github image tag
 *
 * Syntax:
 *   {% img_p slug [title]%}
 */
hexo.extend.tag.register('img_p', function(args, ctx){
    var classes = args[1] || "";
    var imgAttr = args[2] || "{}";
    var slug = args[0] || "";

    var PostAsset = ctx.model('PostAsset');

    var asset = PostAsset.findOne({post: this._id, slug: slug});

    classes = classes.split(',');
    imgAttr = JSON.parse(imgAttr);

    imgAttr.src   = githubResourceUrl + imageId;
    imgAttr.class = classes.join(' ');

    return '';

});<|endoftext|>


<commit_before>'use strict';

var RNG = require('rng')

function first (o) {
  for(var k in o)
    return k
}

var create = module.exports = function (seed, cb) {
  var rng = new RNG.MT(seed)
  var l = 10000

  var heap = []
  var result
  var ended
  var queued = false

  function next () {
    if(queued) return
    queued = true
    if(ended) return

    rng.random() < 0.4 ? setImmediate(call) : setTimeout(call)

    function call() {

      queued = false

      var key = first(heap)
      var cb = heap[key]
      delete heap[key]
      if(cb) {
        try { cb() }
        catch (err) { return async.done(err) }
      }
      else return

      setImmediate(next)

    }
  }

  function async (cb) {
    return function () {
      var args = [].slice.call(arguments)
      var self = this
      function _cb () {
        return cb.apply(self, args)
      }

      if(rng.random() < 0.3)
        try { return _cb() }
        catch (err) { return async.done(err) }

      while (true) {
        var i = rng.range(0, 0xffff)
        if(!heap[i]) {
          heap[i] = _cb
          break;
        }
      }

      next ()

    }
  }

  async.through = function () {
    return function (read) {
      return function (abort, cb) {
        read(abort, async(cb))
      }
    }
  }

  process.on('exit', forgot)
  process.setMaxListeners(Infinity)

  function forgot () {
    async.done(new Error('never called'))
  }

  async.done = function (err, value) {
    if(ended) return
    ended = true
    if(result) {
      result.passed = false
      result.calls ++
      result.error = result.error || new Error('called done twice')
      return
    }

    process.removeListener('exit', forgot)

    result = {
      error: err,
      value: value,
      passed: !err,
      calls: 1,
      seed: seed
    }

    if(cb) cb(err, result)
    else if(err) throw err
    else console.log(result)
  }

  return async
}

create.test = function (test, cb) {
  function run (seed, cb) {
    var async = create(seed, cb)
    test(async)
  }

  var seed = +process.env.INTLVS
  if('number' === typeof seed) {
    return run(seed, function (err, result) {
      if(cb) return cb(err, result)
      else if(err) {
        //DO NOT allow anything to swallow this error.
        console.error(err.stack)
        process.exit(1)
      }
      else console.log(result || 'passed')
    })
  }

  var total = process.env.INTLVR || 100
  var n = total, results = []

  for( var i = 0; i < total; i++)
    (function (i) {

      run(i, function (err, result) {
        if(err) result.error = err
        results[i] = result
        done()
      })

    })(i)

  function done () {
    if(--n) return

    var stats = {
      passes: 0,
      total: results.length,
      failures: 0,
      errors: 0
    }
    var err = null, seed

    results.forEach(function (e) {
      if((!e.error) && e.calls === 1)
        stats.passes ++
      else {
        if(seed == null) seed = e.seed
        if(err == null)  err = e.error
        stats.failures ++
      }
      if(e.calls > 1)
        stats.errors ++
    })

    if(stats.failures) {
      var message =
        '(interleavings: failed ' + stats.failures
      + ' out of ' + stats.total
      + ', first failing seed: ' + seed + ')'

      if(!err) err = new Error(message)
      err.message = err.message + '\n  ' + message
    }
    if(cb) cb(err, results, stats)
    else if(err) {
      //DO NOT allow anything to swallow this error.
      console.error(err.stack)
      process.exit(1)
    }
    else console.log(stats)
  }
}

if(!module.parent) {

  var async = create(Date.now())

  async(function () {
    console.log(1)
  }) ()
  async(function () {
    console.log(2)
  }) ()
  async(function () {
    console.log(3)
  }) ()

}
<commit_msg>test seed properly<commit_after>'use strict';

var RNG = require('rng')

function first (o) {
  for(var k in o)
    return k
}

var create = module.exports = function (seed, cb) {
  var rng = new RNG.MT(seed)
  var l = 10000

  var heap = []
  var result
  var ended
  var queued = false

  function next () {
    if(queued) return
    queued = true
    if(ended) return

    rng.random() < 0.4 ? setImmediate(call) : setTimeout(call)

    function call() {

      queued = false

      var key = first(heap)
      var cb = heap[key]
      delete heap[key]
      if(cb) {
        try { cb() }
        catch (err) { return async.done(err) }
      }
      else return

      setImmediate(next)

    }
  }

  function async (cb) {
    return function () {
      var args = [].slice.call(arguments)
      var self = this
      function _cb () {
        return cb.apply(self, args)
      }

      if(rng.random() < 0.3)
        try { return _cb() }
        catch (err) { return async.done(err) }

      while (true) {
        var i = rng.range(0, 0xffff)
        if(!heap[i]) {
          heap[i] = _cb
          break;
        }
      }

      next ()

    }
  }

  async.through = function () {
    return function (read) {
      return function (abort, cb) {
        read(abort, async(cb))
      }
    }
  }

  process.on('exit', forgot)
  process.setMaxListeners(Infinity)

  function forgot () {
    async.done(new Error('never called'))
  }

  async.done = function (err, value) {
    if(ended) return
    ended = true
    if(result) {
      result.passed = false
      result.calls ++
      result.error = result.error || new Error('called done twice')
      return
    }

    process.removeListener('exit', forgot)

    result = {
      error: err,
      value: value,
      passed: !err,
      calls: 1,
      seed: seed
    }

    if(cb) cb(err, result)
    else if(err) throw err
    else console.log(result)
  }

  return async
}

create.test = function (test, cb) {
  function run (seed, cb) {
    var async = create(seed, cb)
    test(async)
  }

  var seed = +process.env.INTLVS
  if(!isNaN(seed)) {
    return run(seed, function (err, result) {
      if(cb) return cb(err, result)
      else if(err) {
        //DO NOT allow anything to swallow this error.
        console.error(err.stack)
        process.exit(1)
      }
      else console.log(result || 'passed')
    })
  }

  var total = process.env.INTLVR || 100
  var n = total, results = []

  for( var i = 0; i < total; i++)
    (function (i) {

      run(i, function (err, result) {
        if(err) result.error = err
        results[i] = result
        done()
      })

    })(i)

  function done () {
    if(--n) return

    var stats = {
      passes: 0,
      total: results.length,
      failures: 0,
      errors: 0
    }
    var err = null, seed

    results.forEach(function (e) {
      if((!e.error) && e.calls === 1)
        stats.passes ++
      else {
        if(seed == null) seed = e.seed
        if(err == null)  err = e.error
        stats.failures ++
      }
      if(e.calls > 1)
        stats.errors ++
    })

    if(stats.failures) {
      var message =
        '(interleavings: failed ' + stats.failures
      + ' out of ' + stats.total
      + ', first failing seed: ' + seed + ')'

      if(!err) err = new Error(message)
      err.message = err.message + '\n  ' + message
    }
    if(cb) cb(err, results, stats)
    else if(err) {
      //DO NOT allow anything to swallow this error.
      console.error(err.stack)
      process.exit(1)
    }
    else console.log(stats)
  }
}

if(!module.parent) {

  var async = create(Date.now())

  async(function () {
    console.log(1)
  }) ()
  async(function () {
    console.log(2)
  }) ()
  async(function () {
    console.log(3)
  }) ()

}
<|endoftext|>


<commit_before>
var React = require('react')
var ReactDOMServer = require('react-dom/server')
var inject = require('connect-inject')
var path = require('path')
var fs = require('fs')
var layout
var View = require('./view')

function getComponent(file){
    var r = require(file);
    if(r.__esModule && r.default){
        return r.default
    } else {
        return r
    }
}

function cleanOptions(options){
    var opts = options
    delete opts['settings']
    delete opts['_locals']
    delete opts['_csrf']
    delete opts['enrouten']
    delete opts['cache']
    return opts
}

function handler(html, name, options){
    var script = [
        '',
        ''
    ].join('\n')
    return html.replace('', script + '')

}

exports = module.exports = loader = {
    setLayout: function(l) { layout = l },
    list : [],
    view: View,
    initJSX : function(){
        return require('node-jsx').install();
    },

    engine : function (filePath, options, callback){
        delete require.cache[require.resolve(filePath)]

        if(layout){
            var layoutPath = path.join(options.settings.views, layout)
            delete require.cache[require.resolve(layoutPath)]
            var Layout = getComponent(layoutPath)
        }

        var client = getComponent(filePath)

  	if(options.noHashes){
		var render = ReactDOMServer.renderToStaticMarkup
	} else {
		var render = ReactDOMServer.renderToString
	}

        var name = filePath.replace(options.settings.views+'/', '');
        var data = cleanOptions(options)
        var clientApp = React.createFactory(client)(data)
        var Template = Layout ? React.createFactory(Layout)(data, clientApp) : clientApp
        var markup = render(Template)
        markup = '<!DOCTYPE html>' + handler(markup, name, options)

        return callback(null, markup)
    }

}
<commit_msg>adding comma to array<commit_after>
var React = require('react')
var ReactDOMServer = require('react-dom/server')
var inject = require('connect-inject')
var path = require('path')
var fs = require('fs')
var layout
var View = require('./view')

function getComponent(file){
    var r = require(file);
    if(r.__esModule && r.default){
        return r.default
    } else {
        return r
    }
}

function cleanOptions(options){
    var opts = options
    delete opts['settings']
    delete opts['_locals']
    delete opts['_csrf']
    delete opts['enrouten']
    delete opts['cache']
    return opts
}

function handler(html, name, options){
    var script = [
        '',
        ''
    ].join('\n')
    return html.replace('', script + '')

}

exports = module.exports = loader = {
    setLayout: function(l) { layout = l },
    list : [],
    view: View,
    initJSX : function(){
        return require('node-jsx').install();
    },

    engine : function (filePath, options, callback){
        delete require.cache[require.resolve(filePath)]

        if(layout){
            var layoutPath = path.join(options.settings.views, layout)
            delete require.cache[require.resolve(layoutPath)]
            var Layout = getComponent(layoutPath)
        }

        var client = getComponent(filePath)

  	if(options.noHashes){
		var render = ReactDOMServer.renderToStaticMarkup
	} else {
		var render = ReactDOMServer.renderToString
	}

        var name = filePath.replace(options.settings.views+'/', '');
        var data = cleanOptions(options)
        var clientApp = React.createFactory(client)(data)
        var Template = Layout ? React.createFactory(Layout)(data, clientApp) : clientApp
        var markup = render(Template)
        markup = '<!DOCTYPE html>' + handler(markup, name, options)

        return callback(null, markup)
    }

}
<|endoftext|>


<commit_before>var bip39 = require("bip39");
var hdkey = require('ethereumjs-wallet/hdkey');
var ProviderEngine = require("web3-provider-engine");
var FiltersSubprovider = require('web3-provider-engine/subproviders/filters.js');
var WalletSubprovider = require('web3-provider-engine/subproviders/wallet.js');
var HookedSubprovider = require('web3-provider-engine/subproviders/hooked-wallet.js');
var Web3Subprovider = require("web3-provider-engine/subproviders/web3.js");
var Web3 = require("web3");
var Transaction = require('ethereumjs-tx');

function HDWalletProvider(mnemonic, provider_url, address_index=0, num_addresses=1) {
  this.mnemonic = mnemonic;
  this.hdwallet = hdkey.fromMasterSeed(bip39.mnemonicToSeed(mnemonic));
  this.wallet_hdpath = "m/44'/60'/0'/0/";
  this.wallets = {};
  this.addresses = [];

  for (let i = 0; i < num_addresses; i++){
    var wallet = this.hdwallet.derivePath(this.wallet_hdpath + i).getWallet();
    var addr = '0x' + wallet.getAddress().toString('hex');
    this.addresses.push(addr);
    this.wallets[addr] = wallet;
  }

  console.log('this.addresses!', this.addresses)
  const tmp_accounts = this.addresses;
  const tmp_wallets = this.wallets;

  this.engine = new ProviderEngine();
  this.engine.addProvider(new HookedSubprovider({
    getAccounts: function(cb) { cb(null, tmp_accounts) },
    getPrivateKey: function(address, cb) {
      if (!tmp_wallets[address]) { return cb('Account not found'); }
      else { cb(null, tmp_wallets[address].getPrivateKey().toString('hex')); }
    },
    signTransaction: function(txParams, cb, address) {
      let pkey = tmp_wallets[tmp_accounts[0]].getPrivateKey();
      if (address) {
        if (tmp_wallets[address]) { pkey = tmp_wallets[address].getPrivateKey(); }
        else { cb('Account not found'); }
      }
      var tx = new Transaction(txParams);
      tx.sign(pkey);
      var rawTx = '0x' + tx.serialize().toString('hex');
      cb(null, rawTx);
    }
  }));
  // this.engine.addProvider(new WalletSubprovider(this.wallets[this.addresses[0]], {}));
  this.engine.addProvider(new FiltersSubprovider());
  this.engine.addProvider(new Web3Subprovider(new Web3.providers.HttpProvider(provider_url)));
  this.engine.start(); // Required by the provider engine.
};

HDWalletProvider.prototype.sendAsync = function() {
  this.engine.sendAsync.apply(this.engine, arguments);
};

HDWalletProvider.prototype.send = function() {
  return this.engine.send.apply(this.engine, arguments);
};

// returns the address of the given address_index, first checking the cache
HDWalletProvider.prototype.getAddress = function(idx) {
  console.log('getting addresses', this.addresses[0], idx)
  if (!idx) { return this.addresses[0]; }
  else { return this.addresses[idx]; }
}

// returns the addresses cache
HDWalletProvider.prototype.getAddresses = function() {
  return this.addresses;
}

module.exports = HDWalletProvider;
<commit_msg>Just testing<commit_after>var bip39 = require("bip39");
var hdkey = require('ethereumjs-wallet/hdkey');
var ProviderEngine = require("web3-provider-engine");
var FiltersSubprovider = require('web3-provider-engine/subproviders/filters.js');
var WalletSubprovider = require('web3-provider-engine/subproviders/wallet.js');
var HookedSubprovider = require('web3-provider-engine/subproviders/hooked-wallet.js');
var Web3Subprovider = require("web3-provider-engine/subproviders/web3.js");
var Web3 = require("web3");
var Transaction = require('ethereumjs-tx');

function HDWalletProvider(mnemonic, provider_url, address_index=0, num_addresses=1) {
  this.mnemonic = mnemonic;
  this.hdwallet = hdkey.fromMasterSeed(bip39.mnemonicToSeed(mnemonic));
  this.wallet_hdpath = "m/44'/60'/0'/0/";
  this.wallets = {};
  this.addresses = [];

  for (let i = 0; i < num_addresses; i++){
    var wallet = this.hdwallet.derivePath(this.wallet_hdpath + i).getWallet();
    var addr = '0x' + wallet.getAddress().toString('hex');
    this.addresses.push(addr);
    this.wallets[addr] = wallet;
    console.log(wallet.getPrivateKey().toString('hex'))
  }

  const tmp_accounts = this.addresses;
  const tmp_wallets = this.wallets;

  this.engine = new ProviderEngine();
  this.engine.addProvider(new HookedSubprovider({
    getAccounts: function(cb) { cb(null, tmp_accounts) },
    getPrivateKey: function(address, cb) {
      if (!tmp_wallets[address]) { return cb('Account not found'); }
      else { cb(null, tmp_wallets[address].getPrivateKey().toString('hex')); }
    },
    signTransaction: function(txParams, cb, address) {
      let pkey = tmp_wallets[tmp_accounts[0]].getPrivateKey();
      if (address) {
        if (tmp_wallets[address]) { pkey = tmp_wallets[address].getPrivateKey(); }
        else { cb('Account not found'); }
      }
      var tx = new Transaction(txParams);
      tx.sign(pkey);
      var rawTx = '0x' + tx.serialize().toString('hex');
      cb(null, rawTx);
    }
  }));
  // this.engine.addProvider(new WalletSubprovider(this.wallets[this.addresses[0]], {}));
  this.engine.addProvider(new FiltersSubprovider());
  this.engine.addProvider(new Web3Subprovider(new Web3.providers.HttpProvider(provider_url)));
  this.engine.start(); // Required by the provider engine.
};

HDWalletProvider.prototype.sendAsync = function() {
  this.engine.sendAsync.apply(this.engine, arguments);
};

HDWalletProvider.prototype.send = function() {
  return this.engine.send.apply(this.engine, arguments);
};

// returns the address of the given address_index, first checking the cache
HDWalletProvider.prototype.getAddress = function(idx) {
  console.log('getting addresses', this.addresses[0], idx)
  if (!idx) { return this.addresses[0]; }
  else { return this.addresses[idx]; }
}

// returns the addresses cache
HDWalletProvider.prototype.getAddresses = function() {
  return this.addresses;
}

module.exports = HDWalletProvider;
<|endoftext|>


<commit_before>import express from 'express'
import mongoose from 'mongoose'
import winston from 'winston'
import courses from './api/courses'
import buildings from './api/buildings'

// Database connection setup
mongoose.connect(process.env.COBALT_MONGO_URI || 'mongodb://localhost/cobalt', err => {
  if (err) throw new Error(`Failed to connect to MongoDB [${process.env.COBALT_MONGO_URI}]: ${err.message}`)
  winston.debug('Connected to MongoDB')
})

// Express setup
let app = express()

// API routes
let apiVersion = '1.0'
app.use(`/${apiVersion}/courses`, courses)
app.use(`/${apiVersion}/buildings`, buildings)

// Error handlers
app.use((req, res, next) => {
  let err = new Error('Not Found')
  err.status = 404
  next(err)
})

app.use((err, req, res, next) => {
  res.status(err.status || 500)
  res.json({
    error: {
      code: err.status,
      message: err.message
    }
  })
})

export default app
<commit_msg>Error<commit_after>import express from 'express'
import mongoose from 'mongoose'
import winston from 'winston'
import courses from './api/courses'
import buildings from './api/buildings'

// Database connection setup
mongoose.connect(process.env.COBALT_MONGO_URI || 'mongodb://localhost/cobalt', err => {
  if (err) throw new Error(`Failed to connect to MongoDB [${process.env.COBALT_MONGO_URI}]: ${err.message}`)
  winston.debug('Connected to MongoDB')
})

// Express setup
let app = express()

// API routes
let apiVersion = '1.0'
app.use(`/${apiVersion}/courses`, courses)
app.use(`/${apiVersion}/buildings`, buildings)

// Error handlers
app.use((req, res, next) => {
  let err = new Error('Not Found')
  err.status = 404
  next(err)
})

app.use((err, req, res, next) => {
  res.status(err.status || 500)
  let error = {
    code: err.status,
    message: err.message
  }
  res.json({
    error: error
  })
})

export default app
<|endoftext|>


<commit_before>var express = require('express')
var http = require('http')
var path = require('path')
var reload = require('../lib/reload')
var fs = require('fs')
var open = require('open')
var clc = require('cli-color')
var argv = require('minimist')(process.argv.slice(2))

var app = express()

var port = argv._[0]
var dir = argv._[1]
var openBrowser = (argv._[2] === 'true')
var hostname = argv._[3]
var runFile = argv._[4]
var startPage = argv._[5]
var verbose = (argv._[6] === 'true')

var reloadOpts = {
  port: port,
  verbose: verbose
}

var router = express.Router()

app.set('port', port)

router.get('/', function (req, res, next) {
  // Create the start page path.
  var startFile = path.join(dir, startPage)

  fs.access(startFile, function (err) {
    // If the start page doesn't exist (whether it's the deault index.html or specified).
    if (err) {
      res.status(404).send("Can't find " + startPage)
    } else {
      // Else the start page exists send the reload-client code to the HTML.
      sendhtml(startFile, res)
    }
  })
})

// Routing for any HTML, so that we can send the reload-client file to every HTML page when naviagted too.
router.get('*.html', function (req, res) {
  // This wouldn't be efficient in any other context.
  var file = path.join(dir, req.url)
  sendhtml(file, res)
})

app.use('/', router)
app.use('*html', router)

app.use(express.static(dir)) // Should cache static assets.

var server = http.createServer(app)

// Reload call and configurations.
reload(app, reloadOpts, server)

server.listen(app.get('port'), function () {
  if (!fs.existsSync(runFile)) {
    fs.writeFile(runFile, '')

    // If openBrowser, open the browser with the given start page above, at a hostname (localhost default or specified).
    if (openBrowser) {
      open('http://' + hostname + ':' + app.get('port'))
    }
  } else {
    var time = new Date()
    console.log(clc.green('Server restarted  at ' + time.toTimeString().slice(0, 8)))
  }
})

// Function to send reload-client code to the browser.
function sendhtml (file, res) {
  fs.readFile(file, 'utf8', function (err, contents) {
    if (err) {
      console.error(err)
      process.exit(1)
    }

    contents += '\n\n<!-- Inserted by Reload -->\n<script src="/reload/reload.js"></script>\n<!-- End Reload -->\n'
    res.type('text/html')
    res.send(contents)
  })
}
<commit_msg>Updated deprecated call to writeFile replaced with writeFileSync.<commit_after>var express = require('express')
var http = require('http')
var path = require('path')
var reload = require('../lib/reload')
var fs = require('fs')
var open = require('open')
var clc = require('cli-color')
var argv = require('minimist')(process.argv.slice(2))

var app = express()

var port = argv._[0]
var dir = argv._[1]
var openBrowser = (argv._[2] === 'true')
var hostname = argv._[3]
var runFile = argv._[4]
var startPage = argv._[5]
var verbose = (argv._[6] === 'true')

var reloadOpts = {
  port: port,
  verbose: verbose
}

var time

var router = express.Router()

app.set('port', port)

router.get('/', function (req, res, next) {
  // Create the start page path.
  var startFile = path.join(dir, startPage)

  fs.access(startFile, function (err) {
    // If the start page doesn't exist (whether it's the deault index.html or specified).
    if (err) {
      res.status(404).send("Can't find " + startPage)
    } else {
      // Else the start page exists send the reload-client code to the HTML.
      sendhtml(startFile, res)
    }
  })
})

// Routing for any HTML, so that we can send the reload-client file to every HTML page when naviagted too.
router.get('*.html', function (req, res) {
  // This wouldn't be efficient in any other context.
  var file = path.join(dir, req.url)
  sendhtml(file, res)
})

app.use('/', router)
app.use('*html', router)

app.use(express.static(dir)) // Should cache static assets.

var server = http.createServer(app)

// Reload call and configurations.
reload(app, reloadOpts, server)

server.listen(app.get('port'), function () {
  if (!fs.existsSync(runFile)) {
    fs.writeFileSync(runFile)

    // If openBrowser, open the browser with the given start page above, at a hostname (localhost default or specified).
    if (openBrowser) {
      open('http://' + hostname + ':' + app.get('port'))
    }
  } else {
    time = new Date()
    console.log(clc.green('Server restarted  at ' + time.toTimeString().slice(0, 8)))
  }
})

// Function to send reload-client code to the browser.
function sendhtml (file, res) {
  fs.readFile(file, 'utf8', function (err, contents) {
    if (err) {
      console.error(err)
      process.exit(1)
    }

    contents += '\n\n<!-- Inserted by Reload -->\n<script src="/reload/reload.js"></script>\n<!-- End Reload -->\n'
    res.type('text/html')
    res.send(contents)
  })
}
<|endoftext|>


<commit_before>/*
Name:           bitonic
Description:    Node.js API wrapper for Bitonic.nl (unofficial)
License:        The Unlicense (see LICENSE file)
Author:         Franklin (https://fvdm.com)
Source & docs:  https://github.com/fvdm/nodejs-bitonic
*/

const { doRequest } = require ('httpreq');

// Defaults
const config = {
  timeout: 5000,
};

/**
 * Process httpreq response
 *
 * @param     {object}
 * @param     {Error|null}  err       httpreq Error
 * @param     {object}      res       httpreq response
 * @param     {function}    callback  `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function _httpResponse ({
  err,
  res,
  callback,
}) {
  let data;

  if (err) {
    callback (err);
    return;
  }

  data = JSON.parse (res.body);
  callback (null, data);
}

/**
 * Send API request
 *
 * @param     {string}    method    HTTP method, i.e. GET
 * @param     {string}    path      API path, i.e. /sell
 * @param     {function}  callback  `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function _httpRequest ({
  path,
  parameters = null,
  callback,
}) {
  const options = {
    method: 'GET',
    parameters,
    url: `https://bitonic.nl/api${path}`,
    timeout: config.timeout,
    headers: {
      'User-Agent': 'nodejs-bitonic (https://github.com/fvdm/nodejs-bitonic)',
    },
  };

    _httpResponse (err, res, callback);
  doRequest (options, (err, res) => {
  });
}

/**
 * Method: price.average
 *
 * @param     {function}  callback  `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function priceAverage (callback) {
  _httpRequest ({
    path: '/price',
    callback
  });
}

/**
 * Method: price.sell
 *
 * @param     {string}    from      Currency to convert from
 * @param     {number}    amount    Amount to convert
 * @param     {function}  callback  `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function priceSell (from, amount, callback) {
  const parameters = {};

  parameters[from] = amount;

  _httpRequest ({
    path: '/sell',
    parameters,
    callback
  });
}

/**
 * Method: price.buy
 *
 * @param     {string}    from            Currency to convert from
 * @param     {number}    amount          Amount to convert
 * @param     {string}    [method=ideal]  Payment method. `ideal` or `bancontact`
 * @param     {function}  callback        `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function priceBuy (from, amount, method, callback) {
  const parameters = {
    method,
  };

  parameters[from] = amount;

  _httpRequest ({
    path: '/buy',
    parameters,
    callback,
  });
}

/**
 * Package interface & config
 *
 * @param   {object}
 * @param   {number}  [timeout=5000]  Request timeout in ms
 *
 * @return  {object}                  Interface methods
 */

function setup ({
  timeout = 5000,
}) {
  let key;

  return {
    price: {
      buy: priceBuy,
      sell: priceSell,
      average: priceAverage,
    },
  };
}

module.exports = setup;
<commit_msg>Style(lint): Fixed dangling underscores<commit_after>/*
Name:           bitonic
Description:    Node.js API wrapper for Bitonic.nl (unofficial)
License:        The Unlicense (see LICENSE file)
Author:         Franklin (https://fvdm.com)
Source & docs:  https://github.com/fvdm/nodejs-bitonic
*/

const { doRequest } = require ('httpreq');

// Defaults
const config = {
  timeout: 5000,
};

/**
 * Process httpreq response
 *
 * @param     {object}
 * @param     {Error|null}  err       httpreq Error
 * @param     {object}      res       httpreq response
 * @param     {function}    callback  `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function httpResponse ({
  err,
  res,
  callback,
}) {
  let data;

  if (err) {
    callback (err);
    return;
  }

  data = JSON.parse (res.body);
  callback (null, data);
}

/**
 * Send API request
 *
 * @param     {string}    method    HTTP method, i.e. GET
 * @param     {string}    path      API path, i.e. /sell
 * @param     {function}  callback  `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function httpRequest ({
  path,
  parameters = null,
  callback,
}) {
  const options = {
    method: 'GET',
    parameters,
    url: `https://bitonic.nl/api${path}`,
    timeout: config.timeout,
    headers: {
      'User-Agent': 'nodejs-bitonic (https://github.com/fvdm/nodejs-bitonic)',
    },
  };

  doRequest (options, (err, res) => {
    httpResponse (err, res, callback);
  });
}

/**
 * Method: price.average
 *
 * @param     {function}  callback  `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function priceAverage (callback) {
  httpRequest ({
    path: '/price',
    callback
  });
}

/**
 * Method: price.sell
 *
 * @param     {string}    from      Currency to convert from
 * @param     {number}    amount    Amount to convert
 * @param     {function}  callback  `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function priceSell (from, amount, callback) {
  const parameters = {};

  parameters[from] = amount;

  httpRequest ({
    path: '/sell',
    parameters,
    callback
  });
}

/**
 * Method: price.buy
 *
 * @param     {string}    from            Currency to convert from
 * @param     {number}    amount          Amount to convert
 * @param     {string}    [method=ideal]  Payment method. `ideal` or `bancontact`
 * @param     {function}  callback        `(err, data)`
 *
 * @callback  callback
 * @return    {void}
 */

function priceBuy (from, amount, method, callback) {
  const parameters = {
    method,
  };

  parameters[from] = amount;

  httpRequest ({
    path: '/buy',
    parameters,
    callback,
  });
}

/**
 * Package interface & config
 *
 * @param   {object}
 * @param   {number}  [timeout=5000]  Request timeout in ms
 *
 * @return  {object}                  Interface methods
 */

function setup ({
  timeout = 5000,
}) {
  let key;

  return {
    price: {
      buy: priceBuy,
      sell: priceSell,
      average: priceAverage,
    },
  };
}

module.exports = setup;
<|endoftext|>


<commit_before>import domify from 'domify';
import merge from 'merge';
import user from '../user/user.js';
import t from 't-component';
import tagImages from '../tags/images.js';
import forumRouter from '../forum-router/forum-router';

/**
 * Render default modules
 */

export default function render(template, options) {
  var defaults = {
    user: user,
    t: t,
    tagImages: tagImages,
    config: config
  };

  return template(merge(defaults, options));
}

export function dom(template, options) {
  return domify(render(template, options));
}

/**
 * Alias dom method so it doesnt conflicts with 'component-dom' module.
 */

export { dom as domRender };
<commit_msg>remove unnecesary import<commit_after>import domify from 'domify';
import merge from 'merge';
import user from '../user/user.js';
import t from 't-component';
import tagImages from '../tags/images.js';
import config from '../config/config'

/**
 * Render default modules
 */

export default function render(template, options) {
  var defaults = {
    user: user,
    t: t,
    tagImages: tagImages,
    config: config
  };

  return template(merge(defaults, options));
}

export function dom(template, options) {
  return domify(render(template, options));
}

/**
 * Alias dom method so it doesnt conflicts with 'component-dom' module.
 */

export { dom as domRender };
<|endoftext|>


<commit_before>'use strict'

exports = module.exports = SSEBroadcaster

var http         = require('http'),
    assert       = require('assert'),
    inherits     = require('util').inherits,
    EventEmitter = require('events').EventEmitter,
    onFinished   = require('on-finished')

function SSEBroadcaster() {
    if (!(this instanceof SSEBroadcaster))
        return new SSEBroadcaster

    EventEmitter.call(this)
    this.rooms = {}
}

inherits(SSEBroadcaster, EventEmitter)

// static members
Object.defineProperties(exports, {
    Server: {
        enumerable: true,
        value: SSEBroadcaster
    },

    version: {
        enumerable: true,
        get: function () {
            return require(__dirname + '/package.json').version
        }
    },

    proto: {
        enumerable: true,
        value: extendResponseProto
    }
})

function noop() {}

/* instance methods */

SSEBroadcaster.prototype.subscribe = function subscribe(room, res) {
    var list = this.rooms[ room ]

    // room not exists, create it!
    if (!list)
        list = this.rooms[ room ] = []

    // already subscribed
    if (~list.indexOf(res))
        return

    // store the subscription
    list.push(res)

    // disable response buffering to
    // flush chunks immediately after writes
    res.socket.setNoDelay(true)
    // write SSE response headers
    if (!res.headersSent)
        res.writeHead(200, {
            'connection': 'keep-alive',
            'content-type': 'text/event-stream',
            'cache-control': 'no-cache'
        })
    else
        this.emit('warning', 'headers already sent', res)

    // unsubscribe automatically when the response has been finished
    onFinished(res, this.unsubscribe.bind(this, room, res))
}

SSEBroadcaster.prototype.unsubscribe = function unsubscribe(room, res) {
    var list = this.rooms[ room ]

    if (list) {
        // find the response object
        var i = list.indexOf(res)

        // remove if it's in the list
        if (~i)
            list.splice(i, 1)

        // remove room if empty
        if (!list.length)
            delete this.rooms[ room ]
    }
}

SSEBroadcaster.prototype._composeMessage = function _composeMessage(id, event, retry, data, callback) {
    var self    = this,
        message = 'event: ' + event + '\n'

    if (id)
        message += 'id: ' + id + '\n'

    if (!retry)
        retry = this.retry
    if (retry)
        message += 'retry: ' + retry + '\n'

    if (data) {
        // SSE supports string transfer only,
        // so try to serialize other types
        if (typeof data !== 'string') {
            if (data instanceof Buffer)
                data = data.toString('utf8')
            else try {
                // note: it throws if `data` contains a circular reference
                data = JSON.stringify(data)
            }
            catch (ex) {
                self.emit('error', ex)
                return callback(ex)
            }
        }

        message += 'data: ' + data + '\n'
    }

    // todo: optional compression
    callback(null, message += '\n')
}

/**
 * Send a message to all the subscribers of a given room.
 *
 * @param {string} room Name of the room.
 *
 * @param {string|object} eventOrOptions Event name or an options object that specifies the message.
 * @param {string} [eventOrOptions.id]    Optional event identifier.
 * @param {string} eventOrOptions.event   Event name.
 * @param {string} [eventOrOptions.data]  Optional event payload.
 * @param {string} [eventOrOptions.retry] Optional retry time for the receiver.
 *
 * @param {*} [data] Optional event payload.
 *
 * @param {function(Error?)} [callback]
 */
SSEBroadcaster.prototype.publish = function publish(room, eventOrOptions, data, callback) {
    var self = this

    assert(arguments.length >= 2, '`publish()` requires at least two arguments')
    assert.equal(typeof room, 'string', 'first argument must specify the room name')
    assert(eventOrOptions, 'second argument must specify the event name or options')

    if (typeof data === 'function') {
        callback = data
        data     = null
    }
    else if (!callback)
        callback = noop

    if (typeof eventOrOptions === 'object') {
        assert(!data, 'only one can be provided from `options` and `data`. Use `options.data` instead.')

        this._composeMessage(
            eventOrOptions.id,
            eventOrOptions.event,
            eventOrOptions.retry,
            eventOrOptions.data,
            oncomposed
        )
    }
    else if (typeof eventOrOptions === 'string')
        this._composeMessage(null, eventOrOptions, null, data, oncomposed)
    else
        assert.fail(
            typeof eventOrOptions, 'string or object',
            'second argument must specify the event name or options',
            '==='
        )

    function oncomposed(err, message) {
        if (err)
            return callback(err)

        var list = self.rooms[ room ]

        if (list) {
            var pending = list.length

            if (pending)
                list.forEach(function (res) {
                    res.write(message, function done() {
                        --pending || callback(null)
                    })
                })
            else
                process.nextTick(callback, null)
        }
    }
}

/* prototype extension helpers */

function extendResponseProto(broadcaster) {
    assert(
        broadcaster instanceof SSEBroadcaster,
        'prototype extension requires a broadcaster instance'
    )

    var proto = http.ServerResponse.prototype
    proto.subscribe   = subscribeProto(broadcaster)
    proto.unsubscribe = unsubscribeProto(broadcaster)
}

function subscribeProto(broadcaster) {
    return function subscribe(room) {
        broadcaster.subscribe(room, this)
    }
}

function unsubscribeProto(broadcaster) {
    return function unsubscribe(room) {
        broadcaster.unsubscribe(room, this)
    }
}
<commit_msg>add todo for tomorrow<commit_after>'use strict'

exports = module.exports = SSEBroadcaster

var http         = require('http'),
    assert       = require('assert'),
    inherits     = require('util').inherits,
    EventEmitter = require('events').EventEmitter,
    onFinished   = require('on-finished')

function SSEBroadcaster() {
    if (!(this instanceof SSEBroadcaster))
        return new SSEBroadcaster

    EventEmitter.call(this)
    this.rooms = {}
}

inherits(SSEBroadcaster, EventEmitter)

// static members
Object.defineProperties(exports, {
    Server: {
        enumerable: true,
        value: SSEBroadcaster
    },

    version: {
        enumerable: true,
        get: function () {
            return require(__dirname + '/package.json').version
        }
    },

    proto: {
        enumerable: true,
        value: extendResponseProto
    }
})

function noop() {}

/* instance methods */

SSEBroadcaster.prototype.subscribe = function subscribe(room, res) {
    var list = this.rooms[ room ]

    // room not exists, create it!
    if (!list)
        list = this.rooms[ room ] = []

    // already subscribed
    if (~list.indexOf(res))
        return

    // store the subscription
    list.push(res)

    // disable response buffering to
    // flush chunks immediately after writes
    res.socket.setNoDelay(true)
    // write SSE response headers
    if (!res.headersSent)
        res.writeHead(200, {
            'connection': 'keep-alive',
            'content-type': 'text/event-stream',
            'cache-control': 'no-cache'
        })
    else
        this.emit('warning', 'headers already sent', res)

    // unsubscribe automatically when the response has been finished
    onFinished(res, this.unsubscribe.bind(this, room, res))
}

SSEBroadcaster.prototype.unsubscribe = function unsubscribe(room, res) {
    var list = this.rooms[ room ]

    if (list) {
        // find the response object
        var i = list.indexOf(res)

        // remove if it's in the list
        if (~i)
            list.splice(i, 1)

        // remove room if empty
        if (!list.length)
            delete this.rooms[ room ]
    }
}

SSEBroadcaster.prototype._composeMessage = function _composeMessage(id, event, retry, data, callback) {
    var self    = this,
        message = 'event: ' + event + '\n'

    if (id)
        message += 'id: ' + id + '\n'

    if (!retry)
        retry = this.retry
    if (retry)
        message += 'retry: ' + retry + '\n'

    if (data) {
        // SSE supports string transfer only,
        // so try to serialize other types
        if (typeof data !== 'string') {
            if (data instanceof Buffer)
                data = data.toString('utf8')
            else try {
                // note: it throws if `data` contains a circular reference
                data = JSON.stringify(data)
            }
            catch (ex) {
                self.emit('error', ex)
                return callback(ex)
            }
        }

        message += 'data: ' + data + '\n'
    }

    // todo: optional compression
    // todo: compression requires 'content-encoding' header -> some refactor needed,
    //       because currently we're gonig to send headers on 'subscribe' but 'compression' module
    //       needs to manipulate headers later (is it sure?)
    callback(null, message += '\n')
}

/**
 * Send a message to all the subscribers of a given room.
 *
 * @param {string} room Name of the room.
 *
 * @param {string|object} eventOrOptions Event name or an options object that specifies the message.
 * @param {string} [eventOrOptions.id]    Optional event identifier.
 * @param {string} eventOrOptions.event   Event name.
 * @param {string} [eventOrOptions.data]  Optional event payload.
 * @param {string} [eventOrOptions.retry] Optional retry time for the receiver.
 *
 * @param {*} [data] Optional event payload.
 *
 * @param {function(Error?)} [callback]
 */
SSEBroadcaster.prototype.publish = function publish(room, eventOrOptions, data, callback) {
    var self = this

    assert(arguments.length >= 2, '`publish()` requires at least two arguments')
    assert.equal(typeof room, 'string', 'first argument must specify the room name')
    assert(eventOrOptions, 'second argument must specify the event name or options')

    if (typeof data === 'function') {
        callback = data
        data     = null
    }
    else if (!callback)
        callback = noop

    if (typeof eventOrOptions === 'object') {
        assert(!data, 'only one can be provided from `options` and `data`. Use `options.data` instead.')

        this._composeMessage(
            eventOrOptions.id,
            eventOrOptions.event,
            eventOrOptions.retry,
            eventOrOptions.data,
            oncomposed
        )
    }
    else if (typeof eventOrOptions === 'string')
        this._composeMessage(null, eventOrOptions, null, data, oncomposed)
    else
        assert.fail(
            typeof eventOrOptions, 'string or object',
            'second argument must specify the event name or options',
            '==='
        )

    function oncomposed(err, message) {
        if (err)
            return callback(err)

        var list = self.rooms[ room ]

        if (list) {
            var pending = list.length

            if (pending)
                list.forEach(function (res) {
                    res.write(message, function done() {
                        --pending || callback(null)
                    })
                })
            else
                process.nextTick(callback, null)
        }
    }
}

/* prototype extension helpers */

function extendResponseProto(broadcaster) {
    assert(
        broadcaster instanceof SSEBroadcaster,
        'prototype extension requires a broadcaster instance'
    )

    var proto = http.ServerResponse.prototype
    proto.subscribe   = subscribeProto(broadcaster)
    proto.unsubscribe = unsubscribeProto(broadcaster)
}

function subscribeProto(broadcaster) {
    return function subscribe(room) {
        broadcaster.subscribe(room, this)
    }
}

function unsubscribeProto(broadcaster) {
    return function unsubscribe(room) {
        broadcaster.unsubscribe(room, this)
    }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * serverless-mocha-plugin
 * - a plugin for TDD with serverless
 */

const path  = require('path'),
  fs        = require('fs'),
  lambdaWrapper = require('lambda-wrapper'),
  Mocha = require('mocha'),
  chai = require('chai'),
  Path = require('path'),
  BbPromise = require('bluebird'); // Serverless uses Bluebird Promises and we recommend you do to because they provide more than your average Promise :)

const testFolder = 'test'; // Folder used my mocha for tests

module.exports = function(S) { // Always pass in the ServerlessPlugin Class

  /**
   * Adding/Manipulating Serverless classes
   * - You can add or manipulate Serverless classes like this
   */

  S.classes.Project.newStaticMethod     = function() { console.log("A new method!"); };
  S.classes.Project.prototype.newMethod = function() { S.classes.Project.newStaticMethod(); };

  /**
   * Extending the Plugin Class
   * - Here is how you can add custom Actions and Hooks to Serverless.
   * - This class is only required if you want to add Actions and Hooks.
   */

  class PluginBoilerplate extends S.classes.Plugin {

    /**
     * Constructor
     * - Keep this and don't touch it unless you know what you're doing.
     */

    constructor() {
      super();
      this.name = 'io.sc5.mocha';
    }

    /**
     * Register Actions
     * - function mocha-create
     */

    registerActions() {

      S.addAction(this._createAction.bind(this), {
        handler:       '_createAction',
        description:   'Create mocha test for function',
        context:       'function',
        contextAction: 'mocha-create',
        options:       [{ // These must be specified in the CLI like this "-option true" or "-o true"
        }],
        parameters: [ // Use paths when you multiple values need to be input (like an array).  Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3.  Serverless will automatically turn this into an array and attach it to evt.options within your plugin
          {
            parameter: 'paths',
            description: 'Path to function to test. If not defined, test all functions.',
            position: '0->' // Can be: 0, 0-2, 0->  This tells Serverless which params are which.  3-> Means that number and infinite values after it.
          }
        ]
      });

      S.addAction(this._runAction.bind(this), {
        handler:       '_runAction',
        description:   'Create mocha test for function',
        context:       'function',
        contextAction: 'mocha-run',
        options:       [          {
            option:      'region',
            shortcut:    'r',
            description: 'region you want to run your function in'
          },
          {
            option:      'stage',
            shortcut:    's',
            description: 'stage you want to run your function in'
          },
          {
            option:      'reporter',
            shortcut:    'R',
            description: 'specify the reporter to use'
          },
          {
            option:      'reporter-options',
            shortcut:    'O',
            description: 'reporter-specific options'
          }],
        parameters: [ // Use paths when you multiple values need to be input (like an array).  Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3.  Serverless will automatically turn this into an array and attach it to evt.options within your plugin
          {
            parameter: 'paths',
            description: 'Path to function to test. If not defined, test all functions.',
            position: '0->' // Can be: 0, 0-2, 0->  This tells Serverless which params are which.  3-> Means that number and infinite values after it.
          }
        ]
      });

      return BbPromise.resolve();
    }

    /**
     * Register Hooks
     * -  function create (post) creates mocha test file
     */

    registerHooks() {
      S.addHook(this._hookPostFuncCreate.bind(this), {
        action: 'functionCreate',
        event:  'post'
      });

      return BbPromise.resolve();
    }

    /**
     * Custom action serverless function mocha-create functioName
     */

    _createAction(evt) {
      if (S.getProject().getFunction(evt.options.paths[0]) === undefined) {
        return new BbPromise(function(resolve, reject) {
          reject(`MochaPluginError: Function ${evt.options.paths[0]} does not exist in your project`);
        });
      }

      return createTest(evt.options.paths[0]);
    }

    /**
     * Custom action serverless function mocha-create functioName
     */

    _runAction(evt) {
      return new BbPromise(function(resolve, reject) {
          let funcName = evt.options.paths;
          let mocha = new Mocha();
          //This could pose as an issue if several functions share a common ENV name but different values.

          let stage = evt.options.stage || S.getProject().getAllStages()[0].name;
          let region = evt.options.region || S.getProject().getAllRegions(stage)[0].name;

          SetEnvVars(evt.options.paths, {
            stage: stage,
            region: region
          });

          getFilePaths(evt.options.paths)
          .then(function(paths) {
              paths.forEach(function(path,idx) {
                mocha.addFile(path);
              })
              var reporter = evt.options.reporter;
              if ( reporter !== null) {
                var reporterOptions = {};
                if (evt.options["reporter-options"] !== null) {
                  evt.options["reporter-options"].split(",").forEach(function(opt) {
                    var L = opt.split("=");
                    if (L.length > 2 || L.length === 0) {
                      throw new Error("invalid reporter option '" + opt + "'");
                    } else if (L.length === 2) {
                      reporterOptions[L[0]] = L[1];
                    } else {
                      reporterOptions[L[0]] = true;
                    }
                  });
                }
                mocha.reporter(reporter, reporterOptions)
              }
              mocha.run(function(failures){
                process.on('exit', function () {
                  process.exit(failures);  // exit with non-zero status if there were failures
                });
              });
          }, function(error) {

            return reject(error);
          });
      });
    }
    /**
     * Hook for creating the mocha test placeholder after function creation
     */

    _hookPostFuncCreate(evt) {
      // TODO: only run with runtime node4.3
      if (evt.options.runtime != 'nodejs4.3') {
        console.log(evt.options.runtime);
        return;
      }
      let parsedPath = path.parse(evt.options.path);
      let funcName = parsedPath.base;

      return createTest(funcName);
    }
  }

  //Set environment variables
  function SetEnvVars(paths, config) {
    paths.forEach(function(path, idx){
      var funcName = Path.basename(path, '.js');
      var func = S.getProject().getFunction(funcName).toObjectPopulated(config);
      var envVars = func.environment;
      var fields = Object.keys(envVars);

      for (var key in fields) {
        process.env[fields[key]] = envVars[fields[key]];
      }
    });
  }

  // Create the test folder
  function createTestFolder() {
      return new BbPromise(function(resolve, reject) {

        fs.exists(testFolder, function(exists) {
            if (exists) {
                return resolve(testFolder);
            }
            fs.mkdir(testFolder, function(err) {
                if (err) {
                    return reject(err);
                }
                return resolve(testFolder);
            })
        })
      });
  }

  // Create the test file (and test folder)

  function createTest(funcName) {
    return createTestFolder().then(function(testFolder) {
      return new BbPromise(function(resolve, reject) {
        let funcFilePath = testFilePath(funcName);
        let projectPath = S.getProject().getRootPath();
        let funcFullPath = S.getProject().getFunction(funcName).getRootPath();
        let funcPath = path.relative(projectPath, funcFullPath);

        fs.exists(funcFilePath, function (exists) {
           if (exists) {
               return reject(new Error(`File ${funcFilePath} already exists`));
           }
           fs.writeFile(funcFilePath, newTestFile(funcName, funcPath), function(err) {
               if (err) {
                   return reject(new Error(`Creating file ${funcFilePath} failed: ${err}`));
               }
               console.log(`serverless-mocha-plugin: created ${funcFilePath}`);
               return resolve(funcFilePath);
           })
        });
      });
    });
  }

  // getTestFiles. If no functions provided, returns all files
  function getFilePaths(funcs) {
    return new BbPromise(function(resolve, reject) {
        var paths = [];

        if (funcs && (funcs.length > 0)) {
            funcs.forEach(function(val, idx) {
                paths.push(testFilePath(val));
            });
            return resolve(paths);
        }
        // No funcs provided, list all test files
        fs.readdirSync(testFolder).filter(function(file){
          // Only keep the .js files
          return file.substr(-3) === '.js';
        }).forEach(function(file) {
            paths.push(path.join(testFolder, file));
        });
        return resolve(paths);
    });
  };

  // Returns the path to a function's test file
  function testFilePath(funcName) {
      return path.join(testFolder, `${funcName.replace(/.*\//g, '')}.js`);
  }

  function newTestFile(funcName, funcPath) {
      return `'use strict';
// tests for ${funcName}
// Generated by serverless-mocha-plugin

const mod         = require('../${funcPath}/handler.js');
const mochaPlugin = require('serverless-mocha-plugin');
const wrapper     = mochaPlugin.lambdaWrapper;
const expect      = mochaPlugin.chai.expect;

wrapper.init(mod);

describe('${funcName}', () => {
  it('implement tests here', (done) => {
    wrapper.run({}, (err, response) => {
      done('no tests implemented');
    });
  });
});
`;

  }
  // Export Plugin Class
  return PluginBoilerplate;
};

module.exports.lambdaWrapper = lambdaWrapper;
module.exports.chai = chai;
<commit_msg>Wrapper.init should be done in before method<commit_after>'use strict';

/**
 * serverless-mocha-plugin
 * - a plugin for TDD with serverless
 */

const path  = require('path'),
  fs        = require('fs'),
  lambdaWrapper = require('lambda-wrapper'),
  Mocha = require('mocha'),
  chai = require('chai'),
  Path = require('path'),
  BbPromise = require('bluebird'); // Serverless uses Bluebird Promises and we recommend you do to because they provide more than your average Promise :)

const testFolder = 'test'; // Folder used my mocha for tests

module.exports = function(S) { // Always pass in the ServerlessPlugin Class

  /**
   * Adding/Manipulating Serverless classes
   * - You can add or manipulate Serverless classes like this
   */

  S.classes.Project.newStaticMethod     = function() { console.log("A new method!"); };
  S.classes.Project.prototype.newMethod = function() { S.classes.Project.newStaticMethod(); };

  /**
   * Extending the Plugin Class
   * - Here is how you can add custom Actions and Hooks to Serverless.
   * - This class is only required if you want to add Actions and Hooks.
   */

  class PluginBoilerplate extends S.classes.Plugin {

    /**
     * Constructor
     * - Keep this and don't touch it unless you know what you're doing.
     */

    constructor() {
      super();
      this.name = 'io.sc5.mocha';
    }

    /**
     * Register Actions
     * - function mocha-create
     */

    registerActions() {

      S.addAction(this._createAction.bind(this), {
        handler:       '_createAction',
        description:   'Create mocha test for function',
        context:       'function',
        contextAction: 'mocha-create',
        options:       [{ // These must be specified in the CLI like this "-option true" or "-o true"
        }],
        parameters: [ // Use paths when you multiple values need to be input (like an array).  Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3.  Serverless will automatically turn this into an array and attach it to evt.options within your plugin
          {
            parameter: 'paths',
            description: 'Path to function to test. If not defined, test all functions.',
            position: '0->' // Can be: 0, 0-2, 0->  This tells Serverless which params are which.  3-> Means that number and infinite values after it.
          }
        ]
      });

      S.addAction(this._runAction.bind(this), {
        handler:       '_runAction',
        description:   'Create mocha test for function',
        context:       'function',
        contextAction: 'mocha-run',
        options:       [          {
            option:      'region',
            shortcut:    'r',
            description: 'region you want to run your function in'
          },
          {
            option:      'stage',
            shortcut:    's',
            description: 'stage you want to run your function in'
          },
          {
            option:      'reporter',
            shortcut:    'R',
            description: 'specify the reporter to use'
          },
          {
            option:      'reporter-options',
            shortcut:    'O',
            description: 'reporter-specific options'
          }],
        parameters: [ // Use paths when you multiple values need to be input (like an array).  Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3.  Serverless will automatically turn this into an array and attach it to evt.options within your plugin
          {
            parameter: 'paths',
            description: 'Path to function to test. If not defined, test all functions.',
            position: '0->' // Can be: 0, 0-2, 0->  This tells Serverless which params are which.  3-> Means that number and infinite values after it.
          }
        ]
      });

      return BbPromise.resolve();
    }

    /**
     * Register Hooks
     * -  function create (post) creates mocha test file
     */

    registerHooks() {
      S.addHook(this._hookPostFuncCreate.bind(this), {
        action: 'functionCreate',
        event:  'post'
      });

      return BbPromise.resolve();
    }

    /**
     * Custom action serverless function mocha-create functioName
     */

    _createAction(evt) {
      if (S.getProject().getFunction(evt.options.paths[0]) === undefined) {
        return new BbPromise(function(resolve, reject) {
          reject(`MochaPluginError: Function ${evt.options.paths[0]} does not exist in your project`);
        });
      }

      return createTest(evt.options.paths[0]);
    }

    /**
     * Custom action serverless function mocha-create functioName
     */

    _runAction(evt) {
      return new BbPromise(function(resolve, reject) {
          let funcName = evt.options.paths;
          let mocha = new Mocha();
          //This could pose as an issue if several functions share a common ENV name but different values.

          let stage = evt.options.stage || S.getProject().getAllStages()[0].name;
          let region = evt.options.region || S.getProject().getAllRegions(stage)[0].name;

          SetEnvVars(evt.options.paths, {
            stage: stage,
            region: region
          });

          getFilePaths(evt.options.paths)
          .then(function(paths) {
              paths.forEach(function(path,idx) {
                mocha.addFile(path);
              })
              var reporter = evt.options.reporter;
              if ( reporter !== null) {
                var reporterOptions = {};
                if (evt.options["reporter-options"] !== null) {
                  evt.options["reporter-options"].split(",").forEach(function(opt) {
                    var L = opt.split("=");
                    if (L.length > 2 || L.length === 0) {
                      throw new Error("invalid reporter option '" + opt + "'");
                    } else if (L.length === 2) {
                      reporterOptions[L[0]] = L[1];
                    } else {
                      reporterOptions[L[0]] = true;
                    }
                  });
                }
                mocha.reporter(reporter, reporterOptions)
              }
              mocha.run(function(failures){
                process.on('exit', function () {
                  process.exit(failures);  // exit with non-zero status if there were failures
                });
              });
          }, function(error) {

            return reject(error);
          });
      });
    }
    /**
     * Hook for creating the mocha test placeholder after function creation
     */

    _hookPostFuncCreate(evt) {
      // TODO: only run with runtime node4.3
      if (evt.options.runtime != 'nodejs4.3') {
        console.log(evt.options.runtime);
        return;
      }
      let parsedPath = path.parse(evt.options.path);
      let funcName = parsedPath.base;

      return createTest(funcName);
    }
  }

  //Set environment variables
  function SetEnvVars(paths, config) {
    paths.forEach(function(path, idx){
      var funcName = Path.basename(path, '.js');
      var func = S.getProject().getFunction(funcName).toObjectPopulated(config);
      var envVars = func.environment;
      var fields = Object.keys(envVars);

      for (var key in fields) {
        process.env[fields[key]] = envVars[fields[key]];
      }
    });
  }

  // Create the test folder
  function createTestFolder() {
      return new BbPromise(function(resolve, reject) {

        fs.exists(testFolder, function(exists) {
            if (exists) {
                return resolve(testFolder);
            }
            fs.mkdir(testFolder, function(err) {
                if (err) {
                    return reject(err);
                }
                return resolve(testFolder);
            })
        })
      });
  }

  // Create the test file (and test folder)

  function createTest(funcName) {
    return createTestFolder().then(function(testFolder) {
      return new BbPromise(function(resolve, reject) {
        let funcFilePath = testFilePath(funcName);
        let projectPath = S.getProject().getRootPath();
        let funcFullPath = S.getProject().getFunction(funcName).getRootPath();
        let funcPath = path.relative(projectPath, funcFullPath);

        fs.exists(funcFilePath, function (exists) {
           if (exists) {
               return reject(new Error(`File ${funcFilePath} already exists`));
           }
           fs.writeFile(funcFilePath, newTestFile(funcName, funcPath), function(err) {
               if (err) {
                   return reject(new Error(`Creating file ${funcFilePath} failed: ${err}`));
               }
               console.log(`serverless-mocha-plugin: created ${funcFilePath}`);
               return resolve(funcFilePath);
           })
        });
      });
    });
  }

  // getTestFiles. If no functions provided, returns all files
  function getFilePaths(funcs) {
    return new BbPromise(function(resolve, reject) {
        var paths = [];

        if (funcs && (funcs.length > 0)) {
            funcs.forEach(function(val, idx) {
                paths.push(testFilePath(val));
            });
            return resolve(paths);
        }
        // No funcs provided, list all test files
        fs.readdirSync(testFolder).filter(function(file){
          // Only keep the .js files
          return file.substr(-3) === '.js';
        }).forEach(function(file) {
            paths.push(path.join(testFolder, file));
        });
        return resolve(paths);
    });
  };

  // Returns the path to a function's test file
  function testFilePath(funcName) {
      return path.join(testFolder, `${funcName.replace(/.*\//g, '')}.js`);
  }

  function newTestFile(funcName, funcPath) {
      return `'use strict';
// tests for ${funcName}
// Generated by serverless-mocha-plugin

const mod         = require('../${funcPath}/handler.js');
const mochaPlugin = require('serverless-mocha-plugin');
const wrapper     = mochaPlugin.lambdaWrapper;
const expect      = mochaPlugin.chai.expect;

describe('${funcName}', () => {
  before(function (done) {
    wrapper.init(mod);

    done()
  })

  it('implement tests here', (done) => {
    wrapper.run({}, (err, response) => {
      done('no tests implemented');
    });
  });
});
`;

  }
  // Export Plugin Class
  return PluginBoilerplate;
};

module.exports.lambdaWrapper = lambdaWrapper;
module.exports.chai = chai;
<|endoftext|>


<commit_before>'use strict';
// var Lob = {};
// Lob.DEFAULT_HOST = 'api.Lob.com';
// Lob.DEFAULT_PORT = '443';
// Lob.DEFAULT_BASE_PATH = '/v1/';
// Lob.DEFAULT_API_VERSION = null;
//var USER_AGENT = 'Lob/node.js wrapper/1.0.0';

var Jobs = require('./jobs');
var Addresses = require('./addresses');
var Verification = require('./verification');
var Countries = require('./countries');
var States = require('./states');
var Objects = require('./objects');
var Settings = require('./settings');
var Services = require('./services');
var Postcards = require('./postcards');
var Checks = require('./checks');
var BankAccounts = require('./bankAccounts');
var Areas = require('./areas');
var Routes = require('./routes');

var Lob = function (apiKey) {
  if (typeof apiKey === 'string') {
    this.endpoint = 'https://api.lob.com/v1/';
    this.apiKey = apiKey;
  } else {
    throw new Error('API Key must be set');
  }
  this.jobs = new Jobs(this);
  this.addresses = new Addresses(this);
  this.verification = new Verification(this);
  this.states = new States(this);
  this.countries = new Countries(this);
  this.objects = new Objects(this);
  this.settings = new Settings(this);
  this.services = new Services(this);
  this.postcards = new Postcards(this);
  this.checks = new Checks(this);
  this.bankAccounts = new BankAccounts(this);
  this.areas = new Areas(this);
  this.routes = new Routes(this);
};

module.exports = Lob;
<commit_msg>Instantiate if this === undefined<commit_after>'use strict';
// var Lob = {};
// Lob.DEFAULT_HOST = 'api.Lob.com';
// Lob.DEFAULT_PORT = '443';
// Lob.DEFAULT_BASE_PATH = '/v1/';
// Lob.DEFAULT_API_VERSION = null;
//var USER_AGENT = 'Lob/node.js wrapper/1.0.0';

var Jobs = require('./jobs');
var Addresses = require('./addresses');
var Verification = require('./verification');
var Countries = require('./countries');
var States = require('./states');
var Objects = require('./objects');
var Settings = require('./settings');
var Services = require('./services');
var Postcards = require('./postcards');
var Checks = require('./checks');
var BankAccounts = require('./bankAccounts');
var Areas = require('./areas');
var Routes = require('./routes');

var Lob = function (apiKey) {
  if (this === undefined) {
    return new Lob(apiKey);
  }
  if (typeof apiKey === 'string') {
    this.endpoint = 'https://api.lob.com/v1/';
    this.apiKey = apiKey;
  } else {
    throw new Error('API Key must be set');
  }
  this.jobs = new Jobs(this);
  this.addresses = new Addresses(this);
  this.verification = new Verification(this);
  this.states = new States(this);
  this.countries = new Countries(this);
  this.objects = new Objects(this);
  this.settings = new Settings(this);
  this.services = new Services(this);
  this.postcards = new Postcards(this);
  this.checks = new Checks(this);
  this.bankAccounts = new BankAccounts(this);
  this.areas = new Areas(this);
  this.routes = new Routes(this);
};

module.exports = Lob;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017 AriyaLabs, LLC. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

module.exports = {
  'rules': {
    // The rules below are listed in the order they appear on the eslint
    // rules page. All rules are listed to make it easier to keep in sync
    // as new ESLint rules are added.
    // http://eslint.org/docs/rules/
    // - Rules in the `eslint:recommended` ruleset that aren't listed but commented out (so
    //   they don't override a base ruleset).
    // - Rules that are recommended but contradict Pier 1 Imports
    //   are explicitly set to the Pier 1 Imports value.

    // Possible Errors
    // http://eslint.org/docs/rules/#possible-errors
    // ---------------------------------------------
    // 'no-cond-assign': 2,
    'no-console': 1,
    // 'no-constant-condition': 2,
    // 'no-control-regex': 2,
    // 'no-debugger': 2,
    // 'no-dupe-args': 2,
    // 'no-dupe-keys': 2,
    // 'no-duplicate-case': 2,
    // 'no-empty-character-class': 2,
    // 'no-empty': 2,
    // 'no-ex-assign': 2,
    // 'no-extra-boolean-cast': 2,
    // 'no-extra-parens': 0,
    // 'no-extra-semi': 2,
    // 'no-func-assign': 2,
    // 'no-inner-declarations': 2,
    // 'no-invalid-regexp': 2,
    // 'no-irregular-whitespace': 2,
    // 'no-obj-calls': 2,
    // 'no-prototype-builtins': 0,
    // 'no-regex-spaces': 2,
    // 'no-sparse-arrays': 2,
    // 'no-template-curly-in-string': 0,
    // 'no-unexpected-multiline': 2,
    // 'no-unreachable': 2,
    // 'no-unsafe-finally': 2,
    // 'no-unsafe-negation': 0,
    // 'use-isnan': 2
    // 'valid-jsdoc': [
    //   1, {
    //     requireParamDescription: false,
    //     requireReturnDescription: false,
    //     requireReturn: false,
    //     prefer: { returns: 'return' },
    //   }
    // ],
    // 'valid-typeof': 2

    // Best Practices
    // http://eslint.org/docs/rules/#best-practices
    // --------------------------------------------

    // 'accessor-pairs': 0,
    // 'array-callback-return': 0,
    // 'block-scoped-var': 0,
    // 'class-methods-use-this': 0,
    // 'complexity': 0,
    // 'consistent-return': 0
    // 'curly': 0,
    // 'default-case': 0,
    // 'dot-location': 0,
    // 'dot-notation': 0,
    'eqeqeq': 2,
    'guard-for-in': 2,
    // 'no-alert': 0,
    'no-caller': 2,
    // 'no-case-declarations': 2,
    // 'no-div-regex': 0,
    // 'no-else-return': 0,
    // 'no-empty-function': 0,
    // 'no-empty-pattern': 2,
    // 'no-eq-null': 0,
    // 'no-eval': 0,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    // 'no-extra-label': 0,
    // 'no-fallthrough': 2,
    // 'no-floating-decimal': 0,
    // 'no-global-assign': 0,
    'no-implicit-coercion': 2,
    // 'no-implicit-globals': 0,
    // 'no-implied-eval': 0,
    'no-invalid-this': 1,
    // 'no-iterator': 0,
    // 'no-labels': 0,
    // 'no-lone-blocks': 0,
    // 'no-loop-func': 0,
    // 'no-magic-numbers': 0,
    'no-multi-spaces': 2,
    'no-multi-str': 0,
    // 'no-new-func': 0,
    'no-new-wrappers': 2,
    // 'no-new': 0,
    // 'no-octal-escape': 0,
    // 'no-octal': 2,
    'no-param-reassign': 2,
    // 'no-proto': 0,
    // 'no-redeclare': 2,
    // 'no-return-assign': 0,
    // 'no-script-url': 0,
    // 'no-self-assign': 2,
    // 'no-self-compare': 0,
    // 'no-sequences': 0,
    'no-throw-literal': 2,
    // 'no-unmodified-loop-condition': 0,
    // 'no-unused-expressions': 0,
    // 'no-unused-labels': 2,
    // 'no-useless-call': 0,
    // 'no-useless-concat': 0,
    // 'no-useless-escape': 0,
    // 'no-void': 0,
    // 'no-warning-comments': 0,
    'no-with': 2,
    // 'radix': 0,
    // 'vars-on-top': 0,
    // 'wrap-iife': 0,
    // 'yoda': 0,

    // Strict Mode
    // http://eslint.org/docs/rules/#strict-mode
    // -----------------------------------------
    // 'script': 0,

    // Variables
    // http://eslint.org/docs/rules/#variables
    // ---------------------------------------
    // 'init-declarations': 0,
    // 'no-catch-shadow': 0,
    // 'no-delete-var': 2,
    // 'no-label-var': 0,
    // 'no-restricted-globals': 0,
    // 'no-shadow-restricted-names': 0,
    // 'no-shadow': 0,
    // 'no-undef-init': 0,
    // 'no-undef': 2,
    // 'no-undefined': 0,
    'no-unused-vars': [
      1, {
        'vars': 'local',
        'args': 'none',
        'varsIgnorePattern': 'execute',
      },
    ],
    // 'no-use-before-define': 0,

    // Node.js and CommonJS
    // http://eslint.org/docs/rules/#nodejs-and-commonjs
    // -------------------------------------------------
    // 'callback-return': 0,
    // 'global-require': 0,
    // 'handle-callback-err': 0,
    // 'no-mixed-requires': 0,
    // 'no-new-require': 0,
    // 'no-path-concat': 0,
    // 'no-process-env': 0,
    // 'no-process-exit': 0,
    // 'no-restricted-modules': 0,
    // 'no-restricted-properties': 0,
    // 'no-sync': 0,

    // Stylistic Issues
    // http://eslint.org/docs/rules/#stylistic-issues
    // ----------------------------------------------
    'array-bracket-spacing': [2, 'never'],
    // 'block-spacing': 0,
    'brace-style': 0,
    'camelcase': [2, { properties: 'always' }],
    'comma-dangle': [2, {
      'arrays': 'always-multiline',
      'objects': 'always-multiline',
      'imports': 'always-multiline',
      'exports': 'always-multiline',
      'functions': 'always-multiline',
    }],
    'comma-spacing': 2,
    'comma-style': 2,
    'computed-property-spacing': 2,
    // 'consistent-this': 0,
    'eol-last': 2,
    'func-call-spacing': 2,
    // 'func-name-matching': 0,
    // 'func-names': 0,
    // 'func-style': 0,
    // 'id-blacklist': 0,
    // 'id-length': 0,
    // 'id-match': 0,
    'indent': [
      2,
      2,
      { "SwitchCase": 1 }
    ],
    // 'jsx-quotes': 0,
    'key-spacing': 2,
    'keyword-spacing': 2,
    // 'line-comment-position': 0,
    'linebreak-style': 0,
    // 'lines-around-comment': 0,
    // 'lines-around-directive': 0,
    // 'max-depth': 0,
    'max-len': 0,
    // 'max-lines': 0,
    // 'max-nested-callbacks': 0,
    // 'max-params': 0,
    // 'max-statements-per-line': 0,
    // 'max-statements': 0,
    // 'multiline-ternary': 0,
    'new-cap': [
      2, {
        'newIsCap': true,
        'capIsNew': false,
        'properties': true,
      },
    ],
    // 'new-parens': 0,
    // 'newline-after-var': 0,
    // 'newline-before-return': 0,
    // 'newline-per-chained-call': 0,
    'no-array-constructor': 2,
    // 'no-bitwise': 0,
    // 'no-continue': 0,
    // 'no-inline-comments': 0,
    // 'no-lonely-if': 0,
    // 'no-mixed-operators': 0,
    'no-mixed-spaces-and-tabs': 2,
    'no-multiple-empty-lines': [2, { max: 2 }],
    // 'no-negated-condition': 0,
    // 'no-nested-ternary': 0,
    'no-new-object': 2,
    // 'no-plusplus': 0,
    // 'no-restricted-syntax': 0,
    'no-tabs': 2,
    // 'no-ternary': 0,
    // 'no-trailing-spaces': 0,
    // 'no-underscore-dangle': 0,
    // 'no-unneeded-ternary': 0,
    // 'no-whitespace-before-property': 0,
    // 'object-curly-newline': 0,
    'object-curly-spacing': [2, 'always']
    // 'object-property-newline': 0,
    'one-var-declaration-per-line': [2, 'always'],
    'one-var': "off",
    // 'operator-assignment': 0,
    // 'operator-linebreak': 0,
    'padded-blocks': [2, 'never'],
    'quote-props': [2, 'consistent'],
    'quotes': [
      2,
      'single', { allowTemplateLiterals: true },
    ],
    // 'require-jsdoc': [
    //   1, {
    //     require: {
    //       FunctionDeclaration: true,
    //       MethodDefinition: true,
    //       ClassDeclaration: true,
    //     },
    //   }
    // ],
    'semi-spacing': 2,
    'semi': 2,
    // 'sort-keys': 0,
    // 'sort-vars': 0,
    'space-before-blocks': 2,
    'space-before-function-paren': [
      2, {
        'anonymous': 'always',
        'named': 'never',
        'asyncArrow': 'never',
      },
    ],
    // 'space-in-parens': 0,
    // 'space-infix-ops': 0,
    // 'space-unary-ops': 0,
    'spaced-comment': 0,
    // 'unicode-bom': 0,
    // 'wrap-regex': 0,

    // ECMAScript 6
    // http://eslint.org/docs/rules/#ecmascript-6
    // ------------------------------------------
    // 'arrow-body-style': 0,
    'arrow-parens': [0, 'always'],
    // 'arrow-spacing': 0,
    // 'constructor-super': 2,
    'generator-star-spacing': [2, 'after'],
    // 'no-class-assign': 0,
    // 'no-confusing-arrow': 0,
    // 'no-const-assign': 0,
    // 'no-dupe-class-members': 0,
    // 'no-duplicate-imports': 0,
    'no-new-symbol': 2,
    // 'no-restricted-imports': 0,
    // 'no-this-before-super': 2,
    // 'no-useless-computed-key': 0,
    // 'no-useless-constructor': 0,
    // 'no-useless-rename': 0,
    // 'no-var': 0,
    // 'object-shorthand': 0,
    // 'prefer-arrow-callback': 0,
    // 'prefer-const': 0,
    // 'prefer-numeric-literals': 0,
    // 'prefer-reflect': 0,
    // 'prefer-rest-params': 0,
    // 'prefer-spread': 0,
    // 'prefer-template': 0,
    // 'require-yield': 2,
    // 'rest-spread-spacing': 0,
    // 'sort-imports': 0,
    // 'symbol-description': 0,
    // 'template-curly-spacing': 0,
    'yield-star-spacing': [2, 'after'],
  },
  'plugins': [
    'eslint-plugin-react',
    'eslint-plugin-mocha',
  ],
  'parserOptions': {
    'ecmaFeatures': {
      'jsx': true,
    },
  },
  'env': {
    'browser': true,
    'commonjs': true,
    'es6': true,
    'jquery': true,
    'mocha': true,
    'node': true,
  },
  'globals': {},
  'parser': 'babel-eslint',
};
<commit_msg>Fix lint error<commit_after>/**
 * Copyright (c) 2017 AriyaLabs, LLC. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

module.exports = {
  'rules': {
    // The rules below are listed in the order they appear on the eslint
    // rules page. All rules are listed to make it easier to keep in sync
    // as new ESLint rules are added.
    // http://eslint.org/docs/rules/
    // - Rules in the `eslint:recommended` ruleset that aren't listed but commented out (so
    //   they don't override a base ruleset).
    // - Rules that are recommended but contradict Pier 1 Imports
    //   are explicitly set to the Pier 1 Imports value.

    // Possible Errors
    // http://eslint.org/docs/rules/#possible-errors
    // ---------------------------------------------
    // 'no-cond-assign': 2,
    'no-console': 1,
    // 'no-constant-condition': 2,
    // 'no-control-regex': 2,
    // 'no-debugger': 2,
    // 'no-dupe-args': 2,
    // 'no-dupe-keys': 2,
    // 'no-duplicate-case': 2,
    // 'no-empty-character-class': 2,
    // 'no-empty': 2,
    // 'no-ex-assign': 2,
    // 'no-extra-boolean-cast': 2,
    // 'no-extra-parens': 0,
    // 'no-extra-semi': 2,
    // 'no-func-assign': 2,
    // 'no-inner-declarations': 2,
    // 'no-invalid-regexp': 2,
    // 'no-irregular-whitespace': 2,
    // 'no-obj-calls': 2,
    // 'no-prototype-builtins': 0,
    // 'no-regex-spaces': 2,
    // 'no-sparse-arrays': 2,
    // 'no-template-curly-in-string': 0,
    // 'no-unexpected-multiline': 2,
    // 'no-unreachable': 2,
    // 'no-unsafe-finally': 2,
    // 'no-unsafe-negation': 0,
    // 'use-isnan': 2
    // 'valid-jsdoc': [
    //   1, {
    //     requireParamDescription: false,
    //     requireReturnDescription: false,
    //     requireReturn: false,
    //     prefer: { returns: 'return' },
    //   }
    // ],
    // 'valid-typeof': 2

    // Best Practices
    // http://eslint.org/docs/rules/#best-practices
    // --------------------------------------------

    // 'accessor-pairs': 0,
    // 'array-callback-return': 0,
    // 'block-scoped-var': 0,
    // 'class-methods-use-this': 0,
    // 'complexity': 0,
    // 'consistent-return': 0
    // 'curly': 0,
    // 'default-case': 0,
    // 'dot-location': 0,
    // 'dot-notation': 0,
    'eqeqeq': 2,
    'guard-for-in': 2,
    // 'no-alert': 0,
    'no-caller': 2,
    // 'no-case-declarations': 2,
    // 'no-div-regex': 0,
    // 'no-else-return': 0,
    // 'no-empty-function': 0,
    // 'no-empty-pattern': 2,
    // 'no-eq-null': 0,
    // 'no-eval': 0,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    // 'no-extra-label': 0,
    // 'no-fallthrough': 2,
    // 'no-floating-decimal': 0,
    // 'no-global-assign': 0,
    'no-implicit-coercion': 2,
    // 'no-implicit-globals': 0,
    // 'no-implied-eval': 0,
    'no-invalid-this': 1,
    // 'no-iterator': 0,
    // 'no-labels': 0,
    // 'no-lone-blocks': 0,
    // 'no-loop-func': 0,
    // 'no-magic-numbers': 0,
    'no-multi-spaces': 2,
    'no-multi-str': 0,
    // 'no-new-func': 0,
    'no-new-wrappers': 2,
    // 'no-new': 0,
    // 'no-octal-escape': 0,
    // 'no-octal': 2,
    'no-param-reassign': 2,
    // 'no-proto': 0,
    // 'no-redeclare': 2,
    // 'no-return-assign': 0,
    // 'no-script-url': 0,
    // 'no-self-assign': 2,
    // 'no-self-compare': 0,
    // 'no-sequences': 0,
    'no-throw-literal': 2,
    // 'no-unmodified-loop-condition': 0,
    // 'no-unused-expressions': 0,
    // 'no-unused-labels': 2,
    // 'no-useless-call': 0,
    // 'no-useless-concat': 0,
    // 'no-useless-escape': 0,
    // 'no-void': 0,
    // 'no-warning-comments': 0,
    'no-with': 2,
    // 'radix': 0,
    // 'vars-on-top': 0,
    // 'wrap-iife': 0,
    // 'yoda': 0,

    // Strict Mode
    // http://eslint.org/docs/rules/#strict-mode
    // -----------------------------------------
    // 'script': 0,

    // Variables
    // http://eslint.org/docs/rules/#variables
    // ---------------------------------------
    // 'init-declarations': 0,
    // 'no-catch-shadow': 0,
    // 'no-delete-var': 2,
    // 'no-label-var': 0,
    // 'no-restricted-globals': 0,
    // 'no-shadow-restricted-names': 0,
    // 'no-shadow': 0,
    // 'no-undef-init': 0,
    // 'no-undef': 2,
    // 'no-undefined': 0,
    'no-unused-vars': [
      1, {
        'vars': 'local',
        'args': 'none',
        'varsIgnorePattern': 'execute',
      },
    ],
    // 'no-use-before-define': 0,

    // Node.js and CommonJS
    // http://eslint.org/docs/rules/#nodejs-and-commonjs
    // -------------------------------------------------
    // 'callback-return': 0,
    // 'global-require': 0,
    // 'handle-callback-err': 0,
    // 'no-mixed-requires': 0,
    // 'no-new-require': 0,
    // 'no-path-concat': 0,
    // 'no-process-env': 0,
    // 'no-process-exit': 0,
    // 'no-restricted-modules': 0,
    // 'no-restricted-properties': 0,
    // 'no-sync': 0,

    // Stylistic Issues
    // http://eslint.org/docs/rules/#stylistic-issues
    // ----------------------------------------------
    'array-bracket-spacing': [2, 'never'],
    // 'block-spacing': 0,
    'brace-style': 0,
    'camelcase': [2, { properties: 'always' }],
    'comma-dangle': [2, {
      'arrays': 'always-multiline',
      'objects': 'always-multiline',
      'imports': 'always-multiline',
      'exports': 'always-multiline',
      'functions': 'always-multiline',
    }],
    'comma-spacing': 2,
    'comma-style': 2,
    'computed-property-spacing': 2,
    // 'consistent-this': 0,
    'eol-last': 2,
    'func-call-spacing': 2,
    // 'func-name-matching': 0,
    // 'func-names': 0,
    // 'func-style': 0,
    // 'id-blacklist': 0,
    // 'id-length': 0,
    // 'id-match': 0,
    'indent': [
      2,
      2,
      { "SwitchCase": 1 }
    ],
    // 'jsx-quotes': 0,
    'key-spacing': 2,
    'keyword-spacing': 2,
    // 'line-comment-position': 0,
    'linebreak-style': 0,
    // 'lines-around-comment': 0,
    // 'lines-around-directive': 0,
    // 'max-depth': 0,
    'max-len': 0,
    // 'max-lines': 0,
    // 'max-nested-callbacks': 0,
    // 'max-params': 0,
    // 'max-statements-per-line': 0,
    // 'max-statements': 0,
    // 'multiline-ternary': 0,
    'new-cap': [
      2, {
        'newIsCap': true,
        'capIsNew': false,
        'properties': true,
      },
    ],
    // 'new-parens': 0,
    // 'newline-after-var': 0,
    // 'newline-before-return': 0,
    // 'newline-per-chained-call': 0,
    'no-array-constructor': 2,
    // 'no-bitwise': 0,
    // 'no-continue': 0,
    // 'no-inline-comments': 0,
    // 'no-lonely-if': 0,
    // 'no-mixed-operators': 0,
    'no-mixed-spaces-and-tabs': 2,
    'no-multiple-empty-lines': [2, { max: 2 }],
    // 'no-negated-condition': 0,
    // 'no-nested-ternary': 0,
    'no-new-object': 2,
    // 'no-plusplus': 0,
    // 'no-restricted-syntax': 0,
    'no-tabs': 2,
    // 'no-ternary': 0,
    // 'no-trailing-spaces': 0,
    // 'no-underscore-dangle': 0,
    // 'no-unneeded-ternary': 0,
    // 'no-whitespace-before-property': 0,
    // 'object-curly-newline': 0,
    'object-curly-spacing': [2, 'always'],
    // 'object-property-newline': 0,
    'one-var-declaration-per-line': [2, 'always'],
    'one-var': "off",
    // 'operator-assignment': 0,
    // 'operator-linebreak': 0,
    'padded-blocks': [2, 'never'],
    'quote-props': [2, 'consistent'],
    'quotes': [
      2,
      'single', { allowTemplateLiterals: true },
    ],
    // 'require-jsdoc': [
    //   1, {
    //     require: {
    //       FunctionDeclaration: true,
    //       MethodDefinition: true,
    //       ClassDeclaration: true,
    //     },
    //   }
    // ],
    'semi-spacing': 2,
    'semi': 2,
    // 'sort-keys': 0,
    // 'sort-vars': 0,
    'space-before-blocks': 2,
    'space-before-function-paren': [
      2, {
        'anonymous': 'always',
        'named': 'never',
        'asyncArrow': 'never',
      },
    ],
    // 'space-in-parens': 0,
    // 'space-infix-ops': 0,
    // 'space-unary-ops': 0,
    'spaced-comment': 0,
    // 'unicode-bom': 0,
    // 'wrap-regex': 0,

    // ECMAScript 6
    // http://eslint.org/docs/rules/#ecmascript-6
    // ------------------------------------------
    // 'arrow-body-style': 0,
    'arrow-parens': [0, 'always'],
    // 'arrow-spacing': 0,
    // 'constructor-super': 2,
    'generator-star-spacing': [2, 'after'],
    // 'no-class-assign': 0,
    // 'no-confusing-arrow': 0,
    // 'no-const-assign': 0,
    // 'no-dupe-class-members': 0,
    // 'no-duplicate-imports': 0,
    'no-new-symbol': 2,
    // 'no-restricted-imports': 0,
    // 'no-this-before-super': 2,
    // 'no-useless-computed-key': 0,
    // 'no-useless-constructor': 0,
    // 'no-useless-rename': 0,
    // 'no-var': 0,
    // 'object-shorthand': 0,
    // 'prefer-arrow-callback': 0,
    // 'prefer-const': 0,
    // 'prefer-numeric-literals': 0,
    // 'prefer-reflect': 0,
    // 'prefer-rest-params': 0,
    // 'prefer-spread': 0,
    // 'prefer-template': 0,
    // 'require-yield': 2,
    // 'rest-spread-spacing': 0,
    // 'sort-imports': 0,
    // 'symbol-description': 0,
    // 'template-curly-spacing': 0,
    'yield-star-spacing': [2, 'after'],
  },
  'plugins': [
    'eslint-plugin-react',
    'eslint-plugin-mocha',
  ],
  'parserOptions': {
    'ecmaFeatures': {
      'jsx': true,
    },
  },
  'env': {
    'browser': true,
    'commonjs': true,
    'es6': true,
    'jquery': true,
    'mocha': true,
    'node': true,
  },
  'globals': {},
  'parser': 'babel-eslint',
};
<|endoftext|>


<commit_before>'use strict';

const runner = require('toisu-middleware-runner');
const stacks = new WeakMap();
const errorHandlers = new WeakMap();

class Toisu {
  constructor() {
    stacks.set(this, []);
    this.handleError = Toisu.defaultHandleError;
  }

  use(middleware) {
    stacks.get(this).push(middleware);
  }

  setErrorHandler(handler) {
    errorHandlers.set(this, handler);
  }

  get requestHandler() {
    return (req, res) => {
      const stack = stacks.get(this);
      const context = new Map();

      return runner.call(context, req, res, stack)
        .then(() => {
          if (!res.headersSent) {
            res.statusCode = 404;
            res.end();
          }
        })
        .catch(error => this.handleError.call(context, req, res, error));
    };
  }

  static defaultHandleError(req, res) {
    res.statusCode = 502;
    res.end();
  }
}

module.exports = Toisu;
<commit_msg>Removes redundant method.<commit_after>'use strict';

const runner = require('toisu-middleware-runner');
const stacks = new WeakMap();

class Toisu {
  constructor() {
    stacks.set(this, []);
    this.handleError = Toisu.defaultHandleError;
  }

  use(middleware) {
    stacks.get(this).push(middleware);
  }

  get requestHandler() {
    return (req, res) => {
      const stack = stacks.get(this);
      const context = new Map();

      return runner.call(context, req, res, stack)
        .then(() => {
          if (!res.headersSent) {
            res.statusCode = 404;
            res.end();
          }
        })
        .catch(error => this.handleError.call(context, req, res, error));
    };
  }

  static defaultHandleError(req, res) {
    res.statusCode = 502;
    res.end();
  }
}

module.exports = Toisu;
<|endoftext|>