<commit_before>var express = require('express'),
    cors = require('cors'),
    webcommand = require('webcommand'),
    stream = require('event-stream');
var request = require('request');

module.exports = createServer;

function createServer(cmdList){
    var webCommand = webcommand(cmdList);
    var app = express();
    app.use(cors());
    app.get('/getCommands', cors(), function(req,res) {
        res.send(JSON.stringify(webCommand.getCommandList()));
    });

    app.post('/*', function(req,res){
        var cmd = req.path.replace('/',''),
            args = [].concat(req.query.args),
            cStream= stream.through();
        if (!req.query.args) args = null;

        cStream.on('error', function(err) {
            console.error(err);
        });
        if(req.query.pipes){
            var pipes=[],
                curPipe;

            if(typeof (req.query.pipes)!=='string'){
                pipes=  req.query.pipes;
                curPipe=decodeURIComponent(pipes.shift());
            }else{
                curPipe=decodeURIComponent(req.query.pipes);
            }
            var urlPipes='';
            if(pipes.length){
                //if first arg in query string use ?
                if(curPipe.indexOf('?')===-1) urlPipes= '?'
                else urlPipes= '&';
                urlPipes = urlPipes +pipes.map(function(pipe){return 'pipes='+encodeURIComponent(pipe);}).join('&');
            }
            var iStream= stream.through();
            iStream.pipe(request.post(curPipe+urlPipes)).pipe(res);
            webCommand.webCommand(cmd,args, req, iStream, cStream);
        }else{
            webCommand.webCommand(cmd,args, req, res, cStream);
        }
    });

    return app;
}
<commit_msg>Refactored functionality that is now part of webcommand>=1.07<commit_after>var express = require('express'),
    cors = require('cors'),
    webcommand = require('webcommand'),
    parseUrl = require('webcommand').parseUrl,
    generateUrl = require('webcommand').generateUrl,
    stream = require('event-stream');
var request = require('request');

module.exports = createServer;

function createServer(cmdList){
    var webCommand = webcommand(cmdList);
    var app = express();
    app.use(cors());
    app.get('/getCommands', cors(), function(req,res) {
        res.send(JSON.stringify(webCommand.getCommandList()));
    });

    app.post('/*', function(req,res){
        var wc = parseUrl(req.url),
            cStream= stream.through();
        cStream.on('error', function(err) {
            console.error(err);
        });
        if(wc.pipes){
            var curPipe = wc.pipes.shift(),
                purl = generateUrl({
                cmd : curPipe.cmd,
                args : curPipe.args,
                pipes : wc.pipes
            });
            var iStream= stream.through();
            iStream.pipe(request.post(purl)).pipe(res);
            webCommand.webCommand(wc.cmd,wc.args, req, iStream, cStream);
        }
        else{
            webCommand.webCommand(wc.cmd,wc.args, req, res, cStream);
        }
    });
    return app;
}
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var selfie = require('./middleware/selfie-search.js');
var Q = require('q');

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// Templates
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index');
});

// TODO: This isn't technically REST, should be /api/v1/selfie/:email
app.use('/api/v1/selfie', function(request, response, next) {
  selfie.findImg(request.query.email, function(imgSRC) {
    request.imgSRC = imgSRC;
    next();
  });
});

app.get('/api/v1/selfie', function(request, response) {
  response.send({
    imgSRC : request.imgSRC,
    success : !!request.imgSRC
  });
});

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

<commit_msg>Don't need Q library in index.js<commit_after>var express = require('express');
var app = express();
var selfie = require('./middleware/selfie-search.js');

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// Templates
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index');
});

// TODO: This isn't technically REST, should be /api/v1/selfie/:email
app.use('/api/v1/selfie', function(request, response, next) {
  selfie.findImg(request.query.email, function(imgSRC) {
    request.imgSRC = imgSRC;
    next();
  });
});

app.get('/api/v1/selfie', function(request, response) {
  response.send({
    imgSRC : request.imgSRC,
    success : !!request.imgSRC
  });
});

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

<|endoftext|>


<commit_before>'use strict';
var execFile = require('child_process').execFile;
var spawn = require('child_process').spawn;
var path = require('path');
var multiTypeof = require('multi-typeof');

