<commit_before>'use strict';
const execa = require('execa');
const Listr = require('listr');
const version = require('./version');

module.exports = (input, pkg, opts) => {
	let newVersion = null;

	const tasks = [
		{
			title: 'Validate version',
			task: () => {
				if (!version.isValidVersionInput(input)) {
					throw new Error(`Version should be either ${version.SEMVER_INCREMENTS.join(', ')}, or a valid semver version.`);
				}

				newVersion = version.getNewVersion(pkg.version, input);

				if (!version.isVersionGreater(pkg.version, newVersion)) {
					throw new Error(`New version \`${newVersion}\` should be higher than current version \`${pkg.version}\``);
				}
			}
		},
		{
			title: 'Check for pre-release version',
			task: () => {
				if (!pkg.private && version.isPrereleaseVersion(newVersion) && !opts.tag) {
					throw new Error('You must specify a dist-tag using --tag when publishing a pre-release version. This prevents accidentally tagging unstable versions as "latest". https://docs.npmjs.com/cli/dist-tag');
				}
			}
		},
		{
			title: 'Check npm version',
			skip: () => version.isVersionLower('6.0.0', process.version),
			task: () => execa.stdout('npm', ['version', '--json']).then(json => {
				const versions = JSON.parse(json);
				if (!version.satisfies(versions.npm, '>=2.15.8 <3.0.0 || >=3.10.1')) {
					throw new Error(`npm@${versions.npm} has known issues publishing when running Node.js 6. Please upgrade npm or downgrade Node and publish again. https://github.com/npm/npm/issues/5082`);
				}
			})
		},
		{
			title: 'Check yarn.lock integrity',
			enabled: () => opts.yarn,
			task: () => execa.stdout('yarn', ['check', '--integrity'])
				.catch(err => {
					if (err.code === 'ENOENT') {
						throw new Error('Yarn not available, run `npm install -g yarn` to install or use the `--no-yarn` flag');
					}

					throw new Error('`yarn.lock` file is outdated, run `yarn`, commit your changes and try again');
				})
		},
		{
			title: 'Check git tag existence',
			task: () => execa('git', ['fetch'])
				.then(() => execa.stdout('git', ['rev-parse', '--quiet', '--verify', `refs/tags/v${newVersion}`]))
				.then(
					output => {
						if (output) {
							throw new Error(`Git tag \`v${newVersion}\` already exists.`);
						}
					},
					err => {
						// Command fails with code 1 and no output if the tag does not exist, even though `--quiet` is provided
						// https://github.com/sindresorhus/np/pull/73#discussion_r72385685
						if (err.stdout !== '' || err.stderr !== '') {
							throw err;
						}
					}
				)
		}
	];

	return new Listr(tasks);
};
<commit_msg>Disable dist-tag check when running with `--no-publish` - fixes #140 (#142)<commit_after>'use strict';
const execa = require('execa');
const Listr = require('listr');
const version = require('./version');

module.exports = (input, pkg, opts) => {
	let newVersion = null;

	const tasks = [
		{
			title: 'Validate version',
			task: () => {
				if (!version.isValidVersionInput(input)) {
					throw new Error(`Version should be either ${version.SEMVER_INCREMENTS.join(', ')}, or a valid semver version.`);
				}

				newVersion = version.getNewVersion(pkg.version, input);

				if (!version.isVersionGreater(pkg.version, newVersion)) {
					throw new Error(`New version \`${newVersion}\` should be higher than current version \`${pkg.version}\``);
				}
			}
		},
		{
			title: 'Check for pre-release version',
			enabled: () => opts.publish,
			task: () => {
				if (!pkg.private && version.isPrereleaseVersion(newVersion) && !opts.tag) {
					throw new Error('You must specify a dist-tag using --tag when publishing a pre-release version. This prevents accidentally tagging unstable versions as "latest". https://docs.npmjs.com/cli/dist-tag');
				}
			}
		},
		{
			title: 'Check npm version',
			skip: () => version.isVersionLower('6.0.0', process.version),
			task: () => execa.stdout('npm', ['version', '--json']).then(json => {
				const versions = JSON.parse(json);
				if (!version.satisfies(versions.npm, '>=2.15.8 <3.0.0 || >=3.10.1')) {
					throw new Error(`npm@${versions.npm} has known issues publishing when running Node.js 6. Please upgrade npm or downgrade Node and publish again. https://github.com/npm/npm/issues/5082`);
				}
			})
		},
		{
			title: 'Check yarn.lock integrity',
			enabled: () => opts.yarn,
			task: () => execa.stdout('yarn', ['check', '--integrity'])
				.catch(err => {
					if (err.code === 'ENOENT') {
						throw new Error('Yarn not available, run `npm install -g yarn` to install or use the `--no-yarn` flag');
					}

					throw new Error('`yarn.lock` file is outdated, run `yarn`, commit your changes and try again');
				})
		},
		{
			title: 'Check git tag existence',
			task: () => execa('git', ['fetch'])
				.then(() => execa.stdout('git', ['rev-parse', '--quiet', '--verify', `refs/tags/v${newVersion}`]))
				.then(
					output => {
						if (output) {
							throw new Error(`Git tag \`v${newVersion}\` already exists.`);
						}
					},
					err => {
						// Command fails with code 1 and no output if the tag does not exist, even though `--quiet` is provided
						// https://github.com/sindresorhus/np/pull/73#discussion_r72385685
						if (err.stdout !== '' || err.stderr !== '') {
							throw err;
						}
					}
				)
		}
	];

	return new Listr(tasks);
};
<|endoftext|>


<commit_before>'use strict'

var postcss = require('postcss')
var defined = require('defined')

var noop = postcss.plugin('noop', function () {
  return function (css) {}
})

module.exports = postcss.plugin('@emilbayes/css-pipeline', function (options) {
  options = options || {}
  var rtl = defined(options.rtl, process.env.RTL, false)
  var debug = defined(options.debug, process.env.DEBUG, false)

  return postcss([
    require('postcss-import')({
      plugins: [
        debug ? require('stylelint')(require('stylelint-config-standard')) : noop()
      ]
    }),
    require('postcss-url')({url: 'rebase'}),
    rtl ? require('rtlcss')() : noop(),
    require('postcss-cssnext')(),
    !debug ? require('cssnano')({ autoprefixer: false }) : noop(),
    debug ? require('postcss-browser-reporter')() : noop()
  ])
})
<commit_msg>Correctly resolve env vars to their boolean values<commit_after>'use strict'

var postcss = require('postcss')
var defined = require('defined')

var noop = postcss.plugin('noop', function () {
  return function (css) {}
})

module.exports = postcss.plugin('@emilbayes/css-pipeline', function (options) {
  options = options || {}
  var rtl = defined(options.rtl, process.env.RTL == true, false)
  var debug = defined(options.debug, process.env.DEBUG == true, false)

  return postcss([
    require('postcss-import')({
      plugins: [
        debug ? require('stylelint')(require('stylelint-config-standard')) : noop()
      ]
    }),
    require('postcss-url')({url: 'rebase'}),
    rtl ? require('rtlcss')() : noop(),
    require('postcss-cssnext')(),
    !debug ? require('cssnano')({ autoprefixer: false }) : noop(),
    debug ? require('postcss-browser-reporter')() : noop()
  ])
})
<|endoftext|>


<commit_before>var _ = require("lodash");
var phantomjs = require("phantomjs").path;
var spawn = require("child_process").spawn;
var arrayify = require("./lib/utils").arrayify;
var path = require("path");

var script = path.resolve(__dirname, 'lib/task.js');

module.exports = function (src, options, callback) {
	options = _.extend({}, options || {});
	var inject = arrayify(options.inject);
	var tasks = arrayify(options.tasks);
	var jobs = [];
	var phatomargs = [
		options.images ? '--load-images=' + !!options.images : null,
		options.cookies ? '--cookies-file=' + options.cookies : null,
		options.cache ? '--disk-cache=' + !!options.cache : null
	].filter(_.ident);

	var args = [].concat(options, script, src);
	if (options.outpus) {
		args.push('--output');
		args.push(options.output);
	}
	if (options.parallel) {
		args.push('--parallel');
	}
	inject.forEach( function (i) {
		args.push("--inject");
		args.push(i);
	});
	tasks.forEach( function (t) {
		args.push("--task");
		args.push(t);
	});
	var p = spawn(phantomjs, args);
	p.on("exit", function (code) {
		var error;
		if (code !== 0) {
			error = new Error("Phantomjs exited with code: " + code);
		}
		callback(error);
	});
	return p;
};
<commit_msg>Flatten tasks.<commit_after>var _ = require("lodash");
var phantomjs = require("phantomjs").path;
var spawn = require("child_process").spawn;
var arrayify = require("./lib/utils").arrayify;
var path = require("path");

var script = path.resolve(__dirname, 'lib/task.js');

module.exports = function (src, options, callback) {
	options = _.extend({}, options || {});
	var inject = arrayify(options.inject);
	var tasks = _.flatten(arrayify(options.tasks));
	var jobs = [];
	var phatomargs = [
		options.images ? '--load-images=' + !!options.images : null,
		options.cookies ? '--cookies-file=' + options.cookies : null,
		options.cache ? '--disk-cache=' + !!options.cache : null
	].filter(_.ident);

	var args = [].concat(options, script, src);
	if (options.outpus) {
		args.push('--output');
		args.push(options.output);
	}
	if (options.parallel) {
		args.push('--parallel');
	}
	inject.forEach( function (i) {
		args.push("--inject");
		args.push(i);
	});
	tasks.forEach( function (t) {
		args.push("--task");
		args.push(t);
	});
	var p = spawn(phantomjs, args);
	p.on("exit", function (code) {
		var error;
		if (code !== 0) {
			error = new Error("Phantomjs exited with code: " + code);
		}
		callback(error);
	});
	return p;
};
<|endoftext|>


<commit_before>// Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.

let treeNode = (address, setUp) => new Promise(
    function(resolve, reject) {
  let node = {};
  let obj = {};
  let children = [];

  obj.runBefore = () => {};
  obj.run = () => {};
  obj.runAfter = () => {};

  obj.add = function(childSetUp) {
    let a = address.concat(children.length);
    children.push(treeNode(a, childSetUp))
  };

  node.run = logger => new Promise(function(resolveRun, rejectRun) {
    obj.log = (code, message) => new Promise(
        function(resolveLog, rejectLog) {
      let a = [Date.now(), code].concat(address);
      a.push(message || "");

      Promise.resolve(
        logger.log(a)

      ).then(value => {
        resolveLog(value);
      });
    });

    obj.log("begin");

    Promise.resolve(obj.runBefore()).then(function() {
      return Promise.resolve(obj.run());

    }).then(function() {
      let runningChildren = [];
      for (let child of node.children)
        runningChildren.push(child.run(logger));

      return Promise.all(runningChildren);

    }).then(function() {
      return Promise.resolve(obj.runAfter());

    }).then(function() {
      obj.log("done");
      resolveRun();
    });
  });

  Promise.resolve(setUp(obj)).then(function(value) {
    return Promise.all(children);

  }).then(function(childIterator) {
    node.children = [...childIterator];
    resolve(node);
  });
});

let newRootNode = (newLogger, setUp) => new Promise(
    function(resolve, reject) {
  let rootPromise = treeNode([], setUp);
  let logger = newLogger({});

  rootPromise.then(function(root) {
    logger.storeProcess(root.run(logger));
    resolve(logger);
  });
});

