<commit_before>
/**
 * Module dependencies.
 */

var uid2 = require('uid2');
var redis = require('redis').createClient;
var msgpack = require('msgpack-js');
var Adapter = require('socket.io-adapter');
var Emitter = require('events').EventEmitter;
var debug = require('debug')('socket.io-redis');
var async = require('async');

/**
 * Module exports.
 */

module.exports = adapter;

/**
 * Returns a redis Adapter class.
 *
 * @param {String} optional, redis uri
 * @return {RedisAdapter} adapter
 * @api public
 */

function adapter(uri, opts){
  opts = opts || {};

  // handle options only
  if ('object' == typeof uri) {
    opts = uri;
    uri = null;
  }

  // handle uri string
  if (uri) {
    uri = uri.split(':');
    opts.host = uri[0];
    opts.port = uri[1];
  }

  // opts
  var host = opts.host || '127.0.0.1';
  var port = Number(opts.port || 6379);
  var pub = opts.pubClient;
  var sub = opts.subClient;
  var prefix = opts.key || 'socket.io';

  // init clients if needed
  if (!pub) pub = redis(port, host);
  if (!sub) sub = redis(port, host, { detect_buffers: true });

  // this server's key
  var uid = uid2(6);
  var key = prefix + '#' + uid;

  /**
   * Adapter constructor.
   *
   * @param {String} namespace name
   * @api public
   */

  function Redis(nsp){
    Adapter.call(this, nsp);

    this.uid = uid;
    this.prefix = prefix;
    this.pubClient = pub;
    this.subClient = sub;

    var self = this;
    sub.subscribe(prefix + '#' + nsp.name + '#', function(err){
      if (err) self.emit('error', err);
    });
    sub.on('message', this.onmessage.bind(this));
  }

  /**
   * Inherits from `Adapter`.
   */

  Redis.prototype.__proto__ = Adapter.prototype;

  /**
   * Called with a subscription message
   *
   * @api private
   */

  Redis.prototype.onmessage = function(channel, msg){
    var pieces = channel.split('#');
    var args = msgpack.decode(msg);
    var packet;

    if (uid == args.shift()) return debug('ignore same uid');

    packet = args[0];

    if (packet && packet.nsp === undefined) {
      packet.nsp = '/';
    }

    if (!packet || packet.nsp != this.nsp.name) {
      return debug('ignore different namespace');
    }

    args.push(true);

    this.broadcast.apply(this, args);
  };

  /**
   * Broadcasts a packet.
   *
   * @param {Object} packet to emit
   * @param {Object} options
   * @param {Boolean} whether the packet came from another node
   * @api public
   */

  Redis.prototype.broadcast = function(packet, opts, remote){
    Adapter.prototype.broadcast.call(this, packet, opts);
    if (!remote) {
      if (opts.rooms) {
        opts.rooms.forEach(function(room) {
          var packet = msgpack.encode([uid, packet, opts]);
          var channel = prefix + '#' + packet.nsp + '#' + room + '#';
          pub.publish(channel, packet);
        });
      } else {
        var packet = msgpack.encode([uid, packet, opts]);
        pub.publish(prefix + '#' + packet.nsp + '#');
      }
    }
  };

  /**
   * Subscribe client to room messages.
   *
   * @param {String} client id
   * @param {String} room
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.add = function(id, room, fn){
    debug('adding %s to %s ', id, room);
    var self = this;
    this.sids[id] = this.sids[id] || {};
    this.sids[id][room] = true;
    this.rooms[room] = this.rooms[room] || {};
    this.rooms[room][id] = true;
    var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
    sub.subscribe(channel, function(err){
      if (err) {
        self.emit('error', err);
        if (fn) fn(err);
        return;
      }
      if (fn) fn(null);
    });
  };

  /**
   * Unsubscribe client from room messages.
   *
   * @param {String} session id
   * @param {String} room id
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.del = function(id, room, fn){
    var self = this;

    debug('removing ', id, ' from ', room);

    this.sids[id] = this.sids[id] || {};
    this.rooms[room] = this.rooms[room] || {};
    delete this.sids[id][room];
    delete this.rooms[room][id];

    if (this.rooms.hasOwnProperty(room) && !Object.keys(this.rooms[room]).length) {
      delete this.rooms[room];
      var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
      return sub.unsubscribe(channel, function(err){
        if (err) self.emit('error', err);
        if (fn) fn(err);
      });
    } else {
      if (fn) process.nextTick(fn.bind(null, null));
    }
  };

  /**
   * Unsubscribe client completely.
   *
   * @param {String} client id
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.delAll = function(id, fn){
    var self = this,
        rooms = this.sids[id];

    debug('removing ', id, ' from all rooms');

    if (!rooms) return process.nextTick(fn.bind(null, null));

    async.forEach(Object.keys(rooms), function (room, next) {
      if (rooms.hasOwnProperty(room)) {
        delete self.rooms[room][id];
      }

      if (self.rooms.hasOwnProperty(room) && !Object.keys(self.rooms[room]).length) {
        delete self.rooms[room];

        return sub.unsubscribe(prefix + '#' + self.nsp.name + '#' + room + '#', function(err){
          if (err) self.emit('error', err);
          next();
        });
      }

      next();
    }, function(err) {
      if (err) self.emit('error', err);

      delete self.sids[id];

      if (fn) process.nextTick(fn.bind(null, null));
    });
  };

  return Redis;

}
<commit_msg>style<commit_after>
/**
 * Module dependencies.
 */

var uid2 = require('uid2');
var redis = require('redis').createClient;
var msgpack = require('msgpack-js');
var Adapter = require('socket.io-adapter');
var Emitter = require('events').EventEmitter;
var debug = require('debug')('socket.io-redis');
var async = require('async');

/**
 * Module exports.
 */

module.exports = adapter;

/**
 * Returns a redis Adapter class.
 *
 * @param {String} optional, redis uri
 * @return {RedisAdapter} adapter
 * @api public
 */

function adapter(uri, opts){
  opts = opts || {};

  // handle options only
  if ('object' == typeof uri) {
    opts = uri;
    uri = null;
  }

  // handle uri string
  if (uri) {
    uri = uri.split(':');
    opts.host = uri[0];
    opts.port = uri[1];
  }

  // opts
  var host = opts.host || '127.0.0.1';
  var port = Number(opts.port || 6379);
  var pub = opts.pubClient;
  var sub = opts.subClient;
  var prefix = opts.key || 'socket.io';

  // init clients if needed
  if (!pub) pub = redis(port, host);
  if (!sub) sub = redis(port, host, { detect_buffers: true });

  // this server's key
  var uid = uid2(6);
  var key = prefix + '#' + uid;

  /**
   * Adapter constructor.
   *
   * @param {String} namespace name
   * @api public
   */

  function Redis(nsp){
    Adapter.call(this, nsp);

    this.uid = uid;
    this.prefix = prefix;
    this.pubClient = pub;
    this.subClient = sub;

    var self = this;
    sub.subscribe(prefix + '#' + nsp.name + '#', function(err){
      if (err) self.emit('error', err);
    });
    sub.on('message', this.onmessage.bind(this));
  }

  /**
   * Inherits from `Adapter`.
   */

  Redis.prototype.__proto__ = Adapter.prototype;

  /**
   * Called with a subscription message
   *
   * @api private
   */

  Redis.prototype.onmessage = function(channel, msg){
    var pieces = channel.split('#');
    var args = msgpack.decode(msg);
    var packet;

    if (uid == args.shift()) return debug('ignore same uid');

    packet = args[0];

    if (packet && packet.nsp === undefined) {
      packet.nsp = '/';
    }

    if (!packet || packet.nsp != this.nsp.name) {
      return debug('ignore different namespace');
    }

    args.push(true);

    this.broadcast.apply(this, args);
  };

  /**
   * Broadcasts a packet.
   *
   * @param {Object} packet to emit
   * @param {Object} options
   * @param {Boolean} whether the packet came from another node
   * @api public
   */

  Redis.prototype.broadcast = function(packet, opts, remote){
    Adapter.prototype.broadcast.call(this, packet, opts);
    if (!remote) {
      if (opts.rooms) {
        opts.rooms.forEach(function(room) {
          var packet = msgpack.encode([uid, packet, opts]);
          var channel = prefix + '#' + packet.nsp + '#' + room + '#';
          pub.publish(channel, packet);
        });
      } else {
        var packet = msgpack.encode([uid, packet, opts]);
        pub.publish(prefix + '#' + packet.nsp + '#');
      }
    }
  };

  /**
   * Subscribe client to room messages.
   *
   * @param {String} client id
   * @param {String} room
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.add = function(id, room, fn){
    debug('adding %s to %s ', id, room);
    var self = this;
    this.sids[id] = this.sids[id] || {};
    this.sids[id][room] = true;
    this.rooms[room] = this.rooms[room] || {};
    this.rooms[room][id] = true;
    var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
    sub.subscribe(channel, function(err){
      if (err) {
        self.emit('error', err);
        if (fn) fn(err);
        return;
      }
      if (fn) fn(null);
    });
  };

  /**
   * Unsubscribe client from room messages.
   *
   * @param {String} session id
   * @param {String} room id
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.del = function(id, room, fn){
    var self = this;

    debug('removing ', id, ' from ', room);

    this.sids[id] = this.sids[id] || {};
    this.rooms[room] = this.rooms[room] || {};
    delete this.sids[id][room];
    delete this.rooms[room][id];

    if (this.rooms.hasOwnProperty(room) && !Object.keys(this.rooms[room]).length) {
      delete this.rooms[room];
      var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
      return sub.unsubscribe(channel, function(err){
        if (err) self.emit('error', err);
        if (fn) fn(err);
      });
    } else {
      if (fn) process.nextTick(fn.bind(null, null));
    }
  };

  /**
   * Unsubscribe client completely.
   *
   * @param {String} client id
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.delAll = function(id, fn){
    debug('removing %s from all rooms', id);

    var self = this;
    var rooms = this.sids[id];

    if (!rooms) return process.nextTick(fn.bind(null, null));

    async.forEach(Object.keys(rooms), function(room, next){
      if (rooms.hasOwnProperty(room)) {
        delete self.rooms[room][id];
      }

      if (self.rooms.hasOwnProperty(room) && !Object.keys(self.rooms[room]).length) {
        delete self.rooms[room];

        return sub.unsubscribe(prefix + '#' + self.nsp.name + '#' + room + '#', function(err){
          if (err) self.emit('error', err);
          next();
        });
      }

      next();
    }, function(err) {
      if (err) self.emit('error', err);

      delete self.sids[id];

      if (fn) process.nextTick(fn.bind(null, null));
    });
  };

  return Redis;

}
<|endoftext|>


<commit_before>
// CoreOS always uses this ip for the host ip.
var COREOS_ETCD_ENDPOINT = '172.17.42.1';
var COREOS_ETCD_PORT = '4001';

var BEANSTALK_WORKTUBE_NAME = 'work';
var BEANSTALK_RESULTTUBE_NAME = 'result';

var Etcd = require('node-etcd');
var fivebeans = require('fivebeans');

var log = require('log-colors');
var etcd = new Etcd(COREOS_ETCD_ENDPOINT, COREOS_ETCD_PORT);

// Set this to true if you want to locally spin up beanstalk
var autodiscoverBeanstalkd = true;
var localBeanstalkEndpoint = 'localhost';

if(autodiscoverBeanstalkd) {
    // Connect to etcd and retrieve the beanstalkd endpoint ipaddr
    etcd.get("/beanstalkd", function(err, result) {
        if (err) {
            // Key is not set yet
            if (err.errorCode == 100)
            {
                // In this case, we watch for the key to be set
                log.error("Key not set yet - Beanstalk is probably not running. Will wait on it");

                etcd.watch('/beanstalkd', function(err, result) {
                    var beanstalkEndpoint = result.node.value ;
                    log.debug('Found beanstalkd instance at ' + beanstalkEndpoint);
                    connectToQueuesAndStartWorking(beanstalkEndpoint);
                });
            }
        }
        else
        {
            var beanstalkEndpoint = result.node.value ;
            log.debug('Found beanstalkd instance at ' + beanstalkEndpoint);
            connectToQueuesAndStartWorking(beanstalkEndpoint);
        }
    });
} else {
    connectToQueuesAndStartWorking(localBeanstalkEndpoint);
}

var jobClient;
var resultClient;

function connectToQueuesAndStartWorking (endpoint) {
    jobClient = new fivebeans.client(endpoint, 11300);
    resultClient = new fivebeans.client(endpoint, 11300);
    jobClient
        .on('connect', function()
        {
            log.debug('Job Tube connected successfully');
            reserveNextJob(jobClient);

        })
        .connect();

    resultClient
        .on('connect', function()
        {
            log.debug('Result Tube connected successfully');
            resultClient.use(BEANSTALK_RESULTTUBE_NAME, function(err, tubename) {
                // TODO: Synchronize such that this happens before any jobs are done
            });
        })
        .connect();
}

function reserveNextJob () {
    jobClient.watch(BEANSTALK_WORKTUBE_NAME, function(err, numwatched) {
        jobClient.reserve(function(err, jobid, payload) {
            if(!err) {
                processJob(jobid, payload, jobClient);
            }
        });
    });
}

// Dummy job here for now
// Simply wait some random amount between 0 - 10 seconds and then mark the job as done
function processJob (jobId, jobPayload, client) {
    log.debug("Working on: " + jobId + " | Payload: " + jobPayload);
    setTimeout( function () {
        client.destroy(jobId, function(err) {
            log.debug("Done with: " + jobId);

            // Post the result as the same job payload
            postResult("/" + jobPayload);
        });
    },
    Math.floor(Math.random() * 10 * 1000));
}

function postResult (resultPayload, client) {

    resultClient.put(0, 0, 120, resultPayload, function(err, jobid) {
        if(err) {
            log.error(err);
        } else {
            // Reserve the next job
            setImmediate(reserveNextJob);
        }
    });
}

<commit_msg>Added a comment.<commit_after>//
// CoreOS always uses this ip for the host ip.
var COREOS_ETCD_ENDPOINT = '172.17.42.1';
var COREOS_ETCD_PORT = '4001';

var BEANSTALK_WORKTUBE_NAME = 'work';
var BEANSTALK_RESULTTUBE_NAME = 'result';

var Etcd = require('node-etcd');
var fivebeans = require('fivebeans');

var log = require('log-colors');
var etcd = new Etcd(COREOS_ETCD_ENDPOINT, COREOS_ETCD_PORT);

// Set this to true if you want to locally spin up beanstalk
var autodiscoverBeanstalkd = true;
var localBeanstalkEndpoint = 'localhost';

if(autodiscoverBeanstalkd) {
    // Connect to etcd and retrieve the beanstalkd endpoint ipaddr
    etcd.get("/beanstalkd", function(err, result) {
        if (err) {
            // Key is not set yet
            if (err.errorCode == 100)
            {
                // In this case, we watch for the key to be set
                log.error("Key not set yet - Beanstalk is probably not running. Will wait on it");

                etcd.watch('/beanstalkd', function(err, result) {
                    var beanstalkEndpoint = result.node.value ;
                    log.debug('Found beanstalkd instance at ' + beanstalkEndpoint);
                    connectToQueuesAndStartWorking(beanstalkEndpoint);
                });
            }
        }
        else
        {
            var beanstalkEndpoint = result.node.value ;
            log.debug('Found beanstalkd instance at ' + beanstalkEndpoint);
            connectToQueuesAndStartWorking(beanstalkEndpoint);
        }
    });
} else {
    connectToQueuesAndStartWorking(localBeanstalkEndpoint);
}

var jobClient;
var resultClient;

function connectToQueuesAndStartWorking (endpoint) {
    jobClient = new fivebeans.client(endpoint, 11300);
    resultClient = new fivebeans.client(endpoint, 11300);
    jobClient
        .on('connect', function()
        {
            log.debug('Job Tube connected successfully');
            reserveNextJob(jobClient);

        })
        .connect();

    resultClient
        .on('connect', function()
        {
            log.debug('Result Tube connected successfully');
            resultClient.use(BEANSTALK_RESULTTUBE_NAME, function(err, tubename) {
                // TODO: Synchronize such that this happens before any jobs are done
            });
        })
        .connect();
}

function reserveNextJob () {
    jobClient.watch(BEANSTALK_WORKTUBE_NAME, function(err, numwatched) {
        jobClient.reserve(function(err, jobid, payload) {
            if(!err) {
                processJob(jobid, payload, jobClient);
            }
        });
    });
}

// Dummy job here for now
// Simply wait some random amount between 0 - 10 seconds and then mark the job as done
function processJob (jobId, jobPayload, client) {
    log.debug("Working on: " + jobId + " | Payload: " + jobPayload);
    setTimeout( function () {
        client.destroy(jobId, function(err) {
            log.debug("Done with: " + jobId);

            // Post the result as the same job payload
            postResult("/" + jobPayload);
        });
    },
    Math.floor(Math.random() * 10 * 1000));
}

function postResult (resultPayload, client) {

    resultClient.put(0, 0, 120, resultPayload, function(err, jobid) {
        if(err) {
            log.error(err);
        } else {
            // Reserve the next job
            setImmediate(reserveNextJob);
        }
    });
}

<|endoftext|>


<commit_before>var request = require('superagent');
var config = require('./config');
var debug = require('debug')('cyan-git-stats');

var personalAccessToken = config.personalAccessToken;

debug('token', personalAccessToken);<commit_msg>Make a request against github's api.<commit_after>var request = require('superagent');
var config = require('./config');
var debug = require('debug')('cyan-git-stats');

// Config properties
var personalAccessToken = config.personalAccessToken;

debug('token', personalAccessToken);

request.get('https://api.github.com/user')
    .auth(personalAccessToken, 'x-oauth-basic')
    .accept('application/vnd.github.v3+json')
    .set('Agent', 'tylerpeterson')
    .end(function (res) {
      if (res.ok) {
        debug('ok', JSON.stringify(res.body, null, '  '));
      } else {
        debug('not ok');
      }
    });<|endoftext|>


<commit_before>'use strict';

var dollars = require('dollars')
  , display = require('fn.name');

/**
 * Representation of a single middleware layer.
 *
 * @constructor
 * @param {String} name Identification of the middleware.
 * @param {Function} fn Middleware function.
 * @param {Mixed} context Execution context of the function.
 * @api private
 */
function Layer(name, fn) {
  this.length = fn.length;
  this.name = name;
  this.fn = fn;
}

/**
 * A minimal middleware layer system.
 *
 * @constructor
 * @param {EventEmitter} provider EventEmitter instance.
 * @api public
 */
function Supply(provider) {
  if (!this) return new Supply();

  this.provider = provider || this;
  this.layers = [];
  this.length = 0;
}

Supply.extend = require('extendible');
Supply.Layer = Layer;

/**
 * Removes the middleware from the stack.
 *
 * @param {String} name Name of the layer we wish to remove.
 * @returns {Boolean} Indication of successful removal.
 * @api public
 */
Supply.prototype.remove = function remove(name) {
  var i = this.indexOf(name)
    , layer;

  if (i === -1) return false;

  layer = this.layers.splice(i, 1)[0];

  this.length--;
  if (this.provider.emit) this.provider.emit('remove', layer);

  return true;
};

/**
 * Add a new middleware layer at the beginning of the stack.
 *
 * @param {String} name Middleware name
 * @param {Function} fn Function to execute
 * @param {Object} opts Additional middleware configuration.
 * @returns {Provider|Supply}
 * @api public
 */
Supply.prototype.before = function before(name, fn, opts) {
  if ('function' === typeof name) {
    fn = name;
    name = display(name);
  }

  return this.use(name, fn, dollars.object.concat(opts || {}, {
    at: 0
  }));
};

/**
 * Add a new middleware layer to the stack.
 *
 * @param {String} name Middleware name
 * @param {Function} fn Function to execute
 * @param {Object} opts Additional middleware configuration.
 * @returns {Provider|Supply}
 * @api public
 */
Supply.prototype.use = function use(name, fn, opts) {
  if ('function' === typeof name) {
    fn = name;
    name = display(name);
  }

  opts = dollars.object.concat({
    at: this.layers.length
  }, opts || {});

  if ('string' === typeof opts.at) opts.at = this.indexOf(opts.at);
  if (opts.at > this.layers.length) opts.at = this.layers.length;
  if (opts.at < 0) opts.at = 0;

  var layer = new Layer(name, fn, opts);
  this.layers.splice(opts.at, 0, layer);

  this.length++;
  if (this.provider.emit) this.provider.emit('use', layer);

  return this.provider;
};

/**
 * Find the index an object which has the given name.
 *
 * @param {Array} array Array to search for index.
 * @param {String} name Name we should match.
 * @returns {Number} Index.
 * @api private
 */
Supply.prototype.indexOf = function index(name) {
  for (var i = 0, l = this.layers.length; i < l; i++) {
    if (name === this.layers[i].name) return i;
  }

  return -1;
};

/**
 * Iterate over all existing middleware layers.
 *
 * @returns {Supply}
 * @api public
 */
Supply.prototype.each = function each() {
  var length = arguments.length
    , args = new Array(length)
    , fn = dollars.nope
    , supply = this
    , i = 0;

  //
  // Create a copy of the arguments to prevent it from leaking.
  //
  for (; i < length; i++) {
    args[i] = arguments[i];
  }

  if ('function' === typeof args[args.length - 1]) fn = args.pop();

  /**
   * Simple middleware layer iterator.
   *
   * @param {Error} err A failed middleware iteration.
   * @param {Boolean} done Stop iterating the layers as we are done.
   * @api private
   */
  function next(err, done) {
    var layer = supply.layers[i++];

    if (err || done || !layer) return fn(err, !!done);

    if (layer.length > length) return layer.fn.apply(supply.provider, args.concat(next));
    else dollars.catch(function catching() {
      return layer.fn.apply(supply.provider, args);
    }, next);
  }

  length = args.length;
  i = 0;
  next();

  return this.provider;
};

/**
 * Completely destroy the instance and nuke all references.
 *
 * @returns {Boolean}
 * @api public
 */
Supply.prototype.destroy = function supply() {
  if (!this.layers) return false;

  this.layers = this.provider = null;

  return true;
};

//
// Expose the middleware layer.
//
module.exports = Supply;
<commit_msg>[minor] Allow an optional initialize function<commit_after>'use strict';

var dollars = require('dollars')
  , display = require('fn.name');

/**
 * Representation of a single middleware layer.
 *
 * @constructor
 * @param {String} name Identification of the middleware.
 * @param {Function} fn Middleware function.
 * @param {Mixed} context Execution context of the function.
 * @api private
 */
function Layer(name, fn) {
  this.length = fn.length;
  this.name = name;
  this.fn = fn;
}

/**
 * A minimal middleware layer system.
 *
 * @constructor
 * @param {EventEmitter} provider EventEmitter instance.
 * @param {Object} options Optional options.
 * @api public
 */
function Supply(provider, options) {
  if (!this) return new Supply();
  options = options || {};

  this.provider = provider || this;
  this.layers = [];
  this.length = 0;

  if ('function' === typeof this.initialize) {
    this.initialize(options);
  }
}

Supply.extend = require('extendible');
Supply.Layer = Layer;

/**
 * Removes the middleware from the stack.
 *
 * @param {String} name Name of the layer we wish to remove.
 * @returns {Boolean} Indication of successful removal.
 * @api public
 */
Supply.prototype.remove = function remove(name) {
  var i = this.indexOf(name)
    , layer;

  if (i === -1) return false;

  layer = this.layers.splice(i, 1)[0];

  this.length--;
  if (this.provider.emit) this.provider.emit('remove', layer);

  return true;
};

/**
 * Add a new middleware layer at the beginning of the stack.
 *
 * @param {String} name Middleware name
 * @param {Function} fn Function to execute
 * @param {Object} opts Additional middleware configuration.
 * @returns {Provider|Supply}
 * @api public
 */
Supply.prototype.before = function before(name, fn, opts) {
  if ('function' === typeof name) {
    fn = name;
    name = display(name);
  }

  return this.use(name, fn, dollars.object.concat(opts || {}, {
    at: 0
  }));
};

/**
 * Add a new middleware layer to the stack.
 *
 * @param {String} name Middleware name
 * @param {Function} fn Function to execute
 * @param {Object} opts Additional middleware configuration.
 * @returns {Provider|Supply}
 * @api public
 */
Supply.prototype.use = function use(name, fn, opts) {
  if ('function' === typeof name) {
    fn = name;
    name = display(name);
  }

  opts = dollars.object.concat({
    at: this.layers.length
  }, opts || {});

  if ('string' === typeof opts.at) opts.at = this.indexOf(opts.at);
  if (opts.at > this.layers.length) opts.at = this.layers.length;
  if (opts.at < 0) opts.at = 0;

  var layer = new Layer(name, fn, opts);
  this.layers.splice(opts.at, 0, layer);

  this.length++;
  if (this.provider.emit) this.provider.emit('use', layer);

  return this.provider;
};

/**
 * Find the index an object which has the given name.
 *
 * @param {Array} array Array to search for index.
 * @param {String} name Name we should match.
 * @returns {Number} Index.
 * @api private
 */
Supply.prototype.indexOf = function index(name) {
  for (var i = 0, l = this.layers.length; i < l; i++) {
    if (name === this.layers[i].name) return i;
  }

  return -1;
};

/**
 * Iterate over all existing middleware layers.
 *
 * @returns {Supply}
 * @api public
 */
Supply.prototype.each = function each() {
  var length = arguments.length
    , args = new Array(length)
    , fn = dollars.nope
    , supply = this
    , i = 0;

  //
  // Create a copy of the arguments to prevent it from leaking.
  //
  for (; i < length; i++) {
    args[i] = arguments[i];
  }

  if ('function' === typeof args[args.length - 1]) fn = args.pop();

  /**
   * Simple middleware layer iterator.
   *
   * @param {Error} err A failed middleware iteration.
   * @param {Boolean} done Stop iterating the layers as we are done.
   * @api private
   */
  function next(err, done) {
    var layer = supply.layers[i++];

    if (err || done || !layer) return fn(err, !!done);

    if (layer.length > length) return layer.fn.apply(supply.provider, args.concat(next));
    else dollars.catch(function catching() {
      return layer.fn.apply(supply.provider, args);
    }, next);
  }

  length = args.length;
  i = 0;
  next();

  return this.provider;
};

/**
 * Completely destroy the instance and nuke all references.
 *
 * @returns {Boolean}
 * @api public
 */
Supply.prototype.destroy = function supply() {
  if (!this.layers) return false;

  this.layers = this.provider = null;

  return true;
};

//
// Expose the middleware layer.
//
module.exports = Supply;
<|endoftext|>


<commit_before>var fill = require('flood-fill')

module.exports = scan

function scan(grid, opts) {
  opts = opts || {}

  var indexer = 'indexer' in opts ? functor(opts.indexer) : defaultIndexer
    , empty = opts.empty || defaultEmpty
    , limit = opts.limit || Infinity
    , length = grid.data.length
    , height = grid.shape[1]
    , width = grid.shape[0]
    , data = grid.data
    , metrics = []
    , metric
    , idx = 0
    , n = 0
    , x, y

  top:
  for (x = 0; x < width; x += 1)
  for (y = 0; y < height; y += 1, n += 1) {
    if (empty(data[n])) {
      metric = fill(grid, x, y, indexer(idx++))
      metric.start = [x, y]
      metrics.push(metric)
      if (idx > limit) break top
    }
  }

  return metrics
}

function functor(x) {
  if (typeof x === 'function') return x
  return function() {
    return x
  }
}

function defaultIndexer(x) {
  return x + 2
}

function defaultEmpty(x) {
  return x === 0
}
<commit_msg>Use .get instead of accessing .data directly<commit_after>var fill = require('flood-fill')

module.exports = scan

function scan(grid, opts) {
  opts = opts || {}

  var indexer = 'indexer' in opts ? functor(opts.indexer) : defaultIndexer
    , empty = opts.empty || defaultEmpty
    , limit = opts.limit || Infinity
    , length = grid.data.length
    , height = grid.shape[1]
    , width = grid.shape[0]
    , data = grid.data
    , metrics = []
    , metric
    , idx = 0
    , x, y

  top:
  for (x = 0; x < width; x += 1)
  for (y = 0; y < height; y += 1) {
    if (empty(grid.get(x, y))) {
      metric = fill(grid, x, y, indexer(idx++))
      metric.start = [x, y]
      metrics.push(metric)
      if (idx > limit) break top
    }
  }

  return metrics
}

function functor(x) {
  if (typeof x === 'function') return x
  return function() {
    return x
  }
}

function defaultIndexer(x) {
  return x + 2
}

function defaultEmpty(x) {
  return x === 0
}
<|endoftext|>


<commit_before>var d3 = require('d3')
  , EventEmitter = require('events').EventEmitter
  , Stream = require('stream').Stream
  , util = require('util')
  , defaults = {
    toggleOnSelect: true, // By default each select will toggle the node if needed. This prevents the toggle
    depth: 20, // indentation depth
    height: 36, // height of each row
    accessors: {
      id: 'id',
      label: 'label',
      icon: 'icon',
      color: 'color'
    }
  }
  , styles = window.getComputedStyle(document.documentElement, '')
  , prefix = Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/)[0]
  , resize = require('./lib/resize')
  , partialRight = require('./lib/partial-right')

/**
 * Create a new d3 tree with the given config.
 */
var Tree = function (options) {
  if (!options) {
    throw new Error('options are required')
  }
  if (!options.stream) {
    throw new Error('options.stream is required')
  }

  this.options = defaults
  for (var p in options) {
    if (p === 'accessors') {
      for (var pp in options.accessors) {
        this.options.accessors[pp] = options.accessors[pp]
      }
    } else {
      this.options[p] = options[p]
    }
  }

  this.resizer = resize(prefix)

  this.tree = d3.layout.tree()
                       .nodeSize([0, this.options.depth])
}

util.inherits(Tree, EventEmitter)

Tree.prototype.render = function () {
  var self = this

  this.el = d3.select(document.createElement('div'))
              .attr('class', 'tree-container')

  this.node = this.el.append('div')
                       .attr('class', 'tree')
                       .append('ul')
                         .selectAll('li.node')

  this._nodeData = []
  this.root = null

  this.options.stream.on('data', function (n) {
    var p = self._nodeData[n.parentId]
    self._nodeData[n.id] = n

    if (p) {
      n.parent = p
      if (p == self.root || p.children) {
        // if the parent is the root, or the parent has visible children, then push onto its children so this node is visible
        (p.children || (p.children = [])).push(n)
        if (self.options.initialSelection === n.id) {
          self.select(n.id, { silent: true })
        } else {
          self.draw()
        }
      } else if (self.options.initialSelection === n.id) {
        // There's a initialSelection option equal to this node
        if (p._children) {
          // This parent has hidden children. Transfer them so they are visible
          p.children = p._children
          p._children = null
        }
        // Push this node onto the parents visible children
        (p.children || (p.children = [])).push(n)
        // And select it
        self.select(n.id, { silent: true })
      } else {
        // push to _children so it's hidden, no need to draw
        (p._children || (p._children = [])).push(n)
      }
    } else {
      self.root = n
      // root, draw it.
      self.draw()
    }
  })
  .on('end', self.draw.bind(self))

  return this
}

Tree.prototype.resize = function () {
  var box = this.el.select('div.tree').node().parentNode.getBoundingClientRect()
  this.resizer.height(this.options.height)
  this.node.call(this.resizer)
}

Tree.prototype.draw = function (source, opt) {
  opt = opt || {}

  var self = this

  this.node = this.node.data(this.tree.nodes(this.root), function (d) {
    return d[self.options.accessors.id]
  })

  var enter = this.node.enter().append('li')
      .attr('class', 'node')
      .on('click', partialRight(this._onSelect.bind(this), self.options))
      .style(prefix + 'transform', function (d) {
        return 'translate(0px,' + (source ? source._y : d.y) + 'px)'
      })
      .style('opacity', 1e-6)

  // Add the node contents
  var contents = enter.append('div')
                        .attr('class', 'node-contents')
                        .attr('style', function (d) {
                          return prefix + 'transform:' + 'translate(' + (d.parent ? d.parent._x : 0) + 'px,0px)'
                        })

  // Add the toggler
  contents.append('div')
          .attr('class', 'toggler')
            .on('click', this._onToggle.bind(this))
            .append('svg')
              .append('use')
                .attr('xlink:href', '#icon-collapsed')

  // icon to represent the node tpye
  contents.append('svg')
          .attr('class', 'icon')
            .append('use')

  contents.append('div')
         .attr('class', 'label')

  // Now the indicator light
  enter.append('div')
          .attr('class', 'indicator')

  // disable animations if necessary
  this.node.classed('notransition', opt.animate === false)

  // Update the color if it changed
  this.node.selectAll('div.indicator')
      .attr('class', function (d) {
        return 'indicator ' + d[self.options.accessors.color]
      })

  // The icon maybe changed
  this.node.selectAll('svg.icon')
           .attr('class', function (d) {
             return 'icon ' + d[self.options.accessors.color]
           })
           .selectAll('use')
            .attr('xlink:href', function (d) {
              return '#icon-' + d[self.options.accessors.icon]
            })

  // change the state of the toggle icon by adjusting its class
  this.node.selectAll('.toggler')
           .attr('class', function (d) {
             return 'toggler ' + (d._children ? 'collapsed' : d.children ? 'expanded' : 'leaf')
           })

  // Perhaps the name changed
  this.node.selectAll('div.label')
            .text(function (d) {
              return d[self.options.accessors.label]
            })

  // if we are manipulating a single node, we may have to adjust selected properties
  if (source) {
    this.node.classed('selected', function (d) {
      return d.selected
    })
  }

  // If this node has been removed, let's remove it.
  var exit = this.node.exit()
  exit.selectAll('div.node-contents')
      .style(prefix + 'transform', function (d) {
        return 'translate(' + d.parent._x + 'px,0px)'
      })

  exit.style(prefix + 'transform', function (d) {
        return 'translate(0px,' + source._y + 'px)'
      })
      .style('opacity', 1e-6)
      .transition()
      .duration(300) // copied in css
      .remove()

  // Now resize things
  this.resize()

  // Now remove the notransition class
  if (opt.animate === false) {
    process.nextTick(function () {
      self.node.classed('notransition', false)
    })
  }
}

Tree.prototype.select = function (id, opt) {
  opt = opt || this.options
  var d = this.get(id)

  if (d) {
    this._onSelect(d, null, null, opt)
  }
}

/*
 * Returns a node object by id. This searches all the underlying data, not
 * just the visible nodes.
 *
 * if no id is sent, returns the root, essentially the entire tree
 */
Tree.prototype.get = function (id) {
  if (typeof id === 'undefined') {
    return this.root
  }

  return this._nodeData[id]
}

/*
 * Returns the currently selected d3 selection. This is the d3 object that contains
 * the currently selected node. The underlying dom node can be accessed by invoking
 * .node() on the selection.
 *
 * e.g.
 *    tree.getSelected().node()
 */
Tree.prototype.getSelected = function () {
  if (!this._selected) {
    return
  }

  var self = this
  return this.node.filter(function (d) {
    return d == self._selected
  })
}

Tree.prototype._onSelect = function (d, i, j, opt) {
  opt = opt || {}

  // determines if we should toggle the node. We don't toggle if it's the root node
  // or the node is already expanded, but not selected.
  var toggle = opt.toggleOnSelect && !(d.children && !d.selected) && i !== 0

  // tree_.selected stores a previously selected node
  if (this._selected) {
    // delete the selected field from that node
    delete this._selected.selected
  }

  d.selected = true
  this._selected = d

  // Make sure all ancestors are visible
  ;(function e (node) {
    if (!node) {
      return
    }
    if (node._children) {
      node.children = node._children
      node._children = null
    }
    if (node && node.parent) {
      e(node.parent)
    }
  })(d.parent)

  if (toggle) {
    this.toggle(d, opt)
  } else {
    this.draw(d, opt)
  }

  if (!opt.silent) {
    this.emit('select', d)
  }
}

Tree.prototype._onToggle = function (d, i) {
  d3.event.stopPropagation()
  if (i === 0) {
    // Never toggle root
    return
  }
  this.toggle(d)
}

/*
 * Adds a new node to the tree. Pass in d as the data that represents
 * the node, parent (which can be the parent object or an id), and an optional
 * index. If the index is sent, the node will be inserted at that index within the
 * parent's children.
 */
Tree.prototype.add = function (d, parent, idx) {
  if (this.get(d.id)) {
    // can't add a node that we already have
    return
  }
  parent = this.get(typeof parent === 'object' ? parent.id : parent)

  if (!parent) {
    return
  }

  var children = parent.children || parent._children
  this._nodeData[d.id] = d

  d.parent = parent

  if (typeof idx !== 'undefined') {
    children.splice(idx, 0, d)
  } else {
    if (!children) {
      children = parent.children = []
    }
    children.push(d)
  }

  this.draw(parent)
  return this.get(d.id)
}

/*
 * Returns if the tree is in edit mode.
 */
Tree.prototype.isEditable = function () {
  return this.el.select('.tree').classed('editable')
}

/*
 * Toggles the tree's editable state
 */
Tree.prototype.editable = function () {
  var t = this.el.select('.tree')
  t.classed('editable', !t.classed('editable'))
}

/*
 * Edits a node
 */
Tree.prototype.edit = function (d) {
  if (d.id && this.get(d.id)) {
    this._patch(d)
  }
}

/*
 * Toggle all isn't necessary the best name, because it doesn't toggle the root node,
 * since the first children are always visible
 */
Tree.prototype._toggleAll = function (fn) {
  var self = this
  this._nodeData.forEach(function (d) {
    if (d != self.root) {
      fn(d)
    }
  })
  this.draw(this.root)
}

Tree.prototype.expandAll = function () {
  this._toggleAll(function (d) {
    if (d._children) {
      d.children = d._children
      d._children = null
    }
  })
}

Tree.prototype.collapseAll = function () {
  this._toggleAll(function (d) {
    if (d.children) {
      d._children = d.children
      d.children = null
    }
  })
}

/*
 * Receives an array of patch changes, or a stream that emits data events with
 * the node and the changes.
 */
Tree.prototype.patch = function (obj) {
  var self = this
  if (obj instanceof Stream) {
    obj.on('data', function (d) {
      self._patch(d)
    })
  } else if (Array.isArray(obj)) {
    obj.forEach(this._patch.bind(this))
  }
}

/*
 * Merges properties from obj into the data object in the tree with the same id
 * as obj
 */
Tree.prototype._patch = function (obj) {
  var d = this.get(obj.id)
  if (d) {
    for (var prop in obj) {
      d[prop] = obj[prop]
    }
    this.draw(d)
  }
}

/*
 * Removes a node from the tree. obj can be the node id or the node itself
 */
Tree.prototype.remove = function (obj) {
  var node = this.get(typeof obj === 'object' ? obj.id : obj)

  if (!node) {
    return
  }

  var parent = node.parent
    , self = this
  if (parent) {
    // Remove the child from parent
    var children = parent.children || parent._children
    children.splice(children.indexOf(node), 1)
    this.draw(parent)

    // Cleanup _nodeData
    ;[node].reduce(function reduce(p, c) {
      var children = c.children || c._children
      if (children) {
        return p.concat(children.reduce(reduce, []))
      }
      return p.concat(c.id)
    }, []).forEach(function (id) {
      delete self._nodeData[id]
    })
  }
}

Tree.prototype.toggle = function (d, opt) {
  if (d.children) {
    d._children = d.children
    d.children = null
  } else {
    d.children = d._children
    d._children = null
  }
  this.draw(d, opt)
}

module.exports = Tree
<commit_msg>Patching an array draws once.<commit_after>var d3 = require('d3')
  , EventEmitter = require('events').EventEmitter
  , Stream = require('stream').Stream
  , util = require('util')
  , defaults = {
    toggleOnSelect: true, // By default each select will toggle the node if needed. This prevents the toggle
    depth: 20, // indentation depth
    height: 36, // height of each row
    accessors: {
      id: 'id',
      label: 'label',
      icon: 'icon',
      color: 'color'
    }
  }
  , styles = window.getComputedStyle(document.documentElement, '')
  , prefix = Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/)[0]
  , resize = require('./lib/resize')
  , partialRight = require('./lib/partial-right')