function checkInput(input) {
	if (!multiTypeof(input, ['string', 'array'])) {
		throw new TypeError('Expected a string or an array as input');
	}

	if (!Array.isArray(input)) {
		var reg = new RegExp(/[^\s"']+|"([^"]*)"|'([^']*)'/g);
		input = input.match(reg);

		input.forEach(function (el) {
			input[input.indexOf(el)] = el.replace(/"/g, '');
		});
	}

	return input;
}

module.exports = function (input, opts, cb) {
	opts = opts || {};

	if (process.platform !== 'win32') {
		throw new Error('Only Windows systems are supported');
	}

	if (typeof opts === 'function') {
		cb = opts;
		opts = {};
	}

	execFile(path.join(__dirname, 'nircmd.exe'), checkInput(input), opts, function (err, res) {
		if (err) {
			cb(err);
			return;
		}

		cb(null, res);
	});
};

module.exports.spawn = function (input, opts) {
	opts = opts || {};

	if (process.platform !== 'win32') {
		throw new Error('Only Windows systems are supported');
	}

	return spawn(path.join(__dirname, 'nircmd.exe'), checkInput(input), opts);
};
<commit_msg>Handle the weird success exit code<commit_after>'use strict';
var execFile = require('child_process').execFile;
var spawn = require('child_process').spawn;
var path = require('path');
var multiTypeof = require('multi-typeof');

function checkInput(input) {
	if (!multiTypeof(input, ['string', 'array'])) {
		throw new TypeError('Expected a string or an array as input');
	}

	if (!Array.isArray(input)) {
		var reg = new RegExp(/[^\s"']+|"([^"]*)"|'([^']*)'/g);
		input = input.match(reg);

		input.forEach(function (el) {
			input[input.indexOf(el)] = el.replace(/"/g, '');
		});
	}

	return input;
}

module.exports = function (input, opts, cb) {
	opts = opts || {};

	if (process.platform !== 'win32') {
		throw new Error('Only Windows systems are supported');
	}

	if (typeof opts === 'function') {
		cb = opts;
		opts = {};
	}

	execFile(path.join(__dirname, 'nircmd.exe'), checkInput(input), opts, function (err, res) {
		// NirCmd exits with this weird code even though it worked
		if (err && err.code !== 4207175) {
			cb(err);
			return;
		}

		cb(null, res);
	});
};

module.exports.spawn = function (input, opts) {
	opts = opts || {};

	if (process.platform !== 'win32') {
		throw new Error('Only Windows systems are supported');
	}

	return spawn(path.join(__dirname, 'nircmd.exe'), checkInput(input), opts);
};
<|endoftext|>


<commit_before>var request = require('request');
var parse = require('./parseWikiText');
var separator = Math.random().toString(36).slice(2).toUpperCase();

var page = "Breaking_Bad";
var apiURL = "http://en.wikipedia.org/w/api.php?format=json&action=query&prop=revisions&rvprop=content&titles=" + page;
var wikiURL = "http://en.wikipedia.org/wiki/";

request.get(apiURL, function(error, data, body){
  if (error) {
    console.log('ERROR: ', error);
    return;
  }

  var content = JSON.parse(body);
  content = content.query.pages;

  var page = Object.keys(content);
  content = content[page].revisions[0]['*'];

  var startingPointRegex = /\{\{\s*[Ii]nfobox/;

  var macz = content.match(startingPointRegex).index;

  var end = parse(content.substr(macz, content.length));

  content = content.substr(macz, end);

  var result = content.match(/\[\[(.+?)\]\]|\{\{(.+?)\}\}/ig);

  result.forEach(function(link) {
    content = content.replace(link, link.replace(/\|/g, separator));
  });

  content = content.split('|');
  content.shift();

  var output = {};
  content.forEach(function(element) {
    var splited = element.split('=');
    splited = splited.map(function(el) {
      return el.trim();
    });

    output[splited[0]] = linkToObject(splited[1].replace(new RegExp(separator, 'g'), '|'));
  });

  console.log(output);
  //console.log(output);
//console.log(content);
  //console.log(content.substr(macz, content.length);

});

var linkToObject = function(link) {
  //var match = link.match(/\[\[(.*)\]\]/);
  var matches = [];
  link.replace(/\[\[(.*?)\]\]/g, function(g0,g1){ console.log(g1);matches.push(g1);})
  if (matches.length > 0) {
    var results = [];
    var obj = {
      type: "link"
    };
    matches.forEach(function(matchElement) {
      matchElement = matchElement.split('|');
      if (matchElement.length > 1) {
        obj.text = matchElement[1];
        obj.url = wikiURL + matchElement[0];
      } else {
        obj.text = matchElement[0];
        obj.url = wikiURL + matchElement[0];
      }
      results.push(obj);
    });
    return results;

  } else {
    return link;
  }
}
<commit_msg>[WIKI-INFOBOX] - :running: multiple links support works as expected<commit_after>var request = require('request');
var parse = require('./parseWikiText');
var separator = Math.random().toString(36).slice(2).toUpperCase();

var page = "Breaking_Bad";
var apiURL = "http://en.wikipedia.org/w/api.php?format=json&action=query&prop=revisions&rvprop=content&titles=" + page;
var wikiURL = "http://en.wikipedia.org/wiki/";

request.get(apiURL, function(error, data, body){
  if (error) {
    console.log('ERROR: ', error);
    return;
  }

  var content = JSON.parse(body);
  content = content.query.pages;

  var page = Object.keys(content);
  content = content[page].revisions[0]['*'];

  var startingPointRegex = /\{\{\s*[Ii]nfobox/;

  var macz = content.match(startingPointRegex).index;

  var end = parse(content.substr(macz, content.length));

  content = content.substr(macz, end);

  var result = content.match(/\[\[(.+?)\]\]|\{\{(.+?)\}\}/ig);

  result.forEach(function(link) {
    content = content.replace(link, link.replace(/\|/g, separator));
  });

  content = content.split('|');
  content.shift();

  var output = {};
  content.forEach(function(element) {
    var splited = element.split('=');
    splited = splited.map(function(el) {
      return el.trim();
    });

    output[splited[0]] = linkToObject(splited[1].replace(new RegExp(separator, 'g'), '|'));
  });

  console.log(output);
  //console.log(output);
//console.log(content);
  //console.log(content.substr(macz, content.length);

});

var linkToObject = function(link) {
  //var match = link.match(/\[\[(.*)\]\]/);
  var matches = [];
  link.replace(/\[\[(.*?)\]\]/g, function(g0,g1){matches.push(g1);})
  if (matches.length > 0) {
    var results = [];
    var obj = {
      type: "link"
    };
    matches.forEach(function(matchElement) {
      obj = {
        type: "link"
      }
      matchElement = matchElement.split('|');
      if (matchElement.length > 1) {
        obj.text = matchElement[1];
        obj.url = wikiURL + matchElement[0];
      } else {
        obj.text = matchElement[0];
        obj.url = wikiURL + matchElement[0];
      }
      results.push(obj);
    });
    return results;

  } else {
    return link;
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = require('./dist/index');<commit_msg>update<commit_after>module.exports = require('./dist/index');<|endoftext|>


<commit_before>"use strict";

var convar           = require('convar')
  , env              = convar('node_env') || 'development'
  , Winston          = require('winston')
;

function CeoLogger(meta, forceJson) {
  var ceoLogger = this
    , metaData      = meta
    , config        = convar('ceo-logger') || {}
    , SysLog        = config.syslog     || convar('syslog')
    , LogEntries    = config.logentries || convar('logentries')
    , Loggly        = config.loggly     || convar('logly')
    , Riak          = config.riak       || convar('riak')
    , MongoDB       = config.mongodb    || convar('mongodb')
    , SimpleDB      = config.simpledb   || convar('simpledb')
    , ForceJson     = config.forceJson  || forceJson
    , logLevels = { // syslog log levels
        debug:   0, // debug-level message
        info:    1, // informational message
        notice:  2, // normal, but significant, condition
        warning: 3, // warning conditions
        error:   4, // error conditions
        crit:    5, // critical conditions
        alert:   6, // action must be taken immediately
        emerg:   7  // system is unusable
      }
    , transports = [ new Winston.transports.Console({ handleExceptions: true, json: ForceJson }) ]
  ;

  function add(logr, options) {
    if (ForceJson) options.json = true
    var Logr = new logr(options)
    transports.push(Logr)
  }

  if (SysLog)     add(require('winston-syslog').Syslog,     SysLog)
  if (LogEntries) add(require('winston-logentries-transport').Logentries, LogEntries)
  if (Loggly)     add(require('winston-loggly').Loggly,     Loggly)
  if (Riak)       add(require('winston-riak').Riak,         Riak)
  if (MongoDB)    add(require('winston-mongodb').MongoDB,   MongoDB)
  if (SimpleDB)   add(require('winston-simpledb').SimpleDB, SimpleDB)

  var winston = new Winston.Logger({
    transports:  transports,
    exitOnError: false
  })

  winston.setLevels(logLevels)

  ceoLogger.debug   = function(message) { winston.debug(message,   metaData) }
  ceoLogger.info    = function(message) { winston.info(message,    metaData) }
  ceoLogger.notice  = function(message) { winston.notice(message,  metaData) }
  ceoLogger.warning = function(message) { winston.warning(message, metaData) }
  ceoLogger.err     = function(message) { winston.err(message,     metaData) }
  ceoLogger.crit    = function(message) { winston.crit(message,    metaData) }
  ceoLogger.alert   = function(message) { winston.alert(message,   metaData) }
  ceoLogger.emerg   = function(message) { winston.emerg(message,   metaData) }

  // matching aliases
  ceoLogger.information = function(message) { winston.info(message,    metaData) } // informational message
  ceoLogger.warn        = function(message) { winston.warning(message, metaData) } // warning conditions
  ceoLogger.error       = function(message) { winston.err(message,     metaData) } // error conditions
  ceoLogger.critical    = function(message) { winston.crit(message,    metaData) } // critical conditions
  ceoLogger.emergency   = function(message) { winston.emerg(message,   metaData) } // system is unusable

  // remapped alternatives
  ceoLogger.trace   = function(message) { winston.debug(message,   metaData) } // debug-level message
  ceoLogger.silly   = function(message) { winston.debug(message,   metaData) } // debug-level message
  ceoLogger.verbose = function(message) { winston.info(message,    metaData) } // informational message

  return ceoLogger
}

module.exports = CeoLogger
<commit_msg>metadata fix<commit_after>"use strict";

var convar           = require('convar')
  , env              = convar('node_env') || 'development'
  , Winston          = require('winston')
;

function CeoLogger(meta, forceJson) {
  var ceoLogger     = this
    , metaData      = meta              || null
    , config        = convar('ceo-logger') || {}
    , SysLog        = config.syslog     || convar('syslog')
    , LogEntries    = config.logentries || convar('logentries')
    , Loggly        = config.loggly     || convar('logly')
    , Riak          = config.riak       || convar('riak')
    , MongoDB       = config.mongodb    || convar('mongodb')
    , SimpleDB      = config.simpledb   || convar('simpledb')
    , ForceJson     = config.forceJson  || forceJson
    , logLevels = { // syslog log levels
        debug:   0, // debug-level message
        info:    1, // informational message
        notice:  2, // normal, but significant, condition
        warning: 3, // warning conditions
        error:   4, // error conditions
        crit:    5, // critical conditions
        alert:   6, // action must be taken immediately
        emerg:   7  // system is unusable
      }
    , transports = [ new Winston.transports.Console({ handleExceptions: true, json: ForceJson }) ]
  ;

  function add(logr, options) {
    if (ForceJson) options.json = true
    var Logr = new logr(options)
    transports.push(Logr)
  }

  if (SysLog)     add(require('winston-syslog').Syslog,     SysLog)
  if (LogEntries) add(require('winston-logentries-transport').Logentries, LogEntries)
  if (Loggly)     add(require('winston-loggly').Loggly,     Loggly)
  if (Riak)       add(require('winston-riak').Riak,         Riak)
  if (MongoDB)    add(require('winston-mongodb').MongoDB,   MongoDB)
  if (SimpleDB)   add(require('winston-simpledb').SimpleDB, SimpleDB)

  var winston = new Winston.Logger({
    transports:  transports,
    exitOnError: false
  })

  winston.setLevels(logLevels)

  ceoLogger.debug   = function(message) { winston.debug(message,   metaData) }
  ceoLogger.info    = function(message) { winston.info(message,    metaData) }
  ceoLogger.notice  = function(message) { winston.notice(message,  metaData) }
  ceoLogger.warning = function(message) { winston.warning(message, metaData) }
  ceoLogger.err     = function(message) { winston.err(message,     metaData) }
  ceoLogger.crit    = function(message) { winston.crit(message,    metaData) }
  ceoLogger.alert   = function(message) { winston.alert(message,   metaData) }
  ceoLogger.emerg   = function(message) { winston.emerg(message,   metaData) }

  // matching aliases
  ceoLogger.information = function(message) { winston.info(message,    metaData) } // informational message
  ceoLogger.warn        = function(message) { winston.warning(message, metaData) } // warning conditions
  ceoLogger.error       = function(message) { winston.err(message,     metaData) } // error conditions
  ceoLogger.critical    = function(message) { winston.crit(message,    metaData) } // critical conditions
  ceoLogger.emergency   = function(message) { winston.emerg(message,   metaData) } // system is unusable

  // remapped alternatives
  ceoLogger.trace   = function(message) { winston.debug(message,   metaData) } // debug-level message
  ceoLogger.silly   = function(message) { winston.debug(message,   metaData) } // debug-level message
  ceoLogger.verbose = function(message) { winston.info(message,    metaData) } // informational message

  return ceoLogger
}

module.exports = CeoLogger
<|endoftext|>


<commit_before>'use strict';

var gutil = require('gulp-util');
var through = require('through2');
var assign = require('object-assign');
var path = require('path');
var applySourceMap = require('vinyl-sourcemaps-apply');

var PLUGIN_NAME = 'gulp-sass';

//////////////////////////////
// Main Gulp Sass function
//////////////////////////////
var gulpSass = function gulpSass(options, sync) {
  return through.obj(function(file, enc, cb) {
    var opts,
        filePush,
        errorM,
        callback,
        result;

    if (file.isNull()) {
      return cb(null, file);
    }
    if (file.isStream()) {
      return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }
    if (!file.contents.length) {
      return cb(null, file);
    }
    if (path.basename(file.path).indexOf('_') === 0) {
      return cb();
    }

    opts = assign({}, options);
    opts.data = file.contents.toString();

    // Ensure `indentedSyntax` is true if a `.sass` file
    if (path.extname(file.path) === '.sass') {
      opts.indentedSyntax = true;
    }

    // Ensure file's parent directory in the include path
    if (opts.includePaths) {
      if (typeof opts.includePaths === 'string') {
        opts.includePaths = [opts.includePaths];
      }
    }
    else {
      opts.includePaths = [];
    }

    opts.includePaths.unshift(path.dirname(file.path));

    // Generate Source Maps if plugin source-map present
    if (file.sourceMap) {
      opts.sourceMap = file.path;
      opts.omitSourceMapUrl = true;
    }

    //////////////////////////////
    // Handles returning the file to the stream
    //////////////////////////////
    filePush = function filePush(sassObj) {
      var sassMap,
          sassMapFile,
          sassFileSrc;

      // Build Source Maps!
      if (sassObj.map) {
        // Transform map into JSON
        sassMap = JSON.parse(sassObj.map.toString());
        // Grab the stdout and transform it into stdin
        sassMapFile = sassMap.file.replace('stdout', 'stdin');
        // Grab the base file name that's being worked on
        sassFileSrc = file.path.split('/').pop();
        // Replace the stdin with the original file name
        sassMap.sources[sassMap.sources.indexOf(sassMapFile)] = sassFileSrc;
        // Replace the map file with the original file name (but new extension)
        sassMap.file = gutil.replaceExtension(sassFileSrc, '.css');
        // Apply the map
        applySourceMap(file, sassMap);
      }

      file.contents = sassObj.css;
      file.path = gutil.replaceExtension(file.path, '.css');

      cb(null, file);
    };

    //////////////////////////////
    // Handles error message
    //////////////////////////////
    errorM = function errorM(error) {
      var relativePath = '',
          filePath = error.file === 'stdin' ? file.path : error.file,
          message = '';

      filePath = filePath ? filePath : file.path;
      relativePath = path.relative(process.cwd(), filePath);

      message += gutil.colors.underline(relativePath) + '\n';
      message += gutil.colors.gray('  ' + error.line + ':' + error.column) + '  ';
      message += error.message;

      error.messageFormatted = message;
      error.message = gutil.colors.stripColor(message);

      return cb(new gutil.PluginError(
          PLUGIN_NAME, error
        ));
    };

    if (sync !== true) {
      //////////////////////////////
      // Async Sass render
      //////////////////////////////
      callback = function(error, obj) {
        if (error) {
          return errorM(error);
        }
        filePush(obj);
      };

      gulpSass.compiler.render(opts, callback);
    }
    else {
      //////////////////////////////
      // Sync Sass render
      //////////////////////////////
      try {
        result = gulpSass.compiler.renderSync(opts);

        filePush(result);
      }
      catch(error) {
        return errorM(error);
      }
    }
  });
};

//////////////////////////////
// Sync Sass render
//////////////////////////////
gulpSass.sync = function sync(options) {
  return gulpSass(options, true);
};

//////////////////////////////
// Log errors nicely
//////////////////////////////
gulpSass.logError = function logError(error) {
  var message = new gutil.PluginError('sass', error.messageFormatted).toString();
  process.stderr.write(message + '\n');
  this.emit('end');
};

//////////////////////////////
// Store compiler in a prop
//////////////////////////////
gulpSass.compiler = require('node-sass');

module.exports = gulpSass;
<commit_msg>:bug: Fix empty partials copied to CSS folder<commit_after>'use strict';

var gutil = require('gulp-util');
var through = require('through2');
var assign = require('object-assign');
var path = require('path');
var applySourceMap = require('vinyl-sourcemaps-apply');

var PLUGIN_NAME = 'gulp-sass';

//////////////////////////////
// Main Gulp Sass function
//////////////////////////////
var gulpSass = function gulpSass(options, sync) {
  return through.obj(function(file, enc, cb) {
    var opts,
        filePush,
        errorM,
        callback,
        result;

    if (file.isNull()) {
      return cb(null, file);
    }
    if (file.isStream()) {
      return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }
    if (path.basename(file.path).indexOf('_') === 0) {
      return cb();
    }
    if (!file.contents.length) {
      return cb(null, file);
    }

    opts = assign({}, options);
    opts.data = file.contents.toString();

    // Ensure `indentedSyntax` is true if a `.sass` file
    if (path.extname(file.path) === '.sass') {
      opts.indentedSyntax = true;
    }

    // Ensure file's parent directory in the include path
    if (opts.includePaths) {
      if (typeof opts.includePaths === 'string') {
        opts.includePaths = [opts.includePaths];
      }
    }
    else {
      opts.includePaths = [];
    }

    opts.includePaths.unshift(path.dirname(file.path));

    // Generate Source Maps if plugin source-map present
    if (file.sourceMap) {
      opts.sourceMap = file.path;
      opts.omitSourceMapUrl = true;
    }

    //////////////////////////////
    // Handles returning the file to the stream
    //////////////////////////////
    filePush = function filePush(sassObj) {
      var sassMap,
          sassMapFile,
          sassFileSrc;

      // Build Source Maps!
      if (sassObj.map) {
        // Transform map into JSON
        sassMap = JSON.parse(sassObj.map.toString());
        // Grab the stdout and transform it into stdin
        sassMapFile = sassMap.file.replace('stdout', 'stdin');
        // Grab the base file name that's being worked on
        sassFileSrc = file.path.split('/').pop();
        // Replace the stdin with the original file name
        sassMap.sources[sassMap.sources.indexOf(sassMapFile)] = sassFileSrc;
        // Replace the map file with the original file name (but new extension)
        sassMap.file = gutil.replaceExtension(sassFileSrc, '.css');
        // Apply the map
        applySourceMap(file, sassMap);
      }

      file.contents = sassObj.css;
      file.path = gutil.replaceExtension(file.path, '.css');

      cb(null, file);
    };

    //////////////////////////////
    // Handles error message
    //////////////////////////////
    errorM = function errorM(error) {
      var relativePath = '',
          filePath = error.file === 'stdin' ? file.path : error.file,
          message = '';

      filePath = filePath ? filePath : file.path;
      relativePath = path.relative(process.cwd(), filePath);

      message += gutil.colors.underline(relativePath) + '\n';
      message += gutil.colors.gray('  ' + error.line + ':' + error.column) + '  ';
      message += error.message;

      error.messageFormatted = message;
      error.message = gutil.colors.stripColor(message);

      return cb(new gutil.PluginError(
          PLUGIN_NAME, error
        ));
    };

    if (sync !== true) {
      //////////////////////////////
      // Async Sass render
      //////////////////////////////
      callback = function(error, obj) {
        if (error) {
          return errorM(error);
        }
        filePush(obj);
      };

      gulpSass.compiler.render(opts, callback);
    }
    else {
      //////////////////////////////
      // Sync Sass render
      //////////////////////////////
      try {
        result = gulpSass.compiler.renderSync(opts);

        filePush(result);
      }
      catch(error) {
        return errorM(error);
      }
    }
  });
};

//////////////////////////////
// Sync Sass render
//////////////////////////////
gulpSass.sync = function sync(options) {
  return gulpSass(options, true);
};

//////////////////////////////
// Log errors nicely
//////////////////////////////
gulpSass.logError = function logError(error) {
  var message = new gutil.PluginError('sass', error.messageFormatted).toString();
  process.stderr.write(message + '\n');
  this.emit('end');
};

//////////////////////////////
// Store compiler in a prop
//////////////////////////////
gulpSass.compiler = require('node-sass');

module.exports = gulpSass;
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-keen-tracking',

  contentFor: function(type) {
    if(type === 'head') {
      return '<script src="https://d26b395fwzu5fz.cloudfront.net/3.2.4/keen-tracker.min.js" type="text/javascript"></script>';
    }
  }
};
<commit_msg>Push to kickstart travis<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-keen-tracking',
  contentFor: function(type) {
    if(type === 'head') {
      return '<script src="https://d26b395fwzu5fz.cloudfront.net/3.2.4/keen-tracker.min.js" type="text/javascript"></script>';
    }
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Kyle E. Mitchell
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
*/

function indent(depth) {
  return new Array((depth * 2) + 1).join(' ') }

function isArrayOfScalars(array) {
  return array.every(function(element) {
    var type = typeof element
    return (
      type === 'string' ||
      type === 'number' ||
      type === 'boolean' ||
      element === null ) }) }

function lispyJSON(depth, flush, argument, MAX_WIDTH) {
  MAX_WIDTH = MAX_WIDTH || 72
  var type = typeof argument
  if (type === 'string') {
    return JSON.stringify(argument) }
  else if (type === 'number') {
    return isFinite(argument) ? String(argument) : 'null' }
  else if (type === 'boolean') {
    return argument ? 'true' : 'false' }
  else if (type === 'object') {
    if (!argument) {
      return 'null' }
    else {
      if (Array.isArray(argument)) {
        var stringifiedElements = argument.map(function(element) {
          return lispyJSON(depth + 1, true, element, MAX_WIDTH) || 'null' })
        if (stringifiedElements.length === 0) {
          return '[ ]' }
        else {
          var leadingSpaces = indent(depth + 1)
          if (isArrayOfScalars(argument)) {
            var lastStringified = stringifiedElements.length - 1
            var rows = stringifiedElements
              .reduce(function(rows, stringified, stringifiedIndex) {
                var lastRowIndex = rows.length - 1
                var lastRow = rows[lastRowIndex]
                var isLast = stringifiedIndex === lastStringified
                var comma = (isLast ? '' : ',')
                var additionalLength = stringified.length + comma.length + 1
                if (leadingSpaces.length + lastRow.length + additionalLength > MAX_WIDTH) {
                  rows.push(' ' + stringified + comma) }
                else {
                  rows[lastRowIndex] = (
                    lastRow + ( lastRow.length > 0 ? ' ' : '' ) + stringified + comma )}
                return rows
              }, [''])
            return (
              '[ ' +
              rows
                .map(function(x) { return x.trim() })
                .join('\n' + leadingSpaces) +
              ' ]' ) }
          else {
            return (
              '[' +
              (flush ? ' ' : '\n' + leadingSpaces) +
              stringifiedElements.join(',\n' + leadingSpaces) +
              ' ]' ) } } }
      else { // object
        var properties = new Array
        for (var key in argument) {
          if (argument.hasOwnProperty(key)) {
            var value = lispyJSON(
              depth + 1, false, argument[key], MAX_WIDTH)
            if (value) {
              properties.push(JSON.stringify(key) + ': ' + value) } } }
        if (properties.length === 0) {
          return '{ }' }
        else {
          return (
            '{' +
            (flush ? ' ' : '\n' + indent(depth + (flush ? 2 : 1))) +
            properties.join(',\n' + indent(depth + 1)) +
            ' }' ) } } } } }

module.exports = lispyJSON.bind(this, 0, true)
<commit_msg>Fix array indentation<commit_after>/*
 * Copyright 2015 Kyle E. Mitchell
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
*/

function indent(depth) {
  return new Array((depth * 2) + 1).join(' ') }

function isArrayOfScalars(array) {
  return array.every(function(element) {
    var type = typeof element
    return (
      type === 'string' ||
      type === 'number' ||
      type === 'boolean' ||
      element === null ) }) }

function lispyJSON(depth, flush, argument, MAX_WIDTH) {
  MAX_WIDTH = MAX_WIDTH || 72
  var type = typeof argument
  if (type === 'string') {
    return JSON.stringify(argument) }
  else if (type === 'number') {
    return isFinite(argument) ? String(argument) : 'null' }
  else if (type === 'boolean') {
    return argument ? 'true' : 'false' }
  else if (type === 'object') {
    if (!argument) {
      return 'null' }
    else {
      if (Array.isArray(argument)) {
        var stringified = argument.map(function(element) {
          return lispyJSON(depth + 1, true, element, MAX_WIDTH) || 'null' })
        if (stringified.length === 0) {
          return '[ ]' }
        else {
          var leadingSpaces = indent(depth + 1)
          var singleLineLength = (
            leadingSpaces +
            stringified.reduce(function(length, element) {
              return length + element.length
            }, 0))
          var fitsOnSingleLine = singleLineLength < MAX_WIDTH
          if (isArrayOfScalars(argument)) {
            var lastStringified = stringified.length - 1
            var rows = stringified.reduce(function(rows, string, index) {
              var lastRowIndex = rows.length - 1
              var lastRow = rows[lastRowIndex]
              var isLast = index === lastStringified
              var comma = (isLast ? '' : ',')
              var additionalLength = string.length + comma.length + 1
              if (( leadingSpaces.length +
                    lastRow.length +
                    additionalLength ) > MAX_WIDTH ) {
                rows.push(' ' + string + comma) }
              else {
                rows[lastRowIndex] = (
                  lastRow +
                  ( lastRow.length > 0 ? ' ' : '' ) +
                  string +
                  comma )}
              return rows
            }, [ '' ])
            return (
              '[' +
              ( ( fitsOnSingleLine || flush ) ?
                ' ' : ( '\n' + leadingSpaces ) ) +
              rows
                .map(function(x) { return x.trim() })
                .join('\n' + leadingSpaces) +
              ' ]' ) }
          else {
            return (
              '[' +
              (flush ? ' ' : '\n' + leadingSpaces) +
              stringified.join(',\n' + leadingSpaces) +
              ' ]' ) } } }
      else { // object
        var properties = new Array
        for (var key in argument) {
          if (argument.hasOwnProperty(key)) {
            var value = lispyJSON(
              depth + 1, false, argument[key], MAX_WIDTH)
            if (value) {
              properties.push(JSON.stringify(key) + ': ' + value) } } }
        if (properties.length === 0) {
          return '{ }' }
        else {
          return (
            '{' +
            (flush ? ' ' : '\n' + indent(depth + (flush ? 2 : 1))) +
            properties.join(',\n' + indent(depth + 1)) +
            ' }' ) } } } } }

module.exports = lispyJSON.bind(this, 0, true)
<|endoftext|>


<commit_before>var pg = require('pg')
var express = require('express')
var http = require('http');
var fs = require('fs');
var bodyParser = require('body-parser')

var cool = require('cool-ascii-faces')

var app = express()
app.set('port', (process.env.PORT || 5000))

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
	extended: true
}));

// parse application/json
app.use(bodyParser.json());

app.get('/setup_database', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('CREATE TABLE IF NOT EXISTS highscores (id serial PRIMARY KEY NOT NULL, uuid VARCHAR(255) NOT NULL, name VARCHAR (255) NOT NULL, score integer NOT NULL, timestamp TIMESTAMP)', function(err, result) {
			done();
			if (err){
				console.error(err); response.send("Error " + err);
			} else {
				response.send(result);
			}
		});
	});
})

app.get('/drop_table', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('DROP TABLE highscores;', function(err, result) {
			done();
			if (err){
				console.error(err); response.send("Error " + err);
			} else {
				response.send(result);
			}
		});
	});
})

app.get('/truncate', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('TRUNCATE highscores;', function(err, result) {
			done();
			if (err){
				console.error(err); response.send("Error " + err);
			} else {
				response.send(result);
			}
		});
	});
})