module.exports = newRootNode;
<commit_msg>:muscle: Inline needless declaration<commit_after>// Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.

let treeNode = (address, setUp) => new Promise(
    function(resolve, reject) {
  let node = {};
  let obj = {};
  let children = [];

  obj.runBefore = () => {};
  obj.run = () => {};
  obj.runAfter = () => {};

  obj.add = function(childSetUp) {
    children.push(treeNode(address.concat(children.length),
                           childSetUp))
  };

  node.run = logger => new Promise(function(resolveRun, rejectRun) {
    obj.log = (code, message) => new Promise(
        function(resolveLog, rejectLog) {
      let a = [Date.now(), code].concat(address);
      a.push(message || "");

      Promise.resolve(
        logger.log(a)

      ).then(value => {
        resolveLog(value);
      });
    });

    obj.log("begin");

    Promise.resolve(obj.runBefore()).then(function() {
      return Promise.resolve(obj.run());

    }).then(function() {
      let runningChildren = [];
      for (let child of node.children)
        runningChildren.push(child.run(logger));

      return Promise.all(runningChildren);

    }).then(function() {
      return Promise.resolve(obj.runAfter());

    }).then(function() {
      obj.log("done");
      resolveRun();
    });
  });

  Promise.resolve(setUp(obj)).then(function(value) {
    return Promise.all(children);

  }).then(function(childIterator) {
    node.children = [...childIterator];
    resolve(node);
  });
});

let newRootNode = (newLogger, setUp) => new Promise(
    function(resolve, reject) {
  let rootPromise = treeNode([], setUp);
  let logger = newLogger({});

  rootPromise.then(function(root) {
    logger.storeProcess(root.run(logger));
    resolve(logger);
  });
});

module.exports = newRootNode;
<|endoftext|>


<commit_before>var comments = require('parse-comments');

var cache = {};
var urlPrefix = "";

module.exports = (server, options) => {
  options = options || {};
  urlPrefix = options.prefix || urlPrefix;

  // override json formatter
  // add HAL data to body and then invoke normal json formatter
  var _formatJSON = server.formatters["application/json"];
  var halFormatter = (request, response, body, cb) => {
    body._links = request.hal;
    return _formatJSON(request, response, body, cb);
  }
  server.acceptable.push('application/hal+json');
  server.formatters["application/hal+json"] = halFormatter;
  if (options.overrideJSON) {
    server.formatters["application/json"] = halFormatter;
  }

  // fires on every request
  // renders the HAL data and puts it in cache if not present already
  return (request, response, next) => {
    var url = request.url;
    var routes = server.router.routes;
    var routeChains = server.routes;

    if (!cache[url]) {
      cache[url] = getHAL(url, routes, routeChains);
    }
    request.hal = cache[url];
    next();
  }
}

var getHAL = (url, routes, routeChains) => {
  var result = [];

  // routes are grouped by method (GET, PUT, POST, DELETE, ...)
  for (var method in routes) {

    for (var i = 0; i < routes[method].length; i++) {
      var route = routes[method][i];

      // path as it was defined by the developer in server.get(<path>)
      var path = route.spec.path;

      // route might contain parameters
      // check piece by piece to deal with url parameters
      var urlPieces = removeLastIfEmpty(url.split("/"));
      var pathPieces = removeLastIfEmpty(path.split("/"));

      // check if this path should be added to the HAL response of this request
      if ( urlMatches(pathPieces, urlPieces) ) {
        var halObj = {}

        var name;
        if (urlPieces.length == pathPieces.length) {
          name = "self";
        } else {
          name = route.name;
          // rewrite trailing url parameter to URI Template
          // https://tools.ietf.org/html/rfc6570
          if (pathPieces[pathPieces.length-1].indexOf(":") > -1) {
            var piece = pathPieces[pathPieces.length-1].substring(1);
            pathPieces[pathPieces.length-1] = `{${piece}}`;
            halObj.templated = true;
          }
        }
        halObj.href = urlPrefix + pathPieces.join("/");
        if (halObj.href == "") {
          halObj.href = "/";
        }

        // get the set of functions associated with this url call
        var chain = routeChains[route.name];
        // check each of them for HAL documentation
        for (var z = 0; z < chain.length; z++) {
          // process the comments in the function code
          var code = comments(chain[z] + "");
          // go over each comment block
          for (var j = 0; j < code.length; j++) {
            var piece = code[j];
            // we only process it if the description starts with `HAL: `
            if (piece.description && piece.description.substring(0,5) == "HAL: ") {
              piece.description = piece.description.substring(5);
              // override the name if set
              if (piece.name && name != "self") {
                name = piece.name;
              }
              // set the type
              halObj.type = piece.type;
              // set the deprecation flag
              halObj.deprecation = piece.deprecated;
              // profile refers to a validation document
              // value must be a URL
              if (piece.returns[0]) {
                halObj.profile = piece.returns[0].description;
              }
              // title, used by client UI's to know what to put in a button or something
              halObj.title = piece.alias;
              // description is not in the JSON-HAL spec, but it's useful
              halObj.description = piece.description;
              // JSON-HAL doesn't specify a way to document parameters
              // URI Templates do though
              if (piece.params) {
                halObj.templated = true;

                halObj.href += "{?";
                for (var a = 0; a < piece.params.length; a++) {
                  var param = piece.params[a];
                  halObj.href += param.name || param.description;
                  if (a != piece.params.length-1) {
                    halObj.href += ",";
                  }
                }
                halObj.href += "}";

              }
            }
          }
        }
        halObj.rel = name;
        result.push(halObj);

      }
    }

  }
  return result;
}

var removeLastIfEmpty = array => {
  var lastItem = array[array.length-1];
  if (!lastItem || lastItem == "") {
    array.pop();
  }
  return array;
}

var urlMatches = (pathPieces, urlPieces) => {
  if (pathPieces.length < urlPieces.length || pathPieces.length > urlPieces.length + 1) {
    // this path is shorter than our url -> no match
    // or
    // this path is at least 2 parts longer -> not a related resource
    return false;
  } else {
    for (var j = 0; j < urlPieces.length; j++) {
      if (pathPieces[j].indexOf(":") > -1) {
        // url parameter, assume it matches
        // replace the :paramname with the actually used value
        pathPieces[j] = urlPieces[j];
      } else if (pathPieces[j] != urlPieces[j]) {
        return false;
      }
    }
  }
  return true;
};
<commit_msg>fixed error when @returns is not set<commit_after>var comments = require('parse-comments');

var cache = {};
var urlPrefix = "";

module.exports = (server, options) => {
  options = options || {};
  urlPrefix = options.prefix || urlPrefix;

  // override json formatter
  // add HAL data to body and then invoke normal json formatter
  var _formatJSON = server.formatters["application/json"];
  var halFormatter = (request, response, body, cb) => {
    body._links = request.hal;
    return _formatJSON(request, response, body, cb);
  }
  server.acceptable.push('application/hal+json');
  server.formatters["application/hal+json"] = halFormatter;
  if (options.overrideJSON) {
    server.formatters["application/json"] = halFormatter;
  }

  // fires on every request
  // renders the HAL data and puts it in cache if not present already
  return (request, response, next) => {
    var url = request.url;
    var routes = server.router.routes;
    var routeChains = server.routes;

    if (!cache[url]) {
      cache[url] = getHAL(url, routes, routeChains);
    }
    request.hal = cache[url];
    next();
  }
}

var getHAL = (url, routes, routeChains) => {
  var result = [];

  // routes are grouped by method (GET, PUT, POST, DELETE, ...)
  for (var method in routes) {

    for (var i = 0; i < routes[method].length; i++) {
      var route = routes[method][i];

      // path as it was defined by the developer in server.get(<path>)
      var path = route.spec.path;

      // route might contain parameters
      // check piece by piece to deal with url parameters
      var urlPieces = removeLastIfEmpty(url.split("/"));
      var pathPieces = removeLastIfEmpty(path.split("/"));

      // check if this path should be added to the HAL response of this request
      if ( urlMatches(pathPieces, urlPieces) ) {
        var halObj = {}

        var name;
        if (urlPieces.length == pathPieces.length) {
          name = "self";
        } else {
          name = route.name;
          // rewrite trailing url parameter to URI Template
          // https://tools.ietf.org/html/rfc6570
          if (pathPieces[pathPieces.length-1].indexOf(":") > -1) {
            var piece = pathPieces[pathPieces.length-1].substring(1);
            pathPieces[pathPieces.length-1] = `{${piece}}`;
            halObj.templated = true;
          }
        }
        halObj.href = urlPrefix + pathPieces.join("/");
        if (halObj.href == "") {
          halObj.href = "/";
        }

        // get the set of functions associated with this url call
        var chain = routeChains[route.name];
        // check each of them for HAL documentation
        for (var z = 0; z < chain.length; z++) {
          // process the comments in the function code
          var code = comments(chain[z] + "");
          // go over each comment block
          for (var j = 0; j < code.length; j++) {
            var piece = code[j];
            // we only process it if the description starts with `HAL: `
            if (piece.description && piece.description.substring(0,5) == "HAL: ") {
              piece.description = piece.description.substring(5);
              // override the name if set
              if (piece.name && name != "self") {
                name = piece.name;
              }
              // set the type
              halObj.type = piece.type;
              // set the deprecation flag
              halObj.deprecation = piece.deprecated;
              // profile refers to a validation document
              // value must be a URL
              if (piece.returns && piece.returns[0]) {
                halObj.profile = piece.returns[0].description;
              }
              // title, used by client UI's to know what to put in a button or something
              halObj.title = piece.alias;
              // description is not in the JSON-HAL spec, but it's useful
              halObj.description = piece.description;
              // JSON-HAL doesn't specify a way to document parameters
              // URI Templates do though
              if (piece.params) {
                halObj.templated = true;

                halObj.href += "{?";
                for (var a = 0; a < piece.params.length; a++) {
                  var param = piece.params[a];
                  halObj.href += param.name || param.description;
                  if (a != piece.params.length-1) {
                    halObj.href += ",";
                  }
                }
                halObj.href += "}";

              }
            }
          }
        }
        halObj.rel = name;
        result.push(halObj);

      }
    }

  }
  return result;
}

var removeLastIfEmpty = array => {
  var lastItem = array[array.length-1];
  if (!lastItem || lastItem == "") {
    array.pop();
  }
  return array;
}

var urlMatches = (pathPieces, urlPieces) => {
  if (pathPieces.length < urlPieces.length || pathPieces.length > urlPieces.length + 1) {
    // this path is shorter than our url -> no match
    // or
    // this path is at least 2 parts longer -> not a related resource
    return false;
  } else {
    for (var j = 0; j < urlPieces.length; j++) {
      if (pathPieces[j].indexOf(":") > -1) {
        // url parameter, assume it matches
        // replace the :paramname with the actually used value
        pathPieces[j] = urlPieces[j];
      } else if (pathPieces[j] != urlPieces[j]) {
        return false;
      }
    }
  }
  return true;
};
<|endoftext|>


<commit_before>/*!
 * fill-range <https://github.com/jonschlinkert/fill-range>
 *
 * Copyright (c) 2014 Jon Schlinkert, contributors.
 * Licensed under the MIT license.
 */

'use strict';

var repeat = require('repeat-string');
var isNumber = require('is-number');

/**
 * Expose `fillRange`
 */

module.exports = fillRange;