/**
 * Create a new d3 tree with the given config.
 */
var Tree = function (options) {
  if (!options) {
    throw new Error('options are required')
  }
  if (!options.stream) {
    throw new Error('options.stream is required')
  }

  this.options = defaults
  for (var p in options) {
    if (p === 'accessors') {
      for (var pp in options.accessors) {
        this.options.accessors[pp] = options.accessors[pp]
      }
    } else {
      this.options[p] = options[p]
    }
  }

  this.resizer = resize(prefix)

  this.tree = d3.layout.tree()
                       .nodeSize([0, this.options.depth])
}

util.inherits(Tree, EventEmitter)

Tree.prototype.render = function () {
  var self = this

  this.el = d3.select(document.createElement('div'))
              .attr('class', 'tree-container')

  this.node = this.el.append('div')
                       .attr('class', 'tree')
                       .append('ul')
                         .selectAll('li.node')

  this._nodeData = []
  this.root = null

  this.options.stream.on('data', function (n) {
    var p = self._nodeData[n.parentId]
    self._nodeData[n.id] = n

    if (p) {
      n.parent = p
      if (p == self.root || p.children) {
        // if the parent is the root, or the parent has visible children, then push onto its children so this node is visible
        (p.children || (p.children = [])).push(n)
        if (self.options.initialSelection === n.id) {
          self.select(n.id, { silent: true })
        } else {
          self.draw()
        }
      } else if (self.options.initialSelection === n.id) {
        // There's a initialSelection option equal to this node
        if (p._children) {
          // This parent has hidden children. Transfer them so they are visible
          p.children = p._children
          p._children = null
        }
        // Push this node onto the parents visible children
        (p.children || (p.children = [])).push(n)
        // And select it
        self.select(n.id, { silent: true })
      } else {
        // push to _children so it's hidden, no need to draw
        (p._children || (p._children = [])).push(n)
      }
    } else {
      self.root = n
      // root, draw it.
      self.draw()
    }
  })
  .on('end', self.draw.bind(self))

  return this
}

