<commit_before>var reader = require('./lib/reader'),
    initializer = require('./lib/initializer'),
    formatter = require('./lib/formatter'),
    dependency = require('./lib/dependency'),
    absorb = require('absorb'),
    widget = require('./lib/widget'),
    server = require('./lib/http-server'),
    colors = require('colors'),
    shell = require('shelljs'),
    path = require('./lib/path'),
    yaml = require('js-yaml'),
    Hexo = require('hexo'),
    glob = require('glob'),
    json = require('jsonfile'),
    fs = require('fs');

var conf, defaultConf;
var packageJSON = json.readFileSync(path.fromModule('package.json'));
var hexoConfig, mergedConfig;
var widgetFiles;

var checkPath = function(path, configVarName, canSkip) {
    var skip = canSkip || false;
    if (shell.test('-e', path)) {
        return true;
    } else {
        if (skip) {
            return false;
        }
        var varName = configVarName || false;
        if (varName) {
            console.error(' ERROR: '.red + ' the file ' + (path).red + ' in ' + (varName).yellow + ' property from your ' + 'a-pollo.yml'.yellow + ' config not found.');
        } else {
            console.error(' ERROR: '.red + ' file ' + (path).red + ' in your ' + 'a-pollo.yml'.yellow + ' config not found.');
        }
        return false;
    }
};

var addThemeImage = function(imageName) {
    var defaultLogoSource, defaultLogoTarget, defaultLogoTargetPath;
    defaultLogoTarget = path.fromModule('/hexo/source/css/theme/assets/' + imageName);
    defaultLogoTargetPath = path.trimRight(path.fromModule('/hexo/source/css/theme/assets/'));
    if (!shell.test('-e', defaultLogoTarget)) {
        defaultLogoSource = path.fromModule('/frontsize/themes/a-pollo/img/' + imageName);
        shell.cp('-f', defaultLogoSource, defaultLogoTargetPath);
    }
};

var prepareFiles = function() {

    if (shell.test('-e', path.fromProcess(conf.public_dir))) {
        shell.rm('-Rf', path.fromProcess(conf.public_dir));
    }

    shell.mkdir('-p', path.fromModule('/hexo/source'));
    shell.mkdir('-p', path.fromModule('/hexo/source/_posts'));
    shell.mkdir('-p', path.fromModule('/source'));

    if (conf.pages !== undefined || conf.pages) {
        if (checkPath(path.fromProcess(conf.pages), 'pages')) {
            shell.cp('-R', path.inside(path.fromProcess(conf.pages)), path.fromModule('/hexo/source'));
        }
    } else {
        shell.cp('-R', path.fromModule('/hexo/_default_source/*'), path.fromModule('/hexo/source'));
    }

    shell.mkdir('-p', path.fromModule('/hexo/source/css/theme'));
    shell.mkdir('-p', path.fromModule('/hexo/source/css/theme/img'));
    shell.mkdir('-p', path.fromModule('/hexo/source/css/theme/fonts'));

    console.log('Copying CSS theme images and fonts');

    if (checkPath(path.fromProcess(conf.style.images), 'style.images')) {
        shell.cp('-R', path.inside(path.fromProcess(conf.style.images)), path.fromModule('/hexo/source/css/theme/assets'));
        addThemeImage('apollo-logo__icon.svg');
        addThemeImage('apollo-logo__icon-grey.svg');
        addThemeImage('apollo-logo__icon-black.svg');
    }
    if (checkPath(path.fromProcess(conf.style.fonts), 'style.fonts')) {
        shell.cp('-R', path.inside(path.fromProcess(conf.style.fonts)), path.fromModule('/hexo/source/css/theme/assets'));
    }
};

var checkTheme = function() {
    var defaultTheme = 'a-pollo';
    if (conf.theme !== undefined) {
        if (!shell.test('-e', path.fromModule('/hexo/themes/' + conf.theme))) {
            console.log('Theme ' + (' ' + conf.theme + ' ').yellow.bgBlack + ' not installed, searching on project folder');
            if (!shell.test('-e', path.fromProcess(conf.theme))) {
                console.log('Theme ' + (' ' + conf.theme + ' ').yellow.bgBlack + ' not found, it will be used ' + (' ' + defaultTheme + ' ').yellow.bgBlack + ' as default theme');
                conf.theme = defaultTheme;
            } else {
                console.log('Installing found theme ' + (' ' + conf.theme + ' ').yellow.bgBlack);
                shell.cp('-R', path.inside(path.fromProcess(conf.theme)), path.fromModule('/hexo/themes/' + conf.theme));
            }
        } else {
            console.log('Using selected theme ' + (' ' + conf.theme + ' ').yellow.bgBlack);
        }
    } else {
        console.log('Theme not set, it will be used ' + (' ' + defaultTheme + ' ').yellow.bgBlack + ' as default theme');
        conf.theme = defaultTheme;
    }
};

var generateDocs = function () {
    shell.mv('-f', path.fromProcess('/source/_posts'), path.fromModule('/hexo/source'));
    shell.exec('cd ' + path.fromModule('/hexo') + ' && ../node_modules/.bin/hexo generate');
    shell.mv('-f', path.fromModule('/hexo/' + path.trimLeft(conf.public_dir)), path.fromProcess(conf.public_dir));
};

var removeFiles = function() {
    if (shell.test('-e', path.fromModule('/hexo/source'))) { shell.rm('-Rf', path.fromModule('/hexo/source')); }
    if (shell.test('-e', path.fromModule('/source'))) { shell.rm('-Rf', path.fromModule('/source')); }
    if (shell.test('-e', path.fromModule('/hexo/_config.yml'))) { shell.rm('-f', path.fromModule('/hexo/_config.yml')); }
};

var prepareHTTP = function() {

    setTimeout(function(){
        removeFiles();
    }, 500);

    console.log('Build finished successfully.'.green);

    if (conf.http_server !== undefined && conf.http_server !== false) {
        server.start(conf.public_dir, conf.url);
    } else {
        console.log('The style guide was generated here: ' + conf.public_dir.toString().yellow);
    }
};

var postCreated = function(widgetFilesLength) {
    var posts = glob.sync(path.fromProcess('/source/_posts/**/*.md'));
    if (posts.length === widgetFilesLength) {
        generateDocs();
        setTimeout(function(){
            prepareHTTP();
        }, 1000);
    } else {
        setTimeout(function(){
            postCreated(widgetFilesLength);
        }, 500);
    }
};