function fillRange(a, b, increment, fn) {
  if (typeof increment === 'function') {
    fn = increment;
    increment = undefined;
  }

  validateRange(a, b, increment);

  // Was an increment (step) passed?
  increment = typeof increment !== 'undefined'
    ? Math.abs(increment)
    : 1;

  var strA = a.toString();

  // is the range alphabetical? or numeric?
  var isLetter = !isNumber(a);
  a = isLetter ? a.charCodeAt(0) : +a;
  b = isLetter ? b.charCodeAt(0) : +b;

  var padding = isPadded(strA, isLetter);
  var res, pad, arr = [];
  var reverse = b < a;
  var i = 0;

  while (reverse ? (a >= b) : (a <= b)) {
    if (padding && !isLetter) {
      pad = padding(a);
    }

    if (typeof fn === 'function') {
      res = fn(a, isLetter, pad, i++);
    } else if (isLetter) {
      res = String.fromCharCode(a);
    } else {
      res = String(pad ? pad + a : a);
    }

    arr.push(res);

    if (reverse) {
      a -= increment
    } else {
      a += increment;
    }
  }
  return arr;
}

function isPadded(strA, isLetter) {
  return !isLetter && /^-*0+[1-9]/.test(strA)
    ? function (a) {
      var num = strA.length - a.toString().length;
      return repeat('0', num);
    } : false;
}

function validateRange(a, b, increment) {
  if (!/[\w\d]/.test(a) || !/[\w\d]/.test(b)) {
    throw new Error('fill-range: invalid range arguments.');
  }
  if (!isNumber(a) && isNumber(b)) {
    throw new TypeError('fill-range: incompatible range arguments.');
  }
  if (isNumber(a) && !isNumber(b)) {
    throw new TypeError('fill-range: incompatible range arguments.');
  }
  if (increment && !isNumber(increment)) {
    throw new TypeError('fill-range: invalid increment.');
  }
}<commit_msg>fix copyright date<commit_after>/*!
 * fill-range <https://github.com/jonschlinkert/fill-range>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var repeat = require('repeat-string');
var isNumber = require('is-number');

/**
 * Expose `fillRange`
 */

module.exports = fillRange;

function fillRange(a, b, increment, fn) {
  if (typeof increment === 'function') {
    fn = increment;
    increment = undefined;
  }

  validateRange(a, b, increment);

  // Was an increment (step) passed?
  increment = typeof increment !== 'undefined'
    ? Math.abs(increment)
    : 1;

  var strA = a.toString();

  // is the range alphabetical? or numeric?
  var isLetter = !isNumber(a);
  a = isLetter ? a.charCodeAt(0) : +a;
  b = isLetter ? b.charCodeAt(0) : +b;

  var padding = isPadded(strA, isLetter);
  var res, pad, arr = [];
  var reverse = b < a;
  var i = 0;

  while (reverse ? (a >= b) : (a <= b)) {
    if (padding && !isLetter) {
      pad = padding(a);
    }

    if (typeof fn === 'function') {
      res = fn(a, isLetter, pad, i++);
    } else if (isLetter) {
      res = String.fromCharCode(a);
    } else {
      res = String(pad ? pad + a : a);
    }

    arr.push(res);

    if (reverse) {
      a -= increment
    } else {
      a += increment;
    }
  }
  return arr;
}

function isPadded(strA, isLetter) {
  return !isLetter && /^-*0+[1-9]/.test(strA)
    ? function (a) {
      var num = strA.length - a.toString().length;
      return repeat('0', num);
    } : false;
}

function validateRange(a, b, increment) {
  if (!/[\w\d]/.test(a) || !/[\w\d]/.test(b)) {
    throw new Error('fill-range: invalid range arguments.');
  }
  if (!isNumber(a) && isNumber(b)) {
    throw new TypeError('fill-range: incompatible range arguments.');
  }
  if (isNumber(a) && !isNumber(b)) {
    throw new TypeError('fill-range: incompatible range arguments.');
  }
  if (increment && !isNumber(increment)) {
    throw new TypeError('fill-range: invalid increment.');
  }
}<|endoftext|>


<commit_before>'use strict'

//====================================================================================================
// Libralies
//====================================================================================================
var express = require('express');
var path = require('path');

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

//====================================================================================================
// Served Contents
//====================================================================================================
app.use(express.static(__dirname + '/angular1/dist'));

app.use('/angular1', express.static(path.join(__dirname, 'angular1/dist')));
app.use('/angular2', express.static(path.join(__dirname, 'angular2/dist')));
app.use('/react-redux', express.static(path.join(__dirname, 'react-redux/dist')));

//====================================================================================================
// Start Server
//====================================================================================================
app.listen(app.get('port'), function() {
  console.log('Served: http://localhost:' + app.get('port'));
});
<commit_msg>index.js test<commit_after>'use strict'

//====================================================================================================
// Libralies
//====================================================================================================
var express = require('express');
var path = require('path');

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

//====================================================================================================
// Served Contents
//====================================================================================================
app.use(express.static(__dirname + '/angular1/dist'));

app.use('/angular1', express.static(path.join(__dirname, 'angular1/dist')));
app.use('/angular2', express.static(path.join(__dirname, 'angular2/dist')));
app.use('/react-redux', express.static(path.join(__dirname, 'react-redux/dist')));

//====================================================================================================
// Start Server
//====================================================================================================
app.listen(app.get('port'), function() {
  console.log('Served: http://localhost:' + app.get('port'));
});

app.get('/', function(request, response) {
  response.redirect('/angular1');
});
<|endoftext|>


<commit_before>/**
 * lzma-native - Node.js bindings for liblzma
 * Copyright (C) 2014 Hauke Henningsen <sqrt@entless.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 **/

(function() {
'use strict';

var native = require('bindings')('lzma_native.node');
var stream = require('readable-stream');
var util = require('util');
var extend = require('util-extend');

extend(exports, native);

exports.version = '0.2.11';

var Stream = exports.Stream;

Stream.curAsyncStreams = [];
Stream.maxAsyncStreamCount = 32;

Stream.prototype.getStream =
Stream.prototype.asyncStream =
Stream.prototype.syncStream = function(options) {
	options = options || {};

	var _forceNextTickCb = function() {
		/* I know this looks like “magic/more magic”, but
		 * apparently works around a bogus process.nextTick in
		 * node v0.11. This probably does not affect real
		 * applications which perform other I/O than LZMA compression. */
		setTimeout(function() {}, 1);
	};

	var ret = function(nativeStream) {
		ret.super_.call(this, options);
		var self = this;

		self.nativeStream = nativeStream;
		self.synchronous = (options.synchronous || !native.asyncCodeAvailable) ? true : false;
		self.chunkCallbacks = [];

		if (!self.synchronous) {
			Stream.curAsyncStreams.push(self);
			var cleanup = function() {
				var index = Stream.curAsyncStreams.indexOf(self);

				if (index != -1)
					Stream.curAsyncStreams.splice(index, 1);

				self.nativeStream = null;
			}

			self.once('finish', cleanup);
			self.once('error',  cleanup);
		}

		self.nativeStream.bufferHandler = function(buf, shouldInvokeChunkCallbacks, err) {
			process.nextTick(function() {
				if (err) {
					self.push(null);
					self.emit('error', err);
					_forceNextTickCb();
				}

				if (shouldInvokeChunkCallbacks) {
					// rotate the chunkCallbacks property, since more callbacks
					// may be added by the current ones
					var chunkCallbacks = self.chunkCallbacks;
					self.chunkCallbacks = [];

					while (chunkCallbacks.length > 0)
						chunkCallbacks.shift()();

					_forceNextTickCb();
				} else {
					self.push(buf);
				}
			});

			_forceNextTickCb();
		};

		// add all methods from the native Stream
		Object.keys(native.Stream.prototype).forEach(function(key) {
			self[key] = function() { return self.nativeStream[key].apply(self.nativeStream, arguments); };
		});
	};

	util.inherits(ret, stream.Transform);

	ret.prototype._transform = function(chunk, encoding, callback) {
		this.chunkCallbacks.push(callback);

		try {
			this.nativeStream.code(chunk, !this.synchronous);
		} catch (e) {
			this.emit('error', e);
		}
	};

	ret.prototype._flush = function(callback) {
		this._transform(null, null, callback);
	};

	return new ret(this);
};

Stream.prototype.rawEncoder = function(options) {
	return this.rawEncoder_(options.filters || []);
};

Stream.prototype.rawDecoder = function(options) {
	return this.rawDecoder_(options.filters || []);
};

Stream.prototype.easyEncoder = function(options) {
	return this.easyEncoder_(options.preset || exports.PRESET_DEFAULT, options.check || exports.CHECK_CRC32);
};

Stream.prototype.streamEncoder = function(options) {
	return this.streamEncoder_(options.filters || [], options.check || exports.CHECK_CRC32);
};

Stream.prototype.streamDecoder = function(options) {
	return this.streamDecoder_(options.memlimit || null, options.flags || 0);
};

Stream.prototype.autoDecoder = function(options) {
	return this.autoDecoder_(options.memlimit || null, options.flags || 0);
};

Stream.prototype.aloneDecoder = function(options) {
	return this.aloneDecoder_(options.memlimit || null);
};

var createStream =
exports.createStream = function(coder, options) {
	if (['number', 'object'].indexOf(typeof coder) != -1 && !options) {
		options = coder;
		coder = null;
	}

	if (parseInt(options) == options)
		options = {preset: parseInt(options)};

	coder = coder || 'easyEncoder';
	options = options || {};

	var stream = new Stream();
	stream[coder](options);

	if (options.memlimit)
		stream.memlimitSet(options.memlimit);

	if (!options.synchronous)
		options.synchronous = ((Stream.curAsyncStreams.length >= Stream.maxAsyncStreamCount) && !options.forceAsynchronous);

	return stream.getStream(options);
};

exports.crc32 = function(input, encoding, presetCRC32) {
	if (typeof encoding == 'number') {
		encoding = null;
		presetCRC32 = encoding;
	}

	if (typeof input == 'string')
		input = new Buffer(input, encoding);

	return exports.crc32_(input, presetCRC32 || 0);
};

/* compatibility: node-xz (https://github.com/robey/node-xz) */
exports.Compressor = function(preset, options) {
	options = extend({}, options);

	if (preset)
		options.preset = preset;

	return createStream('easyEncoder', options);
};

exports.Decompressor = function(options) {
	return createStream('autoDecoder', options);
};

/* compatibility: LZMA-JS (https://github.com/nmrugg/LZMA-JS) */
function singleStringCoding(stream, string, on_finish, on_progress) {
	on_progress = on_progress || function() {};
	on_finish = on_finish || function() {};

	var buffers = [];

	stream.on('data', function(b) { buffers.push(b); });
	stream.once('end', function() {
		on_progress(1);
		on_finish(Buffer.concat(buffers));
	});

	on_progress(0);

	// possibly our input is an array of byte integers
	// or a typed array
	if (!Buffer.isBuffer(string))
		string = new Buffer(string);

	stream.end(string);
}

exports.LZMA = function() {
	return {
		compress: function(string, mode, on_finish, on_progress) {
			var opt = {};

			if (parseInt(mode) == mode && mode >= 1 && mode <= 9)
				opt.preset = parseInt(mode);

			var stream = createStream('aloneEncoder', opt);

			return singleStringCoding(stream, string, on_finish, on_progress);
		},
		decompress: function(byte_array, on_finish, on_progress) {
			var stream = createStream('aloneDecoder');

			return singleStringCoding(stream, byte_array, on_finish, on_progress);
		}
	};
};

exports.compress = function(string, opt, on_finish) {
	if (typeof opt == 'function') {
		on_finish = opt;
		opt = {};
	}

	var stream = createStream('easyEncoder', opt);
	return singleStringCoding(stream, string, on_finish);
};

exports.decompress = function(string, opt, on_finish) {
	if (typeof opt == 'function') {
		on_finish = opt;
		opt = {};
	}

	var stream = createStream('autoDecoder', opt);
	return singleStringCoding(stream, string, on_finish);
};

})();
<commit_msg>Combine chunks in _writev method of stream<commit_after>/**
 * lzma-native - Node.js bindings for liblzma
 * Copyright (C) 2014 Hauke Henningsen <sqrt@entless.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 **/