app.get('/all_highscore', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('SELECT * FROM highscores ORDER BY score DESC;', function(err, result) {
			done();
			if (err){
				console.error(err);
				response.status(500).send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
})

app.get('/highscore', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('SELECT highscores.id, highscores.name, merge.score, highscores.timestamp FROM highscores JOIN (SELECT uuid, max(score) AS score FROM highscores GROUP BY uuid ORDER BY score) AS merge ON merge.uuid = highscores.uuid ORDER BY score DESC LIMIT 5;', function(err, result) {
			done();
			if (err){
				console.error(err);
				response.status(500).send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
})

app.post('/highscore', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('INSERT INTO highscores (uuid, name, score, timestamp) VALUES($1, $2, $3, $4) RETURNING *;', [request.body.uuid, request.body.name, request.body.score, new Date()], function(err, result) {
			done();
			if (err){
				console.error(err);
				response.status(500).send("Error " + err);
			} else {
				response.send(result.rows[0]);
			}
		});
	});
})

app.get('/', function (req, res) {
	res.send(cool())
})

var server = app.listen(app.get("port"), function () {

  var host = server.address().address
  var port = server.address().port

  console.log('Example app listening at http://%s:%s', host, port)

})<commit_msg>sdfsdfdl<commit_after>var pg = require('pg')
var express = require('express')
var http = require('http');
var fs = require('fs');
var bodyParser = require('body-parser')

var cool = require('cool-ascii-faces')

var app = express()
app.set('port', (process.env.PORT || 5000))

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
	extended: true
}));