var copyThemeAssets = function() {
    var cssFileData, url;
    if (checkPath(path.fromProcess(conf.style.css), 'style.css')) {
        console.log('Copying style CSS to display');
        url = path.trimRight(conf.url);
        cssFileData = fs.readFileSync(path.fromProcess(conf.style.css), 'utf8');
        cssFileData = cssFileData.replace(/url\(('|"){1,}(.*\/)(.*)('|"){1,}\)/g, 'url($1' + url + '/css/theme/assets/$3$4)');
        fs.writeFileSync(path.fromModule('/hexo/source/css/theme/theme.css'), cssFileData);
    } else {
        return false;
    }
};

var runBuild = function() {
    var hexo;
    checkTheme();
    dependency.check();
    prepareFiles();
    copyThemeAssets();

    console.log('Hexo: Initializing...'.grey);

    if (checkPath(path.fromModule('/hexo/_config.yml'))) {
        console.log('Hexo: Loading configuration'.grey);
    }

    hexo = new Hexo(process.cwd(), {
        debug: false,
        config: path.fromModule('/hexo/_config.yml')
    });

    hexo.init().then(function(){
        var postData;
        console.log('Hexo: Crunching a-pollo doc annotations to posts...'.grey);
        for (var i = 0; i < widgetFiles.length; i += 1) {
            console.log('Creating post for ' + (' ' + widgetFiles[i][0].file + ' ').yellow.bgBlack);
            postData = formatter.toHexo(widgetFiles[i]);
            postData.content = widget.toMarkdown(widgetFiles[i], conf);
            hexo.post.create(postData, true);
        }
        console.log('Hexo: Waiting to finish...'.grey);
        postCreated(widgetFiles.length);
    });
};

var runProcess = function() {

    console.log('Starting ' + 'a-pollo '.rainbow + packageJSON.version);

    removeFiles();

    var initializerStarted = false;

    process.argv.forEach(function(val) {
        if (val === 'init') {
            initializer.start();
            return;
        }
    });

    if (initializerStarted) {
        return;
    }

    var filename = process.cwd() + '/a-pollo.yml';
    process.argv.forEach(function(val) {
        if (val.indexOf('config=') === 0) {
            filename = process.cwd() + val.replace('config=', '/');
        }
    });

    if (shell.test('-e', filename)) {
        var confToMerge = yaml.safeLoad(fs.readFileSync(filename, 'utf-8'));
        confToMerge.apollo = {
            version: packageJSON.version,
            homepage: packageJSON.homepage
        };
        defaultConf = yaml.safeLoad(fs.readFileSync(path.fromModule('/a-pollo.yml'), 'utf-8'));

        delete defaultConf.pages;
        delete defaultConf.libs;

        conf = absorb(confToMerge, defaultConf, false, true);
        hexoConfig   = yaml.safeLoad(fs.readFileSync(path.fromModule('/hexo/_default_config.yml'), 'utf-8'));

        if (conf.libs !== undefined) {
            if (conf.libs.node !== undefined) {
                if (checkPath(path.fromProcess(conf.libs.node), 'libs.node')) {
                    conf.libs.nodeDependencies = yaml.safeLoad(fs.readFileSync(path.fromProcess(conf.libs.node))).dependencies;
                }
            }
            if (conf.libs.bower !== undefined) {
                if (checkPath(path.fromProcess(conf.libs.bower), 'libs.bower')) {
                    conf.libs.bowerDependencies = yaml.safeLoad(fs.readFileSync(path.fromProcess(conf.libs.bower))).dependencies;
                }
            }
        }

        console.log('Loading doc annotations data from ' + (' ' + conf.style.docs + ' ').yellow.bgBlack + ' folder');
        widgetFiles = reader.load(path.fromProcess(conf.style.docs));

        conf = formatter.setProjectStats(conf, widgetFiles);
        mergedConfig = absorb(conf, hexoConfig, false, true);

        fs.writeFileSync(path.fromModule('/hexo/_config.yml'), yaml.safeDump(mergedConfig));

        runBuild();
    } else {
        var isInitProcess = false;
        process.argv.forEach(function(val) {
            if (val.indexOf('init') === 0) {
                isInitProcess = true;
            }
        });
        if (!isInitProcess) {
            console.log('ERROR: '.red + 'file ' + filename.toString().red + ' not found, please run ' + 'a-pollo init'.yellow + ' or ' + './node_modules/.bin/a-pollo init'.yellow + ' to create one.');
        }
    }
};

runProcess();
<commit_msg>Change hexo bin path<commit_after>var reader = require('./lib/reader'),
    initializer = require('./lib/initializer'),
    formatter = require('./lib/formatter'),
    dependency = require('./lib/dependency'),
    absorb = require('absorb'),
    widget = require('./lib/widget'),
    server = require('./lib/http-server'),
    colors = require('colors'),
    shell = require('shelljs'),
    path = require('./lib/path'),
    yaml = require('js-yaml'),
    Hexo = require('hexo'),
    glob = require('glob'),
    json = require('jsonfile'),
    fs = require('fs');

var conf, defaultConf;
var packageJSON = json.readFileSync(path.fromModule('package.json'));
var hexoConfig, mergedConfig;
var widgetFiles;

var checkPath = function(path, configVarName, canSkip) {
    var skip = canSkip || false;
    if (shell.test('-e', path)) {
        return true;
    } else {
        if (skip) {
            return false;
        }
        var varName = configVarName || false;
        if (varName) {
            console.error(' ERROR: '.red + ' the file ' + (path).red + ' in ' + (varName).yellow + ' property from your ' + 'a-pollo.yml'.yellow + ' config not found.');
        } else {
            console.error(' ERROR: '.red + ' file ' + (path).red + ' in your ' + 'a-pollo.yml'.yellow + ' config not found.');
        }
        return false;
    }
};

var addThemeImage = function(imageName) {
    var defaultLogoSource, defaultLogoTarget, defaultLogoTargetPath;
    defaultLogoTarget = path.fromModule('/hexo/source/css/theme/assets/' + imageName);
    defaultLogoTargetPath = path.trimRight(path.fromModule('/hexo/source/css/theme/assets/'));
    if (!shell.test('-e', defaultLogoTarget)) {
        defaultLogoSource = path.fromModule('/frontsize/themes/a-pollo/img/' + imageName);
        shell.cp('-f', defaultLogoSource, defaultLogoTargetPath);
    }
};

var prepareFiles = function() {

    if (shell.test('-e', path.fromProcess(conf.public_dir))) {
        shell.rm('-Rf', path.fromProcess(conf.public_dir));
    }

    shell.mkdir('-p', path.fromModule('/hexo/source'));
    shell.mkdir('-p', path.fromModule('/hexo/source/_posts'));
    shell.mkdir('-p', path.fromModule('/source'));

    if (conf.pages !== undefined || conf.pages) {
        if (checkPath(path.fromProcess(conf.pages), 'pages')) {
            shell.cp('-R', path.inside(path.fromProcess(conf.pages)), path.fromModule('/hexo/source'));
        }
    } else {
        shell.cp('-R', path.fromModule('/hexo/_default_source/*'), path.fromModule('/hexo/source'));
    }

    shell.mkdir('-p', path.fromModule('/hexo/source/css/theme'));
    shell.mkdir('-p', path.fromModule('/hexo/source/css/theme/img'));
    shell.mkdir('-p', path.fromModule('/hexo/source/css/theme/fonts'));

    console.log('Copying CSS theme images and fonts');

    if (checkPath(path.fromProcess(conf.style.images), 'style.images')) {
        shell.cp('-R', path.inside(path.fromProcess(conf.style.images)), path.fromModule('/hexo/source/css/theme/assets'));
        addThemeImage('apollo-logo__icon.svg');
        addThemeImage('apollo-logo__icon-grey.svg');
        addThemeImage('apollo-logo__icon-black.svg');
    }
    if (checkPath(path.fromProcess(conf.style.fonts), 'style.fonts')) {
        shell.cp('-R', path.inside(path.fromProcess(conf.style.fonts)), path.fromModule('/hexo/source/css/theme/assets'));
    }
};

var checkTheme = function() {
    var defaultTheme = 'a-pollo';
    if (conf.theme !== undefined) {
        if (!shell.test('-e', path.fromModule('/hexo/themes/' + conf.theme))) {
            console.log('Theme ' + (' ' + conf.theme + ' ').yellow.bgBlack + ' not installed, searching on project folder');
            if (!shell.test('-e', path.fromProcess(conf.theme))) {
                console.log('Theme ' + (' ' + conf.theme + ' ').yellow.bgBlack + ' not found, it will be used ' + (' ' + defaultTheme + ' ').yellow.bgBlack + ' as default theme');
                conf.theme = defaultTheme;
            } else {
                console.log('Installing found theme ' + (' ' + conf.theme + ' ').yellow.bgBlack);
                shell.cp('-R', path.inside(path.fromProcess(conf.theme)), path.fromModule('/hexo/themes/' + conf.theme));
            }
        } else {
            console.log('Using selected theme ' + (' ' + conf.theme + ' ').yellow.bgBlack);
        }
    } else {
        console.log('Theme not set, it will be used ' + (' ' + defaultTheme + ' ').yellow.bgBlack + ' as default theme');
        conf.theme = defaultTheme;
    }
};

var generateDocs = function () {
    shell.mv('-f', path.fromProcess('/source/_posts'), path.fromModule('/hexo/source'));
    if (shell.test('-e', path.fromModule('/node_modules/.bin/hexo'))) {
        shell.exec('cd ' + path.fromModule('/hexo') + ' && ../node_modules/.bin/hexo generate');
    } else {
        shell.exec('cd ' + path.fromModule('/hexo') + ' && ../../.bin/hexo generate');
    }
    shell.mv('-f', path.fromModule('/hexo/' + path.trimLeft(conf.public_dir)), path.fromProcess(conf.public_dir));
};

var removeFiles = function() {
    if (shell.test('-e', path.fromModule('/hexo/source'))) { shell.rm('-Rf', path.fromModule('/hexo/source')); }
    if (shell.test('-e', path.fromModule('/source'))) { shell.rm('-Rf', path.fromModule('/source')); }
    if (shell.test('-e', path.fromModule('/hexo/_config.yml'))) { shell.rm('-f', path.fromModule('/hexo/_config.yml')); }
};

var prepareHTTP = function() {

    setTimeout(function(){
        removeFiles();
    }, 500);

    console.log('Build finished successfully.'.green);

    if (conf.http_server !== undefined && conf.http_server !== false) {
        server.start(conf.public_dir, conf.url);
    } else {
        console.log('The style guide was generated here: ' + conf.public_dir.toString().yellow);
    }
};

var postCreated = function(widgetFilesLength) {
    var posts = glob.sync(path.fromProcess('/source/_posts/**/*.md'));
    if (posts.length === widgetFilesLength) {
        generateDocs();
        setTimeout(function(){
            prepareHTTP();
        }, 1000);
    } else {
        setTimeout(function(){
            postCreated(widgetFilesLength);
        }, 500);
    }
};

var copyThemeAssets = function() {
    var cssFileData, url;
    if (checkPath(path.fromProcess(conf.style.css), 'style.css')) {
        console.log('Copying style CSS to display');
        url = path.trimRight(conf.url);
        cssFileData = fs.readFileSync(path.fromProcess(conf.style.css), 'utf8');
        cssFileData = cssFileData.replace(/url\(('|"){1,}(.*\/)(.*)('|"){1,}\)/g, 'url($1' + url + '/css/theme/assets/$3$4)');
        fs.writeFileSync(path.fromModule('/hexo/source/css/theme/theme.css'), cssFileData);
    } else {
        return false;
    }
};

var runBuild = function() {
    var hexo;
    checkTheme();
    dependency.check();
    prepareFiles();
    copyThemeAssets();

    console.log('Hexo: Initializing...'.grey);

    if (checkPath(path.fromModule('/hexo/_config.yml'))) {
        console.log('Hexo: Loading configuration'.grey);
    }

    hexo = new Hexo(process.cwd(), {
        debug: false,
        config: path.fromModule('/hexo/_config.yml')
    });

    hexo.init().then(function(){
        var postData;
        console.log('Hexo: Crunching a-pollo doc annotations to posts...'.grey);
        for (var i = 0; i < widgetFiles.length; i += 1) {
            console.log('Creating post for ' + (' ' + widgetFiles[i][0].file + ' ').yellow.bgBlack);
            postData = formatter.toHexo(widgetFiles[i]);
            postData.content = widget.toMarkdown(widgetFiles[i], conf);
            hexo.post.create(postData, true);
        }
        console.log('Hexo: Waiting to finish...'.grey);
        postCreated(widgetFiles.length);
    });
};

var runProcess = function() {

    console.log('Starting ' + 'a-pollo '.rainbow + packageJSON.version);

    removeFiles();

    var initializerStarted = false;

    process.argv.forEach(function(val) {
        if (val === 'init') {
            initializer.start();
            return;
        }
    });

    if (initializerStarted) {
        return;
    }

    var filename = process.cwd() + '/a-pollo.yml';
    process.argv.forEach(function(val) {
        if (val.indexOf('config=') === 0) {
            filename = process.cwd() + val.replace('config=', '/');
        }
    });

    if (shell.test('-e', filename)) {
        var confToMerge = yaml.safeLoad(fs.readFileSync(filename, 'utf-8'));
        confToMerge.apollo = {
            version: packageJSON.version,
            homepage: packageJSON.homepage
        };
        defaultConf = yaml.safeLoad(fs.readFileSync(path.fromModule('/a-pollo.yml'), 'utf-8'));

        delete defaultConf.pages;
        delete defaultConf.libs;

        conf = absorb(confToMerge, defaultConf, false, true);
        hexoConfig   = yaml.safeLoad(fs.readFileSync(path.fromModule('/hexo/_default_config.yml'), 'utf-8'));

        if (conf.libs !== undefined) {
            if (conf.libs.node !== undefined) {
                if (checkPath(path.fromProcess(conf.libs.node), 'libs.node')) {
                    conf.libs.nodeDependencies = yaml.safeLoad(fs.readFileSync(path.fromProcess(conf.libs.node))).dependencies;
                }
            }
            if (conf.libs.bower !== undefined) {
                if (checkPath(path.fromProcess(conf.libs.bower), 'libs.bower')) {
                    conf.libs.bowerDependencies = yaml.safeLoad(fs.readFileSync(path.fromProcess(conf.libs.bower))).dependencies;
                }
            }
        }

        console.log('Loading doc annotations data from ' + (' ' + conf.style.docs + ' ').yellow.bgBlack + ' folder');
        widgetFiles = reader.load(path.fromProcess(conf.style.docs));

        conf = formatter.setProjectStats(conf, widgetFiles);
        mergedConfig = absorb(conf, hexoConfig, false, true);

        fs.writeFileSync(path.fromModule('/hexo/_config.yml'), yaml.safeDump(mergedConfig));

        runBuild();
    } else {
        var isInitProcess = false;
        process.argv.forEach(function(val) {
            if (val.indexOf('init') === 0) {
                isInitProcess = true;
            }
        });
        if (!isInitProcess) {
            console.log('ERROR: '.red + 'file ' + filename.toString().red + ' not found, please run ' + 'a-pollo init'.yellow + ' or ' + './node_modules/.bin/a-pollo init'.yellow + ' to create one.');
        }
    }
};

runProcess();
<|endoftext|>


<commit_before>'use strict';
let defaultInterval = 10;
let oneSecInMs = 1000;
let zsetMetricAppendName = "zset"
const path = require('path');
const util = require('util');
const infoParser = require('./lib/info-parser');
const redisClientFactory = require('./lib/redis-client-factory');
const libUtils = require('./lib/utils');
let keyCounter = require('./lib/redis-key-counter');
var configDir = path.resolve(process.argv[2] || './');

const StatsD = require('statsd-client');

util.log('starting...');
util.log(`using config from ${configDir}`);

var statsConfig = require(path.join(configDir, 'statsd'));
var statsdClient = new StatsD({ host: statsConfig.host, port: statsConfig.port, debug: statsConfig.debug });

var redisClients = require(path.join(configDir, 'redis')).map(redisClientFactory);

redisClients.forEach((c) => {
  setInterval(() => {
    var action = c.isCluster ? 'clusterInfo' : 'info';

    c[action]((err, res) => {
      if (err) {
        util.log(`[${c.host}] ${err}`);
        return;
      }

      infoParser(res).forEach((shard) => {
        var prefix = libUtils.getPrefix(c, shard.name);
        var suffix = libUtils.getSuffix(c, shard.name);

        Object.keys(shard.stats).forEach((k) => {
          statsdClient.gauge(`${prefix}${k}${suffix}`, shard.stats[k]);
        });

      });
    });

    keyCounter.count(c, (err, stat) => {
      var prefix = libUtils.getPrefix(c, zsetMetricAppendName);
      var suffix = libUtils.getSuffix(c, zsetMetricAppendName);

      if (err) {
        util.log(`[${c.host}] ${err}`);
        return;
      }

      statsdClient.gauge(`${prefix}${stat.key}${suffix}`, stat.count);
    });

  }, (statsConfig.interval || defaultInterval) * oneSecInMs);
});
<commit_msg>Fix failing build and renamed const to be more appropriate<commit_after>'use strict';
let defaultInterval = 10;
let oneSecInMs = 1000;
let keyCountAppendName = 'keyCounter';
const path = require('path');
const util = require('util');
const infoParser = require('./lib/info-parser');
const redisClientFactory = require('./lib/redis-client-factory');
const libUtils = require('./lib/utils');
let keyCounter = require('./lib/redis-key-counter');
var configDir = path.resolve(process.argv[2] || './');

const StatsD = require('statsd-client');

util.log('starting...');
util.log(`using config from ${configDir}`);

var statsConfig = require(path.join(configDir, 'statsd'));
var statsdClient = new StatsD({ host: statsConfig.host, port: statsConfig.port, debug: statsConfig.debug });

var redisClients = require(path.join(configDir, 'redis')).map(redisClientFactory);

redisClients.forEach((c) => {
  setInterval(() => {
    var action = c.isCluster ? 'clusterInfo' : 'info';

    c[action]((err, res) => {
      if (err) {
        util.log(`[${c.host}] ${err}`);
        return;
      }

      infoParser(res).forEach((shard) => {
        var prefix = libUtils.getPrefix(c, shard.name);
        var suffix = libUtils.getSuffix(c, shard.name);

        Object.keys(shard.stats).forEach((k) => {
          statsdClient.gauge(`${prefix}${k}${suffix}`, shard.stats[k]);
        });

      });
    });

    keyCounter.count(c, (err, stat) => {
      var prefix = libUtils.getPrefix(c, keyCountAppendName);
      var suffix = libUtils.getSuffix(c, keyCountAppendName);

      if (err) {
        util.log(`[${c.host}] ${err}`);
        return;
      }

      statsdClient.gauge(`${prefix}${stat.key}${suffix}`, stat.count);
    });

  }, (statsConfig.interval || defaultInterval) * oneSecInMs);
});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var querystring = require('querystring');
var bookmarkletPath = path.resolve(__dirname, './dist/bookmarklet.js')
var indexPath = path.resolve(__dirname, './index.html');
var log = function (text) {
  return console.log(text); // eslint-disable-line no-console
};

log('Creating ' + indexPath + ' page with bookmarklet from ' + bookmarkletPath + '.');

var code = fs.readFileSync(bookmarkletPath, 'utf8');
var link = 'javascript:' + querystring.escape(code);

var indexHtml = [
  '<!DOCTYPE html>', '',
  '',
  '<meta charset="utf-8">', '<title>FastMail Markdown Bookmarklet</title>',
  '',
  '',
  '
Bookmarklet enhancing FastMail Plain Text content with Markdown rendering
',
  '
Drag and drop this sweet bookmarklet to your bookmarks bar, if you so dare ;)
',
  '
',
  '',
  '
',
  'Then navigate to your FastMail Notes ',
  'or FastMail Mails ',
  'and click on the bookmark to toggle markdown rendering for your plain text notes',
  '
',
  'The source code is available on GitHub.',
  '
',
  '',
  ''
].join('');

fs.writeFileSync(indexPath, indexHtml);

log('Done! :)');
<commit_msg>docs(index.js): add sponsor & license sections<commit_after>var fs = require('fs');
var path = require('path');
var querystring = require('querystring');
var bookmarkletPath = path.resolve(__dirname, './dist/bookmarklet.js')
var indexPath = path.resolve(__dirname, './index.html');
var log = function (text) {
  return console.log(text); // eslint-disable-line no-console
};

log('Creating ' + indexPath + ' page with bookmarklet from ' + bookmarkletPath + '.');

var code = fs.readFileSync(bookmarkletPath, 'utf8');
var link = 'javascript:' + querystring.escape(code);

var indexHtml = [
  '<!DOCTYPE html>', '',
  '',
  '<meta charset="utf-8">', '<title>FastMail Markdown Bookmarklet</title>',
  '',
  '',
  '
Bookmarklet enhancing FastMail Plain Text content with Markdown rendering
',
  '
Drag and drop this sweet bookmarklet to your bookmarks bar, if you so dare ;)
',
  '
',
  '',
  '
',
  'Then navigate to your FastMail Notes ',
  'or FastMail Mails ',
  'and click on the bookmark to toggle markdown rendering for your plain text notes',
  '
',
  '
Source Code
',
  '
',
  'The source code is available on GitHub.',
  '
',
  '
Sponsor
',
  '
',
  'Support my work on this project via PayPal.',
  '
',
  '
License
',
  '
MIT License © Jan Raasch
',
  '',
  ''
].join('');

fs.writeFileSync(indexPath, indexHtml);

log('Done! :)');
<|endoftext|>


<commit_before>/* jshint -W084, -W093 */
(function () {
    /**
     * Expose `Retext`. Defined below, and used to instantiate a new
     * Retext object.
     */
    exports = module.exports = Retext;

    function useImmediately(rootNode, use) {
        return function (plugin) {
            var self = this,
                length = self.plugins.length;

            use.apply(self, arguments);

            if (length !== self.plugins.length) {
                plugin(rootNode, self);
            }

            return self;
        };
    }

    /**
     * Define `Retext`. Exported above, and used to instantiate a new
     * `Retext`.
     *
     * Note that, when parser is a string or not given, the to-require module
     * is first removed from the Require cache. This results in a completly
     * new parser module, and a new TextOM object, thus clearing any changes
     * made to TextOM or the parser and that, for example, the following is
     * true:
     *
     *   !(new Retext().parse() instanceof new Retext().parse().constructor);
     *
     * The following however, is also true:
     *
     *   var retext = new Retext();
     *   retext.parse() instanceof retext.parse().constructor;
     *
     *
     * @param {(Object|String)?} parser - the parser, or its name, to use.
     *                                    Defaults to "parse-english".
     * @api public
     * @constructor
     */
    function Retext(parser) {
        var self = this,
            cache = require.cache,
            attribute;

        if (!parser) {
            /* istanbul ignore if: Not all `require` providers support dynamic
             * loading, needed for the next step, thus we skip the next
             * branch early. */
            if (require.client || require.component) {
                parser = require('parse-english')();
            } else {
                parser = 'parse-english';
            }
        }

        if (typeof parser === 'string') {
            parser = require(parser)();
        }

        self.parser = parser;
        self.plugins = [];
    }

    /**
     * `Retext#use` takes a plugin—a humble function—and when the parse
     * method of the Retext instance is called, the plugin will be called
     * with the parsed tree, and the retext instance as arguments.
     *
     * Note that, during the parsing stage, when the `use` method is called
     * by a plugin, the nested plugin is immediately called, before continuing
     * on with its parent plugin.
     *
     * @param {Function} plugin - the plugin to call when parsing.
     * @param {Function?} plugin.attach - called only once with a Retext
     *                                    instance. If you're planning on
     *                                    modifying TextOM or a parser, do it
     *                                    in this method.
     * @return this
     * @api public
     */
    Retext.prototype.use = function (plugin) {
        if (typeof plugin !== 'function') {
            throw new TypeError('Illegal invocation: \'' + plugin +
                '\' is not a valid argument for \'Retext.prototype.use\'');
        }

        var self = this,
            plugins = self.plugins;

        if (plugins.indexOf(plugin) === -1) {
            if (plugin.attach) {
                plugin.attach(self);
            }

            plugins.push(plugin);
        }

        return self;
    };

    /**
     * `Retext#parse` takes a source to be given (and parsed) by the parser.
     * Then, `parse` iterates over all plugins, and allows them to modify the
     * TextOM tree created by the parser.
     *
     * Note that, during the parsing stage, when the `use` plugin is called
     * by a plugin, the nested plugin is immediately called, before continuing
     * on with its parent plugin.
     *
     * @param {(String|Node)?} source - The source to convert.
     * @return {Node} - A RootNode containing the tokenised source.
     * @api public
     */
    Retext.prototype.parse = function (source) {
        var self = this,
            parser = self.parser,
            plugins = self.plugins.concat(),
            iterator = -1,
            use = self.use,
            rootNode = parser(source),
            plugin;

        self.use = useImmediately(rootNode, use);

        while (plugin = plugins[++iterator]) {
            plugin(rootNode, this);
        }

        self.use = use;

        return rootNode;
    };
})();
<commit_msg>Fixed a bug where, with component.js, when `"parse-english"` was passed to parser, an error was thrown<commit_after>/* jshint -W084, -W093 */
(function () {
    /**
     * Expose `Retext`. Defined below, and used to instantiate a new
     * Retext object.
     */
    exports = module.exports = Retext;

    function useImmediately(rootNode, use) {
        return function (plugin) {
            var self = this,
                length = self.plugins.length;

            use.apply(self, arguments);

            if (length !== self.plugins.length) {
                plugin(rootNode, self);
            }

            return self;
        };
    }

    /**
     * Define `Retext`. Exported above, and used to instantiate a new
     * `Retext`.
     *
     * Note that, when parser is a string or not given, the to-require module
     * is first removed from the Require cache. This results in a completly
     * new parser module, and a new TextOM object, thus clearing any changes
     * made to TextOM or the parser and that, for example, the following is
     * true:
     *
     *   !(new Retext().parse() instanceof new Retext().parse().constructor);
     *
     * The following however, is also true:
     *
     *   var retext = new Retext();
     *   retext.parse() instanceof retext.parse().constructor;
     *
     *
     * @param {(Object|String)?} parser - the parser, or its name, to use.
     *                                    Defaults to "parse-english".
     * @api public
     * @constructor
     */
    function Retext(parser) {
        var self = this,
            cache = require.cache,
            attribute;

        if (!parser) {
            parser = 'parse-english';
        }

        if (typeof parser === 'string') {
            /* Load the parser for vendors without dynamic-require's */
            if (parser === 'parse-english') {
                parser = require('parse-english');
            } else {
                parser = require(parser);
            }

            parser = parser();
        }

        self.parser = parser;
        self.plugins = [];
    }

    /**
     * `Retext#use` takes a plugin—a humble function—and when the parse
     * method of the Retext instance is called, the plugin will be called
     * with the parsed tree, and the retext instance as arguments.
     *
     * Note that, during the parsing stage, when the `use` method is called
     * by a plugin, the nested plugin is immediately called, before continuing
     * on with its parent plugin.
     *
     * @param {Function} plugin - the plugin to call when parsing.
     * @param {Function?} plugin.attach - called only once with a Retext
     *                                    instance. If you're planning on
     *                                    modifying TextOM or a parser, do it
     *                                    in this method.
     * @return this
     * @api public
     */
    Retext.prototype.use = function (plugin) {
        if (typeof plugin !== 'function') {
            throw new TypeError('Illegal invocation: \'' + plugin +
                '\' is not a valid argument for \'Retext.prototype.use\'');
        }

        var self = this,
            plugins = self.plugins;

        if (plugins.indexOf(plugin) === -1) {
            if (plugin.attach) {
                plugin.attach(self);
            }

            plugins.push(plugin);
        }

        return self;
    };

    /**
     * `Retext#parse` takes a source to be given (and parsed) by the parser.
     * Then, `parse` iterates over all plugins, and allows them to modify the
     * TextOM tree created by the parser.
     *
     * Note that, during the parsing stage, when the `use` plugin is called
     * by a plugin, the nested plugin is immediately called, before continuing
     * on with its parent plugin.
     *
     * @param {(String|Node)?} source - The source to convert.
     * @return {Node} - A RootNode containing the tokenised source.
     * @api public
     */
    Retext.prototype.parse = function (source) {
        var self = this,
            parser = self.parser,
            plugins = self.plugins.concat(),
            iterator = -1,
            use = self.use,
            rootNode = parser(source),
            plugin;

        self.use = useImmediately(rootNode, use);

        while (plugin = plugins[++iterator]) {
            plugin(rootNode, this);
        }

        self.use = use;

        return rootNode;
    };
})();
<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

module.exports = {
  name: 'ember-power-select',

  included(appOrAddon) {
    let app = appOrAddon.app || appOrAddon;
    if (!app.__emberPowerSelectIncludedInvoked) {
      app.__emberPowerSelectIncludedInvoked = true;

      let options = typeof app.options === 'object' ? app.options : {};
      let addonConfig = options['ember-power-select'] || {};

      // Since ember-power-select styles already `@import` styles of ember-basic-dropdown,
      // this flag tells to ember-basic-dropdown to skip importing its styles provided
      // we're using a theme (or the default styles)
      if (addonConfig.theme !== false) {
        app.__skipEmberBasicDropdownStyles = true;
      }

      this._super.included.apply(this, arguments);

      let hasSass = !!app.registry.availablePlugins['ember-cli-sass'];
      let hasLess = !!app.registry.availablePlugins['ember-cli-less'];

      // Don't include the precompiled css file if the user uses a supported CSS preprocessor
      if (!hasSass && !hasLess) {
        if (addonConfig.theme) {
          app.import(`vendor/ember-power-select-${addonConfig.theme}.css`);
        } else if (addonConfig.theme !== false) {
          app.import('vendor/ember-power-select.css');
        }
      }
    }
  },

  contentFor(type, config) {
    let emberBasicDropdown = this.addons.find((a) => a.name === 'ember-basic-dropdown');
    return emberBasicDropdown.contentFor(type, config);
  }
};
 <commit_msg>Fix app.import bug<commit_after>/* eslint-env node */
'use strict';

function lookupApp(appOrAddon) {
  if (appOrAddon.app) {
    return appOrAddon.app || appOrAddon;
  } else if (appOrAddon.parent){
    return appOrAddon.parent.app;
  }
}

module.exports = {
  name: 'ember-power-select',

  included(appOrAddon) {
    let app = lookupApp(appOrAddon);
    if (!app.__emberPowerSelectIncludedInvoked) {
      app.__emberPowerSelectIncludedInvoked = true;

      let options = typeof app.options === 'object' ? app.options : {};
      let addonConfig = options['ember-power-select'] || {};

      // Since ember-power-select styles already `@import` styles of ember-basic-dropdown,
      // this flag tells to ember-basic-dropdown to skip importing its styles provided
      // we're using a theme (or the default styles)
      if (addonConfig.theme !== false) {
        app.__skipEmberBasicDropdownStyles = true;
      }

      this._super.included.apply(this, arguments);

      let hasSass = !!app.registry.availablePlugins['ember-cli-sass'];
      let hasLess = !!app.registry.availablePlugins['ember-cli-less'];

      // Don't include the precompiled css file if the user uses a supported CSS preprocessor
      if (!hasSass && !hasLess) {
        if (addonConfig.theme) {
          app.import(`vendor/ember-power-select-${addonConfig.theme}.css`);
        } else if (addonConfig.theme !== false) {
          app.import('vendor/ember-power-select.css');
        }
      }
    }
  },

  contentFor(type, config) {
    let emberBasicDropdown = this.addons.find((a) => a.name === 'ember-basic-dropdown');
    return emberBasicDropdown.contentFor(type, config);
  }
};
<|endoftext|>


<commit_before>var mount = require('./dist/mount').default;

module.exports = {
  mount
};<commit_msg>Remove destructuring from index<commit_after>var mount = require('./dist/mount').default;

module.exports = {
  mount: mount
};<|endoftext|>


<commit_before>'use strict'

const SERVER_ERROR_CODE = 500
const WEBSOCKET_IDENTIFIER_ROUNDS = 16

// IMPORT
// =============================================================================
const Koa = require('koa')
const session = require('koa-session')
const router = require('koa-router')()
const app = new Koa()
require('koa-qs')(app)
const koaBody = require('koa-body')
const TrafficControl = require('./api/TrafficControl')
const render = require('koa-ejs')
const path = require('path')
const http = require('http')
const ws = require('ws')
const { URL } = require('url')
const logger = require('./api/logger')
const { promisify } = require('util')

const Permission = require('./api/permission')
const uid = require('uid-safe')
const npid = require('npid')

// Import config
const config = require('./config')

const Error = require('./api/errors')

// Import controllers
const Authentication = require('./api/controllers/auth')
const client = require('./api/controllers/client')
const decal = require('./api/controllers/decal')
const login = require('./api/controllers/login')
const nicknames = require('./api/controllers/nicknames')
const oauth2 = require('./api/controllers/oauth2')
const profile = require('./api/controllers/profile')
const rat = require('./api/controllers/rat')
const register = require('./api/controllers/register')
const reset = require('./api/controllers/reset')
const rescue = require('./api/controllers/rescue')
const ship = require('./api/controllers/ship')
const statistics = require('./api/controllers/statistics')
const user = require('./api/controllers/user')
const version = require('./api/controllers/version')
const WebSocketManager = require('./api/websocket')
const jiraDrill = require('./api/controllers/jira/drill')
const { AnopeWebhook } = require('./api/controllers/anope-webhook')
const { db } = require('./api/db')

try {
  npid.remove('api.pid')
  let pid = npid.create('api.pid')
  pid.removeOnExit()
} catch (err) {
  process.exit(1)
}

app.keys = [config.cookie.secret]

let sessionConfiguration = {
  key: 'fuelrats:session',
  overwrite: true,
  signed: true
}

app.use(session(sessionConfiguration, app))
app.use(require('koa-static')('static', {
  hidden: false,
  gzip: true
}))
app.use(koaBody())

let port = config.port || process.env.PORT

app.use(async function (ctx, next) {
  ctx.data = ctx.request.body
  ctx.meta = WebSocketManager.meta
  ctx.client = {}

  let { query } = ctx
  ctx.query = parseQuery(query)

  ctx.inet = ctx.request.req.headers['x-forwarded-for'] || ctx.request.ip
  await next()
})

app.use(async function (ctx, next) {
  if (Array.isArray(ctx.data) || typeof ctx.data === 'object') {
    ['id', 'createdAt', 'updatedAt', 'deletedAt'].map((cleanField) => {
      delete ctx.data[cleanField]
    })
  }
  await next()
})

const traffic = new TrafficControl()

app.use(async (ctx, next) => {
  try {
    await Authentication.authenticate(ctx)

    let rateLimit = traffic.validateRateLimit(ctx)

    ctx.set('X-API-Version', '2.0')
    ctx.set('X-Rate-Limit-Limit', rateLimit.total)
    ctx.set('X-Rate-Limit-Remaining', rateLimit.remaining)
    ctx.set('X-Rate-Limit-Reset', rateLimit.nextResetDate)

    logger.info({ tags: ['request'] }, `Request by ${ctx.inet} to ${ctx.request.path}`, {
      'ip': ctx.inet,
      'path': ctx.request.path,
      'rate-limit-limit': rateLimit.total,
      'rate-limit-remaining': rateLimit.remaining,
      'query': ctx.query,
      'body': censor(ctx.data),
      'method': ctx.request.req.method
    })

    if (rateLimit.exceeded) {
      return next(Error.template('rate_limit_exceeded'))
    }

    let result = await next()
    if (result === true) {
      ctx.status = 204
    } else if (result) {
      ctx.body = result
    }
  } catch (ex) {
    let error = ex
    if (!error.code) {
      error = Error.template('server_error', error)
    }
    ctx.body = {
      errors: [error]
    }

    ctx.status = error.code || SERVER_ERROR_CODE
    if (error.code === SERVER_ERROR_CODE) {
      logger.error(error)
      ctx.app.emit('error', ex, ctx)
    }
  }
})

render(app, {
  root: path.join(__dirname, 'views'),
  layout: false,
  viewExt: 'html',
  cache: false,
  debug: true
})

// ROUTES
// =============================================================================
router.get('/rescues', Authentication.isAuthenticated, Permission.required(['rescue.read']), rescue.search)
router.get('/rescues/:id', Authentication.isAuthenticated, Permission.required(['rescue.read']), rescue.findById)
router.post('/rescues', Authentication.isAuthenticated, Permission.required(['rescue.write']), rescue.create)
router.put('/rescues/:id', Authentication.isAuthenticated, rescue.update)
router.put('/rescues/assign/:id', Authentication.isAuthenticated, rescue.assign)
router.put('/rescues/addquote/:id', Authentication.isAuthenticated, rescue.assign)
router.put('/rescues/unassign/:id', Authentication.isAuthenticated, rescue.unassign)
router.delete('/rescues/:id', Authentication.isAuthenticated, Permission.required(['rescue.delete']), rescue.delete)

router.get('/clients', Authentication.isAuthenticated, Permission.required(['client.read']), client.search)
router.get('/clients/:id', Authentication.isAuthenticated, client.findById)
router.post('/clients', Authentication.isAuthenticated, client.create)
router.put('/clients/:id', Authentication.isAuthenticated, client.update)
router.delete('/clients/:id', Authentication.isAuthenticated, Permission.required(['client.delete']), client.delete)

router.get('/users', Authentication.isAuthenticated, Permission.required(['user.read']), user.search)
router.get('/users/:id', Authentication.isAuthenticated, user.findById)
router.get('/users/image/:id', user.image)
router.post('/users', Authentication.isAuthenticated, user.create)
router.put('/users/setpassword', Authentication.isAuthenticated, user.setpassword)
router.post('/users/image/:id', Authentication.isAuthenticated, user.setimage)
router.put('/users/:id/updatevirtualhost', Authentication.isAuthenticated,
  Permission.required(['user.write']), user.updatevirtualhost)
router.put('/users/:id', clean('image', 'password'), Authentication.isAuthenticated, user.update)
router.delete('/users/:id', Authentication.isAuthenticated, Permission.required(['user.delete']), user.delete)

router.get('/nicknames/info/:nickname', Authentication.isAuthenticated, nicknames.info)
router.get('/nicknames/:nickname', Authentication.isAuthenticated, nicknames.search)
router.post('/nicknames', Authentication.isAuthenticated, nicknames.register)
router.put('/nicknames', Authentication.isAuthenticated, nicknames.connect)
router.delete('/nicknames/:nickname', Authentication.isAuthenticated, nicknames.delete)

router.get('/rats', rat.search)
router.get('/rats/:id', rat.findById)
router.post('/rats', rat.create)
router.put('/rats/:id', rat.update)
router.delete('/rats/:id', Permission.required(['rat.delete']), rat.delete)

router.get('/ships', ship.search)
router.get('/ships/:id', ship.findById)
router.post('/ships', fields('name', 'shipType', 'ratId'), clean('shipId'), ship.create)
router.put('/ships/:id', clean('shipId'), ship.update)
router.delete('/ships/:id', rat.delete)

router.get('/welcome', (ctx) => {
  ctx.redirect('https://fuelrats.com/profile')
  ctx.status = 301
})

router.post('/login', fields('email', 'password'), login.login)
router.post('/register', fields('email', 'password', 'name', 'platform', 'nickname'),
  register.create)
router.get('/profile', Authentication.isAuthenticated, Permission.required(['user.read.me']), profile.read)

router.post('/anope', Authentication.isWhitelisted, AnopeWebhook.update)

router.get('/oauth2/authorize',
  Authentication.isAuthenticated,
  oauth2.authorizationValidateFields,
  oauth2.authorizationValidateRedirect,
  oauth2.authorizationRender
)

router.post('/oauth2/authorize', Authentication.isAuthenticated, ...oauth2.server.decision())

// Create endpoint handlers for oauth2 token
router.post('/oauth2/token',
  Authentication.isClientAuthenticated,
  oauth2.server.token(),
  oauth2.server.errorHandler())

router.post('/oauth2/revoke', Authentication.isClientAuthenticated, oauth2.revoke)
router.post('/oauth2/revokeall', Authentication.isClientAuthenticated, oauth2.revokeAll)

router.get('/statistics/rescues', statistics.rescues)
router.get('/statistics/systems', statistics.systems)
router.get('/statistics/rats', statistics.rats)

router.get('/version', version.read)
router.post('/reset', fields('email'), reset.requestReset)
router.get('/reset/:token', reset.validateReset)
router.post('/reset/:token', fields('password'), reset.resetPassword)

router.get('/decals/check', Authentication.isAuthenticated, decal.check)
router.get('/decals/redeem', Authentication.isAuthenticated, decal.redeem)
router.post('/jira/drill', Authentication.isAuthenticated, Permission.required(['user.write']), jiraDrill.update)

/*

router.get('/news', API.route(news.list))

router.get('/logout', logout.post)
router.post('/logout', logout.post)

router.post('/jira/drill', auth.isJiraAuthenticated(), Permission.required('user.update', false), jiraDrill.post)
router.post('/irc/message', auth.isAuthenticated(false), Permission.required('irc.oper', false), irc.message)
router.post('/irc/action', auth.isAuthenticated(false), Permission.required('irc.oper', false), irc.action)

 */

app.use(router.routes())
app.use(router.allowedMethods())

/**
 * Parses an object of URL query parameters and builds a nested object by delimiting periods into sub objects.
 * @param query an array of URL query parameters
 * @returns {{}} a nested object
 */
function parseQuery (query) {
  let queryObj = {}

  // Iterate over each individual query item
  for (let key of Object.keys(query)) {
    // Split them into period delimited arrays
    let keys = key.split('.')
    let target = queryObj

    // Iterate over the period delimited arrays to construct a nested hierarchy
    for (let keyPair of keys.entries()) {
      let [, subkey ] = keyPair
      if (keyPair[0] === keys.length - 1) {
        // We have reached the end of the delimited array which means we can insert the value

        target[subkey] = query[key]
      } else if (!target[subkey]) {
        /* We have not reached the end of the delimited array so we need to create a nested object unless
        it already exists */
        target[subkey] = {}
        target = target[subkey]
      }
    }
  }
  return queryObj
}

let server = http.createServer(app.callback())
const wss = new ws.Server({ server })

const websocketManager = new WebSocketManager(wss, traffic)

wss.on('connection', async function connection (client, req) {
  let url = new URL(`http://localhost:8082${req.url}`)
  client.req = req
  client.clientId = uid.sync(WEBSOCKET_IDENTIFIER_ROUNDS)
  client.subscriptions = []

  let bearer = url.searchParams.get('bearer')
  if (bearer) {
    let { user, scope } = await Authentication.bearerAuthenticate(bearer)
    if (user) {
      client.user = user
      client.scope = scope
    }
  }

  websocketManager.onConnection(client)

  client.on('message', (message) => {
    client.websocket = wss
    try {
      let request = JSON.parse(message)
      websocketManager.onMessage(client, request)
    } catch (ex) {
      logger.info('Failed to parse incoming websocket message')
    }
  })
})

/**
 * Goes through an object and sets properties commonly usde to hold sensitive information to a static value.
 * @param obj The object to censor
 * @returns {{}} A censored object
 */
function censor (obj) {
  let censoredObj = {}
  Object.assign(censoredObj, obj)

  if (censoredObj.password) {
    censoredObj.password = '[CENSORED]'
  }
  if (censoredObj.secret) {
    censoredObj.secret = '[CENSORED]'
  }

  return censoredObj
}

/**
 * Makes sure the request object has the required data fields specified
 * @param requiredFields The data fields to require
 * @returns {Function} A promise
 */
function fields (...requiredFields) {
  return function (ctx, next) {
    let missingFields = requiredFields.filter((requiredField) => {
      return ctx.data.hasOwnProperty(requiredField) === false
    })
    if (missingFields.length > 0) {
      throw Error.template('missing_required_fields', missingFields)
    }
    return next()
  }
}

/**
 * Removes the specified data fields from the request object
 * @param cleanFields The data fields to clean away
 * @returns {Function} A promise
 */
function clean (...cleanFields) {
  return function (ctx, next) {
    if (Array.isArray(ctx.data) || typeof ctx.data === 'object') {
      cleanFields.map((cleanField) => {
        ctx.data[cleanField] = undefined
      })
    }
    return next()
  }
}

(async function startServer () {
  try {
    await db.sync()
    const listen = promisify(server.listen.bind(server))
    await listen(port, config.hostname)
    logger.info(`HTTP Server listening on ${config.hostname} port ${port}`)
  } catch (error) {
    logger.error(error)
  }
})()

// allow launch of app from unit tests
module.exports = server<commit_msg>Get the actual IP of user not all the proxy pass IPs<commit_after>'use strict'

const SERVER_ERROR_CODE = 500
const WEBSOCKET_IDENTIFIER_ROUNDS = 16

// IMPORT
// =============================================================================
const Koa = require('koa')
const session = require('koa-session')
const router = require('koa-router')()
const app = new Koa()
require('koa-qs')(app)
const koaBody = require('koa-body')
const TrafficControl = require('./api/TrafficControl')
const render = require('koa-ejs')
const path = require('path')
const http = require('http')
const ws = require('ws')
const { URL } = require('url')
const logger = require('./api/logger')
const { promisify } = require('util')

const Permission = require('./api/permission')
const uid = require('uid-safe')
const npid = require('npid')

// Import config
const config = require('./config')

const Error = require('./api/errors')

// Import controllers
const Authentication = require('./api/controllers/auth')
const client = require('./api/controllers/client')
const decal = require('./api/controllers/decal')
const login = require('./api/controllers/login')
const nicknames = require('./api/controllers/nicknames')
const oauth2 = require('./api/controllers/oauth2')
const profile = require('./api/controllers/profile')
const rat = require('./api/controllers/rat')
const register = require('./api/controllers/register')
const reset = require('./api/controllers/reset')
const rescue = require('./api/controllers/rescue')
const ship = require('./api/controllers/ship')
const statistics = require('./api/controllers/statistics')
const user = require('./api/controllers/user')
const version = require('./api/controllers/version')
const WebSocketManager = require('./api/websocket')
const jiraDrill = require('./api/controllers/jira/drill')
const { AnopeWebhook } = require('./api/controllers/anope-webhook')
const { db } = require('./api/db')

try {
  npid.remove('api.pid')
  let pid = npid.create('api.pid')
  pid.removeOnExit()
} catch (err) {
  process.exit(1)
}

app.keys = [config.cookie.secret]

let sessionConfiguration = {
  key: 'fuelrats:session',
  overwrite: true,
  signed: true
}

app.use(session(sessionConfiguration, app))
app.use(require('koa-static')('static', {
  hidden: false,
  gzip: true
}))
app.use(koaBody())

let port = config.port || process.env.PORT

app.use(async function (ctx, next) {
  ctx.data = ctx.request.body
  ctx.meta = WebSocketManager.meta
  ctx.client = {}

  let { query } = ctx
  ctx.query = parseQuery(query)

  ctx.inet = ctx.request.req.headers['x-forwarded-for'] || ctx.request.ip
  if (Object.isArray(ctx.inet)) {
    [ctx.inet] = ctx.inet
  }
  await next()
})

app.use(async function (ctx, next) {
  if (Array.isArray(ctx.data) || typeof ctx.data === 'object') {
    ['id', 'createdAt', 'updatedAt', 'deletedAt'].map((cleanField) => {
      delete ctx.data[cleanField]
    })
  }
  await next()
})

const traffic = new TrafficControl()

app.use(async (ctx, next) => {
  try {
    await Authentication.authenticate(ctx)

    let rateLimit = traffic.validateRateLimit(ctx)

    ctx.set('X-API-Version', '2.0')
    ctx.set('X-Rate-Limit-Limit', rateLimit.total)
    ctx.set('X-Rate-Limit-Remaining', rateLimit.remaining)
    ctx.set('X-Rate-Limit-Reset', rateLimit.nextResetDate)

    logger.info({ tags: ['request'] }, `Request by ${ctx.inet} to ${ctx.request.path}`, {
      'ip': ctx.inet,
      'path': ctx.request.path,
      'rate-limit-limit': rateLimit.total,
      'rate-limit-remaining': rateLimit.remaining,
      'query': ctx.query,
      'body': censor(ctx.data),
      'method': ctx.request.req.method
    })

    if (rateLimit.exceeded) {
      return next(Error.template('rate_limit_exceeded'))
    }

    let result = await next()
    if (result === true) {
      ctx.status = 204
    } else if (result) {
      ctx.body = result
    }
  } catch (ex) {
    let error = ex
    if (!error.code) {
      error = Error.template('server_error', error)
    }
    ctx.body = {
      errors: [error]
    }

    ctx.status = error.code || SERVER_ERROR_CODE
    if (error.code === SERVER_ERROR_CODE) {
      logger.error(error)
      ctx.app.emit('error', ex, ctx)
    }
  }
})

render(app, {
  root: path.join(__dirname, 'views'),
  layout: false,
  viewExt: 'html',
  cache: false,
  debug: true
})

// ROUTES
// =============================================================================
router.get('/rescues', Authentication.isAuthenticated, Permission.required(['rescue.read']), rescue.search)
router.get('/rescues/:id', Authentication.isAuthenticated, Permission.required(['rescue.read']), rescue.findById)
router.post('/rescues', Authentication.isAuthenticated, Permission.required(['rescue.write']), rescue.create)
router.put('/rescues/:id', Authentication.isAuthenticated, rescue.update)
router.put('/rescues/assign/:id', Authentication.isAuthenticated, rescue.assign)
router.put('/rescues/addquote/:id', Authentication.isAuthenticated, rescue.assign)
router.put('/rescues/unassign/:id', Authentication.isAuthenticated, rescue.unassign)
router.delete('/rescues/:id', Authentication.isAuthenticated, Permission.required(['rescue.delete']), rescue.delete)

router.get('/clients', Authentication.isAuthenticated, Permission.required(['client.read']), client.search)
router.get('/clients/:id', Authentication.isAuthenticated, client.findById)
router.post('/clients', Authentication.isAuthenticated, client.create)
router.put('/clients/:id', Authentication.isAuthenticated, client.update)
router.delete('/clients/:id', Authentication.isAuthenticated, Permission.required(['client.delete']), client.delete)

router.get('/users', Authentication.isAuthenticated, Permission.required(['user.read']), user.search)
router.get('/users/:id', Authentication.isAuthenticated, user.findById)
router.get('/users/image/:id', user.image)
router.post('/users', Authentication.isAuthenticated, user.create)
router.put('/users/setpassword', Authentication.isAuthenticated, user.setpassword)
router.post('/users/image/:id', Authentication.isAuthenticated, user.setimage)
router.put('/users/:id/updatevirtualhost', Authentication.isAuthenticated,
  Permission.required(['user.write']), user.updatevirtualhost)
router.put('/users/:id', clean('image', 'password'), Authentication.isAuthenticated, user.update)
router.delete('/users/:id', Authentication.isAuthenticated, Permission.required(['user.delete']), user.delete)

router.get('/nicknames/info/:nickname', Authentication.isAuthenticated, nicknames.info)
router.get('/nicknames/:nickname', Authentication.isAuthenticated, nicknames.search)
router.post('/nicknames', Authentication.isAuthenticated, nicknames.register)
router.put('/nicknames', Authentication.isAuthenticated, nicknames.connect)
router.delete('/nicknames/:nickname', Authentication.isAuthenticated, nicknames.delete)

router.get('/rats', rat.search)
router.get('/rats/:id', rat.findById)
router.post('/rats', rat.create)
router.put('/rats/:id', rat.update)
router.delete('/rats/:id', Permission.required(['rat.delete']), rat.delete)

router.get('/ships', ship.search)
router.get('/ships/:id', ship.findById)
router.post('/ships', fields('name', 'shipType', 'ratId'), clean('shipId'), ship.create)
router.put('/ships/:id', clean('shipId'), ship.update)
router.delete('/ships/:id', rat.delete)

router.get('/welcome', (ctx) => {
  ctx.redirect('https://fuelrats.com/profile')
  ctx.status = 301
})

router.post('/login', fields('email', 'password'), login.login)
router.post('/register', fields('email', 'password', 'name', 'platform', 'nickname'),
  register.create)
router.get('/profile', Authentication.isAuthenticated, Permission.required(['user.read.me']), profile.read)

router.post('/anope', Authentication.isWhitelisted, AnopeWebhook.update)

router.get('/oauth2/authorize',
  Authentication.isAuthenticated,
  oauth2.authorizationValidateFields,
  oauth2.authorizationValidateRedirect,
  oauth2.authorizationRender
)

router.post('/oauth2/authorize', Authentication.isAuthenticated, ...oauth2.server.decision())

// Create endpoint handlers for oauth2 token
router.post('/oauth2/token',
  Authentication.isClientAuthenticated,
  oauth2.server.token(),
  oauth2.server.errorHandler())

router.post('/oauth2/revoke', Authentication.isClientAuthenticated, oauth2.revoke)
router.post('/oauth2/revokeall', Authentication.isClientAuthenticated, oauth2.revokeAll)

router.get('/statistics/rescues', statistics.rescues)
router.get('/statistics/systems', statistics.systems)
router.get('/statistics/rats', statistics.rats)

router.get('/version', version.read)
router.post('/reset', fields('email'), reset.requestReset)
router.get('/reset/:token', reset.validateReset)
router.post('/reset/:token', fields('password'), reset.resetPassword)

router.get('/decals/check', Authentication.isAuthenticated, decal.check)
router.get('/decals/redeem', Authentication.isAuthenticated, decal.redeem)
router.post('/jira/drill', Authentication.isAuthenticated, Permission.required(['user.write']), jiraDrill.update)

/*

router.get('/news', API.route(news.list))

router.get('/logout', logout.post)
router.post('/logout', logout.post)

router.post('/jira/drill', auth.isJiraAuthenticated(), Permission.required('user.update', false), jiraDrill.post)
router.post('/irc/message', auth.isAuthenticated(false), Permission.required('irc.oper', false), irc.message)
router.post('/irc/action', auth.isAuthenticated(false), Permission.required('irc.oper', false), irc.action)

 */

app.use(router.routes())
app.use(router.allowedMethods())

/**
 * Parses an object of URL query parameters and builds a nested object by delimiting periods into sub objects.
 * @param query an array of URL query parameters
 * @returns {{}} a nested object
 */
function parseQuery (query) {
  let queryObj = {}

  // Iterate over each individual query item
  for (let key of Object.keys(query)) {
    // Split them into period delimited arrays
    let keys = key.split('.')
    let target = queryObj

    // Iterate over the period delimited arrays to construct a nested hierarchy
    for (let keyPair of keys.entries()) {
      let [, subkey ] = keyPair
      if (keyPair[0] === keys.length - 1) {
        // We have reached the end of the delimited array which means we can insert the value

        target[subkey] = query[key]
      } else if (!target[subkey]) {
        /* We have not reached the end of the delimited array so we need to create a nested object unless
        it already exists */
        target[subkey] = {}
        target = target[subkey]
      }
    }
  }
  return queryObj
}

let server = http.createServer(app.callback())
const wss = new ws.Server({ server })

const websocketManager = new WebSocketManager(wss, traffic)

wss.on('connection', async function connection (client, req) {
  let url = new URL(`http://localhost:8082${req.url}`)
  client.req = req
  client.clientId = uid.sync(WEBSOCKET_IDENTIFIER_ROUNDS)
  client.subscriptions = []

  let bearer = url.searchParams.get('bearer')
  if (bearer) {
    let { user, scope } = await Authentication.bearerAuthenticate(bearer)
    if (user) {
      client.user = user
      client.scope = scope
    }
  }

  websocketManager.onConnection(client)

  client.on('message', (message) => {
    client.websocket = wss
    try {
      let request = JSON.parse(message)
      websocketManager.onMessage(client, request)
    } catch (ex) {
      logger.info('Failed to parse incoming websocket message')
    }
  })
})

/**
 * Goes through an object and sets properties commonly usde to hold sensitive information to a static value.
 * @param obj The object to censor
 * @returns {{}} A censored object
 */
function censor (obj) {
  let censoredObj = {}
  Object.assign(censoredObj, obj)

  if (censoredObj.password) {
    censoredObj.password = '[CENSORED]'
  }
  if (censoredObj.secret) {
    censoredObj.secret = '[CENSORED]'
  }

  return censoredObj
}

/**
 * Makes sure the request object has the required data fields specified
 * @param requiredFields The data fields to require
 * @returns {Function} A promise
 */
function fields (...requiredFields) {
  return function (ctx, next) {
    let missingFields = requiredFields.filter((requiredField) => {
      return ctx.data.hasOwnProperty(requiredField) === false
    })
    if (missingFields.length > 0) {
      throw Error.template('missing_required_fields', missingFields)
    }
    return next()
  }
}

/**
 * Removes the specified data fields from the request object
 * @param cleanFields The data fields to clean away
 * @returns {Function} A promise
 */
function clean (...cleanFields) {
  return function (ctx, next) {
    if (Array.isArray(ctx.data) || typeof ctx.data === 'object') {
      cleanFields.map((cleanField) => {
        ctx.data[cleanField] = undefined
      })
    }
    return next()
  }
}

(async function startServer () {
  try {
    await db.sync()
    const listen = promisify(server.listen.bind(server))
    await listen(port, config.hostname)
    logger.info(`HTTP Server listening on ${config.hostname} port ${port}`)
  } catch (error) {
    logger.error(error)
  }
})()

// allow launch of app from unit tests
module.exports = server<|endoftext|>


<commit_before>var extend = require('extend')
var kiki = require('kiki')

// TODO: remove kiki (after migration)
module.exports = extend({
  Sections: require('./lib/sectionTypes'),
  Identity: require('./lib/identity'),
  AddressBook: require('./lib/addressbook'),
  defaultKeySet: require('./lib/defaultKeySet')
}, kiki)
<commit_msg>don't export kiki anymore<commit_after>
module.exports = {
  Sections: require('./lib/sectionTypes'),
  Identity: require('./lib/identity'),
  AddressBook: require('./lib/addressbook'),
  defaultKeySet: require('./lib/defaultKeySet')
}
<|endoftext|>


<commit_before>var _ = require('underscore')
  , _s = require('underscore.string')
  , async = require('async')
  , exec = require('child_process').exec
  , fs = require('fs')
  , path = require('path')
  , qs = require('qs')
  , request = require('request')
  , temp = require('temp');

module.exports = function (options, callback) {
  var params = {
      client: 'chromium'
    , lang: 'en-US'
    , maxResults: 1
    , pfilter: 1
    , xjerr: 1
  }

  options = _.defaults(options, params, {
      clipSize: 15
    , maxRequests: 4
    , sampleRate: 16000
  });

  var headers = {'content-type': 'audio/x-flac; rate=' + options.sampleRate}
    , url = 'https://www.google.com/speech-api/v1/recognize?' + qs.stringify(params);

  var getSpeech = function (file, callback) {
    fs.readFile(file, function (err, data) {
      if (err) return callback(err);

      request.post({body: data, headers: headers, url: url},
        function (err, res, body) {
          if (err) return callback(err);
          if (_s.contains(body, 'HTML')) return callback(body);

          try {
            callback(null, JSON.parse(body));
          }
          catch (e) {
            callback(e);
          }
          finally {
            fs.unlink(file);
          }
      });
    });
  };

  // get audio duration
  var cmd = _s.sprintf('sox --i -D %s', options.file);

  exec(cmd, function (err, duration) {
    if (err) return callback(err);

    // normalize audio
    var output = temp.path();
    cmd = _s.sprintf('sox "%s" -r %d "%s.flac" gain -n -5 silence 1 5 2%%', options.file, options.sampleRate, output);

    exec(cmd, function (err) {
      if (err) return callback(err);

      // split into 15 second sound clips
      cmd = _s.sprintf('sox "%s.flac" "%s%%1n.flac" trim 0 %d : newfile : restart', output, output, options.clipSize);

      exec(cmd, function (err) {
        fs.unlink(output + '.flac');
        if (err) return callback(err);

        var files = []
          , count = Math.ceil(duration / options.clipSize);

        // push sound clip file names to array
        _.times(count, function (n) {
          files.push(output + (n + 1) + '.flac');
        });

        // get speech for each sound clip
        async.mapLimit(files, options.maxRequests, getSpeech, callback);
      });
    });
  });
};<commit_msg>fix unset parameters<commit_after>var _ = require('underscore')
  , _s = require('underscore.string')
  , async = require('async')
  , exec = require('child_process').exec
  , fs = require('fs')
  , path = require('path')
  , qs = require('qs')
  , request = require('request')
  , temp = require('temp');

module.exports = function (options, callback) {
  var params = {
      client: 'chromium'
    , lang: 'en-US'
    , maxResults: 1
    , pfilter: 1
    , xjerr: 1
  };

  params = _.extend(params, _.pick.apply(this, [options].concat(_.keys(params))));

  options = _.defaults(options, params, {
      clipSize: 15
    , maxRequests: 4
    , sampleRate: 16000
  });

  var headers = {'content-type': 'audio/x-flac; rate=' + options.sampleRate}
    , url = 'https://www.google.com/speech-api/v1/recognize?' + qs.stringify(params);

  var getSpeech = function (file, callback) {
    fs.readFile(file, function (err, data) {
      if (err) return callback(err);

      request.post({body: data, headers: headers, url: url},
        function (err, res, body) {
          if (err) return callback(err);
          if (_s.contains(body, 'HTML')) return callback(body);

          try {
            callback(null, JSON.parse(body));
          }
          catch (e) {
            callback(e);
          }
          finally {
            fs.unlink(file);
          }
      });
    });
  };

  // get audio duration
  var cmd = _s.sprintf('sox --i -D %s', options.file);

  exec(cmd, function (err, duration) {
    if (err) return callback(err);

    // normalize audio
    var output = temp.path();
    cmd = _s.sprintf('sox "%s" -r %d "%s.flac" gain -n -5 silence 1 5 2%%', options.file, options.sampleRate, output);

    exec(cmd, function (err) {
      if (err) return callback(err);

      // split into 15 second sound clips
      cmd = _s.sprintf('sox "%s.flac" "%s%%1n.flac" trim 0 %d : newfile : restart', output, output, options.clipSize);

      exec(cmd, function (err) {
        fs.unlink(output + '.flac');
        if (err) return callback(err);

        var files = []
          , count = Math.ceil(duration / options.clipSize);

        // push sound clip file names to array
        _.times(count, function (n) {
          files.push(output + (n + 1) + '.flac');
        });

        // get speech for each sound clip
        async.mapLimit(files, options.maxRequests, getSpeech, callback);
      });
    });
  });
};<|endoftext|>


<commit_before>/*!
 * pwrline-js <https://github.com/akileez/pwrline-js>
 *
 * Copyright (c) 2015 Keith Williams.
 * Licensed under the ISC license.
 */

'use strict'

module.exports = function () {
  // do stuff
}
<commit_msg>remove index.js<commit_after><|endoftext|>


<commit_before>'use strict';

// Check that libusb was initialized.
if (!chrome.usb) {
  throw new Error('Could not initialize libusb. Check your app manifest permissions.');
}

function toBuffer(ab) {
  var buffer = new Buffer(ab.byteLength);
  var view = new Uint8Array(ab);
  for (var i = 0; i < buffer.length; ++i) {
      buffer[i] = view[i];
  }
  return buffer;
}

function toArrayBuffer(buffer) {
  var ab = new ArrayBuffer(buffer.length);
  var view = new Uint8Array(ab);
  for (var i = 0; i < buffer.length; ++i) {
      view[i] = buffer[i];
  }
  return ab;
}

// convenience method for finding a device by vendor and product id
exports.findByIds = function(vid, pid, cb) {
  chrome.usb.getDevices({'vendorId': vid, 'productId': pid}, function(devices){
    if(typeof devices === undefined){
      return cb(new Error('Permission denied.'));
    }

    if (devices.length === 0){
      return cb();
    }

    cb(null, new Device(devices[0]));

  });

  var Device = function(device) {
    this.device = device;
    this.handle = null;
  };

  Device.prototype.controlTransfer = function(bmRequestType, bRequest, wValue, wIndex, data_or_length, cb){

    var transferInfo = {
      request: bRequest,
      value: wValue,
      index: wIndex
    };

    // in libusb requesttype is (USB_ENDPOINT_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE)
    // in chrome they're split out to direction requestType and recipient
    // so take bmRequestType and mask off the bits we want for vendor

    var requestType = (bmRequestType & 0x60) >> 5;
     switch (requestType) {
      case 0:
        transferInfo.requestType = 'standard';
        break;
      case 1:
        transferInfo.requestType = 'class';
        break;
      case 2:
        transferInfo.requestType = 'vendor';
        break;
      case 3:
        transferInfo.requestType = 'reserved';
        break;
    }

    var recipient = (bmRequestType & 0x1F);
     switch (recipient) {
      case 0:
        transferInfo.recipient = 'device';
        break;
      case 1:
        transferInfo.recipient = 'interface';
        break;
      case 2:
        transferInfo.recipient = 'endpoint';
        break;
      case 3:
        transferInfo.recipient = 'other';
        break;
    }

    if(typeof data_or_length === 'number'){
      transferInfo.direction = 'in';
      transferInfo.length = data_or_length;
    }

    if(Buffer.isBuffer(data_or_length)){
      transferInfo.direction = 'out';
      transferInfo.data = toArrayBuffer(data_or_length);
    }

    chrome.usb.controlTransfer( this.handle, transferInfo, function(info){

      //info.data undefined for output transfers, maybe also if there is no data?
      cb(chrome.runtime.lastError, toBuffer(info.data));
    });

  };

  Device.prototype.open = function(cb){
    var self = this;
    chrome.usb.openDevice(this.device, function (handle) {
        self.handle = handle;
        return cb();
    });

  };

  Device.prototype.close = function(){
    chrome.usb.closeDevice(this.handle);
  };

};
<commit_msg>pull open the Device type<commit_after>'use strict';

// Check that libusb was initialized.
if (!chrome.usb) {
  throw new Error('Could not initialize libusb. Check your app manifest permissions.');
}

function toBuffer(ab) {
  var buffer = new Buffer(ab.byteLength);
  var view = new Uint8Array(ab);
  for (var i = 0; i < buffer.length; ++i) {
      buffer[i] = view[i];
  }
  return buffer;
}

function toArrayBuffer(buffer) {
  var ab = new ArrayBuffer(buffer.length);
  var view = new Uint8Array(ab);
  for (var i = 0; i < buffer.length; ++i) {
      view[i] = buffer[i];
  }
  return ab;
}

var Device = function(device) {
  this.device = device;
  this.handle = null;
};

Device.prototype.controlTransfer = function(bmRequestType, bRequest, wValue, wIndex, data_or_length, cb){

  var transferInfo = {
    request: bRequest,
    value: wValue,
    index: wIndex
  };

  // in libusb requesttype is (USB_ENDPOINT_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE)
  // in chrome they're split out to direction requestType and recipient
  // so take bmRequestType and mask off the bits we want for vendor

  var requestType = (bmRequestType & 0x60) >> 5;
   switch (requestType) {
    case 0:
      transferInfo.requestType = 'standard';
      break;
    case 1:
      transferInfo.requestType = 'class';
      break;
    case 2:
      transferInfo.requestType = 'vendor';
      break;
    case 3:
      transferInfo.requestType = 'reserved';
      break;
  }

  var recipient = (bmRequestType & 0x1F);
   switch (recipient) {
    case 0:
      transferInfo.recipient = 'device';
      break;
    case 1:
      transferInfo.recipient = 'interface';
      break;
    case 2:
      transferInfo.recipient = 'endpoint';
      break;
    case 3:
      transferInfo.recipient = 'other';
      break;
  }

  if(typeof data_or_length === 'number'){
    transferInfo.direction = 'in';
    transferInfo.length = data_or_length;
  }

  if(Buffer.isBuffer(data_or_length)){
    transferInfo.direction = 'out';
    transferInfo.data = toArrayBuffer(data_or_length);
  }

  chrome.usb.controlTransfer( this.handle, transferInfo, function(info){

    //info.data undefined for output transfers, maybe also if there is no data?
    cb(chrome.runtime.lastError, toBuffer(info.data));
  });

};

Device.prototype.open = function(cb){
  var self = this;
  chrome.usb.openDevice(this.device, function (handle) {
      self.handle = handle;
      return cb();
  });

};

Device.prototype.close = function(){
  chrome.usb.closeDevice(this.handle);
};

// convenience method for finding a device by vendor and product id
exports.findByIds = function(vid, pid, cb) {
  chrome.usb.getDevices({'vendorId': vid, 'productId': pid}, function(devices){
    if(typeof devices === undefined){
      return cb(new Error('Permission denied.'));
    }

    if (devices.length === 0){
      return cb();
    }

    cb(null, new Device(devices[0]));

  });
};
<|endoftext|>


<commit_before>/*!
 * copyright-regex <https://github.com/regexps/copyright-regex>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function copyrightRegex() {
  return /(?!.*(?:\{|\}|\);))(?:(copyright)[ \t]*(?:(©|\(c\)|&#(?:169|xa9;)|©)[ \t]+)?)(?:((?:((?:(?:19|20)[0-9]{2}))[^\w]*)*)([\w\s]*))/i;
};
<commit_msg>allow commas in names<commit_after>/*!
 * copyright-regex <https://github.com/regexps/copyright-regex>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function copyrightRegex() {
  return /(?!.*(?:\{|\}|\);))(?:(copyright)[ \t]*(?:(©|\(c\)|&#(?:169|xa9;)|©)[ \t]+)?)(?:((?:((?:(?:19|20)[0-9]{2}))[^\w]*)*)([\w\s,]*))/i;
};
<|endoftext|>


<commit_before>var reduce = require('universal-reduce')
var reduced = reduce.reduced

var getStep = require('./get-step')
var done = require('./done')

module.exports = photocopy

function photocopy (original, tx, seed, step) {
  if (typeof tx !== 'function') tx = identity
  if (typeof seed === 'undefined') {
    seed = new (original.constructor || Object)
  }
  if (typeof step !== 'function') step = getStep(seed)
  // Initialize transducer
  var transducer = tx(step)
  // apply to the collection
  var acc = reduce(original, transducer, seed)
  // flush remaining state.
  var finalVal = transducer(acc)
  if (finalVal instanceof reduced) return finalVal.val
  return finalVal
}

function identity (next) {
  return next
}

function cat (next) {
  return function (acc, value, key) {
    return reduce(value, next, acc)
  }
}

var filter = simple(function (fn, next, acc, val, key) {
  return fn(val, key) ? next(acc, val, key) : acc
})

var map = simple(function (fn, next, acc, val, key) {
  return next(acc, fn(val, key), key)
})

var keyMap = simple(function (fn, next, acc, val, key) {
  return next(acc, val, fn(val, key))
})

function take (n) {
  return function (next) {
    var i = 0
    return function (acc, val, key) {
      if (i >= n) return acc
      i += 1
      return next(acc, val, key)
    }
  }
}

function skip (n) {
  return function (next) {
    var i = 0
    return function (acc, val, key) {
      if (i >= n) return next(acc, val, key)
      i += 1
      return acc
    }
  }
}

photocopy({
  identity: identity,
  cat: cat,
  simple: simple,
  filter: filter,
  map: map,
  keyMap: keyMap,
  reduced: reduced,
  byKey: byKey,
  comp: comp,
  done: done,
  take: take,
  skip: skip
}, null, photocopy)

function byKey (acc, value, key) {
  if (done(acc, value, key)) {
    return acc
  }
  var arr = acc[key] || (acc[key] = [])
  arr.push(value)
  return acc
}

function simple (setup) {
  return function (fn) {
    return function (next) {
      // setup state here
      return function (acc, val, key) {
        if (done(acc, val, key)) {
          return next.apply(null, arguments)
        }
        return setup(fn, next, acc, val, key)
      }
    }
  }
}

function comp () {
  var args = Array.prototype.slice.call(arguments)
  return function (next) {
    return args.reduceRight(function (acc, fn) {
      return fn(acc)
    }, next)
  }
}
<commit_msg>One more case.<commit_after>var reduce = require('universal-reduce')
var reduced = reduce.reduced

var getStep = require('./get-step')
var done = require('./done')

module.exports = photocopy

function photocopy (original, tx, seed, step) {
  if (typeof tx !== 'function') tx = identity
  if (typeof seed === 'undefined') {
    seed = new (original.constructor || Object)
  }
  if (typeof step !== 'function') step = getStep(seed)
  // Initialize transducer
  var transducer = tx(step)
  // apply to the collection
  var acc = reduce(original, transducer, seed)
  // flush remaining state.
  var finalVal = transducer(acc)
  if (finalVal instanceof reduced) return finalVal.val
  return finalVal
}

function identity (next) {
  return next
}

function cat (next) {
  return function (acc, value, key) {
    return reduce(value, next, acc)
  }
}

var filter = simple(function (fn, next, acc, val, key) {
  return fn(val, key) ? next(acc, val, key) : acc
})

var map = simple(function (fn, next, acc, val, key) {
  return next(acc, fn(val, key), key)
})

var keyMap = simple(function (fn, next, acc, val, key) {
  return next(acc, val, fn(val, key))
})

function take (n) {
  return function (next) {
    var i = 0
    return function (acc, val, key) {
      if (done(acc, val, key)) {
        return next.apply(null, arguments)
      }
      if (i >= n) return acc
      i += 1
      return next(acc, val, key)
    }
  }
}

function skip (n) {
  return function (next) {
    var i = 0
    return function (acc, val, key) {
      if (done(acc, val, key)) {
        return next.apply(null, arguments)
      }
      if (i >= n) return next(acc, val, key)
      i += 1
      return acc
    }
  }
}

photocopy({
  identity: identity,
  cat: cat,
  simple: simple,
  filter: filter,
  map: map,
  keyMap: keyMap,
  reduced: reduced,
  byKey: byKey,
  comp: comp,
  done: done,
  take: take,
  skip: skip
}, null, photocopy)

function byKey (acc, value, key) {
  if (done(acc, value, key)) {
    return acc
  }
  var arr = acc[key] || (acc[key] = [])
  arr.push(value)
  return acc
}

function simple (setup) {
  return function (fn) {
    return function (next) {
      // setup state here
      return function (acc, val, key) {
        if (done(acc, val, key)) {
          return next.apply(null, arguments)
        }
        return setup(fn, next, acc, val, key)
      }
    }
  }
}

function comp () {
  var args = Array.prototype.slice.call(arguments)
  return function (next) {
    return args.reduceRight(function (acc, fn) {
      return fn(acc)
    }, next)
  }
}
<|endoftext|>


<commit_before>'use strict'

const http = require('http')
const url = require('url')

const axios = require('axios')
const nodeAdapter = require('axios/lib/adapters/http')

const createAdapter = callback => config => {
  const urlObject = url.parse(config.url)

  // Forcely set protocol to HTTP
  urlObject.protocol = 'http:'
  urlObject.slashes = true

  const host = urlObject.host
  delete urlObject.host
  urlObject.hostname = '127.0.0.1'
  // Apply original host to request header
  if (host != null && config.headers.host == null) {
    config.headers.host = host
  }

  const server = http.createServer(callback)

  return new Promise((resolve, reject) => {
    server.on('error', reject)
    server.listen(0, '127.0.0.1', () => {
      urlObject.port = server.address().port
      config.url = url.format(urlObject)
      resolve(nodeAdapter(config))
    })
  }).then(value => new Promise(resolve => {
    server.close(() => resolve(value))
  }), reason => new Promise((resolve, reject) => {
    server.close(() => reject(reason))
  }))
}

const axiosist = callback => {
  return axios.create({
    adapter: createAdapter(callback)
  })
}

exports = module.exports = axiosist
exports.default = axiosist
exports.createAdapter = createAdapter
<commit_msg>Fix typing<commit_after>'use strict'

const http = require('http')
const url = require('url')

const axios = require('axios').default
const nodeAdapter = require('axios/lib/adapters/http')

const createAdapter = callback => config => {
  const urlObject = url.parse(config.url)

  // Forcely set protocol to HTTP
  urlObject.protocol = 'http:'
  urlObject.slashes = true

  const host = urlObject.host
  delete urlObject.host
  urlObject.hostname = '127.0.0.1'
  // Apply original host to request header
  if (host != null && config.headers.host == null) {
    config.headers.host = host
  }

  const server = http.createServer(callback)

  return new Promise((resolve, reject) => {
    server.on('error', reject)
    server.listen(0, '127.0.0.1', () => {
      urlObject.port = server.address().port
      config.url = url.format(urlObject)
      resolve(nodeAdapter(config))
    })
  }).then(value => new Promise(resolve => {
    server.close(() => resolve(value))
  }), reason => new Promise((resolve, reject) => {
    server.close(() => reject(reason))
  }))
}

const axiosist = callback => {
  return axios.create({
    adapter: createAdapter(callback)
  })
}

exports = module.exports = axiosist
exports.default = axiosist
exports.createAdapter = createAdapter
<|endoftext|>


<commit_before>var fs = require('fs')
var _ = require('lodash')
var player = require('./player')
var card = require('./card')
var PDFDocument = require('pdfkit')

var player_stats = player("Kris Bryant")
var player_card = card(player_stats)
var text_list = []

//loop through player card and make a list of all results
_.forEach(player_card, function(value) {
	var play = ''
  _.forEach(value['result'], function(result) {
	  play += result.text + ' '
  })
  text_list.push(play)
});

var doc = new PDFDocument({
  layout: 'portrait',
  size: [216, 360],
  margin: 9
})

//output a pdf with player name as file name
doc.pipe(fs.createWriteStream(_.snakeCase(player_stats.name) + '.pdf'))

doc.image('baseball.jpg', 150, 9, {fit: [30, 225]})

//box 1
doc.rect(9, 72, 66, 18)
.fillOpacity(0.2)
.fill('#cadcf9')
.fontSize(12)
.fill('black')
.text('1', 38, 76)

//box 2
doc.rect(75, 72, 66, 18)
.fillOpacity(0.2)
.fill('#cadcf9')
.fontSize(12)
.fill('black')
.text('2', 104, 76)
//box 3
doc.rect(141, 72, 66, 18)
.fillOpacity(0.2)
.fill('#cadcf9')
.fontSize(12)
.fill('black')
.text('3', 170, 76)

//lines
doc.moveTo(9, 72)
.lineTo(207, 72)
.stroke()
.moveTo(9, 90)
.lineTo(207, 90)
.stroke()
.moveTo(9, 306)
.lineTo(207, 306)
.stroke()
.moveTo(75, 72)
.lineTo(75, 306)
.stroke()
.moveTo(141, 72)
.lineTo(141, 306)
.stroke()

//logo
doc.fontSize(18)
.fill('black')
.font('computerfont.ttf')
.text('Stat-O-Magic', 9, 9)

//player name
doc.fontSize(10)
.moveDown()
.font('Helvetica-Bold')
.text(_.upperCase(player_stats.name))

//position
doc.fontSize(8)
.moveUp()
.font('Helvetica')
.text(player_stats.positions[0], {align:'center'})

//stealing
doc.fontSize(8)
.moveUp()
.font('Helvetica')
.text('stealing-' + player_stats.som_steal, {align:'right'})
.moveDown(0.2)
.text('running ' + player_stats.som_run, {align:'right'})

//BATTING RECORD
doc.fontSize(8)
.font('Helvetica-Bold')
.text('BATTING RECORD', 12, 311, {align:'center'})

//blue box
doc.rect(9, 320, 198, 31)
.fillOpacity(0.2)
.fill('#cadcf9')

//batting average
doc.fontSize(8)
.fill('black')
.font('Helvetica')
.text('AVG', 15, 326)
.moveDown(0.2)
.text(player_stats.avg)

//at bats
doc.fontSize(8)
.fill('black')
.font('Helvetica')
.text('AB', 50, 326)
.moveDown(0.2)
.text(player_stats.ab)

//2B
doc.fontSize(8)
.fill('black')
.font('Helvetica')
.text('2B', 85, 326)
.moveDown(0.2)
.text(player_stats.doubles)

//3B
doc.fontSize(8)
.fill('black')
.font('Helvetica')
.text('3B', 120, 326)
.moveDown(0.2)
.text(player_stats.triples)

//HR
doc.fontSize(8)
.fill('black')
.font('Helvetica')
.text('HR', 155, 326)
.moveDown(0.2)
.text(player_stats.homeruns)

//RBI
doc.fontSize(8)
.fill('black')
.font('Helvetica')
.text('RBI', 185, 326)
.moveDown(0.2)
.text(player_stats.rbi)

//column 1
//2
doc.fontSize(8)
.fill('black')
.font('Helvetica-Bold')
.text('2-', 12, 96, {continued: true, width: 60})
.font('Helvetica')
.text(text_list[0])

//3
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('3-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[1])

//4
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('4-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[2])

//5
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('5-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[3])

//6
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('6-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[4])

//7
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('7-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[5])

//8
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('8-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[6])

//9
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('9-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[7])

//10
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('10-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[8])

//11
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('11-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[9])

//12
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('12-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[10])

//column 2
//2
doc.fontSize(8)
.font('Helvetica-Bold')
.text('2-', 78, 96, {continued: true, width: 60})
.font('Helvetica')
.text(text_list[11])

//3
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('3-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[12])

//4
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('4-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[13])

//5
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('5-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[14])

//6
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('6-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[15])

//7
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('7-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[16])

//8
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('8-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[17])

//9
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('9-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[18])

//10
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('10-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[19])

//11
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('11-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[20])

//12
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('12-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[21])

//column 3
//2
doc.fontSize(8)
.font('Helvetica-Bold')
.text('2-', 144, 96, {continued: true, width: 60})
.font('Helvetica')
.text(text_list[22])

//3
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('3-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[23])

//4
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('4-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[24])

//5
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('5-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[25])

//6
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('6-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[26])

//7
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('7-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[27])

//8
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('8-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[28])

//9
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('9-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[29])

//10
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('10-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[30])

//11
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('11-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[31])

//12
doc.fontSize(8)
.moveDown(0.2)
.font('Helvetica-Bold')
.text('12-',{continued: true, width: 60})
.font('Helvetica')
.text(text_list[32])

doc.end()<commit_msg>remove index<commit_after><|endoftext|>


<commit_before>var semver = require('semver')

function isFunction (f) {
  return 'function' === typeof f
}

function isObject (o) {
  return o && 'object' === typeof o
}

function find (ary, test) {
  for(var i in ary)
    if(test(ary[i], i, ary))
      return ary[i]
}

function each(obj, iter) {
  for(var k in obj)
    iter(obj[k], k, obj)
}

function copy (_a, a) {
  _a = _a || {}
  for(var k in a)
    _a[k] = _a[k] || a[k]
  return _a
}

function merge(ary) {
  return ary.reduce(copy, {})
}

function _pluck(name) {
  return function (obj) {
    return obj[name]
  }
}

function allow () {

  function perms () {}

  perms.pre = function () {}
  perms.post = function (value) {
    return value
  }

  return perms
}

module.exports = function () {

  var layers = []

  function resolve(name, range) {
    return find(layers, function (layer) {
      return name === layer.name && semver.satisfies(layer.version, range)
    })
  }

  return {
    api: function (perms) {
      //return a flatterned api snapshot.
      var root = {}

      perms = perms || allow()

      //add layers into one api object under their root[name]
      //except where layer.core === true, add those directly to root
      layers.forEach(function (layer) {
        var api, path = []
        if(layer.core) api = root
        else {
          api = root[layer.name] = {}
          path = [layer.name]
        }
        each(layer.manifest, function (type, name) {
          var _path = path.concat(name)
          api[name] = function (arg, cb) {
            perms.pre(arg, _path, type) //should throw if invalid.

            var value = layer.api[name].call(root, arg)
            value = perms.post(value, _path, type)
            if(cb && type === 'async') value(cb)
            else                       return value
          }
        })
      })

      return root
    },

    //install a subapi.
    use: function (layer) {
      if(!layer) layer = name, name = null

      //check it's actually possible to use this layer.
      if(isObject(layer.dependencies))
        each(layer.dependencies, function (range, name) {
          if(!resolve(name, range))
            throw new Error('missing dependency:'+name+'@'+version)
        })

      //initialize the api... but what about the api's permissions?

      if(layer.init) {
        var API = this.api()
        layer.api = layer.init.call(API, API)
      }

      layers.push(layer)

      return this
    },

    manifest: function () {
      console.log(layers.map(_pluck('manifest')))
      return merge(layers.map(function (layer) {
        if(layer.core) return layer.manifest
        var o = {}
        o[layer.name] = layer.manifest
        return o
      }))
    }
  }

}

<commit_msg>pass data (config) to constructor, and share it with init functions<commit_after>var semver = require('semver')
var EventEmitter = require('events').EventEmitter

function isFunction (f) {
  return 'function' === typeof f
}

function isObject (o) {
  return o && 'object' === typeof o
}

function find (ary, test) {
  for(var i in ary)
    if(test(ary[i], i, ary))
      return ary[i]
}

function each(obj, iter) {
  for(var k in obj)
    iter(obj[k], k, obj)
}

function copy (_a, a) {
  _a = _a || {}
  for(var k in a)
    _a[k] = _a[k] || a[k]
  return _a
}

function merge(ary, initial) {
  return ary.reduce(copy, initial || {})
}

function _pluck(name) {
  return function (obj) {
    return obj[name]
  }
}

function allow () {

  function perms () {}

  perms.pre = function () {}
  perms.post = function (value) {
    return value
  }

  return perms
}

module.exports = function (config) {

  var layered
  var layers = []

  function resolve(name, range) {
    return find(layers, function (layer) {
      return name === layer.name && semver.satisfies(layer.version, range)
    })
  }

  return layered = {
    config: config,
    api: function (perms) {
      //return a flatterned api snapshot.
      var root = new EventEmitter()

      perms = perms || allow()

      //add layers into one api object under their root[name]
      //except where layer.core === true, add those directly to root
      layers.forEach(function (layer) {
        var api, path = []
        if(layer.core) api = root
        else {
          api = root[layer.name] = {}
          path = [layer.name]
        }
        each(layer.manifest, function (type, name) {
          var _path = path.concat(name)
          api[name] = function (arg, cb) {
            perms.pre(arg, _path, type, config) //should throw if invalid.

            var value = layer.api[name].call(root, arg)
            value = perms.post(value, _path, type, config)
            if(cb && type === 'async') value(cb)
            else                       return value
          }
        })
      })

      return root
    },

    //install a subapi.
    use: function (layer) {
      if(!layer) layer = name, name = null

      //check it's actually possible to use this layer.
      if(isObject(layer.dependencies))
        each(layer.dependencies, function (range, name) {
          if(!resolve(name, range))
            throw new Error('missing dependency:'+name+'@'+version)
        })

      //initialize the api... but what about the api's permissions?

      if(layer.init) {
        var API = layered.api()
        layer.api = layer.init.call(API, API, config)
      }

      layers.push(layer)

      return this
    },

    manifest: function () {
      return merge(layers.map(function (layer) {
        if(layer.core) return layer.manifest
        var o = {}
        o[layer.name] = layer.manifest
        return o
      }))
    }
  }

}

<|endoftext|>