(function() {
'use strict';

var native = require('bindings')('lzma_native.node');
var stream = require('readable-stream');
var util = require('util');
var extend = require('util-extend');

extend(exports, native);

exports.version = '0.2.11';

var Stream = exports.Stream;

Stream.curAsyncStreams = [];
Stream.maxAsyncStreamCount = 32;

Stream.prototype.getStream =
Stream.prototype.asyncStream =
Stream.prototype.syncStream = function(options) {
	options = options || {};

	var _forceNextTickCb = function() {
		/* I know this looks like “magic/more magic”, but
		 * apparently works around a bogus process.nextTick in
		 * node v0.11. This probably does not affect real
		 * applications which perform other I/O than LZMA compression. */
		setTimeout(function() {}, 1);
	};

	var ret = function(nativeStream) {
		ret.super_.call(this, options);
		var self = this;

		self.nativeStream = nativeStream;
		self.synchronous = (options.synchronous || !native.asyncCodeAvailable) ? true : false;
		self.chunkCallbacks = [];

		if (!self.synchronous) {
			Stream.curAsyncStreams.push(self);
			var cleanup = function() {
				var index = Stream.curAsyncStreams.indexOf(self);

				if (index != -1)
					Stream.curAsyncStreams.splice(index, 1);

				self.nativeStream = null;
			}

			self.once('finish', cleanup);
			self.once('error',  cleanup);
		}

		self.nativeStream.bufferHandler = function(buf, shouldInvokeChunkCallbacks, err) {
			process.nextTick(function() {
				if (err) {
					self.push(null);
					self.emit('error', err);
					_forceNextTickCb();
				}

				if (shouldInvokeChunkCallbacks) {
					// rotate the chunkCallbacks property, since more callbacks
					// may be added by the current ones
					var chunkCallbacks = self.chunkCallbacks;
					self.chunkCallbacks = [];

					while (chunkCallbacks.length > 0)
						chunkCallbacks.shift()();

					_forceNextTickCb();
				} else {
					self.push(buf);
				}
			});

			_forceNextTickCb();
		};

		// add all methods from the native Stream
		Object.keys(native.Stream.prototype).forEach(function(key) {
			self[key] = function() { return self.nativeStream[key].apply(self.nativeStream, arguments); };
		});
	};

	util.inherits(ret, stream.Transform);

	ret.prototype._transform = function(chunk, encoding, callback) {
		this.chunkCallbacks.push(callback);

		try {
			this.nativeStream.code(chunk, !this.synchronous);
		} catch (e) {
			this.emit('error', e);
		}
	};

	ret.prototype._writev = function(chunks, callback) {
		chunks = chunks.map(function (chunk) { return chunk.chunk; });
		this._write(Buffer.concat(chunks), null, callback);
	};

	ret.prototype._flush = function(callback) {
		this._transform(null, null, callback);
	};

	return new ret(this);
};

Stream.prototype.rawEncoder = function(options) {
	return this.rawEncoder_(options.filters || []);
};

Stream.prototype.rawDecoder = function(options) {
	return this.rawDecoder_(options.filters || []);
};

Stream.prototype.easyEncoder = function(options) {
	return this.easyEncoder_(options.preset || exports.PRESET_DEFAULT, options.check || exports.CHECK_CRC32);
};

Stream.prototype.streamEncoder = function(options) {
	return this.streamEncoder_(options.filters || [], options.check || exports.CHECK_CRC32);
};

Stream.prototype.streamDecoder = function(options) {
	return this.streamDecoder_(options.memlimit || null, options.flags || 0);
};

Stream.prototype.autoDecoder = function(options) {
	return this.autoDecoder_(options.memlimit || null, options.flags || 0);
};

Stream.prototype.aloneDecoder = function(options) {
	return this.aloneDecoder_(options.memlimit || null);
};

var createStream =
exports.createStream = function(coder, options) {
	if (['number', 'object'].indexOf(typeof coder) != -1 && !options) {
		options = coder;
		coder = null;
	}

	if (parseInt(options) == options)
		options = {preset: parseInt(options)};

	coder = coder || 'easyEncoder';
	options = options || {};

	var stream = new Stream();
	stream[coder](options);

	if (options.memlimit)
		stream.memlimitSet(options.memlimit);

	if (!options.synchronous)
		options.synchronous = ((Stream.curAsyncStreams.length >= Stream.maxAsyncStreamCount) && !options.forceAsynchronous);

	return stream.getStream(options);
};

exports.crc32 = function(input, encoding, presetCRC32) {
	if (typeof encoding == 'number') {
		encoding = null;
		presetCRC32 = encoding;
	}

	if (typeof input == 'string')
		input = new Buffer(input, encoding);

	return exports.crc32_(input, presetCRC32 || 0);
};

/* compatibility: node-xz (https://github.com/robey/node-xz) */
exports.Compressor = function(preset, options) {
	options = extend({}, options);

	if (preset)
		options.preset = preset;

	return createStream('easyEncoder', options);
};

exports.Decompressor = function(options) {
	return createStream('autoDecoder', options);
};

/* compatibility: LZMA-JS (https://github.com/nmrugg/LZMA-JS) */
function singleStringCoding(stream, string, on_finish, on_progress) {
	on_progress = on_progress || function() {};
	on_finish = on_finish || function() {};

	var buffers = [];

	stream.on('data', function(b) { buffers.push(b); });
	stream.once('end', function() {
		on_progress(1);
		on_finish(Buffer.concat(buffers));
	});

	on_progress(0);

	// possibly our input is an array of byte integers
	// or a typed array
	if (!Buffer.isBuffer(string))
		string = new Buffer(string);

	stream.end(string);
}

exports.LZMA = function() {
	return {
		compress: function(string, mode, on_finish, on_progress) {
			var opt = {};

			if (parseInt(mode) == mode && mode >= 1 && mode <= 9)
				opt.preset = parseInt(mode);

			var stream = createStream('aloneEncoder', opt);

			return singleStringCoding(stream, string, on_finish, on_progress);
		},
		decompress: function(byte_array, on_finish, on_progress) {
			var stream = createStream('aloneDecoder');

			return singleStringCoding(stream, byte_array, on_finish, on_progress);
		}
	};
};

exports.compress = function(string, opt, on_finish) {
	if (typeof opt == 'function') {
		on_finish = opt;
		opt = {};
	}

	var stream = createStream('easyEncoder', opt);
	return singleStringCoding(stream, string, on_finish);
};

exports.decompress = function(string, opt, on_finish) {
	if (typeof opt == 'function') {
		on_finish = opt;
		opt = {};
	}

	var stream = createStream('autoDecoder', opt);
	return singleStringCoding(stream, string, on_finish);
};

})();
<|endoftext|>


<commit_before>var chai = require('chai');
var should = chai.should();
var expect = chai.expect;

var testNumbers = [0, 1, 3, 4, 1968, 2999, 3000, 10000];
var testChars = [null, '', "I", "III", "IIII", "IV", "V", 'CDXXIX', 'CD1X', 'error', 'MCDLXXXII', 'MMMMCMXCIX', 'MMMMDMXCIX', '1493'];

describe('Number', function(){
  it('should return number', function()
  {
    /*
    var number = RomanNumber(20);
    expect(number.toInt()).not.to.be.NaN;
    */
  });

  it('should be between 1 and 3999', function()
  {
    var invalidNumber = function(){new RomanNumber(4000)}
    expect(invalidNumber).to.throw(Error);
  });

  it('should not be undefined', function()
  {
    var invalidNumber = function(){new RomanNumber()}
    expect(invalidNumber).to.throw(Error);
  });
  it('should not be null', function()
  {
    var invalidNumber = function(){new RomanNumber(null)}
    expect(invalidNumber).to.throw(Error);
  });
  it('should not return an error');

  it('should test multiple numbers', function()
  {
    testNumbers.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      if(number >=1 && number <= 3999)
      {
        expect(testValue).not.to.throw(Error);
      }
      else
      {
        expect(testValue).to.throw(Error);
      }
    });
  });
});

describe('Roman Numeral', function(){
  it('should validate to ensure a valid roman numeral was entered', function()
  {

  });
  it('should throw error if roman numeral is not valid', function()
  {
    var number = function(){new RomanNumber("JARED")}
    expect(number).to.throw(Error);
  });

  it('should return roman numeral', function()
  {
    var number = RomanNumber(21);
    expect(number.toString()).to.equal("XXI");
  });
  it('should not be null', function()
  {
    var number = function(){new RomanNumber(null)}
    expect(number).to.throw(Error);
  });
  it('should not return an error', function()
  {
    var number = function(){new RomanNumber("XX")}
    expect(number).to.not.throw(Error);
  });

  it('should be between 1 and 3999', function()
  {
    var invalidNumber = function(){new RomanNumber("MMMMDMXCIX")}
    expect(invalidNumber).to.throw(Error);
  });
  it('should test multiple numbers', function()
  {
    testChars.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

      if(validator.test(number) && number != null && number != "")
      {
        expect(testValue).not.to.throw(Error);
      }
      else
      {
        expect(testValue).to.throw(Error);
      }
    });
  });
});

function RomanNumber(pNumber)
{
	if (!(this instanceof RomanNumber)){
        return new RomanNumber(pNumber);
   }

var lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};

var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

   //Checks the user value added
   if(typeof pNumber === 'string')
   {

     if(validator.test(pNumber) && pNumber != null && pNumber != "")
     {
       this.romanNumeral = pNumber;
     }
     else
     {
        throw new Error("Please enter valid Roman Numeral");
     }
   }
   else
   {
      if(pNumber !== undefined && pNumber >=1 && pNumber <= 3999)
     	{
        this.integer = pNumber;
      }
      else if(pNumber !== undefined)
    	{
    		throw new Error("Please enter number");
    	}
      else
      {
          throw new Error("Number must be between 1 and 3999");
      }
   }

	this.toInt = function()
	{
    if(this.romanNumeral !== undefined)
    {
      var	token = /[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,
        num = 0, m;
      while (m = token.exec(this.romanNumeral))
      {
        num += lookup[m[0]];
      }
      return num;
    }
    else
    {
      return this.integer;
    }
	};

	this.toString = function()
	{
    var roman = '';

    for ( var i in lookup ) {
      while ( this.integer >= lookup[i] ) {
        roman += i;
        this.integer -= lookup[i];
      }
    }
    return roman;
	};
}
<commit_msg>Test for Strings and Numbers<commit_after>var chai = require('chai');
var should = chai.should();
var expect = chai.expect;