Tree.prototype.resize = function () {
  var box = this.el.select('div.tree').node().parentNode.getBoundingClientRect()
  this.resizer.height(this.options.height)
  this.node.call(this.resizer)
}

Tree.prototype.draw = function (source, opt) {
  opt = opt || {}

  var self = this

  this.node = this.node.data(this.tree.nodes(this.root), function (d) {
    return d[self.options.accessors.id]
  })

  var enter = this.node.enter().append('li')
      .attr('class', 'node')
      .on('click', partialRight(this._onSelect.bind(this), self.options))
      .style(prefix + 'transform', function (d) {
        return 'translate(0px,' + (source ? source._y : d.y) + 'px)'
      })
      .style('opacity', 1e-6)

  // Add the node contents
  var contents = enter.append('div')
                        .attr('class', 'node-contents')
                        .attr('style', function (d) {
                          return prefix + 'transform:' + 'translate(' + (d.parent ? d.parent._x : 0) + 'px,0px)'
                        })

  // Add the toggler
  contents.append('div')
          .attr('class', 'toggler')
            .on('click', this._onToggle.bind(this))
            .append('svg')
              .append('use')
                .attr('xlink:href', '#icon-collapsed')

  // icon to represent the node tpye
  contents.append('svg')
          .attr('class', 'icon')
            .append('use')

  contents.append('div')
         .attr('class', 'label')

  // Now the indicator light
  enter.append('div')
          .attr('class', 'indicator')

  // disable animations if necessary
  this.node.classed('notransition', opt.animate === false)

  // Update the color if it changed
  this.node.selectAll('div.indicator')
      .attr('class', function (d) {
        return 'indicator ' + d[self.options.accessors.color]
      })

  // The icon maybe changed
  this.node.selectAll('svg.icon')
           .attr('class', function (d) {
             return 'icon ' + d[self.options.accessors.color]
           })
           .selectAll('use')
            .attr('xlink:href', function (d) {
              return '#icon-' + d[self.options.accessors.icon]
            })

  // change the state of the toggle icon by adjusting its class
  this.node.selectAll('.toggler')
           .attr('class', function (d) {
             return 'toggler ' + (d._children ? 'collapsed' : d.children ? 'expanded' : 'leaf')
           })

  // Perhaps the name changed
  this.node.selectAll('div.label')
            .text(function (d) {
              return d[self.options.accessors.label]
            })

  // if we are manipulating a single node, we may have to adjust selected properties
  if (source) {
    this.node.classed('selected', function (d) {
      return d.selected
    })
  }

  // If this node has been removed, let's remove it.
  var exit = this.node.exit()
  exit.selectAll('div.node-contents')
      .style(prefix + 'transform', function (d) {
        return 'translate(' + d.parent._x + 'px,0px)'
      })

  exit.style(prefix + 'transform', function (d) {
        return 'translate(0px,' + source._y + 'px)'
      })
      .style('opacity', 1e-6)
      .transition()
      .duration(300) // copied in css
      .remove()

  // Now resize things
  this.resize()

  // Now remove the notransition class
  if (opt.animate === false) {
    process.nextTick(function () {
      self.node.classed('notransition', false)
    })
  }
}