// parse application/json
app.use(bodyParser.json());

app.get('/setup_database', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('CREATE TABLE IF NOT EXISTS highscores (id serial PRIMARY KEY NOT NULL, uuid VARCHAR(255) NOT NULL, name VARCHAR (255) NOT NULL, score integer NOT NULL, timestamp TIMESTAMP)', function(err, result) {
			done();
			if (err){
				console.error(err); response.send("Error " + err);
			} else {
				response.send(result);
			}
		});
	});
})

app.get('/drop_table', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('DROP TABLE highscores;', function(err, result) {
			done();
			if (err){
				console.error(err); response.send("Error " + err);
			} else {
				response.send(result);
			}
		});
	});
})

app.get('/truncate', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('TRUNCATE highscores;', function(err, result) {
			done();
			if (err){
				console.error(err); response.send("Error " + err);
			} else {
				response.send(result);
			}
		});
	});
})

app.get('/all_highscore', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('SELECT * FROM highscores ORDER BY score DESC;', function(err, result) {
			done();
			if (err){
				console.error(err);
				response.status(500).send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
})

app.get('/uuid_highscore', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('SELECT uuid, max(score) AS score FROM highscores GROUP BY uuid;', function(err, result) {
			done();
			if (err){
				console.error(err);
				response.status(500).send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
})

app.get('/highscore', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('SELECT highscores.id, highscores.name, merge.score, highscores.timestamp, highscores.uuid FROM highscores JOIN (SELECT uuid, max(score) AS score FROM highscores GROUP BY uuid) AS merge ON merge.uuid = highscores.uuid ORDER BY score DESC LIMIT 5;', function(err, result) {
			done();
			if (err){
				console.error(err);
				response.status(500).send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
})

app.post('/highscore', function (request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('INSERT INTO highscores (uuid, name, score, timestamp) VALUES($1, $2, $3, $4) RETURNING *;', [request.body.uuid, request.body.name, request.body.score, new Date()], function(err, result) {
			done();
			if (err){
				console.error(err);
				response.status(500).send("Error " + err);
			} else {
				response.send(result.rows[0]);
			}
		});
	});
})

app.get('/', function (req, res) {
	res.send(cool())
})

var server = app.listen(app.get("port"), function () {

  var host = server.address().address
  var port = server.address().port

  console.log('Example app listening at http://%s:%s', host, port)

})<|endoftext|>


<commit_before>const pkg = require('./package.json');

const redis = require('redis');
const path = require('path');
const fs = require('fs');
const once = require('once');

const NodeRateLimiter = require('node-rate-limiter');

const script = fs.readFileSync(path.join(__dirname, 'script.lua'), 'utf-8');

module.exports = RedisAdaptor;

RedisAdaptor.name = 'redis';
RedisAdaptor.ver = pkg.version;

function RedisAdaptor(opts) {
    opts = opts || {};
    opts.timeout = opts.timeout || NodeRateLimiter.defaultTimeout;
    opts.client = opts.client || redis.createClient();

    const adaptorOpts = opts;

    this.prepare = (callback) => prepare(adaptorOpts, callback);
    this.reset = (id, callback) => reset(adaptorOpts, id, callback);
    this.get = (id, opts, callback) => get(adaptorOpts, id, opts, callback);
}

function reset(adaptorOpts, id, callback) {
    const keyClient = 'ratelimiter.' + id;
    const keyClientTotal = keyClient + '.total';
    const keyClientLimit = keyClient + '.limit';

    const onDoneOnce = once(onDone);

    adaptorOpts.client
        .multi()
        .del(keyClientTotal)
        .del(keyClientLimit)
        .exec(onExecDoneOnce);

    let timerId = registerTimeout(adaptorOpts.timeout, onExecDoneOnce);

    function onDone(err, res) {
        if (timerId) {
            clearTimeout(timerId);
            timerId = null;
        }

        callback(err, res);
    }
}

function get(adaptorOpts, id, opts, callback) {
    const limit = opts && opts.limit || NodeRateLimiter.defaultRateLimit;
    const expire = opts && opts.expire || NodeRateLimiter.defaultExpiration;

    const onEvalshaDoneOnce = once(onEvalshaDone);

    adaptorOpts.client.evalsha(adaptorOpts.scriptSha, 3, id, limit, expire, onEvalshaDoneOnce);
    let timerId = registerTimeout(adaptorOpts.timeout, onEvalshaDoneOnce);

    function onEvalshaDone(err, res) {
        if (timerId) {
            clearTimeout(timerId);
            timerId = null;
        }

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

        const result = {
            limit: res[0],
            remaining: res[0] - res[1] + 1,
            reset: res[2]
        };
        callback(null, result);
    }
}

function prepare(adaptorOpts, callback) {
    if (adaptorOpts.scriptSha) {
        return callback(null);
    }

    const onScriptLoadedOnce = once(onScriptLoaded);

    adaptorOpts.client.script('load', script, onScriptLoadedOnce);
    let timerId = registerTimeout(adaptorOpts.timeout, onScriptLoadedOnce);

    function onScriptLoaded(err, sha) {
        if (timerId) {
            clearTimeout(timerId);
            timerId = null;
        }

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

        adaptorOpts.scriptSha = sha;
        callback(null);
    }
}

function registerTimeout(timeout, callback) {
    return setTimeout(() => {
        const error = new NodeRateLimiter.TimeoutError(null, {after: timeout});
        callback(error);
    }, timeout);
}<commit_msg>mistype fix<commit_after>const pkg = require('./package.json');

const redis = require('redis');
const path = require('path');
const fs = require('fs');
const once = require('once');

const NodeRateLimiter = require('node-rate-limiter');

const script = fs.readFileSync(path.join(__dirname, 'script.lua'), 'utf-8');

module.exports = RedisAdaptor;

RedisAdaptor.name = 'redis';
RedisAdaptor.ver = pkg.version;

function RedisAdaptor(opts) {
    opts = opts || {};
    opts.timeout = opts.timeout || NodeRateLimiter.defaultTimeout;
    opts.client = opts.client || redis.createClient();

    const adaptorOpts = opts;

    this.prepare = (callback) => prepare(adaptorOpts, callback);
    this.reset = (id, callback) => reset(adaptorOpts, id, callback);
    this.get = (id, opts, callback) => get(adaptorOpts, id, opts, callback);
}

function reset(adaptorOpts, id, callback) {
    const keyClient = 'ratelimiter.' + id;
    const keyClientTotal = keyClient + '.total';
    const keyClientLimit = keyClient + '.limit';

    const onDoneOnce = once(onDone);

    adaptorOpts.client
        .multi()
        .del(keyClientTotal)
        .del(keyClientLimit)
        .exec(onDoneOnce);

    let timerId = registerTimeout(adaptorOpts.timeout, onDoneOnce);

    function onDone(err, res) {
        if (timerId) {
            clearTimeout(timerId);
            timerId = null;
        }

        callback(err, res);
    }
}

function get(adaptorOpts, id, opts, callback) {
    const limit = opts && opts.limit || NodeRateLimiter.defaultRateLimit;
    const expire = opts && opts.expire || NodeRateLimiter.defaultExpiration;

    const onEvalshaDoneOnce = once(onEvalshaDone);

    adaptorOpts.client.evalsha(adaptorOpts.scriptSha, 3, id, limit, expire, onEvalshaDoneOnce);
    let timerId = registerTimeout(adaptorOpts.timeout, onEvalshaDoneOnce);

    function onEvalshaDone(err, res) {
        if (timerId) {
            clearTimeout(timerId);
            timerId = null;
        }

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

        const result = {
            limit: res[0],
            remaining: res[0] - res[1] + 1,
            reset: res[2]
        };
        callback(null, result);
    }
}

function prepare(adaptorOpts, callback) {
    if (adaptorOpts.scriptSha) {
        return callback(null);
    }

    const onScriptLoadedOnce = once(onScriptLoaded);

    adaptorOpts.client.script('load', script, onScriptLoadedOnce);
    let timerId = registerTimeout(adaptorOpts.timeout, onScriptLoadedOnce);

    function onScriptLoaded(err, sha) {
        if (timerId) {
            clearTimeout(timerId);
            timerId = null;
        }

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

        adaptorOpts.scriptSha = sha;
        callback(null);
    }
}

function registerTimeout(timeout, callback) {
    return setTimeout(() => {
        const error = new NodeRateLimiter.TimeoutError(null, {after: timeout});
        callback(error);
    }, timeout);
}<|endoftext|>


<commit_before>
/**
 * Expose compositor.
 */

module.exports = compose;

/**
 * Compose `middleware` returning
 * a fully valid middleware comprised
 * of all those which are passed.
 *
 * @param {Array} middleware
 * @return {Function}
 * @api public
 */

function compose(middleware){
  return function *(downstream){
    var done = false;
    var ctx = this;
    var i = 0;

    yield next();

    function next(){
      var mw = middleware[i++];

      if (!mw) {
        if (done) throw new Error('middleware yielded control multiple times');
        done = true;
        return downstream || noop();
      }

      return mw.call(ctx, next());
    }
  }
}

/**
 * Noop.
 *
 * @api private
 */

function *noop(){}<commit_msg>use generator delegation<commit_after>
/**
 * Expose compositor.
 */

module.exports = compose;

/**
 * Compose `middleware` returning
 * a fully valid middleware comprised
 * of all those which are passed.
 *
 * @param {Array} middleware
 * @return {Function}
 * @api public
 */

function compose(middleware){
  return function *(downstream){
    var done = false;
    var ctx = this;
    var i = 0;

    yield *next();

    function next(){
      var mw = middleware[i++];

      if (!mw) {
        if (done) throw new Error('middleware yielded control multiple times');
        done = true;
        return downstream || noop();
      }

      return mw.call(ctx, next());
    }
  }
}

/**
 * Noop.
 *
 * @api private
 */

function *noop(){}<|endoftext|>


<commit_before>var domToReact = require('./lib/dom-to-react');
var attributesToProps = require('./lib/attributes-to-props');
var htmlToDOM = require('html-dom-parser');

var domParserOptions = { lowerCaseAttributeNames: false };

/**
 * Converts HTML string to React elements.
 *
 * @param  {String}   html                    - HTML string.
 * @param  {Object}   [options]               - Parser options.
 * @param  {Object}   [options.htmlparser2]   - htmlparser2 options.
 * @param  {Object}   [options.library]       - Library for React, Preact, etc.
 * @param  {Function} [options.replace]       - Replace method.
 * @return {JSX.Element|JSX.Element[]|String} - React element(s), empty array, or string.
 */
function HTMLReactParser(html, options) {
  if (typeof html !== 'string') {
    throw new TypeError('First argument must be a string');
  }
  if (html === '') {
    return [];
  }
  options = options || {};
  return domToReact(
    htmlToDOM(html, options.htmlparser2 || domParserOptions),
    options
  );
}

HTMLReactParser.domToReact = domToReact;
HTMLReactParser.htmlToDOM = htmlToDOM;
HTMLReactParser.attributesToProps = attributesToProps;
HTMLReactParser.Element = require('domhandler/lib/node').Element;

// support CommonJS and ES Modules
module.exports = HTMLReactParser;
module.exports.default = HTMLReactParser;
<commit_msg>fix: ensure backwards compatibility for html-dom-parser's ES Module<commit_after>var domToReact = require('./lib/dom-to-react');
var attributesToProps = require('./lib/attributes-to-props');
var htmlToDOM = require('html-dom-parser');

// support backwards compatibility for ES Module
htmlToDOM =
  typeof htmlToDOM.default === 'function' ? htmlToDOM.default : htmlToDOM;

var domParserOptions = { lowerCaseAttributeNames: false };

/**
 * Converts HTML string to React elements.
 *
 * @param  {String}   html                    - HTML string.
 * @param  {Object}   [options]               - Parser options.
 * @param  {Object}   [options.htmlparser2]   - htmlparser2 options.
 * @param  {Object}   [options.library]       - Library for React, Preact, etc.
 * @param  {Function} [options.replace]       - Replace method.
 * @return {JSX.Element|JSX.Element[]|String} - React element(s), empty array, or string.
 */
function HTMLReactParser(html, options) {
  if (typeof html !== 'string') {
    throw new TypeError('First argument must be a string');
  }
  if (html === '') {
    return [];
  }
  options = options || {};
  return domToReact(
    htmlToDOM(html, options.htmlparser2 || domParserOptions),
    options
  );
}

HTMLReactParser.domToReact = domToReact;
HTMLReactParser.htmlToDOM = htmlToDOM;
HTMLReactParser.attributesToProps = attributesToProps;
HTMLReactParser.Element = require('domhandler/lib/node').Element;

// support CommonJS and ES Modules
module.exports = HTMLReactParser;
module.exports.default = HTMLReactParser;
<|endoftext|>


<commit_before>'use strict';
const devices = require('./data').devices;
const customDevices = require('./custom');

module.exports = items => {
	const list = devices.concat(customDevices);

	if (items && !Array.isArray(items)) {
		throw new Error(`Expected \`Array\`, got \`${typeof items}\``);
	}

	if (!items) {
		return list;
	}

	items = items.map(x => x.split(' ').join('').toLowerCase());

	let ret = [];

	for (const x of items) {
		ret = ret.concat(list.filter(y => y.name.split(' ').join('').includes(x)));
	}

	if (!ret.length) {
		throw new Error('Couldn\'t get any items');
	}

	return ret;
};
<commit_msg>Fix lint issues<commit_after>'use strict';
const devices = require('./data').devices;
const customDevices = require('./custom');

module.exports = items => {
	const list = devices.concat(customDevices);

	if (items && !Array.isArray(items)) {
		throw new Error(`Expected \`Array\`, got \`${typeof items}\``);
	}

	if (!items) {
		return list;
	}

	items = items.map(x => x.split(' ').join('').toLowerCase());

	let ret = [];

	for (const x of items) {
		ret = ret.concat(list.filter(y => y.name.split(' ').join('').includes(x)));
	}

	if (ret.length === 0) {
		throw new Error('Couldn\'t get any items');
	}

	return ret;
};
<|endoftext|>


<commit_before>/*
  Load in PhraseApp translations with v2 API.
  Must specify an API token, a locale, and a format.
  Default format returned is js for i18n-node-2.
*/

var request = require('request');
var fs = require('fs');
var _ = require('lodash');
var async = require('async');

var path = 'https://api.phraseapp.com/v2';

module.exports = {
  initialize: function(options, callback) {
    if (!options.access_token || !options.project_id) {
      throw new Error('Must supply a value for access_token and project_id');
    }

    if (!callback) {
      callback = function(err) {
        if (err) { throw new Error(err); }
      };
    }

    var config = module.exports.configure(options);
    module.exports.download(config, callback);
  },

  configure: function(options) {
    var default_options = {
      file_format: "node_json",
      file_extension: "js",
      location: process.cwd(),
      transform: function(translations) { return translations; }
    };

    return _.extend({}, default_options, options);
  },

  download: function(options, callback) {
    module.exports.fetchLocales(options,
      function (err, locales) {
        console.log("Got locales", locales);
        if (!err) {
          async.each(locales, function(l, callback) {
            module.exports.downloadTranslationFile(l, options, function(err, res) {
              if (!err) {
                console.log("Translation for " + l + " downloaded successfully.");
                return callback(null);
              } else {
                console.error("Error downloading " + l + ".", err);
                return callback(err);
              }
            });
          }, callback);
        }
      });
  },

  fetchLocales: function(options, callback) {
    var locales;

    request(path + '/projects/' + options.project_id + '/locales?access_token=' + options.access_token, function(err, res, body) {
      if (!err && res.statusCode == 200) {
        locales = _.pluck(JSON.parse(body), "code");
        return callback(null, locales);
      } else if (err) {
        console.error("An error occurred when fetching locales", err);
        return callback(err);
      }
    });
  },

  downloadTranslationFile: function(locale, options, callback) {
    var translationPath = path + '/projects/' + options.project_id + '/locales/' + locale + '/download?access_token=' + options.access_token + '&file_format=' + options.file_format;

    request(translationPath, function(err, res, body) {
      if (!err && res.statusCode >= 200 && res.statusCode < 300) {
        var transformed = options.transform(body);
        var fileName = options.location + "/" + locale + "." + options.file_extension;

        fs.writeFile(fileName, transformed, function(err) {
          if (err) {
            return console.error("An error occured when downloading translation file", err);
          }

          return callback(null, fileName);
        })
      } else {
        if (err) {
          console.error("An error occured when downloading translation file", err);
          return callback(err);
        }
        console.error("Got status code " + res.statusCode);
        return callback(true);
      }
    });
  }
}<commit_msg>limit parallel downloads to 2 due to phraseapp rate limiting<commit_after>/*
  Load in PhraseApp translations with v2 API.
  Must specify an API token, a locale, and a format.
  Default format returned is js for i18n-node-2.
*/

var request = require('request');
var fs = require('fs');
var _ = require('lodash');
var async = require('async');

var path = 'https://api.phraseapp.com/v2';

module.exports = {
  initialize: function(options, callback) {
    if (!options.access_token || !options.project_id) {
      throw new Error('Must supply a value for access_token and project_id');
    }

    if (!callback) {
      callback = function(err) {
        if (err) { throw new Error(err); }
      };
    }

    var config = module.exports.configure(options);
    module.exports.download(config, callback);
  },

  configure: function(options) {
    var default_options = {
      file_format: "node_json",
      file_extension: "js",
      location: process.cwd(),
      transform: function(translations) { return translations; }
    };

    return _.extend({}, default_options, options);
  },

  download: function(options, callback) {
    module.exports.fetchLocales(options,
      function (err, locales) {
        console.log("Got locales", locales);
        if (!err) {
          async.eachLimit(locales, 2, function(l, callback) {
            module.exports.downloadTranslationFile(l, options, function(err, res) {
              if (!err) {
                console.log("Translation for " + l + " downloaded successfully.");
                return callback(null);
              } else {
                console.error("Error downloading " + l + ".", err);
                return callback(err);
              }
            });
          }, callback);
        }
      });
  },

  fetchLocales: function(options, callback) {
    var locales;

    request(path + '/projects/' + options.project_id + '/locales?access_token=' + options.access_token, function(err, res, body) {
      if (!err && res.statusCode == 200) {
        locales = _.pluck(JSON.parse(body), "code");
        return callback(null, locales);
      } else if (err) {
        console.error("An error occurred when fetching locales", err);
        return callback(err);
      }
    });
  },

  downloadTranslationFile: function(locale, options, callback) {
    var translationPath = path + '/projects/' + options.project_id + '/locales/' + locale + '/download?access_token=' + options.access_token + '&file_format=' + options.file_format;

    request(translationPath, function(err, res, body) {
      if (!err && res.statusCode >= 200 && res.statusCode < 300) {
        var transformed = options.transform(body);
        var fileName = options.location + "/" + locale + "." + options.file_extension;

        fs.writeFile(fileName, transformed, function(err) {
          if (err) {
            return console.error("An error occured when downloading translation file", err);
          }

          return callback(null, fileName);
        })
      } else {
        if (err) {
          console.error("An error occured when downloading translation file", err);
          return callback(err);
        }
        console.error("Got status code " + res.statusCode);
        return callback(true);
      }
    });
  }
}<|endoftext|>


<commit_before><commit_msg>First commit<commit_after>/**
 * Module dependencies
 */
var request = require('superagent')
  , _ = require('underscore');

// API endpoint
var endpoint = 'http://productsearch.linksynergy.com/productsearch';

module.exports = function (opts) {
  return new Linkshare (opts);
};

var Linkshare = function (opts) {
  this._keywords = opts.keywords;
};

Linkshare.prototype.id = function (id) {
  return this._id = id, this;
};

Linkshare.prototype.advertiser = function (id) {
  return this._advertiser = id, this;
};

Linkshare.prototype.done = function (cb) {
  return request
    .get(endpoint)
    .query({token: this._id})
    .query({keyword: this._keywords})
    .query({mid: this._advertiser})
    .end(function (err, res) {
      if (err) return cb(err);
      return cb(null, res.text);
    });
};
<|endoftext|>


<commit_before>var app = require('connect')();
var http = require('http');
var util = require('util');
var helpers = require('./helpers.js');
var logger = require('./logger.js');

// Default settings
var settings = {
  // http port to listen to
  http: 80,
  // https port to redirect to
  https: 443,
  // server hostname to bind http server to
  hostname: 'localhost',
  // automatically redirect
  auto: true,
  // http status code to use for automatic redirect
  redirectStatus: 302,
  // false or '/path/to/page' to redirect all requests to
  singleTarget: false,
  // html message format to print to clients
  message: 'Perhaps you are looking for ' +
           'the HTTPS site?',
  // mime content type to use for message
  messageType: 'text/html',
  // http status code to use when showing message
  messageStatus: 404,
  // error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5
  logLevel: 2
};

module.exports = function (options, cb) {
  if (typeof options === 'function') {
    cb = options;
    options = {};
  }

  // Merge custom settings
  helpers.overwrite(settings, options);
  logger.logLevel = settings.logLevel;

  // Register request handler
  app.use(requestHandler);

  // Start listening for http connections
  var server = http.createServer(app).listen(settings.http, settings.hostname, function (err) {
    logger.info(
      'HTTP:%d -> HTTPS:%d redirection service started (%s)',
      settings.http, settings.https, settings.hostname
    );

    // Execute callback when server is running
    if (typeof cb === 'function') {
      return cb(err, settings);
    } else if (err) {
      logger.error(err);
    }
  });

  server.on('error', errorHandler);
};

function requestHandler(req, res) {
  logger.verbose('HTTP Request received : ' + settings.http + req.url);

  // Set redirection url
  var url = util.format('https://%s:%d%s',
    req.hostname,
    settings.https,
    settings.singleTarget || req.originalUrl
  );

  // Redirect automatically if specified
  if (settings.auto) {
    var headers = {
      Location: url
    };
    res.writeHead(settings.redirectStatus, headers);
    return res.end();
  }

  // Or respond with a 404 with custom message
  var body = util.format(settings.message, url);
  res.writeHead(
    settings.messageStatus,
    {
      'Content-Length': Buffer.byteLength(body),
      'Content-Type': 'text/html; charset=utf-8'
    }
  );
  res.write(body);
  res.end();
}

function errorHandler(err) {
  var printedFull = false;

  switch (err.code) {
  case 'EACCES':
    logger.error('Permission denied when attempting to listen to port %d', settings.http);
    break;
  case 'EADDRINUSE':
    logger.error('Port %d is already in use', settings.http);
    break;
  default:
    logger.error(err);
    printedFull = true;
    break;
  }

  // Print error details in verbose mode
  if (!printedFull) {
    logger.verbose(err);
  }

  // Kill process on server errors
  process.exit(1);
}
<commit_msg>Syntax upgrade and route improvements<commit_after>'use strict';

const connect = require('connect');
const http = require('http');
const util = require('util');
const helpers = require('./helpers.js');
const logger = require('./logger.js');
const app = connect();

// Default settings
const settings = {
  // http port to listen to
  http: 80,
  // https port to redirect to
  https: 443,
  // server hostname to bind http server to
  hostname: 'localhost',
  // automatically redirect
  auto: true,
  // http status code to use for automatic redirect
  redirectStatus: 302,
  // false or '/path/to/page' to redirect all requests to
  singleTarget: false,
  // html message format to print to clients
  message: 'Perhaps you are looking for ' +
           'the HTTPS site?',
  // mime content type to use for message
  messageType: 'text/html',
  // http status code to use when showing message
  messageStatus: 404,
  // error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5
  logLevel: 2
};

module.exports = function (options, cb) {
  if (typeof options === 'function') {
    cb = options;
    options = {};
  }

  // Merge custom settings
  helpers.overwrite(settings, options);
  logger.logLevel = settings.logLevel;

  // Request handlers
  app.use(function (req, res, next) {
    logger.verbose('HTTP Request received : ' + settings.http + req.url);
    return next();
  });

  app.use(function (req, res) {
    // Set redirection url
    let url = util.format('https://%s:%d%s',
      req.headers.host.split(':')[0],
      settings.https,
      settings.singleTarget || req.originalUrl
    );
    logger.log(url);

    // Redirect automatically if specified
    if (settings.auto) {
      let headers = {
        Location: url
      };
      res.writeHead(settings.redirectStatus, headers);
      return res.end();
    }

    // Or respond with a 404 with custom message
    let body = util.format(settings.message, url);
    res.writeHead(
      settings.messageStatus,
      {
        'Content-Length': Buffer.byteLength(body),
        'Content-Type': 'text/html; charset=utf-8'
      }
    );
    res.write(body);
    res.end();
  });

  // Start listening for http connections
  const server = http.createServer(app).listen(settings.http, settings.hostname, function (err) {
    logger.info(
      'HTTP:%d -> HTTPS:%d redirection service started (%s)',
      settings.http, settings.https, settings.hostname
    );

    // Execute callback when server is running
    if (typeof cb === 'function') {
      return cb(err, settings);
    } else if (err) {
      logger.error(err);
    }
  });

  server.on('error', errorHandler);
};

function errorHandler(err) {
  let printedFull = false;

  switch (err.code) {
  case 'EACCES':
    logger.error('Permission denied when attempting to listen to port %d', settings.http);
    break;
  case 'EADDRINUSE':
    logger.error('Port %d is already in use', settings.http);
    break;
  default:
    logger.error(err);
    printedFull = true;
    break;
  }

  // Print error details in verbose mode
  if (!printedFull) {
    logger.verbose(err);
  }

  // Kill process on server errors
  process.exit(1);
}
<|endoftext|>


<commit_before>'use strict'

var util = require('util')
var path = require('path')

var color = require('bash-color')
var mongojs = require('mongojs')

var startup = (new Date()).toISOString()
var requestID = 0
var lastMessage = (new Date()).toISOString()
var messageID = 0

module.exports = makeConsole
module.exports.output = output
module.exports.redirect = redirect
module.exports.console = makeConsole
module.exports.root = root
module.exports.rootPath = process.cwd()

module.exports.requests = requests
module.exports.errors = errors
module.exports.handleGlobalErrors = handleGlobalErrors

function makeConsole(filename, startTime) {
  var csl = {}
  csl.log = logger(filename, startTime, 'log')
  csl.info = logger(filename, startTime, 'info')
  csl.warn = logger(filename, startTime, 'warn')
  csl.error = logger(filename, startTime, 'error')
  csl.time = function () {
    return makeConsole(filename, new Date())
  }
  return csl
}

function logger(filename, start, level) {
  return function (type, obj) {
    var result = {type: type, timestamp: new Date()}
    if (type === 'server/request') {
      obj = obj.req
      obj.__chronicle_id__ = startup + '-' + (requestID++)
      obj.__chronicle_start__ = new Date()
      result.requestID = obj.__chronicle_id__
      result.httpVersion = obj.httpVersion
      result.headers = obj.headers
      result.method = obj.method
      result.url = obj.url
    } else if (type === 'server/response') {
      result.requestID = obj.req.__chronicle_id__
      result.statusCode = obj.res.statusCode
      result.duration = ((new Date()) - obj.req.__chronicle_start__)
    } else if (obj instanceof Error) {
      result.message = obj.stack || obj.message
      result.raw = true
    } else if (typeof obj === 'string') {
      result.message = obj
      result.raw = true
    } else {
      obj = clone(obj)
      for (var key in obj) {
        result[key] = obj[key]
      }
    }
    if (obj.req && obj.req.__chronicle_id__) {
      result.requestID = obj.req.__chronicle_id__
      if ('req' in result) delete result.req
    }
    if (start) {
      result.duration = ((new Date()) - start)
    }
    if (filename) {
      result.filename = filename
    }
    if (level) {
      result.level = level
    }
    module.exports.output(result)
  }
}

var loggingRequests = {}
function output(message, indent, callback) {
  indent = indent || ''
  if (message.requestID && message.type === 'server/request') {
    loggingRequests[message.requestID] = {
      req: message,
      logs: [],
      res: null,
      timeout: setTimeout(function () {
        loggingRequests[message.requestID].res = {type: 'server/timeout', level: 'warn', timestamp: new Date()}
        outputRequest(message.requestID)
      }, 60000)
    }
    return
  } else if (message.requestID && message.type === 'server/response' && loggingRequests[message.requestID]) {
    clearTimeout(loggingRequests[message.requestID].timeout)
    loggingRequests[message.requestID].res = message
    outputRequest(message.requestID)
    return
  } else if (message.requestID && loggingRequests[message.requestID]) {
    loggingRequests[message.requestID].logs.push(message)
    return
  }

  var _log = console[message.level] || console.log
  function log(str) {
    _log(str.toString().replace(/^/gm, indent))
  }
  var duration = message.duration ? color.purple(' (' + message.duration + 'ms)') : ''
  var type = color.cyan(message.type) + ' '
  switch (message.type) {
    case 'db/call':
      log(type + message.name + '(' + message.args.map(formatInline).join(', ') + ')' + duration)
      break
    case 'db/update':
      var index = 0
      log(type + message.statement.replace(/\?/g, function () {
        return formatInline(message.values[index++])
      }) + duration)
      break
    case 'cache/invalidate':
    case 'cache/get':
    case 'cache/set':
      log(type + formatInline(message.partition) + ' ' + formatInline(message.row))
      break
    case 'email/sent':
      log(type + formatInline(message.subject) + ' to ' + formatInline(message.to))
      break
    case 'email/batch':
      log(type + ' size: ' + formatInline(message.size))
      break
    default:
      log(type + duration)
      indent += '  '
      log(message.raw ? message.message : util.inspect(message, false, 10, true))
  }
  if (typeof callback === 'function') {
    setTimeout(callback, 0)
  }
}
function outputRequest(requestID) {
  if (!loggingRequests[requestID]) return
  clearTimeout(loggingRequests[requestID].timeout)
  var msg = loggingRequests[requestID]
  loggingRequests[requestID] = null

  var log = console[msg.res.level] || console.log
  var c = 'green'
  if (msg.res.statusCode >= 300 && msg.res.statusCode < 400) {
    c = 'purple'
  } else if (msg.res.statusCode >= 400 && msg.res.statusCode < 500) {
    c = 'yellow'
  } else if (msg.res.statusCode >= 500 || !msg.res.statusCode) {
    c = 'red'
  }
  console.log(msg.req.method.toUpperCase() + ' ' + color[c](msg.res.statusCode || 'TIMEOUT') + ' ' + msg.req.url
    + color.purple(' (' + (msg.res.duration || (msg.res.timestamp - msg.req.timestamp)) + 'ms)'))
  for (var i = 0; i < msg.logs.length; i++) {
    output(msg.logs[i], '  ')
  }
}

function formatInline(arg) {
  return util.inspect(arg, false, 3, true).replace(/^ */gm, '').replace(/ *$/gm, ' ').replace(/\n/g, '').trim()
}

function redirect(db, collection) {
  if (db !== undefined) {
    db = mongojs(db, [collection || 'chronicle'])
    module.exports.output = function (message, indent, callback) {
      var timestamp = (new Date()).toISOString()
      if (timestamp !== lastMessage) {
        lastMessage = timestamp
        messageID++
      }
      message._id = timestamp + '-' + (messageID++)
      if (message.filename) {
        message.filename = path.relative(module.exports.rootPath, message.filename).replace(/\\/g, '/')
      }
      db[collection || 'chronicle'].insert(message, function (err) {
        if (err) console.error(err.stack || err.message || err)
        if (typeof callback === 'function') {
          callback(err)
        }
      })
    }
  }
  return module.exports
}
function root(path) {
  module.exports.rootPath = path
  return module.exports
}
function requests(filename) {
  return function (req, res, next) {
    logger(filename, null, 'log')('server/request', {req: req})
    var end = res.end;
    res.end = function(chunk, encoding){
      res.end = end;
      res.end(chunk, encoding);
      logger(filename, null, res.statusCode >= 400 ? 'error' : 'log')('server/response', {
        req: req,
        res: res
      })
    };
    next()
  }
}
function errors(filename, options) {
  return function (err, req, res, next) {
    logger(filename, null, 'error')('server/error', {
      message: err.stack || err.message || err,
      raw: true,
      req: req
    })
    if (!(options && options.last)) next(err)
  }
}

function handleGlobalErrors() {
  process.once('uncaughtException', onUncaughtException);
  module.exports.handleGlobalErrors = function () {}
  return module.exports
}

function onUncaughtException(err) {
  output({
    type: 'application/crash',
    level: 'error',
    message: err.stack || err.message || err,
    raw: true,
    timestamp: new Date()
  }, '', function () {
    throw err
  })
}

function clone(obj, circular) {
  circular = circular || []
  if (typeof obj !== 'object') {
    return obj
  }
  if (Array.isArray(obj)) {
    obj = obj.map(function (v) {
      if (typeof v !== 'object') return v
      if (circular.indexOf(v) != -1) return undefined
      circular.push(v)
      return v
    })
    for (var i = 0; i < obj.length; i++) {
      obj[i] = clone(obj[i], circular)
    }
    return obj
  } else if (obj) {
    var res = {}
    for (var key in obj) {
      if (typeof v !== 'object') {
        res[key] = obj[key]
      } else if (circular.indexOf(obj[key]) != -1) {
        res[key] = undefined
      } else {
        circular.push(obj[key])
        res[key] = obj[key]
      }
    }
    for (var key in res) {
      res[key] = clone(res[key], circular)
    }
    return res
  } else {
    return obj
  }
}<commit_msg>Fix bug introduced in clone<commit_after>'use strict'

var util = require('util')
var path = require('path')

var color = require('bash-color')
var mongojs = require('mongojs')

var startup = (new Date()).toISOString()
var requestID = 0
var lastMessage = (new Date()).toISOString()
var messageID = 0

module.exports = makeConsole
module.exports.output = output
module.exports.redirect = redirect
module.exports.console = makeConsole
module.exports.root = root
module.exports.rootPath = process.cwd()

module.exports.requests = requests
module.exports.errors = errors
module.exports.handleGlobalErrors = handleGlobalErrors

function makeConsole(filename, startTime) {
  var csl = {}
  csl.log = logger(filename, startTime, 'log')
  csl.info = logger(filename, startTime, 'info')
  csl.warn = logger(filename, startTime, 'warn')
  csl.error = logger(filename, startTime, 'error')
  csl.time = function () {
    return makeConsole(filename, new Date())
  }
  return csl
}

function logger(filename, start, level) {
  return function (type, obj) {
    var result = {type: type, timestamp: new Date()}
    if (type === 'server/request') {
      obj = obj.req
      obj.__chronicle_id__ = startup + '-' + (requestID++)
      obj.__chronicle_start__ = new Date()
      result.requestID = obj.__chronicle_id__
      result.httpVersion = obj.httpVersion
      result.headers = obj.headers
      result.method = obj.method
      result.url = obj.url
    } else if (type === 'server/response') {
      result.requestID = obj.req.__chronicle_id__
      result.statusCode = obj.res.statusCode
      result.duration = ((new Date()) - obj.req.__chronicle_start__)
    } else if (obj instanceof Error) {
      result.message = obj.stack || obj.message
      result.raw = true
    } else if (typeof obj === 'string') {
      result.message = obj
      result.raw = true
    } else {
      obj = clone(obj)
      for (var key in obj) {
        result[key] = obj[key]
      }
    }
    if (obj.req && obj.req.__chronicle_id__) {
      result.requestID = obj.req.__chronicle_id__
      if ('req' in result) delete result.req
    }
    if (start) {
      result.duration = ((new Date()) - start)
    }
    if (filename) {
      result.filename = filename
    }
    if (level) {
      result.level = level
    }
    module.exports.output(result)
  }
}

var loggingRequests = {}
function output(message, indent, callback) {
  indent = indent || ''
  if (message.requestID && message.type === 'server/request') {
    loggingRequests[message.requestID] = {
      req: message,
      logs: [],
      res: null,
      timeout: setTimeout(function () {
        loggingRequests[message.requestID].res = {type: 'server/timeout', level: 'warn', timestamp: new Date()}
        outputRequest(message.requestID)
      }, 60000)
    }
    return
  } else if (message.requestID && message.type === 'server/response' && loggingRequests[message.requestID]) {
    clearTimeout(loggingRequests[message.requestID].timeout)
    loggingRequests[message.requestID].res = message
    outputRequest(message.requestID)
    return
  } else if (message.requestID && loggingRequests[message.requestID]) {
    loggingRequests[message.requestID].logs.push(message)
    return
  }

  var _log = console[message.level] || console.log
  function log(str) {
    _log(str.toString().replace(/^/gm, indent))
  }
  var duration = message.duration ? color.purple(' (' + message.duration + 'ms)') : ''
  var type = color.cyan(message.type) + ' '
  switch (message.type) {
    case 'db/call':
      log(type + message.name + '(' + message.args.map(formatInline).join(', ') + ')' + duration)
      break
    case 'db/update':
      var index = 0
      log(type + message.statement.replace(/\?/g, function () {
        return formatInline(message.values[index++])
      }) + duration)
      break
    case 'cache/invalidate':
    case 'cache/get':
    case 'cache/set':
      log(type + formatInline(message.partition) + ' ' + formatInline(message.row))
      break
    case 'email/sent':
      log(type + formatInline(message.subject) + ' to ' + formatInline(message.to))
      break
    case 'email/batch':
      log(type + ' size: ' + formatInline(message.size))
      break
    default:
      log(type + duration)
      indent += '  '
      log(message.raw ? message.message : util.inspect(message, false, 10, true))
  }
  if (typeof callback === 'function') {
    setTimeout(callback, 0)
  }
}
function outputRequest(requestID) {
  if (!loggingRequests[requestID]) return
  clearTimeout(loggingRequests[requestID].timeout)
  var msg = loggingRequests[requestID]
  loggingRequests[requestID] = null

  var log = console[msg.res.level] || console.log
  var c = 'green'
  if (msg.res.statusCode >= 300 && msg.res.statusCode < 400) {
    c = 'purple'
  } else if (msg.res.statusCode >= 400 && msg.res.statusCode < 500) {
    c = 'yellow'
  } else if (msg.res.statusCode >= 500 || !msg.res.statusCode) {
    c = 'red'
  }
  console.log(msg.req.method.toUpperCase() + ' ' + color[c](msg.res.statusCode || 'TIMEOUT') + ' ' + msg.req.url
    + color.purple(' (' + (msg.res.duration || (msg.res.timestamp - msg.req.timestamp)) + 'ms)'))
  for (var i = 0; i < msg.logs.length; i++) {
    output(msg.logs[i], '  ')
  }
}

function formatInline(arg) {
  return util.inspect(arg, false, 3, true).replace(/^ */gm, '').replace(/ *$/gm, ' ').replace(/\n/g, '').trim()
}

function redirect(db, collection) {
  if (db !== undefined) {
    db = mongojs(db, [collection || 'chronicle'])
    module.exports.output = function (message, indent, callback) {
      var timestamp = (new Date()).toISOString()
      if (timestamp !== lastMessage) {
        lastMessage = timestamp
        messageID++
      }
      message._id = timestamp + '-' + (messageID++)
      if (message.filename) {
        message.filename = path.relative(module.exports.rootPath, message.filename).replace(/\\/g, '/')
      }
      db[collection || 'chronicle'].insert(message, function (err) {
        if (err) console.error(err.stack || err.message || err)
        if (typeof callback === 'function') {
          callback(err)
        }
      })
    }
  }
  return module.exports
}
function root(path) {
  module.exports.rootPath = path
  return module.exports
}
function requests(filename) {
  return function (req, res, next) {
    logger(filename, null, 'log')('server/request', {req: req})
    var end = res.end;
    res.end = function(chunk, encoding){
      res.end = end;
      res.end(chunk, encoding);
      logger(filename, null, res.statusCode >= 400 ? 'error' : 'log')('server/response', {
        req: req,
        res: res
      })
    };
    next()
  }
}
function errors(filename, options) {
  return function (err, req, res, next) {
    logger(filename, null, 'error')('server/error', {
      message: err.stack || err.message || err,
      raw: true,
      req: req
    })
    if (!(options && options.last)) next(err)
  }
}

function handleGlobalErrors() {
  process.once('uncaughtException', onUncaughtException);
  module.exports.handleGlobalErrors = function () {}
  return module.exports
}

function onUncaughtException(err) {
  output({
    type: 'application/crash',
    level: 'error',
    message: err.stack || err.message || err,
    raw: true,
    timestamp: new Date()
  }, '', function () {
    throw err
  })
}

function clone(obj, circular) {
  circular = circular || []
  if (typeof obj !== 'object') {
    return obj
  }
  if (Array.isArray(obj)) {
    obj = obj.map(function (v) {
      if (typeof v !== 'object') return v
      if (circular.indexOf(v) != -1) return undefined
      circular.push(v)
      return v
    })
    for (var i = 0; i < obj.length; i++) {
      obj[i] = clone(obj[i], circular)
    }
    return obj
  } else if (obj) {
    var res = {}
    for (var key in obj) {
      if (typeof obj[key] !== 'object') {
        res[key] = obj[key]
      } else if (circular.indexOf(obj[key]) != -1) {
        res[key] = undefined
      } else {
        circular.push(obj[key])
        res[key] = obj[key]
      }
    }
    for (var key in res) {
      res[key] = clone(res[key], circular)
    }
    return res
  } else {
    return obj
  }
}<|endoftext|>


<commit_before>'use strict';
function parseJs(code, define) {
    //js模板解析

    var promise = {
        data: [],
        len: 0,

        get: function() {
            return this.data[this.len - 1];
        },
        getState: function(all) {
            //是否为true
            var l = this.len - 1;
            if (all === true) {
                l++;
            }
            for (var i = 0; i < l; i++) {
                if (!this.data[i])
                    return false;
            }
            return true;
        },
        set: function(state) {
            this.data[this.len - 1] = this.data[this.len - 1] || state;
            return state;
        },
        pop: function() {
            this.len--;
            return this.len > 0 ? this.data.pop() : this.len = 0;
        },
        push: function(state) {
            this.len++;
            return this.data.push(state),
            state;
        }
    };

    return function() {

        var res = code.replace(/(\{\{.*?\}\})(((?!\{\{)[\s\S])*)/g, function(phrase, condition, codeSniffer) {
            //暂不支持自定义openTag和closeTag
            condition = condition.replace(/(^\{\{|\}\}$)/g, '').trim();
            if (condition.indexOf('=') === 0) {
                return promise.getState(true) ? eval(condition.substring(1)) : '';
            } else {
                var _promise = condition.replace(/^(elseif|else if|\/if|if|else)(.*)/i, function() {
                    var bool = eval(arguments[2]);
                    switch (arguments[1]) {
                    case '=':
                        return true;
                        break;
                    case 'if':
                        promise.push(!!bool);
                        return promise.getState() && !!bool;
                        break;
                    case 'else':
                        return promise.getState() ? promise.get() === false ? true : false : false;
                        break;
                    case 'else if':
                        ;
                    case 'elseif':
                        var old = promise.get();
                        bool = bool && (promise.getState() ? promise.get() === false ? true : false : false);
                        promise.set(bool);
                        return old === false ? bool : false;

                        break;
                    case '/if':
                        promise.pop();
                        return promise.get() && promise.getState();
                        break;
                    }
                }
                );

                if (_promise == 'true') {
                    return codeSniffer;
                }
            }
            return '';
        }
        );
        return res;
    }
}

function render(content, data) {
    data = data || {};
    return parseJs(content, data)();
}

module.exports = function(content, file, conf) {
    if (!content) return '';
    if (content.trim() == '') {
        return content;
    }

    var content = render(content, conf.define);

    return content;
};
<commit_msg>add = operator<commit_after>'use strict';
function parseJs(code, define) {
    //js模板解析

    var promise = {
        data: [],
        len: 0,

        get: function() {
            return this.data[this.len - 1];
        },
        getState: function(all) {
            //是否为true
            var l = this.len - 1;
            if (all === true) {
                l++;
            }
            for (var i = 0; i < l; i++) {
                if (!this.data[i])
                    return false;
            }
            return true;
        },
        set: function(state) {
            this.data[this.len - 1] = this.data[this.len - 1] || state;
            return state;
        },
        pop: function() {
            this.len--;
            return this.len > 0 ? this.data.pop() : this.len = 0;
        },
        push: function(state) {
            this.len++;
            return this.data.push(state),
            state;
        }
    };

    return function() {

        var res = code.replace(/(\{\{.*?\}\})(((?!\{\{)[\s\S])*)/g, function(phrase, condition, codeSniffer) {
            //暂不支持自定义openTag和closeTag
            condition = condition.replace(/(^\{\{|\}\}$)/g, '').trim();
            if (condition.indexOf('=') === 0) {
                return promise.getState(true) ? eval(condition.substring(1)) : '';
            } else {
                var _promise = condition.replace(/^(elseif|else if|\/if|if|else)(.*)/i, function() {
                    var bool = eval(arguments[2]);
                    switch (arguments[1]) {
                    case 'if':
                        promise.push(!!bool);
                        return promise.getState() && !!bool;
                        break;
                    case 'else':
                        return promise.getState() ? promise.get() === false ? true : false : false;
                        break;
                    case 'else if':
                        ;
                    case 'elseif':
                        var old = promise.get();
                        bool = bool && (promise.getState() ? promise.get() === false ? true : false : false);
                        promise.set(bool);
                        return old === false ? bool : false;

                        break;
                    case '/if':
                        promise.pop();
                        return promise.get() && promise.getState();
                        break;
                    }
                }
                );

                if (_promise == 'true') {
                    return codeSniffer;
                }
            }
            return '';
        }
        );
        return res;
    }
}

function render(content, data) {
    data = data || {};
    return parseJs(content, data)();
}

module.exports = function(content, file, conf) {
    if (!content) return '';
    if (content.trim() == '') {
        return content;
    }

    var content = render(content, conf.define);

    return content;
};
<|endoftext|>


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

var app = express();

var port = +process.env.port || 80;

app.get('/', (req, res) => {
    res.send('welcome home');
});

app.get('/500', (req, res) => {
    res.status(500).send('Something broke!');
});

app.listen(port, function(err) {
});<commit_msg>Updates for heroku<commit_after>var express = require('express');

var app = express();

var port = +process.env.port || 80;

app.get('/', (req, res) => {
    res.status(200);
    res.setHeader('Content-Type', 'text/plain');
    res.send('welcome home');
});

app.get('/500', (req, res) => {
    res.setHeader('Content-Type', 'text/plain');
    res.status(500).send('Something broke!');
});

app.listen(port, function(err) {
});<|endoftext|>


<commit_before>// CALCULATE RPS!
var begin = new Date() // for calculating requests per second
var end = new Date()
var __current_rps = 0 // current request per second
var __req_num = 0 // Global application requests number
var __req_num_local = 0 // application requests number, after each RPS calculation
var redis // redis!

// options that can be overwtieen when calling this module
var options = {
  calcRpsEachNseconds: 300,
  maxUserRequestLimitPerMinute: {
    POST: 50,
    GET: 300,
    PUT: 50,
    DELETE: 50
  }
}

/**
 * Checks requests intensivity from single User (if any) OR IP address
 * And skips check in we are in development mode
 * @param req
 * @param res
 * @param next
 * @returns next()
 */
function checkReqsIntensivity (req, res, next) {
  var user_id = req.user && req.user.id ? req.user.id : 0
  var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress

  var minute = parseInt(Date.now() / 1000 / 60, 10)
  var requestKey = 'RateLimitter:' + (user_id || ip) + ':' + req.method + ':' + minute

  function errHandler (err) {
    console.log('RateLimitter Error')
    console.log(err)
    return next()
  }

  function processResponse (info) {
    if (info.too_often) {
      console.log('Please slow down, you post very frequently.')
      return res.sendStatus(429)
    } else {
      // save reqnum into redis
      redis.setex(requestKey, 1 * 60, ++info.reqnum, function (err) {
        if (err) {
          return errHandler(err)
        }
        return next()
      })
    }
  }

  redis.get(requestKey, function (err, reqnum) {
    if (err) {
      return errHandler(err)
    }

    reqnum = parseInt(reqnum, 10) || 0
    var too_often = false
    if (reqnum > options.maxUserRequestLimitPerMinute[req.method]) {
      too_often = true
    }
    processResponse({too_often: too_often, reqnum: reqnum || 0})
  })
}

/**
 * Express middlewear to be called on every request!
 * @param req
 * @param res
 * @param next
 * @returns next()
 */
function checker (req, res, next) {
  // Rate limitter per USER
  checkReqsIntensivity(req, res, next)

  // calculate current rps
  if (__req_num_local === options.calcRpsEachNseconds) {
    // calculate requests per second
    end = new Date()
    __current_rps = (__req_num_local / ((end - begin) / 1000)).toFixed(0)

    // print statistics
    console.log('\n\nIncoming Connections: ' + __req_num)
    console.log('Requests per second: ' + __current_rps + '   Time: ' + ((end - begin) / 1000).toFixed(3) + ', Requests: ' + __req_num_local + '\n')

    __req_num_local = 0
    begin = new Date()
  }

  __req_num++
  __req_num_local++
}

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function mergeOptions (obj1, obj2) {
  var obj3 = {}
  for (var attrname in obj1) { obj3[attrname] = obj1[attrname] }
  for (var attrname2 in obj2) { obj3[attrname2] = obj2[attrname2] }
  return obj3
}

module.exports = function (redisClient, op) {
  if (op) {
    options = mergeOptions(options, op)
  }

  redis = redisClient
  return checker
}
<commit_msg>Add rate limit headers<commit_after>// CALCULATE RPS!
var begin = new Date() // for calculating requests per second
var end = new Date()
var __current_rps = 0 // current request per second
var __req_num = 0 // Global application requests number
var __req_num_local = 0 // application requests number, after each RPS calculation
var redis // redis!

// options that can be overwtieen when calling this module
var options = {
  calcRpsEachNseconds: 300,
  TimeFrameInMinutes: 1,
  maxUserRequestLimitPerTimeFrame: {
    POST: 50,
    GET: 300,
    PUT: 50,
    DELETE: 50
  }
}

/**
 * Checks requests intensivity from single User (if any) OR IP address
 * And skips check in we are in development mode
 * @param req
 * @param res
 * @param next
 * @returns next()
 */
function checkReqsIntensivity (req, res, next) {
  var user_id = req.user && req.user.id ? req.user.id : 0
  var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress

  var minute = parseInt(Date.now() / 1000 / (options.TimeFrameInMinutes * 60), 10)
  var requestKey = 'RateLimitter:' + (user_id || ip) + ':' + req.method + ':' + minute

  // next minute
  var resetMinute = minute * (options.TimeFrameInMinutes * 60) + (options.TimeFrameInMinutes * 60)

  function errHandler (err) {
    console.log('RateLimitter Error')
    console.log(err)
    return next()
  }

  function processResponse (info) {
    if (info.too_often) {
      console.log('Please slow down, you request too frequently.')
      return res.sendStatus(429)
    } else {
      // save reqnum into redis
      redis.setex(requestKey, options.TimeFrameInMinutes * 60, ++info.reqnum, function (err) {
        if (err) {
          return errHandler(err)
        }
        return next()
      })
    }
  }

  redis.get(requestKey, function (err, reqnum) {
    if (err) {
      return errHandler(err)
    }

    reqnum = parseInt(reqnum, 10) || 0
    var too_often = false
    var remaining = options.maxUserRequestLimitPerTimeFrame[req.method] - reqnum
    if (remaining < 0) {
      too_often = true
      res.setHeader('X-Rate-Limit-Remaining', Math.max(remaining, 0))
    }

    res.setHeader('X-Rate-Limit-Limit', options.maxUserRequestLimitPerTimeFrame[req.method])
    res.setHeader('X-Rate-Limit-Reset', resetMinute)

    console.log('reqnum', reqnum)
    console.log('X-Rate-Limit-Limit', options.maxUserRequestLimitPerTimeFrame[req.method])
    console.log('X-Rate-Limit-Reset', resetMinute)
    console.log('X-Rate-Limit-Remaining', remaining)
    console.log('\n')
    processResponse({too_often: too_often, reqnum: reqnum || 0})
  })
}

/**
 * Express middlewear to be called on every request!
 * @param req
 * @param res
 * @param next
 * @returns next()
 */
function checker (req, res, next) {
  // Rate limitter per USER
  checkReqsIntensivity(req, res, next)

  // calculate current rps
  if (__req_num_local === options.calcRpsEachNseconds) {
    // calculate requests per second
    end = new Date()
    __current_rps = (__req_num_local / ((end - begin) / 1000)).toFixed(0)

    // print statistics
    console.log('\n\nIncoming Connections: ' + __req_num)
    console.log('Requests per second: ' + __current_rps + '   Time: ' + ((end - begin) / 1000).toFixed(3) + ', Requests: ' + __req_num_local + '\n')

    __req_num_local = 0
    begin = new Date()
  }

  __req_num++
  __req_num_local++
}

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function mergeOptions (obj1, obj2) {
  var obj3 = {}
  for (var attrname in obj1) { obj3[attrname] = obj1[attrname] }
  for (var attrname2 in obj2) { obj3[attrname2] = obj2[attrname2] }
  return obj3
}

module.exports = function (redisClient, op) {
  if (op) {
    options = mergeOptions(options, op)
  }

  redis = redisClient
  return checker
}
<|endoftext|>