var testNumbers = [0, 1, 3, 4, 1968, 2999, 3000, 10000];
var testChars = [null, '', "I", "III", "IIII", "IV", "V", 'CDXXIX', 'CD1X', 'error', 'MCDLXXXII', 'MMMMCMXCIX', 'MMMMDMXCIX', '1493'];
var testAll = [0, 1, 3, 4, 1968, 2999, 3000, 10000, null, '', "I", "III", "IIII", "IV", "V", 'CDXXIX', 'CD1X', 'error', 'MCDLXXXII', 'MMMMCMXCIX', 'MMMMDMXCIX', '1493'];

describe('Number', function(){
  it('should return number', function()
  {
    /*
    var number = RomanNumber(20);
    expect(number.toInt()).not.to.be.NaN;
    */
  });

  it('should be between 1 and 3999', function()
  {
    var invalidNumber = function(){new RomanNumber(4000)}
    expect(invalidNumber).to.throw(Error);
  });

  it('should not be undefined', function()
  {
    var invalidNumber = function(){new RomanNumber()}
    expect(invalidNumber).to.throw(Error);
  });
  it('should not be null', function()
  {
    var invalidNumber = function(){new RomanNumber(null)}
    expect(invalidNumber).to.throw(Error);
  });
  it('should test multiple numbers', function()
  {
    testNumbers.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      if(number >=1 && number <= 3999)
      {
        expect(testValue).not.to.throw(Error);
      }
      else
      {
        expect(testValue).to.throw(Error);
      }
    });
  });
});

describe('Roman Numeral', function(){
  it('should validate to ensure a valid roman numeral was entered', function()
  {

  });
  it('should throw error if roman numeral is not valid', function()
  {
    var number = function(){new RomanNumber("JARED")}
    expect(number).to.throw(Error);
  });

  it('should return roman numeral', function()
  {
    var number = RomanNumber(21);
    expect(number.toString()).to.equal("XXI");
  });
  it('should not be null', function()
  {
    var number = function(){new RomanNumber(null)}
    expect(number).to.throw(Error);
  });
  it('should not return an error', function()
  {
    var number = function(){new RomanNumber("XX")}
    expect(number).to.not.throw(Error);
  });

  it('should be between 1 and 3999', function()
  {
    var invalidNumber = function(){new RomanNumber("MMMMDMXCIX")}
    expect(invalidNumber).to.throw(Error);
  });
  it('should test multiple numbers', function()
  {
    testChars.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

      if(validator.test(number) && number != null && number != "")
      {
        expect(testValue).not.to.throw(Error);
      }
      else
      {
        expect(testValue).to.throw(Error);
      }
    });
  });
});

describe('All Values', function(){
  it('should test all values', function()
  {
    testAll.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

      if(typeof number === 'string')
      {
        if(validator.test(number) && number != null && number != "")
        {
          expect(testValue).not.to.throw(Error);
        }
        else {
          expect(testValue).to.throw(Error);
        }
      }
      else
      {
        if(number >=1 && number <= 3999)
        {
          expect(testValue).not.to.throw(Error);
        }
        else
        {
          expect(testValue).to.throw(Error);
        }
      }

    });
  });
});

function RomanNumber(pNumber)
{
	if (!(this instanceof RomanNumber)){
        return new RomanNumber(pNumber);
   }

var lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};

var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

   //Checks the user value added
   if(typeof pNumber === 'string')
   {

     if(validator.test(pNumber) && pNumber != null && pNumber != "")
     {
       this.romanNumeral = pNumber;
     }
     else
     {
        throw new Error("Please enter valid Roman Numeral");
     }
   }
   else
   {
      if(pNumber !== undefined && pNumber >=1 && pNumber <= 3999)
     	{
        this.integer = pNumber;
      }
      else if(pNumber !== undefined)
    	{
    		throw new Error("Please enter number");
    	}
      else
      {
          throw new Error("Number must be between 1 and 3999");
      }
   }

	this.toInt = function()
	{
    if(this.romanNumeral !== undefined)
    {
      var	token = /[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,
        num = 0, m;
      while (m = token.exec(this.romanNumeral))
      {
        num += lookup[m[0]];
      }
      return num;
    }
    else
    {
      return this.integer;
    }
	};

	this.toString = function()
	{
    var roman = '';

    for ( var i in lookup ) {
      while ( this.integer >= lookup[i] ) {
        roman += i;
        this.integer -= lookup[i];
      }
    }
    return roman;
	};
}
<|endoftext|>


<commit_before>var parser = require('./parser')
var fs = require('fs')
var util = require('util')

var evaluate = function(o)
{
    if(typeof o !== 'object') return ' ' + o.toString()

    var s = '\n' + o[0]

    for(var i=1; i<o.length; ++i)
    {
        s += evaluate(o[i]).replace(/^/gm, '  ')
    }

    return s
}

var filename = process.argv[2] !== undefined ? process.argv[2] : 'test.shk'
fs.readFile(filename, function(err, data)
{
    if(err) throw err
    var parsed = parser.parse(data.toString())

    parsed.forEach(function(v, k, a)
    {
        console.log(evaluate(v))
    })
})
<commit_msg>Surrounded parse call with try/catch to get error position.<commit_after>var parser = require('./parser')
var fs = require('fs')
var util = require('util')

var evaluate = function(o)
{
    if(typeof o !== 'object') return ' ' + o.toString()

    var s = '\n' + o[0]

    for(var i=1; i<o.length; ++i)
    {
        s += evaluate(o[i]).replace(/^/gm, '  ')
    }

    return s
}

var filename = process.argv[2] !== undefined ? process.argv[2] : 'test.shk'
fs.readFile(filename, function(err, data)
{
    if(err) throw err

    try
    {
        var parsed = parser.parse(data.toString())
    }
    catch(e)
    {
        console.log(e)
        return
    }

    parsed.forEach(function(v, k, a)
    {
        console.log(evaluate(v))
    })
})
<|endoftext|>


<commit_before>'use strict';

var aegis = module.exports = options => {
  var headers = [];

  if (options) {
    Object.keys(aegis).forEach(key => {
      var config = options[key];

      if (config) {
        headers.push(aegis[key](config));
      }
    });
  }

  /**
   * Fi Aegis middleware.
   *
   * @param {Object} req Express request object.
   * @param {Object} res Express response object.
   * @param {Function} next Express next middleware callback.
   */
  function middleware(req, res, next) {
    var chain = next;

    headers.forEach(header => {
      chain = (next => {
        return err => {
          if (err) {
            return next(err);
          }

          header(req, res, next);
        };
      })(chain);
    });

    chain();
  }

  return middleware;
};

aegis.csrf = require('./lib/csrf');
aegis.csp = require('./lib/csp');
aegis.hsts = require('./lib/hsts');
aegis.p3p = require('./lib/p3p');
aegis.xframe = require('./lib/xframes');
aegis.xssProtection = require('./lib/xssprotection');
aegis.nosniff = require('./lib/nosniff');<commit_msg>Added proper docs to the index module<commit_after>'use strict';

/**
 * Fi Aegis.
 *
 * @module fi-aegis
 *
 * @see module:fi-aegis
 */

/**
 * Configures the module.
 *
 * @param {Object} options The options object.
 * @param {Object} options.csp The options for the `csp` module.
 * @param {Object} options.csrf The options for the `csrf` module.
 * @param {Object} options.hsts The options for the `hsts` module.
 * @param {Boolean} options.nosniff Whether to activate the `nosniff` module.
 * @param {String} options.p3p The header value for the `p3p` module.
 * @param {String} options.xframes The header value for the `xframe` module.
 * @param {Object} options.xssprotection The options for the `xssprotection`
 * module.
 *
 * @returns {Function} The Express middleware.
 */
var aegis = module.exports = options => {

  const components = [];

  if (options) {
    Object.keys(aegis).forEach(key => {
      let config = options[key];

      if (config) {
        components.push(aegis[key](config));
      }
    });
  }

  /**
   * Fi Aegis middleware.
   *
   * @param {Object} req Express request object.
   * @param {Object} res Express response object.
   * @param {Function} next Express next middleware callback.
   */
  function middleware(req, res, next) {
    var chain = next;

    components.forEach(component => {
      chain = (next => err => {
        if (err) {
          return next(err);
        }

        component(req, res, next);
      })(chain);
    });

    chain();
  }

  return middleware;

};

aegis.csrf = require('./lib/csrf');
aegis.csp = require('./lib/csp');
aegis.hsts = require('./lib/hsts');
aegis.p3p = require('./lib/p3p');
aegis.xframe = require('./lib/xframes');
aegis.xssProtection = require('./lib/xssprotection');
aegis.nosniff = require('./lib/nosniff');<|endoftext|>


<commit_before>/*
 * Jake JavaScript build tool
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * 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.
 *
*/

var fs = require('fs')
  , path = require('path')
  , exec = require('child_process').exec
  , utils = require('utilities')
  , currDir = process.cwd()
  , FileList = require('./file_list').FileList;

var NpmPublishTask = function () {
  var args = Array.prototype.slice.call(arguments).filter(function (item) {
        return typeof item != 'undefined';
      })
    , arg
    , opts = {}
    , definition
    , prereqs = []
    , createDef = function (arg) {
        return function () {
          this.packageFiles.include(arg);
        };
      };

  this.name = args.shift();

  // Old API, just name + list of files
  if (args.length == 1 && (Array.isArray(args[0]) || typeof args[0] == 'string')) {
    definition = createDef(args.pop());
  }
  // Current API, name + [preeqs] + [opts] + definition
  else {
    while ((arg = args.pop())) {
      // Definition func
      if (typeof arg == 'function') {
        definition = arg;
      }
      // Prereqs
      else if (Array.isArray(arg) || typeof arg == 'string') {
        prereqs = arg;
      }
      // Opts
      else {
        opts = arg;
      }
    }
  }

  this.prereqs = prereqs;
  this.packageFiles = new FileList();
  this.publishCmd = opts.publicCmd || 'npm publish %filename';
  this.gitCmd = opts.gitCmd || 'git';
  this.versionFiles = opts.versionFiles || ['package.json'];
  this.scheduleDelay = 5000;

  // Override utility funcs for testing
  this._ensureRepoClean = function (stdout) {
    if (stdout.length) {
      fail(new Error('Git repository is not clean.'));
    }
  };
  this._getCurrentBranch = function (stdout) {
    return utils.string.trim(stdout);
  };

  if (typeof definition == 'function') {
    definition.call(this);
  }
  this.define();
};