Tree.prototype.select = function (id, opt) {
  opt = opt || this.options
  var d = this.get(id)

  if (d) {
    this._onSelect(d, null, null, opt)
  }
}

/*
 * Returns a node object by id. This searches all the underlying data, not
 * just the visible nodes.
 *
 * if no id is sent, returns the root, essentially the entire tree
 */
Tree.prototype.get = function (id) {
  if (typeof id === 'undefined') {
    return this.root
  }

  return this._nodeData[id]
}

/*
 * Returns the currently selected d3 selection. This is the d3 object that contains
 * the currently selected node. The underlying dom node can be accessed by invoking
 * .node() on the selection.
 *
 * e.g.
 *    tree.getSelected().node()
 */
Tree.prototype.getSelected = function () {
  if (!this._selected) {
    return
  }

  var self = this
  return this.node.filter(function (d) {
    return d == self._selected
  })
}

Tree.prototype._onSelect = function (d, i, j, opt) {
  opt = opt || {}

  // determines if we should toggle the node. We don't toggle if it's the root node
  // or the node is already expanded, but not selected.
  var toggle = opt.toggleOnSelect && !(d.children && !d.selected) && i !== 0

  // tree_.selected stores a previously selected node
  if (this._selected) {
    // delete the selected field from that node
    delete this._selected.selected
  }

  d.selected = true
  this._selected = d

  // Make sure all ancestors are visible
  ;(function e (node) {
    if (!node) {
      return
    }
    if (node._children) {
      node.children = node._children
      node._children = null
    }
    if (node && node.parent) {
      e(node.parent)
    }
  })(d.parent)

  if (toggle) {
    this.toggle(d, opt)
  } else {
    this.draw(d, opt)
  }

  if (!opt.silent) {
    this.emit('select', d)
  }
}

Tree.prototype._onToggle = function (d, i) {
  d3.event.stopPropagation()
  if (i === 0) {
    // Never toggle root
    return
  }
  this.toggle(d)
}

/*
 * Adds a new node to the tree. Pass in d as the data that represents
 * the node, parent (which can be the parent object or an id), and an optional
 * index. If the index is sent, the node will be inserted at that index within the
 * parent's children.
 */
Tree.prototype.add = function (d, parent, idx) {
  if (this.get(d.id)) {
    // can't add a node that we already have
    return
  }
  parent = this.get(typeof parent === 'object' ? parent.id : parent)

  if (!parent) {
    return
  }

  var children = parent.children || parent._children
  this._nodeData[d.id] = d

  d.parent = parent

  if (typeof idx !== 'undefined') {
    children.splice(idx, 0, d)
  } else {
    if (!children) {
      children = parent.children = []
    }
    children.push(d)
  }

  this.draw(parent)
  return this.get(d.id)
}

/*
 * Returns if the tree is in edit mode.
 */
Tree.prototype.isEditable = function () {
  return this.el.select('.tree').classed('editable')
}

/*
 * Toggles the tree's editable state
 */
Tree.prototype.editable = function () {
  var t = this.el.select('.tree')
  t.classed('editable', !t.classed('editable'))
}

/*
 * Edits a node
 */
Tree.prototype.edit = function (d) {
  if (d.id && this.get(d.id)) {
    this._patch(d)
    this.draw(d)
  }
}

/*
 * Toggle all isn't necessary the best name, because it doesn't toggle the root node,
 * since the first children are always visible
 */
Tree.prototype._toggleAll = function (fn) {
  var self = this
  this._nodeData.forEach(function (d) {
    if (d != self.root) {
      fn(d)
    }
  })
  this.draw(this.root)
}

Tree.prototype.expandAll = function () {
  this._toggleAll(function (d) {
    if (d._children) {
      d.children = d._children
      d._children = null
    }
  })
}

Tree.prototype.collapseAll = function () {
  this._toggleAll(function (d) {
    if (d.children) {
      d._children = d.children
      d.children = null
    }
  })
}

/*
 * Receives an array of patch changes, or a stream that emits data events with
 * the node and the changes.
 */
Tree.prototype.patch = function (obj) {
  var self = this
  if (obj instanceof Stream) {
    obj.on('data', function (d) {
      self._patch(d)
      self.draw(d)
    })
  } else if (Array.isArray(obj)) {
    obj.forEach(this._patch.bind(this))
    self.draw()
  }
}

/*
 * Merges properties from obj into the data object in the tree with the same id
 * as obj
 */
Tree.prototype._patch = function (obj) {
  var d = this.get(obj.id)
  if (d) {
    for (var prop in obj) {
      d[prop] = obj[prop]
    }
  }
}

/*
 * Removes a node from the tree. obj can be the node id or the node itself
 */
Tree.prototype.remove = function (obj) {
  var node = this.get(typeof obj === 'object' ? obj.id : obj)

  if (!node) {
    return
  }

  var parent = node.parent
    , self = this
  if (parent) {
    // Remove the child from parent
    var children = parent.children || parent._children
    children.splice(children.indexOf(node), 1)
    this.draw(parent)

    // Cleanup _nodeData
    ;[node].reduce(function reduce(p, c) {
      var children = c.children || c._children
      if (children) {
        return p.concat(children.reduce(reduce, []))
      }
      return p.concat(c.id)
    }, []).forEach(function (id) {
      delete self._nodeData[id]
    })
  }
}

Tree.prototype.toggle = function (d, opt) {
  if (d.children) {
    d._children = d.children
    d.children = null
  } else {
    d.children = d._children
    d._children = null
  }
  this.draw(d, opt)
}