NpmPublishTask.prototype = new (function () {

  var _currentBranch = null;

  var getPackage = function () {
        var pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(),
            '/package.json')).toString());
        return pkg;
      }
    , getPackageVersionNumber = function () {
        return getPackage().version;
      };

  this.define = function () {
    var self = this;

    namespace('npm', function () {
      task('fetchTags', {async: true}, function () {
        // Make sure local tags are up to date
        var cmds = [
          self.gitCmd + ' fetch --tags'
        ];
        jake.exec(cmds, function () {
          console.log('Fetched remote tags.');
          complete();
        });
      });

      task('getCurrentBranch', {async: true}, function () {
        // Figure out what branch to push to
        exec(self.gitCmd + ' symbolic-ref --short HEAD',
            function (err, stdout, stderr) {
          if (err) {
            fail(err);
          }
          if (stderr) {
            fail(new Error(stderr));
          }
          if (!stdout) {
            fail(new Error('No current Git branch found'));
          }
          _currentBranch = self._getCurrentBranch(stdout);
          console.log('On branch ' + _currentBranch);
          complete();
        });
      });

      task('ensureClean', {async: true}, function () {
        // Only bump, push, and tag if the Git repo is clean
        exec(self.gitCmd + ' status --porcelain --untracked-files=no',
            function (err, stdout, stderr) {
          if (err) {
            fail(err);
          }
          if (stderr) {
            fail(new Error(stderr));
          }

          // Throw if there's output
          self._ensureRepoClean(stdout);

          complete();
        });
      });

      task('updateVersionFiles', function () {
        var p
          , pkg
          , version
          , arr
          , patch;

        // Grab the current version-string
        p = path.join(process.cwd(), 'package.json');
        pkg = getPackage();
        version = pkg.version;
        // Increment the patch-number for the version
        arr = version.split('.');
        patch = parseInt(arr.pop(), 10) + 1;
        arr.push(patch);
        version = arr.join('.');

        // Update package.json or other files with the new version-info
        self.versionFiles.forEach(function (file) {
          var p = path.join(process.cwd(), file)
            , data = JSON.parse(fs.readFileSync(p).toString());
          data.version = version;
          fs.writeFileSync(p, JSON.stringify(data, true, 2));
        });
        // Return the version string so that listeners for the 'complete' event
        // for this task can use it (e.g., to update other files before pushing
        // to Git)
        return version;
      });

      task('version', ['ensureClean', 'updateVersionFiles'], {async: true},
          function () {
        var version = getPackageVersionNumber()
          , message = 'Version ' + version
          , cmds = [
              self.gitCmd + ' commit -a -m "' + message + '"'
            , self.gitCmd + ' push origin ' + _currentBranch
            , self.gitCmd + ' tag -a v' + version + ' -m "' + message + '"'
            , self.gitCmd + ' push --tags'
            ];

        var execOpts = {};
        if (process.platform == 'win32') {
          // Windows won't like the quotes in our cmdline
          execOpts.windowsVerbatimArguments = true;
        }

        jake.exec(cmds, function () {
          var version = getPackageVersionNumber();
          console.log('Bumped version number to v' + version + '.');
          complete();
        }, execOpts);

      });

      task('definePackage', self.prereqs, function () {
        var version = getPackageVersionNumber()
          , t;
        t = new jake.PackageTask(self.name, 'v' + version, function () {
          // Replace the PackageTask's FileList with the NPMPublishTask's FileList
          this.packageFiles = self.packageFiles;
          this.needTarGz = true;
        });
      });

      task('package', {async: true}, function () {
        var definePack = jake.Task['npm:definePackage']
          , pack = jake.Task.package
          , version = getPackageVersionNumber();

        // May have already been run
        definePack.reenable(true);
        definePack.addListener('complete', function () {
          pack.addListener('complete', function () {
            console.log('Created package for ' + self.name + ' v' + version);
            complete();
          });
          pack.invoke();
        });
        definePack.invoke();
      });

      task('publish', {async: true}, function () {
        var version = getPackageVersionNumber()
          , filename
          , cmd;

        console.log('Publishing ' + self.name + ' v' + version);

        filename = 'pkg/' + self.name + '-v' + version + '.tar.gz'
        cmd = self.publishCmd.replace(/%filename/gi, filename);

        // Hackity hack -- NPM publish sometimes returns errror like:
        // Error sending version data\nnpm ERR!
        // Error: forbidden 0.2.4 is modified, should match modified time
        setTimeout(function () {
          jake.exec(cmd, function () {
            console.log('Published to NPM');
            complete();
          }, {printStdout: true, printStderr: true});
        }, self.scheduleDelay);
      });

      task('cleanup', {async: true}, function () {
        var clobber = jake.Task.clobber;
        clobber.reenable(true);
        clobber.on('complete', function () {
          console.log('Cleaned up package');
          complete();
        });
        clobber.invoke();
      });

    });

    desc('Bump version-number, package, and publish to NPM.');
    task('publish', self.prereqs.concat(['npm:fetchTags', 'npm:getCurrentBranch', 'npm:version',
        'npm:package', 'npm:publish', 'npm:cleanup']), function () {});

    // Invoke proactively so there will be a callable 'package' task
    // which can be used apart from 'publish'
    jake.Task['npm:definePackage'].invoke();
  };

})();

jake.NpmPublishTask = NpmPublishTask;
exports.NpmPublishTask = NpmPublishTask;

<commit_msg>fix comment typo<commit_after>/*
 * Jake JavaScript build tool
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * 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.
 *
*/

var fs = require('fs')
  , path = require('path')
  , exec = require('child_process').exec
  , utils = require('utilities')
  , currDir = process.cwd()
  , FileList = require('./file_list').FileList;

var NpmPublishTask = function () {
  var args = Array.prototype.slice.call(arguments).filter(function (item) {
        return typeof item != 'undefined';
      })
    , arg
    , opts = {}
    , definition
    , prereqs = []
    , createDef = function (arg) {
        return function () {
          this.packageFiles.include(arg);
        };
      };

  this.name = args.shift();

  // Old API, just name + list of files
  if (args.length == 1 && (Array.isArray(args[0]) || typeof args[0] == 'string')) {
    definition = createDef(args.pop());
  }
  // Current API, name + [prereqs] + [opts] + definition
  else {
    while ((arg = args.pop())) {
      // Definition func
      if (typeof arg == 'function') {
        definition = arg;
      }
      // Prereqs
      else if (Array.isArray(arg) || typeof arg == 'string') {
        prereqs = arg;
      }
      // Opts
      else {
        opts = arg;
      }
    }
  }

  this.prereqs = prereqs;
  this.packageFiles = new FileList();
  this.publishCmd = opts.publicCmd || 'npm publish %filename';
  this.gitCmd = opts.gitCmd || 'git';
  this.versionFiles = opts.versionFiles || ['package.json'];
  this.scheduleDelay = 5000;

  // Override utility funcs for testing
  this._ensureRepoClean = function (stdout) {
    if (stdout.length) {
      fail(new Error('Git repository is not clean.'));
    }
  };
  this._getCurrentBranch = function (stdout) {
    return utils.string.trim(stdout);
  };

  if (typeof definition == 'function') {
    definition.call(this);
  }
  this.define();
};

NpmPublishTask.prototype = new (function () {

  var _currentBranch = null;

  var getPackage = function () {
        var pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(),
            '/package.json')).toString());
        return pkg;
      }
    , getPackageVersionNumber = function () {
        return getPackage().version;
      };

  this.define = function () {
    var self = this;

    namespace('npm', function () {
      task('fetchTags', {async: true}, function () {
        // Make sure local tags are up to date
        var cmds = [
          self.gitCmd + ' fetch --tags'
        ];
        jake.exec(cmds, function () {
          console.log('Fetched remote tags.');
          complete();
        });
      });

      task('getCurrentBranch', {async: true}, function () {
        // Figure out what branch to push to
        exec(self.gitCmd + ' symbolic-ref --short HEAD',
            function (err, stdout, stderr) {
          if (err) {
            fail(err);
          }
          if (stderr) {
            fail(new Error(stderr));
          }
          if (!stdout) {
            fail(new Error('No current Git branch found'));
          }
          _currentBranch = self._getCurrentBranch(stdout);
          console.log('On branch ' + _currentBranch);
          complete();
        });
      });

      task('ensureClean', {async: true}, function () {
        // Only bump, push, and tag if the Git repo is clean
        exec(self.gitCmd + ' status --porcelain --untracked-files=no',
            function (err, stdout, stderr) {
          if (err) {
            fail(err);
          }
          if (stderr) {
            fail(new Error(stderr));
          }

          // Throw if there's output
          self._ensureRepoClean(stdout);

          complete();
        });
      });

      task('updateVersionFiles', function () {
        var p
          , pkg
          , version
          , arr
          , patch;

        // Grab the current version-string
        p = path.join(process.cwd(), 'package.json');
        pkg = getPackage();
        version = pkg.version;
        // Increment the patch-number for the version
        arr = version.split('.');
        patch = parseInt(arr.pop(), 10) + 1;
        arr.push(patch);
        version = arr.join('.');

        // Update package.json or other files with the new version-info
        self.versionFiles.forEach(function (file) {
          var p = path.join(process.cwd(), file)
            , data = JSON.parse(fs.readFileSync(p).toString());
          data.version = version;
          fs.writeFileSync(p, JSON.stringify(data, true, 2));
        });
        // Return the version string so that listeners for the 'complete' event
        // for this task can use it (e.g., to update other files before pushing
        // to Git)
        return version;
      });

      task('version', ['ensureClean', 'updateVersionFiles'], {async: true},
          function () {
        var version = getPackageVersionNumber()
          , message = 'Version ' + version
          , cmds = [
              self.gitCmd + ' commit -a -m "' + message + '"'
            , self.gitCmd + ' push origin ' + _currentBranch
            , self.gitCmd + ' tag -a v' + version + ' -m "' + message + '"'
            , self.gitCmd + ' push --tags'
            ];

        var execOpts = {};
        if (process.platform == 'win32') {
          // Windows won't like the quotes in our cmdline
          execOpts.windowsVerbatimArguments = true;
        }

        jake.exec(cmds, function () {
          var version = getPackageVersionNumber();
          console.log('Bumped version number to v' + version + '.');
          complete();
        }, execOpts);

      });

      task('definePackage', self.prereqs, function () {
        var version = getPackageVersionNumber()
          , t;
        t = new jake.PackageTask(self.name, 'v' + version, function () {
          // Replace the PackageTask's FileList with the NPMPublishTask's FileList
          this.packageFiles = self.packageFiles;
          this.needTarGz = true;
        });
      });

      task('package', {async: true}, function () {
        var definePack = jake.Task['npm:definePackage']
          , pack = jake.Task.package
          , version = getPackageVersionNumber();

        // May have already been run
        definePack.reenable(true);
        definePack.addListener('complete', function () {
          pack.addListener('complete', function () {
            console.log('Created package for ' + self.name + ' v' + version);
            complete();
          });
          pack.invoke();
        });
        definePack.invoke();
      });

      task('publish', {async: true}, function () {
        var version = getPackageVersionNumber()
          , filename
          , cmd;

        console.log('Publishing ' + self.name + ' v' + version);

        filename = 'pkg/' + self.name + '-v' + version + '.tar.gz'
        cmd = self.publishCmd.replace(/%filename/gi, filename);

        // Hackity hack -- NPM publish sometimes returns errror like:
        // Error sending version data\nnpm ERR!
        // Error: forbidden 0.2.4 is modified, should match modified time
        setTimeout(function () {
          jake.exec(cmd, function () {
            console.log('Published to NPM');
            complete();
          }, {printStdout: true, printStderr: true});
        }, self.scheduleDelay);
      });

      task('cleanup', {async: true}, function () {
        var clobber = jake.Task.clobber;
        clobber.reenable(true);
        clobber.on('complete', function () {
          console.log('Cleaned up package');
          complete();
        });
        clobber.invoke();
      });

    });

    desc('Bump version-number, package, and publish to NPM.');
    task('publish', self.prereqs.concat(['npm:fetchTags', 'npm:getCurrentBranch', 'npm:version',
        'npm:package', 'npm:publish', 'npm:cleanup']), function () {});

    // Invoke proactively so there will be a callable 'package' task
    // which can be used apart from 'publish'
    jake.Task['npm:definePackage'].invoke();
  };

})();

jake.NpmPublishTask = NpmPublishTask;
exports.NpmPublishTask = NpmPublishTask;

<|endoftext|>


<commit_before>var net = require('net')
  , util = require('util')
  , Duplex = require('stream').Duplex;

var packetType = {
  0: 'choke',
  1: 'unchoke',
  2: 'interested',
  3: 'uninterested',
  4: 'have',
  5: 'bitfield',
  6: 'request',
  7: 'piece',
  8: 'cancel'
};

var Connection = module.exports = function Connection (opts) {
  var that = this;

  this.state = 'init';
  this.buffer = null;

  this.on('handshake', function () {
    that.state = 'established';
  });

  Duplex.call(this);
};

util.inherits(Connection, Duplex);

Connection.prototype._write = function (data, encoding, done) {
  // Concat incoming data with leftover data from last time
  this.buffer = this.buffer ? Buffer.concat([this.buffer, data]) : data;

  // Parse it
  this.parse(this.buffer, done);
};

Connection.prototype.parse = function (data, done) {
  var read = 0;

  if (this.state === 'init') {
    read = this.parseHandshake(data);
  } else if (this.state === 'established') {
    read = this.parsePacket(data);
  }

  // Short write
  if (read < 0) {
    this.buffer = data;
    done();
  // Long write
  } else if (read < data.length) {
    // Remove used data from buffer
    this.buffer = data.slice(read);
    // Continue parsing
    // TODO: do on next tick to avoid stack smashing
    this.parse(this.buffer, done);
  } else {
    // All data used up
    this.buffer = null;
    done();
  }
};

Connection.prototype._read = function(size) {
  // Nothing to do, probably would process a queue here
};

Connection.prototype.parsePacket = function (data) {
  var pos = 0
    , len = data.length
    , packet = {};

  // Shelve packet until we get at least the length and type
  if (pos + 5 > len) return -1;

  // Parse packet length
  var length = data.readUInt32BE(0);
  pos += 4;

  // Parse packet type
  packet.type = packetType[data[pos++]] || 'unknown';

  // Shelve packet if we haven't got the whole length
  if (pos + length - 1 > len) return -1;

  // Parse payload
  this['parse_' + packet.type](packet, data.slice(pos, pos + length));
  pos += length;

  // Emit the packet
  this.emit(packet.type, packet);

  return pos;
};

['choke', 'unchoke', 'interested', 'uninterested'].forEach(function (t) {
  Connection.prototype['parse_' + t] = function (packet, data) {
    return;
  }
});

Connection.prototype.parse_unknown = function (packet, payload) {
  packet.payload = payload;
};

Connection.prototype.parse_bitfield = function (packet, payload) {
  packet.bitfield = bitfieldToArray(payload);
};

Connection.prototype.parse_have = function (packet, payload) {
  packet.pieceId = payload.readUInt32BE(0);
};

Connection.prototype.parse_request = function (packet, payload) {
  packet.index = payload.readUInt32BE(0);
  packet.offset = payload.readUInt32BE(4);
  packet.length = payload.readUInt32BE(8);
};

Connection.prototype.parse_piece = function (packet, payload) {
  packet.index = payload.readUInt32BE(0);
  packet.offset = payload.readUInt32BE(4);
  packet.piece = payload.slice(8);
};

Connection.prototype.parse_cancel = function (packet, payload) {
  packet.index = payload.readUInt32BE(0);
  packet.offset = payload.readUInt32BE(4);
  packet.length = payload.readUInt32BE(8);
};

/**
 * Connection#parseHandshake - parse a handshake packet
 * @param {Buffer} data - buffer possibly containing handshake
 * @returns {Integer} number of bytes read from the buffer
 * @api private
 */
Connection.prototype.parseHandshake = function (data) {
  var pos = 0
    , len = data.length
    , packet = {type: 'handshake'};

  // Parse protocol length
  var length = data[pos++];

  if (pos >= len) return -1;

  // Parse protocol id
  packet.protocolId = data.slice(pos, pos + length).toString('utf8');
  pos += length;

  if (pos >= len) return -1;

  // Parse reserved bytes
  packet.reserved = data.slice(pos, pos + 8).toString('utf8');
  pos += 8;

  if (pos >= len) return -1;

  // Parse hash
  packet.hash = data.slice(pos, pos + 20).toString('hex');
  pos += 20;

  if (pos + 20 > len) return -1;

  // Parse client id
  packet.clientId = data.slice(pos, pos + 20).toString('utf8');
  pos += 20;

  // Emit the packet
  this.emit('handshake', packet);

  return pos;
};

Connection.prototype.choke = function () {
  this.push(new Buffer([0, 0, 0, 1, 0]));
};

Connection.prototype.unchoke = function () {
  this.push(new Buffer([0, 0, 0, 1, 1]));
};

Connection.prototype.interested = function () {
  this.push(new Buffer([0, 0, 0, 1, 2]));
};

Connection.prototype.uninterested = function () {
  this.push(new Buffer([0, 0, 0, 1, 3]));
};

Connection.prototype.handshake = function (protocolId, reserved, hash, clientId) {
  if ('object' === typeof protocolId) {
    var opts = protocolId;
    return this.handshake(
      opts.protocolId,
      opts.reserved,
      opts.hash,
      opts.clientId
    );
  }

  if (Buffer.byteLength(hash, 'hex') !== 20) throw new Error('Incorrect hash length');
  if (Buffer.byteLength(clientId, 'utf8') !== 20) throw new Error('Incorrect id length');

  var buffer = new Buffer(1 + protocolId.length + 8 + 20 + 20)
    , pos = 0;

  // Write protocol
  buffer.writeUInt8(protocolId.length, pos);
  pos += 1;
  buffer.write(protocolId, 'utf8', pos);
  pos += protocolId.length;

  // Write reserved bytes
  reserved.copy(buffer, pos);
  pos += 8;

  // Write hash
  buffer.write(hash, 'hex', pos);
  pos += 20;

  // Write client id
  buffer.write(clientId, 'utf8', pos);

  // Transmit it
  this.push(buffer);
};

Connection.prototype.have = function (pieceId) {
  // Out of bounds piece id
  if (pieceId < 0 || pieceId > 0xFFFFFFFF) return;

  this.push(new Buffer([0, 0, 0, 5, 4]));
  // Assemble piece id
  var piece = new Buffer(4);
  piece.writeUInt32BE(pieceId, 0);
  // Write it
  this.push(piece);
};

Connection.prototype.bitfield = function (bitfield) {
  // Convert array bitfield to buffer
  if (!Buffer.isBuffer(bitfield)) bitfield = arrayToBitfield(bitfield);

  // Assemble header
  var header = new Buffer(5);
  header.writeUInt32BE(1 + bitfield.length, 0);
  header.writeUInt8(5, 4);

  // Send header
  this.push(header);

  // Send bitfield
  this.push(bitfield);
};

var arrayToBitfield = function (bitArray) {
  var fieldLength = Math.ceil(bitArray.length / 8)
    , field = new Buffer(fieldLength);

  // Zero unused bits
  field.fill(0);

  for (var i = 0, len = bitArray.length; i < len; i++) {
    var byteNum = Math.floor(i / 8)
      , shift = i % 8;

    field[byteNum] = field[byteNum] | bitArray[i] << (7 - shift);
  }

  return field;
};

Connection.prototype.request = function (index, offset, length) {
  // Write header
  this.push(new Buffer([0, 0, 0, 13, 6]));

  // Assemble payload
  var payload = new Buffer(12);
  payload.writeUInt32BE(index, 0);
  payload.writeUInt32BE(offset, 4);
  payload.writeUInt32BE(length, 8);

  this.push(payload);
};

Connection.prototype.piece = function (index, offset, piece) {
  // Assemble header
  var header = new Buffer(5);
  header.writeUInt32BE(9 + piece.length, 0);
  header.writeUInt8(7, 4);

  // Write header
  this.push(header);

  // Write index and offset
  var meta = new Buffer(8);
  meta.writeUInt32BE(index, 0);
  meta.writeUInt32BE(offset, 4);
  this.push(meta);

  // Write payload
  this.push(piece);
};

Connection.prototype.cancel = function (index, offset, length) {
  // Write header
  this.push(new Buffer([0, 0, 0, 13, 8]));

  // Assemble payload
  var payload = new Buffer(12);
  payload.writeUInt32BE(index, 0);
  payload.writeUInt32BE(offset, 4);
  payload.writeUInt32BE(length, 8);

  this.push(payload);
};

var bitfieldToArray = function (bitfield) {
  var bitArray = [];
  for (var i = 0, len = bitfield.length; i < len; i++) {
    var byte = bitfield[i];
    for (var bit = 7; bit + 1; bit--) {
      bitArray.push(!!(byte & 1 << bit));
    }
  }

  return bitArray;
};
<commit_msg>Shuffle order<commit_after>var net = require('net')
  , util = require('util')
  , Duplex = require('stream').Duplex;

var packetType = {
  0: 'choke',
  1: 'unchoke',
  2: 'interested',
  3: 'uninterested',
  4: 'have',
  5: 'bitfield',
  6: 'request',
  7: 'piece',
  8: 'cancel'
};

var Connection = module.exports = function Connection (opts) {
  var that = this;

  this.state = 'init';
  this.buffer = null;

  this.on('handshake', function () {
    that.state = 'established';
  });

  Duplex.call(this);
};

util.inherits(Connection, Duplex);

Connection.prototype._write = function (data, encoding, done) {
  // Concat incoming data with leftover data from last time
  this.buffer = this.buffer ? Buffer.concat([this.buffer, data]) : data;

  // Parse it
  this.parse(this.buffer, done);
};

Connection.prototype.parse = function (data, done) {
  var read = 0;

  if (this.state === 'init') {
    read = this.parseHandshake(data);
  } else if (this.state === 'established') {
    read = this.parsePacket(data);
  }

  // Short write
  if (read < 0) {
    this.buffer = data;
    done();
  // Long write
  } else if (read < data.length) {
    // Remove used data from buffer
    this.buffer = data.slice(read);
    // Continue parsing
    // TODO: do on next tick to avoid stack smashing
    this.parse(this.buffer, done);
  } else {
    // All data used up
    this.buffer = null;
    done();
  }
};

Connection.prototype._read = function(size) {
  // Nothing to do, probably would process a queue here
};

Connection.prototype.parsePacket = function (data) {
  var pos = 0
    , len = data.length
    , packet = {};

  // Shelve packet until we get at least the length and type
  if (pos + 5 > len) return -1;

  // Parse packet length
  var length = data.readUInt32BE(0);
  pos += 4;

  // Parse packet type
  packet.type = packetType[data[pos++]] || 'unknown';

  // Shelve packet if we haven't got the whole length
  if (pos + length - 1 > len) return -1;

  // Parse payload
  this['parse_' + packet.type](packet, data.slice(pos, pos + length));
  pos += length;

  // Emit the packet
  this.emit(packet.type, packet);

  return pos;
};

['choke', 'unchoke', 'interested', 'uninterested'].forEach(function (t) {
  Connection.prototype['parse_' + t] = function (packet, data) {
    return;
  }
});

Connection.prototype.parse_unknown = function (packet, payload) {
  packet.payload = payload;
};

Connection.prototype.parse_bitfield = function (packet, payload) {
  packet.bitfield = bitfieldToArray(payload);
};