module.exports = Tree
<|endoftext|>


<commit_before>// LESS
import './less/availity-bootstrap.less';

// IMAGES
import './images/logo-availity.png';
import './images/default/love.jpg';

// FONTS
import './fonts/availity-icon-font.eot';
import './fonts/availity-icon-font.svg';
import './fonts/availity-icon-font.ttf';
import './fonts/availity-icon-font.woff';

// JS
import './js';

<commit_msg>remove images from js bootstrap file<commit_after>// LESS
import './less/availity-bootstrap.less';

// FONTS
import './fonts/availity-icon-font.eot';
import './fonts/availity-icon-font.svg';
import './fonts/availity-icon-font.ttf';
import './fonts/availity-icon-font.woff';

// JS
import './js';

<|endoftext|>


<commit_before>;(function(undefined) {
	"use strict";

	var $scope
	, conflict, conflictResolution = [];
	if (typeof global == 'object' && global) {
		$scope = global;
	} else if (typeof window !== 'undefined'){
		$scope = window;
	} else {
		$scope = {};
	}
	conflict = $scope.DeepDiff;
	if (conflict) {
		conflictResolution.push(
			function() {
				if ('undefined' !== typeof conflict && $scope.DeepDiff === accumulateDiff) {
					$scope.DeepDiff = conflict;
					conflict = undefined;
				}
			});
	}

	// nodejs compatible on server side and in the browser.
  function inherits(ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  }

  function Diff(kind, path) {
  	Object.defineProperty(this, 'kind', { value: kind, enumerable: true });
  	if (path && path.length) {
  		Object.defineProperty(this, 'path', { value: path, enumerable: true });
  	}
  }

  function DiffEdit(path, origin, value) {
  	DiffEdit.super_.call(this, 'E', path);
  	Object.defineProperty(this, 'lhs', { value: origin, enumerable: true });
  	Object.defineProperty(this, 'rhs', { value: value, enumerable: true });
  }
  inherits(DiffEdit, Diff);

  function DiffNew(path, value) {
  	DiffNew.super_.call(this, 'N', path);
  	Object.defineProperty(this, 'rhs', { value: value, enumerable: true });
  }
  inherits(DiffNew, Diff);

  function DiffDeleted(path, value) {
  	DiffDeleted.super_.call(this, 'D', path);
  	Object.defineProperty(this, 'lhs', { value: value, enumerable: true });
  }
  inherits(DiffDeleted, Diff);

  function DiffArray(path, index, item) {
  	DiffArray.super_.call(this, 'A', path);
  	Object.defineProperty(this, 'index', { value: index, enumerable: true });
  	Object.defineProperty(this, 'item', { value: item, enumerable: true });
  }
  inherits(DiffArray, Diff);

  function checkForDiff(object) {
    if (object && object.kind && object.path){
      switch(object.kind) {
        case 'A':
          if (object.hasOwnProperty('index') && object.hasOwnProperty('item')){
            return true;
          }
          break;
        case 'D':
          if (object.hasOwnProperty('lhs')){
            return true;
          }
          break;
        case 'E':
          if (object.hasOwnProperty('lhs') && object.hasOwnProperty('rhs')){
            return true;
          }
          break;
        case 'N':
          if (object.hasOwnProperty('rhs')){
            return true;
          }
          break;
      }
    }
    return false;
  }

  function arrayRemove(arr, from, to) {
  	var rest = arr.slice((to || from) + 1 || arr.length);
  	arr.length = from < 0 ? arr.length + from : from;
  	arr.push.apply(arr, rest);
  	return arr;
  }

  function deepDiff(lhs, rhs, changes, path, key, stack) {
  	path = path || [];
  	var currentPath = path.slice(0);
  	if (key) { currentPath.push(key); }
  	var ltype = typeof lhs;
  	var rtype = typeof rhs;
  	if (ltype === 'undefined') {
  		if (rtype !== 'undefined') {
  			changes(new DiffNew(currentPath, rhs ));
  		}
  	} else if (rtype === 'undefined') {
  		changes(new DiffDeleted(currentPath, lhs));
  	} else if (ltype !== rtype) {
  		changes(new DiffEdit(currentPath, lhs, rhs));
  	} else if (lhs instanceof Date && rhs instanceof Date && ((lhs-rhs) != 0) ) {
  		changes(new DiffEdit(currentPath, lhs, rhs));
  	} else if (ltype === 'object' && lhs != null && rhs != null) {
  		stack = stack || [];
  		if (stack.indexOf(lhs) < 0) {
  			stack.push(lhs);
  			if (Array.isArray(lhs)) {
  				var i
  				, len = lhs.length
  				, ea = function(d) {
  					changes(new DiffArray(currentPath, i, d));
  				};
  				for(i = 0; i < lhs.length; i++) {
  					if (i >= rhs.length) {
  						changes(new DiffArray(currentPath, i, new DiffDeleted(undefined, lhs[i])));
  					} else {
  						deepDiff(lhs[i], rhs[i], ea, [], null, stack);
  					}
  				}
  				while(i < rhs.length) {
  					changes(new DiffArray(currentPath, i, new DiffNew(undefined, rhs[i++])));
  				}
  			} else {
  				var akeys = Object.keys(lhs);
  				var pkeys = Object.keys(rhs);
  				akeys.forEach(function(k) {
  					var i = pkeys.indexOf(k);
  					if (i >= 0) {
  						deepDiff(lhs[k], rhs[k], changes, currentPath, k, stack);
  						pkeys = arrayRemove(pkeys, i);
  					} else {
  						deepDiff(lhs[k], undefined, changes, currentPath, k, stack);
  					}
  				});
  				pkeys.forEach(function(k) {
  					deepDiff(undefined, rhs[k], changes, currentPath, k, stack);
  				});
  			}
  			stack.length = stack.length - 1;
  		}
  	} else if (lhs !== rhs) {
  		changes(new DiffEdit(currentPath, lhs, rhs));
  	}
  }

  function accumulateDiff(lhs, rhs, accum) {
  	accum = accum || [];
  	deepDiff(lhs, rhs, function(diff) {
  		if (diff) {
  			accum.push(diff);
  		}
  	});
  	return (accum.length) ? accum : undefined;
  }

	function applyArrayChange(arr, index, change) {
		if (change.path && change.path.length) {
			// the structure of the object at the index has changed...
			var it = arr[index], i, u = change.path.length - 1;
			for(i = 0; i < u; i++){
				it = it[change.path[i]];
			}
			switch(change.kind) {
				case 'A':
					// Array was modified...
					// it will be an array...
					applyArrayChange(it[change.path[i]], change.index, change.item);
					break;
				case 'D':
					// Item was deleted...
					delete it[change.path[i]];
					break;
				case 'E':
				case 'N':
					// Item was edited or is new...
					it[change.path[i]] = change.rhs;
					break;
			}
		} else {
			// the array item is different...
			switch(change.kind) {
				case 'A':
					// Array was modified...
					// it will be an array...
					applyArrayChange(arr[index], change.index, change.item);
					break;
				case 'D':
					// Item was deleted...
					arr = arrayRemove(arr, index);
					break;
				case 'E':
				case 'N':
					// Item was edited or is new...
					arr[index] = change.rhs;
					break;
			}
		}
		return arr;
	}

	function applyChange(target, source, change) {
		if (!checkForDiff(change)) {
			throw new TypeError('[Object] Required properties on change are missing');
		}
		if (target && source && change) {
			var it = target, i, u;
			u = change.path.length - 1;
			for(i = 0; i < u; i++){
				if (typeof it[change.path[i]] === 'undefined') {
					it[change.path[i]] = {};
				}
				it = it[change.path[i]];
			}
			switch(change.kind) {
				case 'A':
					// Array was modified...
					// it will be an array...
					applyArrayChange(it[change.path[i]], change.index, change.item);
					break;
				case 'D':
					// Item was deleted...
					delete it[change.path[i]];
					break;
				case 'E':
				case 'N':
					// Item was edited or is new...
					it[change.path[i]] = change.rhs;
					break;
				}
			}
		}

	function applyDiff(target, source, filter) {
		if (target && source) {
			var onChange = function(change) {
				if (!filter || filter(target, source, change)) {
					applyChange(target, source, change);
				}
			};
			deepDiff(target, source, onChange);
		}
	}

	Object.defineProperties(accumulateDiff, {

		diff: { value: accumulateDiff, enumerable:true },
		observableDiff: { value: deepDiff, enumerable:true },
		applyDiff: { value: applyDiff, enumerable:true },
		applyChange: { value: applyChange, enumerable:true },
		isConflict: { get: function() { return 'undefined' !== typeof conflict; }, enumerable: true },
		noConflict: {
			value: function () {
				if (conflictResolution) {
					conflictResolution.forEach(function (it) { it(); });
					conflictResolution = null;
				}
				return accumulateDiff;
			},
			enumerable: true
		}
	});

	if (typeof module != 'undefined' && module && typeof exports == 'object' && exports && module.exports === exports) {
		module.exports = accumulateDiff; // nodejs
	} else {
		$scope.DeepDiff = accumulateDiff; // other... browser?
	}
}());

<commit_msg>Revert "Changed check for required properties on `change`"<commit_after>;(function(undefined) {
	"use strict";

	var $scope
	, conflict, conflictResolution = [];
	if (typeof global == 'object' && global) {
		$scope = global;
	} else if (typeof window !== 'undefined'){
		$scope = window;
	} else {
		$scope = {};
	}
	conflict = $scope.DeepDiff;
	if (conflict) {
		conflictResolution.push(
			function() {
				if ('undefined' !== typeof conflict && $scope.DeepDiff === accumulateDiff) {
					$scope.DeepDiff = conflict;
					conflict = undefined;
				}
			});
	}

	// nodejs compatible on server side and in the browser.
  function inherits(ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  }

  function Diff(kind, path) {
  	Object.defineProperty(this, 'kind', { value: kind, enumerable: true });
  	if (path && path.length) {
  		Object.defineProperty(this, 'path', { value: path, enumerable: true });
  	}
  }

  function DiffEdit(path, origin, value) {
  	DiffEdit.super_.call(this, 'E', path);
  	Object.defineProperty(this, 'lhs', { value: origin, enumerable: true });
  	Object.defineProperty(this, 'rhs', { value: value, enumerable: true });
  }
  inherits(DiffEdit, Diff);

  function DiffNew(path, value) {
  	DiffNew.super_.call(this, 'N', path);
  	Object.defineProperty(this, 'rhs', { value: value, enumerable: true });
  }
  inherits(DiffNew, Diff);

  function DiffDeleted(path, value) {
  	DiffDeleted.super_.call(this, 'D', path);
  	Object.defineProperty(this, 'lhs', { value: value, enumerable: true });
  }
  inherits(DiffDeleted, Diff);

  function DiffArray(path, index, item) {
  	DiffArray.super_.call(this, 'A', path);
  	Object.defineProperty(this, 'index', { value: index, enumerable: true });
  	Object.defineProperty(this, 'item', { value: item, enumerable: true });
  }
  inherits(DiffArray, Diff);

  function arrayRemove(arr, from, to) {
  	var rest = arr.slice((to || from) + 1 || arr.length);
  	arr.length = from < 0 ? arr.length + from : from;
  	arr.push.apply(arr, rest);
  	return arr;
  }

  function deepDiff(lhs, rhs, changes, path, key, stack) {
  	path = path || [];
  	var currentPath = path.slice(0);
  	if (key) { currentPath.push(key); }
  	var ltype = typeof lhs;
  	var rtype = typeof rhs;
  	if (ltype === 'undefined') {
  		if (rtype !== 'undefined') {
  			changes(new DiffNew(currentPath, rhs ));
  		}
  	} else if (rtype === 'undefined') {
  		changes(new DiffDeleted(currentPath, lhs));
  	} else if (ltype !== rtype) {
  		changes(new DiffEdit(currentPath, lhs, rhs));
  	} else if (lhs instanceof Date && rhs instanceof Date && ((lhs-rhs) != 0) ) {
  		changes(new DiffEdit(currentPath, lhs, rhs));
  	} else if (ltype === 'object' && lhs != null && rhs != null) {
  		stack = stack || [];
  		if (stack.indexOf(lhs) < 0) {
  			stack.push(lhs);
  			if (Array.isArray(lhs)) {
  				var i
  				, len = lhs.length
  				, ea = function(d) {
  					changes(new DiffArray(currentPath, i, d));
  				};
  				for(i = 0; i < lhs.length; i++) {
  					if (i >= rhs.length) {
  						changes(new DiffArray(currentPath, i, new DiffDeleted(undefined, lhs[i])));
  					} else {
  						deepDiff(lhs[i], rhs[i], ea, [], null, stack);
  					}
  				}
  				while(i < rhs.length) {
  					changes(new DiffArray(currentPath, i, new DiffNew(undefined, rhs[i++])));
  				}
  			} else {
  				var akeys = Object.keys(lhs);
  				var pkeys = Object.keys(rhs);
  				akeys.forEach(function(k) {
  					var i = pkeys.indexOf(k);
  					if (i >= 0) {
  						deepDiff(lhs[k], rhs[k], changes, currentPath, k, stack);
  						pkeys = arrayRemove(pkeys, i);
  					} else {
  						deepDiff(lhs[k], undefined, changes, currentPath, k, stack);
  					}
  				});
  				pkeys.forEach(function(k) {
  					deepDiff(undefined, rhs[k], changes, currentPath, k, stack);
  				});
  			}
  			stack.length = stack.length - 1;
  		}
  	} else if (lhs !== rhs) {
  		changes(new DiffEdit(currentPath, lhs, rhs));
  	}
  }

  function accumulateDiff(lhs, rhs, accum) {
  	accum = accum || [];
  	deepDiff(lhs, rhs, function(diff) {
  		if (diff) {
  			accum.push(diff);
  		}
  	});
  	return (accum.length) ? accum : undefined;
  }

	function applyArrayChange(arr, index, change) {
		if (change.path && change.path.length) {
			// the structure of the object at the index has changed...
			var it = arr[index], i, u = change.path.length - 1;
			for(i = 0; i < u; i++){
				it = it[change.path[i]];
			}
			switch(change.kind) {
				case 'A':
					// Array was modified...
					// it will be an array...
					applyArrayChange(it[change.path[i]], change.index, change.item);
					break;
				case 'D':
					// Item was deleted...
					delete it[change.path[i]];
					break;
				case 'E':
				case 'N':
					// Item was edited or is new...
					it[change.path[i]] = change.rhs;
					break;
			}
		} else {
			// the array item is different...
			switch(change.kind) {
				case 'A':
					// Array was modified...
					// it will be an array...
					applyArrayChange(arr[index], change.index, change.item);
					break;
				case 'D':
					// Item was deleted...
					arr = arrayRemove(arr, index);
					break;
				case 'E':
				case 'N':
					// Item was edited or is new...
					arr[index] = change.rhs;
					break;
			}
		}
		return arr;
	}

	function applyChange(target, source, change) {
		if (!(change instanceof Diff)) {
			throw new TypeError('[Object] change must be instanceof Diff');
		}
		if (target && source && change) {
			var it = target, i, u;
			u = change.path.length - 1;
			for(i = 0; i < u; i++){
				if (typeof it[change.path[i]] === 'undefined') {
					it[change.path[i]] = {};
				}
				it = it[change.path[i]];
			}
			switch(change.kind) {
				case 'A':
					// Array was modified...
					// it will be an array...
					applyArrayChange(it[change.path[i]], change.index, change.item);
					break;
				case 'D':
					// Item was deleted...
					delete it[change.path[i]];
					break;
				case 'E':
				case 'N':
					// Item was edited or is new...
					it[change.path[i]] = change.rhs;
					break;
				}
			}
		}

	function applyDiff(target, source, filter) {
		if (target && source) {
			var onChange = function(change) {
				if (!filter || filter(target, source, change)) {
					applyChange(target, source, change);
				}
			};
			deepDiff(target, source, onChange);
		}
	}

	Object.defineProperties(accumulateDiff, {

		diff: { value: accumulateDiff, enumerable:true },
		observableDiff: { value: deepDiff, enumerable:true },
		applyDiff: { value: applyDiff, enumerable:true },
		applyChange: { value: applyChange, enumerable:true },
		isConflict: { get: function() { return 'undefined' !== typeof conflict; }, enumerable: true },
		noConflict: {
			value: function () {
				if (conflictResolution) {
					conflictResolution.forEach(function (it) { it(); });
					conflictResolution = null;
				}
				return accumulateDiff;
			},
			enumerable: true
		}
	});

	if (typeof module != 'undefined' && module && typeof exports == 'object' && exports && module.exports === exports) {
		module.exports = accumulateDiff; // nodejs
	} else {
		$scope.DeepDiff = accumulateDiff; // other... browser?
	}
}());

<|endoftext|>


<commit_before>'use strict'

function checkType (fodselsnummer) {
  return parseInt(fodselsnummer[0], 10) > 3 ? 'D' : 'F'
}

module.exports = (fodselsnummer, type) => {
  if (fodselsnummer.length !== 11) {
    throw new Error('Too short. Expected length of 11.')
  }

  var day = fodselsnummer.substr(0, 2)
  var month = fodselsnummer.substr(2, 2)
  var year = fodselsnummer.substr(4, 2)
  var individsiffer = fodselsnummer.substr(6, 3)
  var kontrollsiffer1 = parseInt(fodselsnummer.substr(9, 1), 10)
  var kontrollsiffer2 = parseInt(fodselsnummer.substr(10, 1), 10)

  var d1 = parseInt(day.substr(0, 1), 10)
  var d2 = parseInt(day.substr(1, 1), 10)
  var m1 = parseInt(month.substr(0, 1), 10)
  var m2 = parseInt(month.substr(1, 1), 10)
  var a1 = parseInt(year.substr(0, 1), 10)
  var a2 = parseInt(year.substr(1, 1), 10)
  var i1 = parseInt(individsiffer.substr(0, 1), 10)
  var i2 = parseInt(individsiffer.substr(1, 1), 10)
  var i3 = parseInt(individsiffer.substr(2, 1), 10)
  var k1 = 11 - (((3 * d1) + (7 * d2) + (6 * m1) + m2 + (8 * a1) +
           (9 * a2) + (4 * i1) + (5 * i2) + (2 * i3)) % 11)
  var u1 = k1 === 11 ? 0 : k1
  var k2 = 11 - (((5 * d1) + (4 * d2) + (3 * m1) + (2 * m2) + (7 * a1) +
           (6 * a2) + (5 * i1) + (4 * i2) + (3 * i3) + (2 * u1)) % 11)
  var u2 = k2 === 11 ? 0 : k2

  const result = u1 === kontrollsiffer1 && u2 === kontrollsiffer2

  return type && result !== false ? checkType(fodselsnummer) : result
}
<commit_msg>Replace fat arrow with function syntax<commit_after>'use strict'

function checkType (fodselsnummer) {
  return parseInt(fodselsnummer[0], 10) > 3 ? 'D' : 'F'
}

module.exports = function (fodselsnummer, type) {
  if (fodselsnummer.length !== 11) {
    throw new Error('Too short. Expected length of 11.')
  }

  var day = fodselsnummer.substr(0, 2)
  var month = fodselsnummer.substr(2, 2)
  var year = fodselsnummer.substr(4, 2)
  var individsiffer = fodselsnummer.substr(6, 3)
  var kontrollsiffer1 = parseInt(fodselsnummer.substr(9, 1), 10)
  var kontrollsiffer2 = parseInt(fodselsnummer.substr(10, 1), 10)

  var d1 = parseInt(day.substr(0, 1), 10)
  var d2 = parseInt(day.substr(1, 1), 10)
  var m1 = parseInt(month.substr(0, 1), 10)
  var m2 = parseInt(month.substr(1, 1), 10)
  var a1 = parseInt(year.substr(0, 1), 10)
  var a2 = parseInt(year.substr(1, 1), 10)
  var i1 = parseInt(individsiffer.substr(0, 1), 10)
  var i2 = parseInt(individsiffer.substr(1, 1), 10)
  var i3 = parseInt(individsiffer.substr(2, 1), 10)
  var k1 = 11 - (((3 * d1) + (7 * d2) + (6 * m1) + m2 + (8 * a1) +
           (9 * a2) + (4 * i1) + (5 * i2) + (2 * i3)) % 11)
  var u1 = k1 === 11 ? 0 : k1
  var k2 = 11 - (((5 * d1) + (4 * d2) + (3 * m1) + (2 * m2) + (7 * a1) +
           (6 * a2) + (5 * i1) + (4 * i2) + (3 * i3) + (2 * u1)) % 11)
  var u2 = k2 === 11 ? 0 : k2

  const result = u1 === kontrollsiffer1 && u2 === kontrollsiffer2

  return type && result !== false ? checkType(fodselsnummer) : result
}
<|endoftext|>


<commit_before>'use strict'

module.exports = [
  '0.0.1'
, '0.0.2'
, '0.0.3'
, '0.0.4'
, '0.0.5'
, '0.0.6'
, '0.1.0'
, '0.1.1'
, '0.1.2'
, '0.1.3'
, '0.1.4'
, '0.1.5'
, '0.1.6'
, '0.1.7'
, '0.1.8'
, '0.1.9'
, '0.1.10'
, '0.1.11'
, '0.1.12'
, '0.1.13'
, '0.1.14'
, '0.1.15'
, '0.1.16'
, '0.1.17'
, '0.1.18'
, '0.1.19'
, '0.1.20'
, '0.1.21'
, '0.1.22'
, '0.1.23'
, '0.1.24'
, '0.1.25'
, '0.1.26'
, '0.1.27'
, '0.1.28'
, '0.1.29'
, '0.1.30'
, '0.1.31'
, '0.1.32'
, '0.1.33'
, '0.1.90'
, '0.1.91'
, '0.1.92'
, '0.1.93'
, '0.1.94'
, '0.1.95'
, '0.1.96'
, '0.1.97'
, '0.1.98'
, '0.1.99'
, '0.1.100'
, '0.1.101'
, '0.1.102'
, '0.1.103'
, '0.1.104'
, '0.2.0'
, '0.2.1'
, '0.2.2'
, '0.2.3'
, '0.2.4'
, '0.2.5'
, '0.2.6'
, '0.3.0'
, '0.3.1'
, '0.3.2'
, '0.3.3'
, '0.3.4'
, '0.3.5'
, '0.3.6'
, '0.3.7'
, '0.3.8'
, '0.4.0'
, '0.4.1'
, '0.4.2'
, '0.4.3'
, '0.4.4'
, '0.4.5'
, '0.4.6'
, '0.4.7'
, '0.4.8'
, '0.4.9'
, '0.4.10'
, '0.4.11'
, '0.4.12'
, '0.5.0'
, '0.5.1'
, '0.5.2'
, '0.5.3'
, '0.5.4'
, '0.5.5'
, '0.5.6'
, '0.5.7'
, '0.5.8'
, '0.5.9'
, '0.5.10'
, '0.6.0'
, '0.6.1'
, '0.6.2'
, '0.6.3'
, '0.6.4'
, '0.6.5'
, '0.6.6'
, '0.6.7'
, '0.6.8'
, '0.6.9'
, '0.6.10'
, '0.6.11'
, '0.6.12'
, '0.6.13'
, '0.6.14'
, '0.6.15'
, '0.6.16'
, '0.6.17'
, '0.6.18'
, '0.6.19'
, '0.6.20'
, '0.6.21'
, '0.7.0'
, '0.7.1'
, '0.7.2'
, '0.7.3'
, '0.7.4'
, '0.7.5'
, '0.7.6'
, '0.7.7'
, '0.7.8'
, '0.7.9'
, '0.7.10'
, '0.7.11'
, '0.7.12'
, '0.8.0'
, '0.8.1'
, '0.8.2'
, '0.8.3'
, '0.8.4'
, '0.8.5'
, '0.8.6'
, '0.8.7'
, '0.8.8'
, '0.8.9'
, '0.8.10'
, '0.8.11'
, '0.8.12'
, '0.8.13'
, '0.8.14'
, '0.8.15'
, '0.8.16'
, '0.8.17'
, '0.8.18'
, '0.8.19'
, '0.8.20'
, '0.8.21'
, '0.8.22'
, '0.8.23'
, '0.8.24'
, '0.8.25'
, '0.8.26'
, '0.8.27'
, '0.8.28'
, '0.9.0'
, '0.9.1'
, '0.9.2'
, '0.9.3'
, '0.9.4'
, '0.9.5'
, '0.9.6'
, '0.9.7'
, '0.9.8'
, '0.9.9'
, '0.9.10'
, '0.9.11'
, '0.9.12'
, '0.10.0'
, '0.10.1'
, '0.10.2'
, '0.10.3'
, '0.10.4'
, '0.10.5'
, '0.10.6'
, '0.10.7'
, '0.10.8'
, '0.10.9'
, '0.10.10'
, '0.10.11'
, '0.10.12'
, '0.10.13'
, '0.10.14'
, '0.10.15'
, '0.10.16'
, '0.10.17'
, '0.10.18'
, '0.10.19'
, '0.10.20'
, '0.10.21'
, '0.10.22'
, '0.10.23'
, '0.10.24'
, '0.10.25'
, '0.10.26'
, '0.10.27'
, '0.10.28'
, '0.10.29'
, '0.10.30'
, '0.10.31'
, '0.10.32'
, '0.10.33'
, '0.10.34'
, '0.10.35'
, '0.10.36'
, '0.10.37'
, '0.10.38'
, '0.10.39'
, '0.10.40'
, '0.10.41'
, '0.11.0'
, '0.11.1'
, '0.11.2'
, '0.11.3'
, '0.11.4'
, '0.11.5'
, '0.11.6'
, '0.11.7'
, '0.11.8'
, '0.11.9'
, '0.11.10'
, '0.11.11'
, '0.11.12'
, '0.11.13'
, '0.11.14'
, '0.11.15'
, '0.11.16'
, '0.12.0'
, '0.12.1'
, '0.12.2'
, '0.12.3'
, '0.12.4'
, '0.12.5'
, '0.12.6'
, '0.12.7'
, '0.12.8'
, '0.12.9'
, '1.0.0'
, '1.0.1'
, '1.0.2'
, '1.0.3'
, '1.0.4'
, '1.1.0'
, '1.2.0'
, '1.3.0'
, '1.4.1'
, '1.4.2'
, '1.4.3'
, '1.5.0'
, '1.5.1'
, '1.6.0'
, '1.6.1'
, '1.6.2'
, '1.6.3'
, '1.6.4'
, '1.7.0'
, '1.7.1'
, '1.8.1'
, '1.8.2'
, '1.8.3'
, '1.8.4'
, '2.0.0'
, '2.0.1'
, '2.0.2'
, '2.1.0'
, '2.2.0'
, '2.2.1'
, '2.3.0'
, '2.3.1'
, '2.3.2'
, '2.3.3'
, '2.3.4'
, '2.4.0'
, '2.5.0'
, '3.0.0'
, '3.1.0'
, '3.2.0'
, '3.3.0'
, '3.3.1'
, '4.0.0'
, '4.1.0'
, '4.1.1'
, '4.1.2'
, '4.2.0'
, '4.2.1'
, '4.2.2'
, '4.2.3'
, '4.2.4'
, '5.0.0'
, '5.1.0'
, '5.1.1'
, '5.2.0'
, '5.3.0'
, '5.4.0'
]
<commit_msg>add version 5.4.1<commit_after>'use strict'