Connection.prototype.parse_have = function (packet, payload) {
  packet.pieceId = payload.readUInt32BE(0);
};

Connection.prototype.parse_request = function (packet, payload) {
  packet.index = payload.readUInt32BE(0);
  packet.offset = payload.readUInt32BE(4);
  packet.length = payload.readUInt32BE(8);
};

Connection.prototype.parse_piece = function (packet, payload) {
  packet.index = payload.readUInt32BE(0);
  packet.offset = payload.readUInt32BE(4);
  packet.piece = payload.slice(8);
};

Connection.prototype.parse_cancel = function (packet, payload) {
  packet.index = payload.readUInt32BE(0);
  packet.offset = payload.readUInt32BE(4);
  packet.length = payload.readUInt32BE(8);
};

/**
 * Connection#parseHandshake - parse a handshake packet
 * @param {Buffer} data - buffer possibly containing handshake
 * @returns {Integer} number of bytes read from the buffer
 * @api private
 */
Connection.prototype.parseHandshake = function (data) {
  var pos = 0
    , len = data.length
    , packet = {type: 'handshake'};

  // Parse protocol length
  var length = data[pos++];

  if (pos >= len) return -1;

  // Parse protocol id
  packet.protocolId = data.slice(pos, pos + length).toString('utf8');
  pos += length;

  if (pos >= len) return -1;

  // Parse reserved bytes
  packet.reserved = data.slice(pos, pos + 8).toString('utf8');
  pos += 8;

  if (pos >= len) return -1;

  // Parse hash
  packet.hash = data.slice(pos, pos + 20).toString('hex');
  pos += 20;

  if (pos + 20 > len) return -1;

  // Parse client id
  packet.clientId = data.slice(pos, pos + 20).toString('utf8');
  pos += 20;

  // Emit the packet
  this.emit('handshake', packet);

  return pos;
};

Connection.prototype.choke = function () {
  this.push(new Buffer([0, 0, 0, 1, 0]));
};

Connection.prototype.unchoke = function () {
  this.push(new Buffer([0, 0, 0, 1, 1]));
};

Connection.prototype.interested = function () {
  this.push(new Buffer([0, 0, 0, 1, 2]));
};

Connection.prototype.uninterested = function () {
  this.push(new Buffer([0, 0, 0, 1, 3]));
};

Connection.prototype.handshake = function (protocolId, reserved, hash, clientId) {
  if ('object' === typeof protocolId) {
    var opts = protocolId;
    return this.handshake(
      opts.protocolId,
      opts.reserved,
      opts.hash,
      opts.clientId
    );
  }

  if (Buffer.byteLength(hash, 'hex') !== 20) throw new Error('Incorrect hash length');
  if (Buffer.byteLength(clientId, 'utf8') !== 20) throw new Error('Incorrect id length');

  var buffer = new Buffer(1 + protocolId.length + 8 + 20 + 20)
    , pos = 0;

  // Write protocol
  buffer.writeUInt8(protocolId.length, pos);
  pos += 1;
  buffer.write(protocolId, 'utf8', pos);
  pos += protocolId.length;

  // Write reserved bytes
  reserved.copy(buffer, pos);
  pos += 8;

  // Write hash
  buffer.write(hash, 'hex', pos);
  pos += 20;

  // Write client id
  buffer.write(clientId, 'utf8', pos);

  // Transmit it
  this.push(buffer);
};

Connection.prototype.have = function (pieceId) {
  // Out of bounds piece id
  if (pieceId < 0 || pieceId > 0xFFFFFFFF) return;

  this.push(new Buffer([0, 0, 0, 5, 4]));
  // Assemble piece id
  var piece = new Buffer(4);
  piece.writeUInt32BE(pieceId, 0);
  // Write it
  this.push(piece);
};

Connection.prototype.bitfield = function (bitfield) {
  // Convert array bitfield to buffer
  if (!Buffer.isBuffer(bitfield)) bitfield = arrayToBitfield(bitfield);

  // Assemble header
  var header = new Buffer(5);
  header.writeUInt32BE(1 + bitfield.length, 0);
  header.writeUInt8(5, 4);

  // Send header
  this.push(header);

  // Send bitfield
  this.push(bitfield);
};

Connection.prototype.request = function (index, offset, length) {
  // Write header
  this.push(new Buffer([0, 0, 0, 13, 6]));

  // Assemble payload
  var payload = new Buffer(12);
  payload.writeUInt32BE(index, 0);
  payload.writeUInt32BE(offset, 4);
  payload.writeUInt32BE(length, 8);

  this.push(payload);
};

Connection.prototype.piece = function (index, offset, piece) {
  // Assemble header
  var header = new Buffer(5);
  header.writeUInt32BE(9 + piece.length, 0);
  header.writeUInt8(7, 4);

  // Write header
  this.push(header);

  // Write index and offset
  var meta = new Buffer(8);
  meta.writeUInt32BE(index, 0);
  meta.writeUInt32BE(offset, 4);
  this.push(meta);

  // Write payload
  this.push(piece);
};

Connection.prototype.cancel = function (index, offset, length) {
  // Write header
  this.push(new Buffer([0, 0, 0, 13, 8]));

  // Assemble payload
  var payload = new Buffer(12);
  payload.writeUInt32BE(index, 0);
  payload.writeUInt32BE(offset, 4);
  payload.writeUInt32BE(length, 8);

  this.push(payload);
};

var bitfieldToArray = function (bitfield) {
  var bitArray = [];
  for (var i = 0, len = bitfield.length; i < len; i++) {
    var byte = bitfield[i];
    for (var bit = 7; bit + 1; bit--) {
      bitArray.push(!!(byte & 1 << bit));
    }
  }

  return bitArray;
};

var arrayToBitfield = function (bitArray) {
  var fieldLength = Math.ceil(bitArray.length / 8)
    , field = new Buffer(fieldLength);

  // Zero unused bits
  field.fill(0);

  for (var i = 0, len = bitArray.length; i < len; i++) {
    var byteNum = Math.floor(i / 8)
      , shift = i % 8;

    field[byteNum] = field[byteNum] | bitArray[i] << (7 - shift);
  }

  return field;
};
<|endoftext|>


<commit_before>'use strict';
const toFactory = require('tofactory'),
      utils     = require('./utils'),
      isObject  = utils.isObject,
      isArray   = utils.isArray,
      ObjKeys   = Object.keys;

module.exports = toFactory(QueryParser);

function QueryParser(queryObj) {
    let queryFunction;

    const operators = {
        '$eq': function (key, value) {
            return function (doc) {
                return doc[key] === value;
            };
        },
        '$gt': function (value) {
            return function (field) {
                return field > value;
            };
        },
        '$gte': function (value) {
            return function (field) {
                return field >= value;
            };
        },
        '$lt': function (value) {
            return function (field) {
                return field < value;
            };
        },
        '$lte': function (value) {
            return function (field) {
                return field <= value;
            };
        },
        '$ne': function (value) {
            return function (field) {
                return field !== value;
            };
        },
        '$in': function (values) {
            const has = function (val) {
                return values.some(function (item) {
                    return val === item;
                });
            };

            return function (value) {
                if (isArray(value)) {
                    return value.some(function (val) {
                        return has(val);
                    });
                }
                return has(value);
            };
        },
        '$nin': function (values) {
            const notHas = function (val) {
                return values.every(function (item) {
                    return val !== item;
                });
            };

            return function (value) {
                if (isArray(value)) {
                    return value.every(function (item) {
                        return notHas(item);
                    });
                }
                return notHas(value);
            };
        },

        // {$and: [{a: 1}, {b: 2}]}
        '$and': function (objects) {
            const queryFunctions = [];

            objects.forEach(function (obj, i) {
                queryFunctions[i] = compile(obj);
            });

            return function (fields) {
                return queryFunctions.every(function (queryFn) {
                    return queryFn(fields);
                });
            };
        }
    };

    if (isObject(queryObj)) queryFunction = compile(queryObj);

    return {
        compile,
        match
    };

    function compile(queryObj) {
        let queryFn;
        const keys = ObjKeys(queryObj);

        if (keys.length > 1) { // build implicit $and

            let statements = [];

            keys.forEach(function (key, i) {
                const statement = {};
                statement[key] = queryObj[key];
                statements[i] = statement;
            });

            queryFn = operators.$and(statements);

        } else {
            let key = keys[0];

            queryFn = getOperator(key, queryObj[key]);
        }

        return queryFn;
    }

    function match(doc) {
        return queryFunction(doc);
    }

    function getOperator(key, value) {
        const op = operators[key];

        if (op) return op(key, value);

        if (isObject(value)) {
            value = compile(value);
        }

        return operators.$eq(key, value);
    }

}<commit_msg>created function for value comparison<commit_after>'use strict';
const toFactory = require('tofactory'),
      utils     = require('./utils'),
      isObject  = utils.isObject,
      isRegExp  = utils.isRegExp,
      isArray   = utils.isArray,
      ObjKeys   = Object.keys;

module.exports = toFactory(QueryParser);

function QueryParser(queryObj) {
    let queryFunction;

    const operators = {
        '$eq': function (key, value) {
            const compare = generateValueComparator(value);

            return function (doc) {
                return compare(doc[key]);
            };
        },
        '$gt': function (value) {
            return function (field) {
                return field > value;
            };
        },
        '$gte': function (value) {
            return function (field) {
                return field >= value;
            };
        },
        '$lt': function (value) {
            return function (field) {
                return field < value;
            };
        },
        '$lte': function (value) {
            return function (field) {
                return field <= value;
            };
        },
        '$ne': function (value) {
            return function (field) {
                return field !== value;
            };
        },
        '$in': function (values) {
            const has = function (val) {
                return values.some(function (item) {
                    return val === item;
                });
            };

            return function (value) {
                if (isArray(value)) {
                    return value.some(function (val) {
                        return has(val);
                    });
                }
                return has(value);
            };
        },
        '$nin': function (values) {
            const notHas = function (val) {
                return values.every(function (item) {
                    return val !== item;
                });
            };

            return function (value) {
                if (isArray(value)) {
                    return value.every(function (item) {
                        return notHas(item);
                    });
                }
                return notHas(value);
            };
        },

        // {$and: [{a: 1}, {b: 2}]}
        '$and': function (objects) {
            const queryFunctions = [];

            objects.forEach(function (obj, i) {
                queryFunctions[i] = compile(obj);
            });

            return function (fields) {
                return queryFunctions.every(function (queryFn) {
                    return queryFn(fields);
                });
            };
        }
    };

    if (isObject(queryObj)) queryFunction = compile(queryObj);

    return {
        compile,
        match
    };

    function compile(queryObj) {
        let queryFn;
        const keys = ObjKeys(queryObj);

        if (keys.length > 1) { // build implicit $and

            let statements = [];

            keys.forEach(function (key, i) {
                const statement = {};
                statement[key] = queryObj[key];
                statements[i] = statement;
            });

            queryFn = operators.$and(statements);

        } else {
            let key = keys[0];

            queryFn = getOperator(key, queryObj[key]);
        }

        return queryFn;
    }

    function match(doc) {
        return queryFunction(doc);
    }

    function getOperator(key, value) {
        const op = operators[key];

        if (op) return op(key, value);

        if (isObject(value)) {
            value = compile(value);
        }

        return operators.$eq(key, value);
    }

    function generateValueComparator(value) {

        return function compare(str) {
            return str === value;
        };
    }

}<|endoftext|>