module.exports = [
  '0.0.1'
, '0.0.2'
, '0.0.3'
, '0.0.4'
, '0.0.5'
, '0.0.6'
, '0.1.0'
, '0.1.1'
, '0.1.2'
, '0.1.3'
, '0.1.4'
, '0.1.5'
, '0.1.6'
, '0.1.7'
, '0.1.8'
, '0.1.9'
, '0.1.10'
, '0.1.11'
, '0.1.12'
, '0.1.13'
, '0.1.14'
, '0.1.15'
, '0.1.16'
, '0.1.17'
, '0.1.18'
, '0.1.19'
, '0.1.20'
, '0.1.21'
, '0.1.22'
, '0.1.23'
, '0.1.24'
, '0.1.25'
, '0.1.26'
, '0.1.27'
, '0.1.28'
, '0.1.29'
, '0.1.30'
, '0.1.31'
, '0.1.32'
, '0.1.33'
, '0.1.90'
, '0.1.91'
, '0.1.92'
, '0.1.93'
, '0.1.94'
, '0.1.95'
, '0.1.96'
, '0.1.97'
, '0.1.98'
, '0.1.99'
, '0.1.100'
, '0.1.101'
, '0.1.102'
, '0.1.103'
, '0.1.104'
, '0.2.0'
, '0.2.1'
, '0.2.2'
, '0.2.3'
, '0.2.4'
, '0.2.5'
, '0.2.6'
, '0.3.0'
, '0.3.1'
, '0.3.2'
, '0.3.3'
, '0.3.4'
, '0.3.5'
, '0.3.6'
, '0.3.7'
, '0.3.8'
, '0.4.0'
, '0.4.1'
, '0.4.2'
, '0.4.3'
, '0.4.4'
, '0.4.5'
, '0.4.6'
, '0.4.7'
, '0.4.8'
, '0.4.9'
, '0.4.10'
, '0.4.11'
, '0.4.12'
, '0.5.0'
, '0.5.1'
, '0.5.2'
, '0.5.3'
, '0.5.4'
, '0.5.5'
, '0.5.6'
, '0.5.7'
, '0.5.8'
, '0.5.9'
, '0.5.10'
, '0.6.0'
, '0.6.1'
, '0.6.2'
, '0.6.3'
, '0.6.4'
, '0.6.5'
, '0.6.6'
, '0.6.7'
, '0.6.8'
, '0.6.9'
, '0.6.10'
, '0.6.11'
, '0.6.12'
, '0.6.13'
, '0.6.14'
, '0.6.15'
, '0.6.16'
, '0.6.17'
, '0.6.18'
, '0.6.19'
, '0.6.20'
, '0.6.21'
, '0.7.0'
, '0.7.1'
, '0.7.2'
, '0.7.3'
, '0.7.4'
, '0.7.5'
, '0.7.6'
, '0.7.7'
, '0.7.8'
, '0.7.9'
, '0.7.10'
, '0.7.11'
, '0.7.12'
, '0.8.0'
, '0.8.1'
, '0.8.2'
, '0.8.3'
, '0.8.4'
, '0.8.5'
, '0.8.6'
, '0.8.7'
, '0.8.8'
, '0.8.9'
, '0.8.10'
, '0.8.11'
, '0.8.12'
, '0.8.13'
, '0.8.14'
, '0.8.15'
, '0.8.16'
, '0.8.17'
, '0.8.18'
, '0.8.19'
, '0.8.20'
, '0.8.21'
, '0.8.22'
, '0.8.23'
, '0.8.24'
, '0.8.25'
, '0.8.26'
, '0.8.27'
, '0.8.28'
, '0.9.0'
, '0.9.1'
, '0.9.2'
, '0.9.3'
, '0.9.4'
, '0.9.5'
, '0.9.6'
, '0.9.7'
, '0.9.8'
, '0.9.9'
, '0.9.10'
, '0.9.11'
, '0.9.12'
, '0.10.0'
, '0.10.1'
, '0.10.2'
, '0.10.3'
, '0.10.4'
, '0.10.5'
, '0.10.6'
, '0.10.7'
, '0.10.8'
, '0.10.9'
, '0.10.10'
, '0.10.11'
, '0.10.12'
, '0.10.13'
, '0.10.14'
, '0.10.15'
, '0.10.16'
, '0.10.17'
, '0.10.18'
, '0.10.19'
, '0.10.20'
, '0.10.21'
, '0.10.22'
, '0.10.23'
, '0.10.24'
, '0.10.25'
, '0.10.26'
, '0.10.27'
, '0.10.28'
, '0.10.29'
, '0.10.30'
, '0.10.31'
, '0.10.32'
, '0.10.33'
, '0.10.34'
, '0.10.35'
, '0.10.36'
, '0.10.37'
, '0.10.38'
, '0.10.39'
, '0.10.40'
, '0.10.41'
, '0.11.0'
, '0.11.1'
, '0.11.2'
, '0.11.3'
, '0.11.4'
, '0.11.5'
, '0.11.6'
, '0.11.7'
, '0.11.8'
, '0.11.9'
, '0.11.10'
, '0.11.11'
, '0.11.12'
, '0.11.13'
, '0.11.14'
, '0.11.15'
, '0.11.16'
, '0.12.0'
, '0.12.1'
, '0.12.2'
, '0.12.3'
, '0.12.4'
, '0.12.5'
, '0.12.6'
, '0.12.7'
, '0.12.8'
, '0.12.9'
, '1.0.0'
, '1.0.1'
, '1.0.2'
, '1.0.3'
, '1.0.4'
, '1.1.0'
, '1.2.0'
, '1.3.0'
, '1.4.1'
, '1.4.2'
, '1.4.3'
, '1.5.0'
, '1.5.1'
, '1.6.0'
, '1.6.1'
, '1.6.2'
, '1.6.3'
, '1.6.4'
, '1.7.0'
, '1.7.1'
, '1.8.1'
, '1.8.2'
, '1.8.3'
, '1.8.4'
, '2.0.0'
, '2.0.1'
, '2.0.2'
, '2.1.0'
, '2.2.0'
, '2.2.1'
, '2.3.0'
, '2.3.1'
, '2.3.2'
, '2.3.3'
, '2.3.4'
, '2.4.0'
, '2.5.0'
, '3.0.0'
, '3.1.0'
, '3.2.0'
, '3.3.0'
, '3.3.1'
, '4.0.0'
, '4.1.0'
, '4.1.1'
, '4.1.2'
, '4.2.0'
, '4.2.1'
, '4.2.2'
, '4.2.3'
, '4.2.4'
, '5.0.0'
, '5.1.0'
, '5.1.1'
, '5.2.0'
, '5.3.0'
, '5.4.0'
, '5.4.1'
]
<|endoftext|>


<commit_before>var events = require('events');
var fs = require('fs');
var path = require('path'), basename = path.basename;
var util = require('util');
var camelcase = require('cli-util').camelcase;

var commands = [
  'name',
  'key',
  'id'
]

var properties = commands.concat([
  'optional',
  'multiple',
  'value',
  'converter',
  'extra'
]);

var delimiter = /[ ,|]+/;
var methods = ['description', 'action'];
var required = /^</;
var multiple = /\.\.\./;

function initialize(options, properties) {
  for(var z in options) {
    if(~properties.indexOf(z)) this[z] = options[z];
  }
  if(options.description) this._description = options.description;
  if(options.action) this._action = options.action;
}

function define(obj, name, value, writable) {
  writable = writable || false;
  Object.defineProperty(obj, name,
    {
      enumerable: false,
      configurable: false,
      writable: writable,
      value: value
    }
  );
}

/**
 *  Abstract super class.
 *
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param options The argument options or conversion function.
 */
var Argument = function(name, description, options) {
  if(typeof name == 'object') options = name;
  define(this, '_name', name || '', true);
  define(this, '_description', description || '', true);
  define(this, '_key', '', true);
  define(this, '_id', '', true);
  define(this, '_optional', true, true);
  define(this, '_multiple', false, true);
  define(this, '_value', undefined, true);
  define(this, '_converter', undefined, true);
  define(this, '_action', undefined, true);
  define(this, '_extra', undefined, true);
  define(this, '_names', undefined, true);

  //this._name = name || '';
  //this._description = description || '';
  //this._key = '';
  //this._id = '';
  //this._optional = true;
  //this._multiple = false;
  //this._value;
  //this._converter = null;
  //this._action = null;
  //this._extra = '';
  //

  if(options === JSON) {
    this._converter = JSON;
  }else if(options && (typeof options == 'object') && !Array.isArray(options)) {
    initialize.call(this, options, properties);
  }else if((typeof options == 'function') || this.isFunctionArray(options)){
    this._converter = options;
    if(arguments.length > 3 && this._value === undefined) {
      this._value = arguments[3];
    }
  }else {
    this._value = options;
    if(arguments.length > 3
      && (typeof(arguments[3]) == 'function'
      || this.isFunctionArray(options))) {
      this._converter = arguments[3];
    }
  }
  this._names = this._name.split(delimiter);
  for(var i = 0;i < this._names.length;i++) {
    if(/^(\[|<)/.test(this._names[i])) {
      this._extra = this._names.slice(i).join(' ');
      this._names = this._names.slice(0, i);
      break;
    }
  }
  if(required.test(this._extra)) {
    this._optional = false;
  }
  if(multiple.test(this._extra)) {
    this._multiple = true;
  }
  this._key = this.getKey();
}

util.inherits(Argument, events.EventEmitter);

/**
 *  Determines whether an array consists solely of functions
 *  allowing for the special case JSON.
 *
 *  @param arr The array candidate.
 */
Argument.prototype.isFunctionArray = function(arr) {
  if(!Array.isArray(arr)) return false;
  var i, item;
  for(i = 0;i < arr.length;i++) {
    item = arr[i];
    if(item !== JSON && !(typeof item == 'function')) return false;
  }
  return true;
}

/**
 *  Retrieve the key for the option.
 */
Argument.prototype.getKey = function() {
  var k, i, v;
  for(i = 0;i < this._names.length;i++) {
    v = this._names[i];
    k = camelcase(v.replace(/^-+/, ''));
    if(/^--[^-]/.test(v)) {
      return k;
    }
  }
  return k;
}

Argument.prototype.action = function() {
  return this._action;
}

Argument.prototype.__defineGetter__('names', function() {
  return this._names;
});

properties.forEach(function(prop) {
  Argument.prototype.__defineGetter__(prop, function() {
    return this['_' + prop];
  });
  Argument.prototype.__defineSetter__(prop, function(value) {
    this['_' + prop] = value;
  });
});

/**
 *  Represents an option argument.
 */
var Option = function() {
  Argument.apply(this, arguments);
}

util.inherits(Option, Argument);

/**
 *  Represents a flag argument.
 */
var Flag = function() {
  Argument.apply(this, arguments);
  this._value = false;
}

util.inherits(Flag, Argument);

/**
 *  Represents a command argument.
 */
var Command = function(name, description, options) {
  if(typeof name == 'object') options = name;
  this._commands = {};
  this._arguments = {};
  this.args = null;
  this._name = name || '';
  this._description = description || '';
  this._key = '';
  this._id = '';
  this._action = null;
  if((typeof options == 'object')) {
    initialize.call(this, options, commands);
  }
  this._names = this.name.split(delimiter);
  this._key = this._names[0];
}

util.inherits(Command, events.EventEmitter);

Command.prototype.__defineGetter__('names', function() {
  return this._names;
});

commands.forEach(function(prop) {
  Command.prototype.__defineGetter__(prop, function() {
    return this['_' + prop];
  });
  Command.prototype.__defineSetter__(prop, function(value) {
    this['_' + prop] = value;
  });
});

methods.forEach(function(prop) {
  Command.prototype[prop] = function(value) {
    var key = '_' + prop;
    if(value === undefined) return this[key];
    this[key] = value;
    return this;
  }
});

/**
 *  Define a command argument.
 */
Command.prototype.command = function(name, description, options) {
  var opt = (name instanceof Command) ? name
    : new Command(name, description, options);
  this._commands[opt.key] = opt;
  return description ? this : opt;
}

/**
 *  Define an option argument.
 */
Command.prototype.option = function(name, description, options, coerce, value) {
  var clazz = Option;
  if(typeof name == 'string' && !/[<\[]/.test(name)) {
    clazz = Flag;
  }
  var opt = (name instanceof clazz) ? name
    : new clazz(name, description, options, coerce, value);
  this._arguments[opt.key] = opt;
  return this;
}

/**
 *  Define a flag argument.
 */
Command.prototype.flag = function(name, description, options, coerce, value) {
  var opt = (name instanceof Flag) ? name
    : new Flag(name, description, options, coerce, value);
  this._arguments[opt.key] = opt;
  return this;
}

/**
 *  Represents the program.
 */
var Program = function() {
  Command.apply(this, arguments);
  this._version = '0.0.1';
  this._author = null;
  this._usage = null;
}

util.inherits(Program, Command);

/**
 *  Set the program usage string.
 *
 *  @param usage Program usage.
 */
Program.prototype.usage = function(usage) {
  this._usage = usage;
  return this;
}

/**
 *  Adds a version flag to the program.
 *
 *  @param version A specific version number.
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
Program.prototype.version = function(version, name, description, action) {
  if(typeof version == 'function') {
    action = version;
    version = null;
  }
  if(version) this._version = version;
  name = name || '-V --version';
  var flag = new Flag(
    name, description || 'print the program version', {action: action});
  flag.key = 'version';
  this.flag(flag);
  return this;
}

/**
 *  Adds a help flag to the program.
 *
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
Program.prototype.help = function(name, description, action) {
  if(typeof name == 'function') {
    action = name;
    name = null;
  }
  name = name || '-h --help';
  var flag = new Flag(
    name, description || 'print usage information', {action: action});
  flag.key = 'help';
  this.flag(flag);
  return this;
}

/**
 *  Initialize the root command from a package.json
 *  project descripton.
 *
 *  @param package The path to package.json.
 *  @param name A specific name for the root command (optional).
 *  @param description A specific description for the root command (optional).
 */
function create(package, name, description) {
  var root = new Program(basename(process.argv[1]));
  properties.forEach(function(prop) {
    if(prop != 'name' && prop != 'description') delete root['_' + prop];
  })
  if(fs.existsSync(package)) {
    try {
      var pkg = root._package = require(package);
      root._version = pkg.version;
      if(pkg.author) root._author = pkg.author;
      if(pkg.description) root._description = pkg.description;
    }catch(e) {
      throw new Error(util.format(
        'package parse error %s (malformed json)', package));
    }
  }
  if(name) root.name = name;
  if(description) root.description = description;
  return root;
}

module.exports = create;
module.exports.Program = Program;
module.exports.Command = Command;
module.exports.Option = Option;
module.exports.Flag = Flag;
<commit_msg>Make Command private properties non-enumerable.<commit_after>var events = require('events');
var fs = require('fs');
var path = require('path'), basename = path.basename;
var util = require('util');
var camelcase = require('cli-util').camelcase;

var commands = [
  'name',
  'key',
  'id'
]

var properties = commands.concat([
  'optional',
  'multiple',
  'value',
  'converter',
  'extra'
]);

var delimiter = /[ ,|]+/;
var methods = ['description', 'action'];
var required = /^</;
var multiple = /\.\.\./;

function initialize(options, properties) {
  for(var z in options) {
    if(~properties.indexOf(z)) this[z] = options[z];
  }
  if(options.description) this._description = options.description;
  if(options.action) this._action = options.action;
}

function define(obj, name, value, writable) {
  writable = writable || false;
  Object.defineProperty(obj, name,
    {
      enumerable: false,
      configurable: false,
      writable: writable,
      value: value
    }
  );
}

/**
 *  Abstract super class.
 *
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param options The argument options or conversion function.
 */
var Argument = function(name, description, options) {
  if(typeof name == 'object') options = name;
  define(this, '_name', name || '', true);
  define(this, '_description', description || '', true);
  define(this, '_key', '', true);
  define(this, '_id', '', true);
  define(this, '_optional', true, true);
  define(this, '_multiple', false, true);
  define(this, '_value', undefined, true);
  define(this, '_converter', undefined, true);
  define(this, '_action', undefined, true);
  define(this, '_extra', undefined, true);
  define(this, '_names', undefined, true);

  if(options === JSON) {
    this._converter = JSON;
  }else if(options && (typeof options == 'object') && !Array.isArray(options)) {
    initialize.call(this, options, properties);
  }else if((typeof options == 'function') || this.isFunctionArray(options)){
    this._converter = options;
    if(arguments.length > 3 && this._value === undefined) {
      this._value = arguments[3];
    }
  }else {
    this._value = options;
    if(arguments.length > 3
      && (typeof(arguments[3]) == 'function'
      || this.isFunctionArray(options))) {
      this._converter = arguments[3];
    }
  }
  this._names = this._name.split(delimiter);
  for(var i = 0;i < this._names.length;i++) {
    if(/^(\[|<)/.test(this._names[i])) {
      this._extra = this._names.slice(i).join(' ');
      this._names = this._names.slice(0, i);
      break;
    }
  }
  if(required.test(this._extra)) {
    this._optional = false;
  }
  if(multiple.test(this._extra)) {
    this._multiple = true;
  }
  this._key = this.getKey();
}

util.inherits(Argument, events.EventEmitter);

/**
 *  Determines whether an array consists solely of functions
 *  allowing for the special case JSON.
 *
 *  @param arr The array candidate.
 */
Argument.prototype.isFunctionArray = function(arr) {
  if(!Array.isArray(arr)) return false;
  var i, item;
  for(i = 0;i < arr.length;i++) {
    item = arr[i];
    if(item !== JSON && !(typeof item == 'function')) return false;
  }
  return true;
}

/**
 *  Retrieve the key for the option.
 */
Argument.prototype.getKey = function() {
  var k, i, v;
  for(i = 0;i < this._names.length;i++) {
    v = this._names[i];
    k = camelcase(v.replace(/^-+/, ''));
    if(/^--[^-]/.test(v)) {
      return k;
    }
  }
  return k;
}

Argument.prototype.action = function() {
  return this._action;
}

Argument.prototype.__defineGetter__('names', function() {
  return this._names;
});

properties.forEach(function(prop) {
  Argument.prototype.__defineGetter__(prop, function() {
    return this['_' + prop];
  });
  Argument.prototype.__defineSetter__(prop, function(value) {
    this['_' + prop] = value;
  });
});

/**
 *  Represents an option argument.
 */
var Option = function() {
  Argument.apply(this, arguments);
}

util.inherits(Option, Argument);

/**
 *  Represents a flag argument.
 */
var Flag = function() {
  Argument.apply(this, arguments);
  this._value = false;
}

util.inherits(Flag, Argument);

/**
 *  Represents a command argument.
 */
var Command = function(name, description, options) {
  if(typeof name == 'object') options = name;

  // private
  define(this, '_commands', {}, true);
  define(this, '_arguments', {}, true);
  define(this, '_name', name || '', true);
  define(this, '_description', description || '', true);
  define(this, '_key', '', true);
  define(this, '_id', '', true);
  define(this, '_action', undefined, true);
  define(this, '_names', undefined, true);

  // public
  define(this, 'args', undefined, true);

  if((typeof options == 'object')) {
    initialize.call(this, options, commands);
  }
  this._names = this.name.split(delimiter);
  this._key = this._names[0];
}

util.inherits(Command, events.EventEmitter);

Command.prototype.__defineGetter__('names', function() {
  return this._names;
});

commands.forEach(function(prop) {
  Command.prototype.__defineGetter__(prop, function() {
    return this['_' + prop];
  });
  Command.prototype.__defineSetter__(prop, function(value) {
    this['_' + prop] = value;
  });
});

methods.forEach(function(prop) {
  Command.prototype[prop] = function(value) {
    var key = '_' + prop;
    if(value === undefined) return this[key];
    this[key] = value;
    return this;
  }
});

/**
 *  Define a command argument.
 */
Command.prototype.command = function(name, description, options) {
  var opt = (name instanceof Command) ? name
    : new Command(name, description, options);
  this._commands[opt.key] = opt;
  return description ? this : opt;
}

/**
 *  Define an option argument.
 */
Command.prototype.option = function(name, description, options, coerce, value) {
  var clazz = Option;
  if(typeof name == 'string' && !/[<\[]/.test(name)) {
    clazz = Flag;
  }
  var opt = (name instanceof clazz) ? name
    : new clazz(name, description, options, coerce, value);
  this._arguments[opt.key] = opt;
  return this;
}

/**
 *  Define a flag argument.
 */
Command.prototype.flag = function(name, description, options, coerce, value) {
  var opt = (name instanceof Flag) ? name
    : new Flag(name, description, options, coerce, value);
  this._arguments[opt.key] = opt;
  return this;
}

/**
 *  Represents the program.
 */
var Program = function() {
  Command.apply(this, arguments);
  this._version = '0.0.1';
  this._author = null;
  this._usage = null;
}

util.inherits(Program, Command);

/**
 *  Set the program usage string.
 *
 *  @param usage Program usage.
 */
Program.prototype.usage = function(usage) {
  this._usage = usage;
  return this;
}

/**
 *  Adds a version flag to the program.
 *
 *  @param version A specific version number.
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
Program.prototype.version = function(version, name, description, action) {
  if(typeof version == 'function') {
    action = version;
    version = null;
  }
  if(version) this._version = version;
  name = name || '-V --version';
  var flag = new Flag(
    name, description || 'print the program version', {action: action});
  flag.key = 'version';
  this.flag(flag);
  return this;
}

/**
 *  Adds a help flag to the program.
 *
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
Program.prototype.help = function(name, description, action) {
  if(typeof name == 'function') {
    action = name;
    name = null;
  }
  name = name || '-h --help';
  var flag = new Flag(
    name, description || 'print usage information', {action: action});
  flag.key = 'help';
  this.flag(flag);
  return this;
}

/**
 *  Initialize the root command from a package.json
 *  project descripton.
 *
 *  @param package The path to package.json.
 *  @param name A specific name for the root command (optional).
 *  @param description A specific description for the root command (optional).
 */
function create(package, name, description) {
  var root = new Program(basename(process.argv[1]));
  properties.forEach(function(prop) {
    if(prop != 'name' && prop != 'description') delete root['_' + prop];
  })
  if(fs.existsSync(package)) {
    try {
      var pkg = root._package = require(package);
      root._version = pkg.version;
      if(pkg.author) root._author = pkg.author;
      if(pkg.description) root._description = pkg.description;
    }catch(e) {
      throw new Error(util.format(
        'package parse error %s (malformed json)', package));
    }
  }
  if(name) root.name = name;
  if(description) root.description = description;
  return root;
}

module.exports = create;
module.exports.Program = Program;
module.exports.Command = Command;
module.exports.Option = Option;
module.exports.Flag = Flag;
<|endoftext|>


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

app.set('port', (process.env.PORT || 5000))
app.use(express.static(__dirname + '/public'))

app.get('/', function(request, response) {
  response.send('Hello Quindar!
\n Built 15 via Jenkins')
})

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})
<commit_msg>devops test 16<commit_after>var express = require('express')
var app = express()

app.set('port', (process.env.PORT || 5000))
app.use(express.static(__dirname + '/public'))

app.get('/', function(request, response) {
  response.send('Hello Quindar!
\n Built 16 via Jenkins')
})

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})
<|endoftext|>