<commit_before>'use strict';

var through = require('through2').obj;
var path = require('path');
var checker = require('istanbul-threshold-checker');
var istanbul = require('istanbul');
var gutil = require('gulp-util');
var _ = require('lodash');
var Report = istanbul.Report;
var Collector = istanbul.Collector;
var PluginError = gutil.PluginError;

var PLUGIN_NAME = 'gulp-istanbul';
var COVERAGE_VARIABLE = '$$cov_' + new Date().getTime() + '$$';

var plugin = module.exports = function (opts) {
  opts = opts || {};
  _.defaults(opts, {
    coverageVariable: COVERAGE_VARIABLE,
    instrumenter: istanbul.Instrumenter
  });
  opts.includeUntested = opts.includeUntested === true;

  var instrumenter = new opts.instrumenter(opts);

  return through(function (file, enc, cb) {
    cb = _.once(cb);
    if (!(file.contents instanceof Buffer)) {
      return cb(new PluginError(PLUGIN_NAME, 'streams not supported'));
    }

    instrumenter.instrument(file.contents.toString(), file.path, function (err, code) {
      if (err) {
        return cb(new PluginError(
          PLUGIN_NAME,
          'Unable to parse ' + file.path + '\n\n' + err.message + '\n'
        ));
      }

      file.contents = new Buffer(code);

      // Parse the blank coverage object from the instrumented file and save it
      // to the global coverage variable to enable reporting on non-required
      // files, a workaround for
      // https://github.com/gotwarlost/istanbul/issues/112
      if (opts.includeUntested) {
        var instrumentedSrc = file.contents.toString();
        var covStubRE = /\{.*"path".*"fnMap".*"statementMap".*"branchMap".*\}/g;
        var covStubMatch = covStubRE.exec(instrumentedSrc);
        if (covStubMatch !== null) {
          var covStub = JSON.parse(covStubMatch[0]);
          global[opts.coverageVariable] = global[opts.coverageVariable] || {};
          global[opts.coverageVariable][path.resolve(file.path)] = covStub;
        }
      }

      return cb(err, file);
    });
  });
};

plugin.hookRequire = function (options) {
  var fileMap = {};

  istanbul.hook.unhookRequire();
  istanbul.hook.hookRequire(function (path) {
    return !!fileMap[path];
  }, function (code, path) {
    return fileMap[path];
  }, options);

  return through(function (file, enc, cb) {
    // If the file is already required, delete it from the cache otherwise the covered
    // version will be ignored.
    delete require.cache[path.resolve(file.path)];
    fileMap[file.path] = file.contents.toString();
    return cb();
  });
};

plugin.summarizeCoverage = function (opts) {
  opts = opts || {};
  if (!opts.coverageVariable) opts.coverageVariable = COVERAGE_VARIABLE;

  if (!global[opts.coverageVariable]) throw new Error('no coverage data found, run tests before calling `summarizeCoverage`');

  var collector = new Collector();
  collector.add(global[opts.coverageVariable]);
  return istanbul.utils.summarizeCoverage(collector.getFinalCoverage());
};

plugin.writeReports = function (opts) {
  if (typeof opts === 'string') opts = { dir: opts };
  opts = opts || {};

  var defaultDir = path.join(process.cwd(), 'coverage');
  opts = _.defaults(opts, {
    coverageVariable: COVERAGE_VARIABLE,
    dir: defaultDir,
    reporters: [ 'lcov', 'json', 'text', 'text-summary' ],
    reportOpts: { dir: opts.dir || defaultDir }
  });

  var reporters = opts.reporters.map(function(reporter) {
    if (reporter.TYPE) Report.register(reporter);
    return reporter.TYPE || reporter;
  });

  var invalid = _.difference(reporters, Report.getReportList());
  if (invalid.length) {
    // throw before we start -- fail fast
    throw new PluginError(PLUGIN_NAME, 'Invalid reporters: ' + invalid.join(', '));
  }

  reporters = reporters.map(function (r) {
    var reportOpts = opts.reportOpts[r] || opts.reportOpts;
    return Report.create(r, _.clone(reportOpts));
  });

  var cover = through();

  cover.on('end', function () {
    var collector = new Collector();

    // Revert to an object if there are no matching source files.
    collector.add(global[opts.coverageVariable] || {});

    reporters.forEach(function (report) {
      report.writeReport(collector, true);
    });
  }).resume();

  return cover;
};

plugin.enforceThresholds = function (opts) {
  opts = opts || {};
  opts = _.defaults(opts, {
    coverageVariable: COVERAGE_VARIABLE
  });

  var cover = through();

  cover.on('end', function () {
    var collector = new Collector();

    // Revert to an object if there are no macthing source files.
    collector.add(global[opts.coverageVariable] || {});

    var results = checker.checkFailures(opts.thresholds, collector.getFinalCoverage());
    var criteria = function(type) {
      return (type.global && type.global.failed) || (type.each && type.each.failed);
    };

    if (_.any(results, criteria)) {
      this.emit('error', new PluginError({
        plugin: PLUGIN_NAME,
        message: 'Coverage failed'
      }));
    }

  }).resume();

  return cover;
};
<commit_msg>Added comment to clearify why istanbul should be required after the istanbul-threshold-checker.<commit_after>'use strict';

var through = require('through2').obj;
var path = require('path');
var checker = require('istanbul-threshold-checker');
// Make sure istanbul is `require`d after the istanbul-threshold-checker to use the istanbul version
// defined in this package.json instead of the one defined in istanbul-threshold-checker.
var istanbul = require('istanbul');
var gutil = require('gulp-util');
var _ = require('lodash');
var Report = istanbul.Report;
var Collector = istanbul.Collector;
var PluginError = gutil.PluginError;

var PLUGIN_NAME = 'gulp-istanbul';
var COVERAGE_VARIABLE = '$$cov_' + new Date().getTime() + '$$';

var plugin = module.exports = function (opts) {
  opts = opts || {};
  _.defaults(opts, {
    coverageVariable: COVERAGE_VARIABLE,
    instrumenter: istanbul.Instrumenter
  });
  opts.includeUntested = opts.includeUntested === true;

  var instrumenter = new opts.instrumenter(opts);

  return through(function (file, enc, cb) {
    cb = _.once(cb);
    if (!(file.contents instanceof Buffer)) {
      return cb(new PluginError(PLUGIN_NAME, 'streams not supported'));
    }

    instrumenter.instrument(file.contents.toString(), file.path, function (err, code) {
      if (err) {
        return cb(new PluginError(
          PLUGIN_NAME,
          'Unable to parse ' + file.path + '\n\n' + err.message + '\n'
        ));
      }

      file.contents = new Buffer(code);

      // Parse the blank coverage object from the instrumented file and save it
      // to the global coverage variable to enable reporting on non-required
      // files, a workaround for
      // https://github.com/gotwarlost/istanbul/issues/112
      if (opts.includeUntested) {
        var instrumentedSrc = file.contents.toString();
        var covStubRE = /\{.*"path".*"fnMap".*"statementMap".*"branchMap".*\}/g;
        var covStubMatch = covStubRE.exec(instrumentedSrc);
        if (covStubMatch !== null) {
          var covStub = JSON.parse(covStubMatch[0]);
          global[opts.coverageVariable] = global[opts.coverageVariable] || {};
          global[opts.coverageVariable][path.resolve(file.path)] = covStub;
        }
      }

      return cb(err, file);
    });
  });
};

plugin.hookRequire = function (options) {
  var fileMap = {};

  istanbul.hook.unhookRequire();
  istanbul.hook.hookRequire(function (path) {
    return !!fileMap[path];
  }, function (code, path) {
    return fileMap[path];
  }, options);

  return through(function (file, enc, cb) {
    // If the file is already required, delete it from the cache otherwise the covered
    // version will be ignored.
    delete require.cache[path.resolve(file.path)];
    fileMap[file.path] = file.contents.toString();
    return cb();
  });
};

plugin.summarizeCoverage = function (opts) {
  opts = opts || {};
  if (!opts.coverageVariable) opts.coverageVariable = COVERAGE_VARIABLE;

  if (!global[opts.coverageVariable]) throw new Error('no coverage data found, run tests before calling `summarizeCoverage`');

  var collector = new Collector();
  collector.add(global[opts.coverageVariable]);
  return istanbul.utils.summarizeCoverage(collector.getFinalCoverage());
};

plugin.writeReports = function (opts) {
  if (typeof opts === 'string') opts = { dir: opts };
  opts = opts || {};

  var defaultDir = path.join(process.cwd(), 'coverage');
  opts = _.defaults(opts, {
    coverageVariable: COVERAGE_VARIABLE,
    dir: defaultDir,
    reporters: [ 'lcov', 'json', 'text', 'text-summary' ],
    reportOpts: { dir: opts.dir || defaultDir }
  });

  var reporters = opts.reporters.map(function(reporter) {
    if (reporter.TYPE) Report.register(reporter);
    return reporter.TYPE || reporter;
  });

  var invalid = _.difference(reporters, Report.getReportList());
  if (invalid.length) {
    // throw before we start -- fail fast
    throw new PluginError(PLUGIN_NAME, 'Invalid reporters: ' + invalid.join(', '));
  }

  reporters = reporters.map(function (r) {
    var reportOpts = opts.reportOpts[r] || opts.reportOpts;
    return Report.create(r, _.clone(reportOpts));
  });

  var cover = through();

  cover.on('end', function () {
    var collector = new Collector();

    // Revert to an object if there are no matching source files.
    collector.add(global[opts.coverageVariable] || {});

    reporters.forEach(function (report) {
      report.writeReport(collector, true);
    });
  }).resume();

  return cover;
};

plugin.enforceThresholds = function (opts) {
  opts = opts || {};
  opts = _.defaults(opts, {
    coverageVariable: COVERAGE_VARIABLE
  });

  var cover = through();

  cover.on('end', function () {
    var collector = new Collector();

    // Revert to an object if there are no macthing source files.
    collector.add(global[opts.coverageVariable] || {});

    var results = checker.checkFailures(opts.thresholds, collector.getFinalCoverage());
    var criteria = function(type) {
      return (type.global && type.global.failed) || (type.each && type.each.failed);
    };

    if (_.any(results, criteria)) {
      this.emit('error', new PluginError({
        plugin: PLUGIN_NAME,
        message: 'Coverage failed'
      }));
    }

  }).resume();

  return cover;
};
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var EE = require('events').EventEmitter;
var usb = require('usb');
var statics = require('./lib/statics');

var usbtiny = function(options) {
  if (!(this instanceof usbtiny))
  { return new usbtiny(); }

  EE.call(this);

  this.device = {};
  this.log = options.log || function(){};
  this.options = options;
};
util.inherits(usbtiny, EE);

usbtiny.prototype.open = function(cb){
  var self = this;

  usb.findByIds(this.options.vid, this.options.pid, function(err, device){
    if(err) { return cb(err); }

    self.device = device;
    self.device.open(cb);
  });
};

usbtiny.prototype.close = function(cb){

  this.device.close(cb);
};

usbtiny.prototype.setSCK = function(cb){

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_POWERUP;
  var val = statics.SCK_DEFAULT;
  var index = statics.RESET_LOW;
  var length = 0;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', val.toString(16), ' index: ', index.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, val, index, length, cb);
};

usbtiny.prototype.spi = function(buffer, cb){

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_SPI;
  var val = (buffer[1] << 8) | buffer[0];
  var index = (buffer[3] << 8) | buffer[2];
  var length = 4;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', val.toString(16), ' index: ', index.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, val, index, length, cb);
};

usbtiny.prototype.readFlash = function(delay, address, length, cb){

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_FLASH_READ;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', delay.toString(16), ' index: ', address.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, delay, address, length, cb);
};

//only supporting paged for now
usbtiny.prototype.writeFlash = function(delay, address, buffer, cb){

  var requesttype = 0x40;
  var requestid = statics.USBTINY_FLASH_WRITE;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', delay.toString(16), ' index: ', address.toString(16), ' buflen: ', buffer.length.toString(16));
  // console.log(buffer.toString('hex'));

  this.device.controlTransfer(
    requesttype, requestid, delay, address, buffer, cb);
};

usbtiny.prototype.powerDown = function(cb){

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_POWERDOWN;
  var val = 0;
  var index = 0;
  var length = 0;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', val.toString(16), ' index: ', index.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, val, index, length, cb);
};

//only supporting paged for now and eeprom isnt paged on tiny85
usbtiny.prototype.readEeprom = function(delay, address, length, cb){

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_EEPROM_READ;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', delay.toString(16), ' index: ', address.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, delay, address, length, cb);
};

usbtiny.prototype.writeEeprom = function(delay, address, buffer, cb){

  var requesttype = 0x40;
  var requestid = statics.USBTINY_EEPROM_WRITE;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', delay.toString(16), ' index: ', address.toString(16), ' buflen: ', buffer.toString('hex'));

  this.device.controlTransfer(
   requesttype, requestid, delay, address, buffer, cb);
};

module.exports = usbtiny;

<commit_msg>allow SCK to be set dynamically<commit_after>'use strict';

var util = require('util');
var EE = require('events').EventEmitter;
var usb = require('usb');
var statics = require('./lib/statics');

var usbtiny = function(options) {
  if (!(this instanceof usbtiny))
  { return new usbtiny(); }

  EE.call(this);

  this.device = {};
  this.log = options.log || function(){};
  this.options = options;
};
util.inherits(usbtiny, EE);

usbtiny.prototype.open = function(cb){
  var self = this;

  usb.findByIds(this.options.vid, this.options.pid, function(err, device){
    if(err) { return cb(err); }

    self.device = device;
    self.device.open(cb);
  });
};

usbtiny.prototype.close = function(cb){

  this.device.close(cb);
};

usbtiny.prototype.setSCK = function(val, cb){
  if (!cb) {
    var cb = val;
    var val = statics.SCK_DEFAULT;
  }

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_POWERUP;
  var index = statics.RESET_LOW;
  var length = 0;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', val.toString(16), ' index: ', index.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, val, index, length, cb);
};

usbtiny.prototype.spi = function(buffer, cb){

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_SPI;
  var val = (buffer[1] << 8) | buffer[0];
  var index = (buffer[3] << 8) | buffer[2];
  var length = 4;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', val.toString(16), ' index: ', index.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, val, index, length, cb);
};

usbtiny.prototype.readFlash = function(delay, address, length, cb){

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_FLASH_READ;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', delay.toString(16), ' index: ', address.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, delay, address, length, cb);
};

//only supporting paged for now
usbtiny.prototype.writeFlash = function(delay, address, buffer, cb){

  var requesttype = 0x40;
  var requestid = statics.USBTINY_FLASH_WRITE;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', delay.toString(16), ' index: ', address.toString(16), ' buflen: ', buffer.length.toString(16));
  // console.log(buffer.toString('hex'));

  this.device.controlTransfer(
    requesttype, requestid, delay, address, buffer, cb);
};

usbtiny.prototype.powerDown = function(cb){

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_POWERDOWN;
  var val = 0;
  var index = 0;
  var length = 0;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', val.toString(16), ' index: ', index.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, val, index, length, cb);
};

//only supporting paged for now and eeprom isnt paged on tiny85
usbtiny.prototype.readEeprom = function(delay, address, length, cb){

  var requesttype = 0xC0;
  var requestid = statics.USBTINY_EEPROM_READ;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', delay.toString(16), ' index: ', address.toString(16), ' buflen: ', length.toString(16));

  this.device.controlTransfer(
    requesttype, requestid, delay, address, length, cb);
};

usbtiny.prototype.writeEeprom = function(delay, address, buffer, cb){

  var requesttype = 0x40;
  var requestid = statics.USBTINY_EEPROM_WRITE;

  this.log('requesttype: ', requesttype.toString(16), ' requestid:', requestid.toString(16), ' val: ', delay.toString(16), ' index: ', address.toString(16), ' buflen: ', buffer.toString('hex'));

  this.device.controlTransfer(
   requesttype, requestid, delay, address, buffer, cb);
};

module.exports = usbtiny;

<|endoftext|>


<commit_before>var outcome = require('outcome'),
EventEmitter = require('events').EventEmitter;

//meh, shit's ugly.
function combineArrays(c1,c2,target,property)
{
	var c1p = c1[property];
		c2p = c2[property];

	if(!c1p && !c2p) return;

	c1p = c1p || [];
	c2p = c2p || [];

	c1p = c1p instanceof Array ? c1p : [c1p];
	c2p = c2p instanceof Array ? c2p : [c2p];

	target[property] = c1p.concat(c2p);
}

function _buildMessage()
{
	var msg = arguments[0];

	//error object
	if(msg.message) msg = msg.message;

	for(var i = 1, n = arguments.length; i < n; i++)
	{
		msg = msg.replace(/%\w/, arguments[i]);
	}

	return msg;
}

var Vine =
{

	/**
	 */

	setApi: function(request)
	{
		request.api = Vine.api(request);

		return request;
	},

	/**
	 */

	api: function(request,methods,data)
	{
		if(!data) data = {};

		var methods  = methods || {};

		var invoker =
		{

			/**
			 */

			error: function()
			{
				if(!arguments.length) return data.errors;

				if(!data.errors) data.errors = [];

				data.errors.push({ message: _buildMessage.apply(null, arguments)});
				return this;
			},

			/**
			 * the type of data. Used for
			 */

			type: function(type)
			{
				if(!arguments.length) return data.type;

				data.type = type;

				return this;
			},

			/**
			 */

			warning: function()
			{
				if(!arguments.length) return data.warnings;

				if(!data.warnings) data.warnings = [];

				data.warnings.push({ message: _buildMessage.apply(null, arguments)});
				return this;
			},

			/**
			 */

			'success': function()
			{
				if(!arguments.length) return data.messages;

				if(!data.messages) data.messages = [];

				data.messages.push({ message: _buildMessage.apply(null, arguments)});

				return this;
			},

			/**
			 */

			combine: function(api)
			{
				var thisData = data,
					thatData = api.data || api,
					newData = {};

				for(var i in thisData) newData[i] = thisData;

				combineArrays(thisData,thatData,newData,'errors');
				combineArrays(thisData,thatData,newData,'warnings');
				combineArrays(thisData,thatData,newData,'messages');
				combineArrays(thisData,thatData,newData,'result');

				return Vine.api(null,null,newData);
			},

			/**
			 */

			redirect: function(to)
			{
				if(!arguments.length) return data.redirect;

				data.redirect = to;
				return this;
			},

			/**
			 */

			message: function(msg)
			{
				if(!arguments.length) return data.message;

				data.message = _buildMessage.apply(null, arguments);
				return this;
			},

			/**
			 */

			method: function(method)
			{
				if(!arguments.length) return data.method;
				data.method = method;
				return this;
			},

			/**
			 */

			list: function(data)
			{
				this.result(data);
				return this.method('list');
			},

			/**
			 */

			add: function(data)
			{
				this.result(data);
				return this.method('add');
			},

			/**
			 */

			remove: function(data)
			{
				this.result(data);
				return this.method('remove');
			},

			/**
			 */

			update: function(data)
			{
				this.result(data);
				return this.method('update');
			},

			/**
			 */

			result: function(result)
			{
				if(!arguments.length) return data.result;

				data.result = result;
				return this;
			},

			/**
			 */

			results: function(result)
			{
				if(!arguments.length) return data.result;

				if(!(data.result instanceof Array)) data.result = [];
				data.result.push(result);
				return this;
			},

			/**
			 */

			ttl:function(ttl)
			{
				if(ttl > -1)
					data.ttl = ttl;

				return this;
			},

			/**
			 */

			end: function(target)
			{
				if(target)
				if(target.end)
				{
					target.end(data);
				}
				else
				if(typeof target == 'function')
				{
					target(data);
				}

				return data;
			},

			/**
			 */

			fn: function(fn)
			{
				if(data.errors)
				{
					target(data.errors.length > 1 ? data.errors : data.errors[0]);
				}
				else
				{
					fn(null, data.result);
				}
			},

			/**
			 */

			onOutcome: function(resp, messages)
			{
				if(messages) {
					messages.resp = resp;
				}

				if(!messages) messages = {};

				return outcome.error(function(err)
				{
					invoker.error(messages.error || (err ? err.message : err));

				}).success(function(result)
				{
					invoker.result(messages.success || result);

				}).done(function()
				{
					if(messages.resp) invoker.end(messages.resp);

				});
			},

			/**
			 */

			toJSON: function()
			{
				return invoker.data;
			}
		}

		invoker.data = data;

		return invoker;

	}
}

exports.api = Vine.api;

var v = Vine.api();

Object.keys(v).forEach(function(method) {
	exports[method] = function() {
		var api = exports.api();

		return api[method].apply(api, arguments);
	}
})

<commit_msg>check if error passed is an array<commit_after>var outcome = require('outcome'),
EventEmitter = require('events').EventEmitter;

//meh, shit's ugly.
function combineArrays(c1,c2,target,property)
{
	var c1p = c1[property];
		c2p = c2[property];

	if(!c1p && !c2p) return;

	c1p = c1p || [];
	c2p = c2p || [];

	c1p = c1p instanceof Array ? c1p : [c1p];
	c2p = c2p instanceof Array ? c2p : [c2p];

	target[property] = c1p.concat(c2p);
}

function _buildMessage()
{
	var msg = arguments[0];

	//error object
	if(msg.message) msg = msg.message;

	for(var i = 1, n = arguments.length; i < n; i++)
	{
		msg = msg.replace(/%\w/, arguments[i]);
	}

	return msg;
}

var Vine =
{

	/**
	 */

	setApi: function(request)
	{
		request.api = Vine.api(request);

		return request;
	},

	/**
	 */

	api: function(request,methods,data)
	{
		if(!data) data = {};

		var methods  = methods || {};

		var invoker =
		{

			/**
			 */

			error: function()
			{
				if(!arguments.length) return data.errors;

				if(arguments[0] instanceof Array) {
					arguments[0].forEach(function(err) {
						invoker.error(err);
					})
					return this;
				}

				if(!data.errors) data.errors = [];

				data.errors.push({ message: _buildMessage.apply(null, arguments)});
				return this;
			},

			/**
			 * the type of data. Used for
			 */

			type: function(type)
			{
				if(!arguments.length) return data.type;

				data.type = type;

				return this;
			},

			/**
			 */

			warning: function()
			{
				if(!arguments.length) return data.warnings;

				if(!data.warnings) data.warnings = [];

				data.warnings.push({ message: _buildMessage.apply(null, arguments)});
				return this;
			},

			/**
			 */

			'success': function()
			{
				if(!arguments.length) return data.messages;

				if(!data.messages) data.messages = [];

				data.messages.push({ message: _buildMessage.apply(null, arguments)});

				return this;
			},

			/**
			 */

			combine: function(api)
			{
				var thisData = data,
					thatData = api.data || api,
					newData = {};

				for(var i in thisData) newData[i] = thisData;

				combineArrays(thisData,thatData,newData,'errors');
				combineArrays(thisData,thatData,newData,'warnings');
				combineArrays(thisData,thatData,newData,'messages');
				combineArrays(thisData,thatData,newData,'result');

				return Vine.api(null,null,newData);
			},

			/**
			 */

			redirect: function(to)
			{
				if(!arguments.length) return data.redirect;

				data.redirect = to;
				return this;
			},

			/**
			 */

			message: function(msg)
			{
				if(!arguments.length) return data.message;

				data.message = _buildMessage.apply(null, arguments);
				return this;
			},

			/**
			 */

			method: function(method)
			{
				if(!arguments.length) return data.method;
				data.method = method;
				return this;
			},

			/**
			 */

			list: function(data)
			{
				this.result(data);
				return this.method('list');
			},

			/**
			 */

			add: function(data)
			{
				this.result(data);
				return this.method('add');
			},

			/**
			 */

			remove: function(data)
			{
				this.result(data);
				return this.method('remove');
			},

			/**
			 */

			update: function(data)
			{
				this.result(data);
				return this.method('update');
			},

			/**
			 */

			result: function(result)
			{
				if(!arguments.length) return data.result;

				data.result = result;
				return this;
			},

			/**
			 */

			results: function(result)
			{
				if(!arguments.length) return data.result;

				if(!(data.result instanceof Array)) data.result = [];
				data.result.push(result);
				return this;
			},

			/**
			 */

			ttl:function(ttl)
			{
				if(ttl > -1)
					data.ttl = ttl;

				return this;
			},

			/**
			 */

			end: function(target)
			{
				if(target)
				if(target.end)
				{
					target.end(data);
				}
				else
				if(typeof target == 'function')
				{
					target(data);
				}

				return data;
			},

			/**
			 */

			fn: function(fn)
			{
				if(data.errors)
				{
					target(data.errors.length > 1 ? data.errors : data.errors[0]);
				}
				else
				{
					fn(null, data.result);
				}
			},

			/**
			 */

			onOutcome: function(resp, messages)
			{
				if(messages) {
					messages.resp = resp;
				}

				if(!messages) messages = {};

				return outcome.error(function(err)
				{
					invoker.error(messages.error || (err ? err.message : err));

				}).success(function(result)
				{
					invoker.result(messages.success || result);

				}).done(function()
				{
					if(messages.resp) invoker.end(messages.resp);

				});
			},

			/**
			 */

			toJSON: function()
			{
				return invoker.data;
			}
		}

		invoker.data = data;

		return invoker;

	}
}

exports.api = Vine.api;

var v = Vine.api();

Object.keys(v).forEach(function(method) {
	exports[method] = function() {
		var api = exports.api();

		return api[method].apply(api, arguments);
	}
})

<|endoftext|>


<commit_before>#!/usr/bin/env node

const fs = require(`fs`);
const ArgumentParser = require(`argparse`).ArgumentParser;
const ansi = require(`./ansi`);

const argParser = new ArgumentParser({
  version: `2.0.0`,
  description: `The famous Matrix rain effect of falling green characters as a cli command`,
});

[
  {
    flags: [ `-d`, `--direction` ],
    opts: {
      choices: [`h`, `v`],
      defaultValue: `v`,
      help: `Change direction of rain. h=horizontal, v=vertical`,
    },
  },
  {
    flags: [ `-c`, `--color` ],
    opts: {
      choices: [`green`, `red`, `blue`, `yellow`, `magenta`, `cyan`, `white`],
      defaultValue: `green`,
      dest: `color`,
      help: `Rain color. NOTE: droplet start is always white`,
    },
  },
  {
    flags: [ `-k`, `--char-range` ],
    opts: {
      choices: [`ascii`, `binary`, `braille`, `emoji`, `kanji`],
      defaultValue: `ascii`,
      dest: `charRange`,
      help: `Use rain characters from char-range`,
    },
  },
  {
    flags: [ `-f`, `--file-path` ],
    opts: {
      dest: `filePath`,
      help: `Read characters from a file instead of random characters from char-range`,
    },
  },
].forEach(({flags, opts}) => argParser.addArgument(flags, opts));

// Simple string stream buffer + stdout flush at once
let outBuffer = [];
function write(chars) {
  return outBuffer.push(chars);
}

function flush() {
  process.stdout.write(outBuffer.join(``));
  return outBuffer = [];
}

function rand(start, end) {
  return start + Math.floor(Math.random() * (end - start));
}

class MatrixRain {
  constructor(opts) {
    this.transpose = opts.direction === `h`;
    this.color = opts.color;
    this.charRange = opts.charRange;
    this.maxSpeed = 20;
    this.colDroplets = [];
    this.numCols = 0;
    this.numRows = 0;

    // handle reading from file
    if (opts.filePath) {
      if (!fs.existsSync(opts.filePath)) {
        throw new Error(`${opts.filePath} doesn't exist`);
      }
      this.fileChars = fs.readFileSync(opts.filePath, `utf-8`).trim().split(``);
      this.filePos = 0;
      this.charRange = `file`;
    }
  }

  generateChars(len, charRange) {
    // by default charRange == ascii
    let chars = new Array(len);

    if (charRange === `ascii`) {
      for (let i = 0; i < len; i++) {
        chars[i] = String.fromCharCode(rand(0x21, 0x7E));
      }
    } else if (charRange === `braille`) {
      for (let i = 0; i < len; i++) {
        chars[i] = String.fromCharCode(rand(0x2840, 0x28ff));
      }
    } else if (charRange === `kanji`) {
      for (let i = 0; i < len; i++) {
        chars[i] = String.fromCharCode(rand(0x30a0, 0x30ff));
      }
    } else if (charRange === `emoji`) {
      // emojis are two character widths, so use a prefix
      const emojiPrefix = String.fromCharCode(0xd83d);
      for (let i = 0; i < len; i++) {
        chars[i] = emojiPrefix + String.fromCharCode(rand(0xde01, 0xde4a));
      }
    } else if (charRange === `file`) {
      for (let i = 0; i < len; i++, this.filePos++) {
        this.filePos = this.filePos < this.fileChars.length ? this.filePos : 0;
        chars[i] = this.fileChars[this.filePos];
      }
    }

    return chars;
  }

  makeDroplet(col) {
    return {
      col,
      alive: 0,
      curRow: rand(0, this.numRows),
      height: rand(this.numRows / 2, this.numRows),
      speed: rand(1, this.maxSpeed),
      chars: this.generateChars(this.numRows, this.charRange),
    };
  }

  resizeDroplets() {
    [this.numCols, this.numRows] = process.stdout.getWindowSize();

    // transpose for direction
    if (this.transpose) {
      [this.numCols, this.numRows] = [this.numRows, this.numCols];
    }

    // Create droplets per column
    // add/remove droplets to match column size
    if (this.numCols > this.colDroplets.length) {
      for (let col = this.colDroplets.length; col < this.numCols; ++col) {
        // make two droplets per row that start in random positions
        this.colDroplets.push([this.makeDroplet(col), this.makeDroplet(col)]);
      }
    } else {
      this.colDroplets.splice(this.numCols, this.colDroplets.length - this.numCols);
    }
  }

  writeAt(row, col, str, color) {
    // Only output if in viewport
    if (row >=0 && row < this.numRows && col >=0 && col < this.numCols) {
      const pos = this.transpose ? ansi.cursorPos(col, row) : ansi.cursorPos(row, col);
      write(`${pos}${color || ``}${str || ``}`);
    }
  }

  renderFrame() {
    const ansiColor = ansi.colors[`fg${this.color.charAt(0).toUpperCase()}${this.color.substr(1)}`]();

    for (const droplets of this.colDroplets) {
      for (const droplet of droplets) {
        const {curRow, col: curCol, height} = droplet;
        droplet.alive++;

        if (droplet.alive % droplet.speed === 0) {
          this.writeAt(curRow - 1, curCol, droplet.chars[curRow - 1], ansiColor);
          this.writeAt(curRow, curCol, droplet.chars[curRow], ansi.colors.fgWhite());
          this.writeAt(curRow - height, curCol, ` `);
          droplet.curRow++;
        }

        if (curRow - height > this.numRows) {
          // reset droplet
          Object.assign(droplet, this.makeDroplet(droplet.col), {curRow: 0});
        }
      }
    }

    flush();
  }
}

//// main ////

const args = argParser.parseArgs();
const matrixRain = new MatrixRain(args);

function start() {
  if (!process.stdout.isTTY) {
    console.error(`Error: Output is not a text terminal`);
    process.exit(1);
  }

  // clear terminal and use alt buffer
  process.stdin.setRawMode(true);
  write(ansi.useAltBuffer());
  write(ansi.cursorInvisible());
  write(ansi.colors.bgBlack());
  write(ansi.clearScreen());
  flush();
  matrixRain.resizeDroplets();
}

function stop() {
  write(ansi.cursorVisible());
  write(ansi.clearScreen());
  write(ansi.cursorHome());
  write(ansi.useNormalBuffer());
  flush();
  process.exit();
}

process.on(`SIGINT`, () => stop());
process.stdin.on(`data`, () => stop());
process.stdout.on(`resize`, () => matrixRain.resizeDroplets());
setInterval(() => matrixRain.renderFrame(), 16); // 60FPS

start();
<commit_msg>use fg + bg black and get version number from package.json<commit_after>#!/usr/bin/env node

const fs = require(`fs`);
const ArgumentParser = require(`argparse`).ArgumentParser;
const ansi = require(`./ansi`);
const npmPackage = JSON.parse(fs.readFileSync(`${__dirname}/package.json`));

const argParser = new ArgumentParser({
  version: npmPackage.version,
  description: `The famous Matrix rain effect of falling green characters as a cli command`,
});

[
  {
    flags: [ `-d`, `--direction` ],
    opts: {
      choices: [`h`, `v`],
      defaultValue: `v`,
      help: `Change direction of rain. h=horizontal, v=vertical`,
    },
  },
  {
    flags: [ `-c`, `--color` ],
    opts: {
      choices: [`green`, `red`, `blue`, `yellow`, `magenta`, `cyan`, `white`],
      defaultValue: `green`,
      dest: `color`,
      help: `Rain color. NOTE: droplet start is always white`,
    },
  },
  {
    flags: [ `-k`, `--char-range` ],
    opts: {
      choices: [`ascii`, `binary`, `braille`, `emoji`, `kanji`],
      defaultValue: `ascii`,
      dest: `charRange`,
      help: `Use rain characters from char-range`,
    },
  },
  {
    flags: [ `-f`, `--file-path` ],
    opts: {
      dest: `filePath`,
      help: `Read characters from a file instead of random characters from char-range`,
    },
  },
].forEach(({flags, opts}) => argParser.addArgument(flags, opts));

// Simple string stream buffer + stdout flush at once
let outBuffer = [];
function write(chars) {
  return outBuffer.push(chars);
}

function flush() {
  process.stdout.write(outBuffer.join(``));
  return outBuffer = [];
}

function rand(start, end) {
  return start + Math.floor(Math.random() * (end - start));
}

class MatrixRain {
  constructor(opts) {
    this.transpose = opts.direction === `h`;
    this.color = opts.color;
    this.charRange = opts.charRange;
    this.maxSpeed = 20;
    this.colDroplets = [];
    this.numCols = 0;
    this.numRows = 0;

    // handle reading from file
    if (opts.filePath) {
      if (!fs.existsSync(opts.filePath)) {
        throw new Error(`${opts.filePath} doesn't exist`);
      }
      this.fileChars = fs.readFileSync(opts.filePath, `utf-8`).trim().split(``);
      this.filePos = 0;
      this.charRange = `file`;
    }
  }

  generateChars(len, charRange) {
    // by default charRange == ascii
    let chars = new Array(len);

    if (charRange === `ascii`) {
      for (let i = 0; i < len; i++) {
        chars[i] = String.fromCharCode(rand(0x21, 0x7E));
      }
    } else if (charRange === `braille`) {
      for (let i = 0; i < len; i++) {
        chars[i] = String.fromCharCode(rand(0x2840, 0x28ff));
      }
    } else if (charRange === `kanji`) {
      for (let i = 0; i < len; i++) {
        chars[i] = String.fromCharCode(rand(0x30a0, 0x30ff));
      }
    } else if (charRange === `emoji`) {
      // emojis are two character widths, so use a prefix
      const emojiPrefix = String.fromCharCode(0xd83d);
      for (let i = 0; i < len; i++) {
        chars[i] = emojiPrefix + String.fromCharCode(rand(0xde01, 0xde4a));
      }
    } else if (charRange === `file`) {
      for (let i = 0; i < len; i++, this.filePos++) {
        this.filePos = this.filePos < this.fileChars.length ? this.filePos : 0;
        chars[i] = this.fileChars[this.filePos];
      }
    }

    return chars;
  }

  makeDroplet(col) {
    return {
      col,
      alive: 0,
      curRow: rand(0, this.numRows),
      height: rand(this.numRows / 2, this.numRows),
      speed: rand(1, this.maxSpeed),
      chars: this.generateChars(this.numRows, this.charRange),
    };
  }

  resizeDroplets() {
    [this.numCols, this.numRows] = process.stdout.getWindowSize();

    // transpose for direction
    if (this.transpose) {
      [this.numCols, this.numRows] = [this.numRows, this.numCols];
    }

    // Create droplets per column
    // add/remove droplets to match column size
    if (this.numCols > this.colDroplets.length) {
      for (let col = this.colDroplets.length; col < this.numCols; ++col) {
        // make two droplets per row that start in random positions
        this.colDroplets.push([this.makeDroplet(col), this.makeDroplet(col)]);
      }
    } else {
      this.colDroplets.splice(this.numCols, this.colDroplets.length - this.numCols);
    }
  }

  writeAt(row, col, str, color) {
    // Only output if in viewport
    if (row >=0 && row < this.numRows && col >=0 && col < this.numCols) {
      const pos = this.transpose ? ansi.cursorPos(col, row) : ansi.cursorPos(row, col);
      write(`${pos}${color || ``}${str || ``}`);
    }
  }

  renderFrame() {
    const ansiColor = ansi.colors[`fg${this.color.charAt(0).toUpperCase()}${this.color.substr(1)}`]();

    for (const droplets of this.colDroplets) {
      for (const droplet of droplets) {
        const {curRow, col: curCol, height} = droplet;
        droplet.alive++;

        if (droplet.alive % droplet.speed === 0) {
          this.writeAt(curRow - 1, curCol, droplet.chars[curRow - 1], ansiColor);
          this.writeAt(curRow, curCol, droplet.chars[curRow], ansi.colors.fgWhite());
          this.writeAt(curRow - height, curCol, ` `);
          droplet.curRow++;
        }

        if (curRow - height > this.numRows) {
          // reset droplet
          Object.assign(droplet, this.makeDroplet(droplet.col), {curRow: 0});
        }
      }
    }

    flush();
  }
}

//// main ////

const args = argParser.parseArgs();
const matrixRain = new MatrixRain(args);

function start() {
  if (!process.stdout.isTTY) {
    console.error(`Error: Output is not a text terminal`);
    process.exit(1);
  }

  // clear terminal and use alt buffer
  process.stdin.setRawMode(true);
  write(ansi.useAltBuffer());
  write(ansi.cursorInvisible());
  write(ansi.colors.bgBlack());
  write(ansi.colors.fgBlack());
  write(ansi.clearScreen());
  flush();
  matrixRain.resizeDroplets();
}

function stop() {
  write(ansi.cursorVisible());
  write(ansi.clearScreen());
  write(ansi.cursorHome());
  write(ansi.useNormalBuffer());
  flush();
  process.exit();
}

process.on(`SIGINT`, () => stop());
process.stdin.on(`data`, () => stop());
process.stdout.on(`resize`, () => matrixRain.resizeDroplets());
setInterval(() => matrixRain.renderFrame(), 16); // 60FPS

start();
<|endoftext|>


<commit_before>'use strict'

exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  for (var i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(
      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
    ))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}
<commit_msg>Don't rely on hoisting<commit_after>'use strict'

exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  var i
  for (i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(
      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
    ))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}
<|endoftext|>


<commit_before>/**
 * glob-fs <https://github.com/tunnckoCore/glob-fs>
 *
 * Copyright (c) 2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict';

var File = require('vinyl');
var matcher = require('is-match');
var eachAsync = require('each-async');
var uniqueify = require('uniqueify');
var stripBom = require('strip-bom');
var debug = require('debug')('glob-fs');

var fs = require('graceful-fs');
var path = require('path');
var inherits = require('util').inherits;
var Readable = require('stream').Readable;

function GlobFS(root, options) {
  if (!(this instanceof GlobFS)) {
    return new GlobFS(root, options);
  }
  if (typeof root !== 'string') {
    throw new TypeError('[erasm-stream] expect `root` to be string');
  }
  Readable.call(this, {objectMode: true});

  options = typeof options === 'object' ? options : {};
  options.cwd = typeof options.cwd !== 'string' ? process.cwd() : options.cwd;

  if (typeof options.cwdbase === 'boolean' && options.cwdbase) {
    options.base = options.cwd;
  }

  this.single = false;
  this.root = root;
  this.queue = [root];
  this.options = options;

  var patterns = this.options.patterns;

  if (Array.isArray(patterns)) {
    this.single = patterns.length === 1;
    patterns = this.single ? unrelative(patterns[0]) : uniqueify(patterns);
    patterns = this.single ? patterns : patterns.map(function(pattern) {
      return unrelative(pattern);
    });

    this.isMatch = matcher(patterns, options);
    this.options.patterns = patterns;
    return;
  }
  if (typeof patterns === 'string') {
    this.single = true;
    patterns = unrelative(patterns);
    this.isMatch = matcher(patterns, options);
    this.options.patterns = patterns;
    return;
  }
  this.isMatch = matcher(patterns, options);
};

inherits(GlobFS, Readable);

GlobFS.prototype.getCache = function() {
  return this.cache;
};
GlobFS.prototype._read = function __read() {
  var self = this;

  if (!self.queue.length) {
    debug('(end)');
    this.push(null);
    return;
  }

  var filepath = self.queue.shift();
  debug('(stat) %s', filepath);
  fs.stat(filepath, function(err, stat) {
    if (err) {return error(err);}

    var vinyl = new File({
      path: filepath,
      stat: stat,
      base: self.options.base || path.dirname(filepath),
      cwd: self.options.cwd
    });

    if (self.options.src) {
      if (stat.isFile()) {
        vinyl.contents = stripBom(fs.readFileSync(vinyl.path), 'utf-8');
      }
      if (vinyl.isStream()) {
        vinyl.contents = fs.createReadStream(vinyl.path).pipe(stripBom.stream());
      }
    }

    if (stat.isDirectory()) {
      readdir(filepath, function(err) {
        if (err) {return error(err);}
        push(vinyl);
      });
      return;
    }
    push(vinyl);
  });

  /**
   * helpers for `error`, `push` and recursive `readdir`
   */
  function error(err) {
    debug('(error) %s', err.message);
    self.emit('error', err);
  }

  function push(obj) {
    var match = self.isMatch(obj.path);

    if (self.options.allowEmpty !== true && !match && self.single) {
      self.emit('error', new Error('File not found with singular glob'));
      return;
    }
    var since = match && (self.options.since < obj.stat.mtime);

    if (match || since) {
      debug('(push) %s', obj.path);
      self.push(obj);
      return;
    }

    self._read();
  }

  function readdir(dir, done) {
    debug('(readdir) %s', dir);
    fs.readdir(dir, function(err, filepaths) {
      if (err) {return error(err);}

      eachAsync(filepaths, function _eachFilepaths(fp, i, next) {
        fp = path.join(dir, fp);
        debug('(queue) %s', fp);
        self.queue.push(fp);

        next();
      }, done);
    });
  }
};

/**
 * utils
 */

function arrayify(val) {
  return !Array.isArray(val)
    ? [val]
    : val;
};

function unrelative(cwd, glob) {
  var negate = '';
  var ch = glob.charAt(0);
  if (ch === '!') {
    negate = ch;
    glob = glob.slice(1);
  }
  return negate + path.resolve(cwd, glob);
}

module.exports = GlobFS;
<commit_msg>fix unrelative use, ignore node_modules by default<commit_after>/**
 * glob-fs <https://github.com/tunnckoCore/glob-fs>
 *
 * Copyright (c) 2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict';

var File = require('vinyl');
var matcher = require('is-match');
var eachAsync = require('each-async');
var uniqueify = require('uniqueify');
var stripBom = require('strip-bom');
var debug = require('debug')('glob-fs');

var fs = require('graceful-fs');
var path = require('path');
var inherits = require('util').inherits;
var Readable = require('stream').Readable;

function GlobFS(root, options) {
  if (!(this instanceof GlobFS)) {
    return new GlobFS(root, options);
  }
  if (typeof root !== 'string') {
    throw new TypeError('[erasm-stream] expect `root` to be string');
  }
  Readable.call(this, {objectMode: true});

  options = typeof options === 'object' ? options : {};
  options.cwd = typeof options.cwd !== 'string' ? process.cwd() : options.cwd;

  if (typeof options.cwdbase === 'boolean' && options.cwdbase) {
    options.base = options.cwd;
  }

  this.single = false;
  this.root = root;
  this.queue = [root];
  this.options = options;

  var cwd = this.options.cwd;
  var patterns = this.options.patterns;

  if (Array.isArray(patterns)) {
    this.single = patterns.length === 1;
    patterns = this.single ? unrelative(cwd, patterns[0]) : uniqueify(patterns);
    patterns = this.single ? patterns : patterns.map(function(pattern) {
      return unrelative(cwd, pattern);
    });
    patterns = patterns.concat(unrelative(cwd, 'node_modules'));
    this.isMatch = matcher(patterns, options);
    return;
  }
  if (typeof patterns === 'string') {
    this.single = true;
    patterns = unrelative(cwd, patterns);
    patterns = [patterns].concat(unrelative(cwd, 'node_modules'));
    this.isMatch = matcher(patterns, options);
    return;
  }
  this.isMatch = matcher(this.options.patterns, options);
};

inherits(GlobFS, Readable);

GlobFS.prototype.getCache = function() {
  return this.cache;
};
GlobFS.prototype._read = function __read() {
  var self = this;

  if (!self.queue.length) {
    debug('(end)');
    this.push(null);
    return;
  }

  var filepath = self.queue.shift();
  debug('(stat) %s', filepath);
  fs.stat(filepath, function(err, stat) {
    if (err) {return error(err);}

    var vinyl = new File({
      path: filepath,
      stat: stat,
      base: self.options.base || path.dirname(filepath),
      cwd: self.options.cwd
    });

    if (self.options.src) {
      if (stat.isFile()) {
        vinyl.contents = stripBom(fs.readFileSync(vinyl.path), 'utf8');
      }
      if (vinyl.isStream()) {
        vinyl.contents = fs.createReadStream(vinyl.path).pipe(stripBom.stream());
      }
    }

    if (stat.isDirectory()) {
      readdir(filepath, function(err) {
        if (err) {return error(err);}
        push(vinyl);
      });
      return;
    }
    push(vinyl);
  });

  /**
   * helpers for `error`, `push` and recursive `readdir`
   */
  function error(err) {
    debug('(error) %s', err.message);
    self.emit('error', err);
  }

  function push(obj) {
    var match = self.isMatch(obj.path);

    if (self.options.allowEmpty !== true && !match && self.single) {
      self.emit('error', new Error('File not found with singular glob'));
      return;
    }
    var since = match && (self.options.since < obj.stat.mtime);

    if (match || since) {
      debug('(push) %s', obj.path);
      self.push(obj);
      return;
    }

    self._read();
  }

  function readdir(dir, done) {
    debug('(readdir) %s', dir);
    fs.readdir(dir, function(err, filepaths) {
      if (err) {return error(err);}

      eachAsync(filepaths, function _eachFilepaths(fp, i, next) {
        fp = path.join(dir, fp);
        debug('(queue) %s', fp);
        self.queue.push(fp);

        next();
      }, done);
    });
  }
};

/**
 * utils
 */

function arrayify(val) {
  return !Array.isArray(val)
    ? [val]
    : val;
};

function unrelative(cwd, glob) {
  var negate = '';
  var ch = glob.charAt(0);
  if (ch === '!') {
    negate = ch;
    glob = glob.slice(1);
  }
  return negate + path.resolve(cwd, glob);
}

module.exports = GlobFS;
<|endoftext|>


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

 "use strict";

(function(){

  const os = require('os');
  const fs = require('fs');
  const path = require('path');
  const rmdir = require('rmdir');
  const zlib = require('zlib');
  const tar = require('tar-fs');
  const process = require('process');
  const request = require('request');
  const ProgressBar = require('progress');
  const child_process = require('child_process');

  const major_version = 8;
  const update_number = 131;
  const build_number = 11;
  const hash = 'd54c1d3a095b4ff2b6607d096fa80163';
  const version = major_version + 'u' + update_number;

  const jreDir = exports.jreDir = () => path.join(__dirname, 'jre');

  const fail = reason => {
    console.error(reason);
    process.exit(1);
  };

  var _arch = os.arch();
  switch (_arch) {
    case 'x64': break;
    case 'ia32': _arch = 'i586'; break;
    default:
      fail('unsupported architecture: ' + _arch);
  }
  const arch = exports.arch = () => _arch;

  var _platform = os.platform();
  var _driver;
  switch (_platform) {
    case 'darwin': _platform = 'macosx'; _driver = ['Contents', 'Home', 'bin', 'java']; break;
    case 'win32': _platform = 'windows'; _driver = ['bin', 'javaw.exe']; break;
    case 'linux': _driver = ['bin', 'java']; break;
    default:
      fail('unsupported platform: ' + _platform);
  }
  const platform = exports.platform = () => _platform;

  const getDirectories = dirPath => fs.readdirSync(dirPath).filter(
    file => fs.statSync(path.join(dirPath, file)).isDirectory()
  );

  const driver = exports.driver = () => {
    var jreDirs = getDirectories(jreDir());
    if (jreDirs.length < 1)
      fail('no jre found in archive');
    var d = _driver.slice();
    d.unshift(jreDirs[0]);
    d.unshift(jreDir());
    return path.join.apply(path, d);
  };

  const getArgs = exports.getArgs = (classpath, classname, args) => {
    args = (args || []).slice();
    classpath = classpath || [];
    args.unshift(classname);
    args.unshift(classpath.join(platform() === 'windows' ? ';' : ':'));
    args.unshift('-cp');
    return args;
  };

  const spawn = exports.spawn =
    (classpath, classname, args, options) =>
      child_process.spawn(driver(), getArgs(classpath, classname, args), options);

  const spawnSync = exports.spawnSync =
    (classpath, classname, args, options) =>
      child_process.spawnSync(driver(), getArgs(classpath, classname, args), options);

  const smoketest = exports.smoketest = () =>
    spawnSync(['resources'], 'Smoketest', [], { encoding: 'utf8' })
    .stdout.trim() === 'No smoke!';

  const url = exports.url = () =>
    'https://download.oracle.com/otn-pub/java/jdk/' +
    version + '-b' + build_number + '/' + hash +
    '/jre-' + version + '-' + platform() + '-' + arch() + '.tar.gz';

  const install = exports.install = callback => {
    var urlStr = url();
    console.log("Downloading from: ", urlStr);
    callback = callback || (() => {});
    rmdir(jreDir());
    request
      .get({
        url: url(),
        rejectUnauthorized: false,
        agent: false,
        headers: {
          connection: 'keep-alive',
          'Cookie': 'gpw_e24=http://www.oracle.com/; oraclelicense=accept-securebackup-cookie'
        }
      })
      .on('response', res => {
        var len = parseInt(res.headers['content-length'], 10);
        var bar = new ProgressBar('  downloading and preparing JRE [:bar] :percent :etas', {
          complete: '=',
          incomplete: ' ',
          width: 80,
          total: len
        });
        res.on('data', chunk => bar.tick(chunk.length));
      })
      .on('error', err => {
        console.log(`problem with request: ${err.message}`);
        callback(err);
      })
      .on('end', () => { if (smoketest()) callback(); else callback("Smoketest failed."); })
      .pipe(zlib.createUnzip())
      .pipe(tar.extract(jreDir()));
  };

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

 "use strict";

(function(){

  const os = require('os');
  const fs = require('fs');
  const path = require('path');
  const rmdir = require('rmdir');
  const zlib = require('zlib');
  const tar = require('tar-fs');
  const process = require('process');
  const request = require('request');
  const ProgressBar = require('progress');
  const child_process = require('child_process');

  const major_version = 8;
  const update_number = 144;
  const build_number = 01;
  const hash = '090f390dda5b47b9b721c7dfaa008135';
  const version = major_version + 'u' + update_number;

  const jreDir = exports.jreDir = () => path.join(__dirname, 'jre');

  const fail = reason => {
    console.error(reason);
    process.exit(1);
  };

  var _arch = os.arch();
  switch (_arch) {
    case 'x64': break;
    case 'ia32': _arch = 'i586'; break;
    default:
      fail('unsupported architecture: ' + _arch);
  }
  const arch = exports.arch = () => _arch;

  var _platform = os.platform();
  var _driver;
  switch (_platform) {
    case 'darwin': _platform = 'macosx'; _driver = ['Contents', 'Home', 'bin', 'java']; break;
    case 'win32': _platform = 'windows'; _driver = ['bin', 'javaw.exe']; break;
    case 'linux': _driver = ['bin', 'java']; break;
    default:
      fail('unsupported platform: ' + _platform);
  }
  const platform = exports.platform = () => _platform;

  const getDirectories = dirPath => fs.readdirSync(dirPath).filter(
    file => fs.statSync(path.join(dirPath, file)).isDirectory()
  );

  const driver = exports.driver = () => {
    var jreDirs = getDirectories(jreDir());
    if (jreDirs.length < 1)
      fail('no jre found in archive');
    var d = _driver.slice();
    d.unshift(jreDirs[0]);
    d.unshift(jreDir());
    return path.join.apply(path, d);
  };

  const getArgs = exports.getArgs = (classpath, classname, args) => {
    args = (args || []).slice();
    classpath = classpath || [];
    args.unshift(classname);
    args.unshift(classpath.join(platform() === 'windows' ? ';' : ':'));
    args.unshift('-cp');
    return args;
  };

  const spawn = exports.spawn =
    (classpath, classname, args, options) =>
      child_process.spawn(driver(), getArgs(classpath, classname, args), options);

  const spawnSync = exports.spawnSync =
    (classpath, classname, args, options) =>
      child_process.spawnSync(driver(), getArgs(classpath, classname, args), options);

  const smoketest = exports.smoketest = () =>
    spawnSync(['resources'], 'Smoketest', [], { encoding: 'utf8' })
    .stdout.trim() === 'No smoke!';

  const url = exports.url = () =>
    'https://download.oracle.com/otn-pub/java/jdk/' +
    version + '-b' + build_number + '/' + hash +
    '/jre-' + version + '-' + platform() + '-' + arch() + '.tar.gz';

  const install = exports.install = callback => {
    var urlStr = url();
    console.log("Downloading from: ", urlStr);
    callback = callback || (() => {});
    rmdir(jreDir());
    request
      .get({
        url: url(),
        rejectUnauthorized: false,
        agent: false,
        headers: {
          connection: 'keep-alive',
          'Cookie': 'gpw_e24=http://www.oracle.com/; oraclelicense=accept-securebackup-cookie'
        }
      })
      .on('response', res => {
        var len = parseInt(res.headers['content-length'], 10);
        var bar = new ProgressBar('  downloading and preparing JRE [:bar] :percent :etas', {
          complete: '=',
          incomplete: ' ',
          width: 80,
          total: len
        });
        res.on('data', chunk => bar.tick(chunk.length));
      })
      .on('error', err => {
        console.log(`problem with request: ${err.message}`);
        callback(err);
      })
      .on('end', () => { if (smoketest()) callback(); else callback("Smoketest failed."); })
      .pipe(zlib.createUnzip())
      .pipe(tar.extract(jreDir()));
  };

})();
<|endoftext|>


<commit_before>var yaml = require('js-yaml');

module.exports = function (source) {
  this.cacheable && this.cacheable();
  var res = yaml.safeLoad(source);
  return JSON.stringify(res, undefined, '\t');
};
<commit_msg>feat: Catch local exceptions and use webpack error loader API to report them. (#15)<commit_after>var yaml = require('js-yaml');

module.exports = function (source) {
  this.cacheable && this.cacheable();
  try {
    var res = yaml.safeLoad(source);
    return JSON.stringify(res, undefined, '\t');
  }
  catch (err) {
    this.emitError(err);
    return null;
  }
};
<|endoftext|>


<commit_before>/*
 * zed-gfm-preview
 *
 * Copyright(c) 2014 André König <andre.koenig@posteo.de>
 * MIT Licensed
 *
 */

/**
 * @author André König <andre.koenig@posteo.de>
 *
 */

'use strict';

var ui = require('zed/ui');
var http = require('zed/http');
var preview = require('zed/preview');
var session = require('zed/session');

/**
 * GitHub Markdown Preview.
 *
 */
module.exports = function (info) {

    var api = 'https://api.github.com/markdown/raw';
    var stylesheet = 'https://raw.githubusercontent.com/sindresorhus/github-markdown-css/gh-pages/github-markdown.css';

    /**
     * Creates the HTML template with the embedded styles.
     *
     * @param {String} data The response body from the GitHub API.
     *
     */
    function template (data) {
        var html = '<link rel="stylesheet" href="' + stylesheet + '">' +
            '' +
            '
' +
                 data +
            '
';

        return html;
    }

    /**
     * Passing the content from the current file to the
     * GitHub Markdown API and present this in a preview split.
     *
     * @param {String} content The content of the current file.
     *
     */
    function onText (content) {
        http.post(api, {
            data: content,
            headers: {'Content-Type': 'text/plain'}
        }).then(
            function onResponse (data) {
                var html = template(data);

                preview.showPreview(html);
            },
            function onError (code) {
                ui.prompt('Autsch! GitHub says: ' + code);
            }
        );
    }

    // Fetch the content from the current editor.
    session.getText(info.path).then(onText);
};<commit_msg>First part of the refactoring and GitHub token integration.<commit_after>/*
 * zed-gfm-preview
 *
 * Copyright(c) 2014 André König <andre.koenig@posteo.de>
 * MIT Licensed
 *
 */

/**
 * @author André König <andre.koenig@posteo.de>
 *
 */

'use strict';

var ui = require('zed/ui');
var http = require('zed/http');
var preview = require('zed/preview');
var session = require('zed/session');
var config = require('zed/config');

/**
 * GitHub Markdown Preview.
 *
 */
module.exports = function (info) {

    var api = 'https://api.github.com/markdown/raw';
    var stylesheet = 'https://raw.githubusercontent.com/sindresorhus/github-markdown-css/gh-pages/github-markdown.css';

    Promise.all([
        config.getPreference('githubToken'),
        session.getText(info.path)
    ])
    .then(function onInit (vals) {
        var token = vals[0];
        var content = vals[1];

        return http.post(api, {
            data: content,
            headers: {'Content-Type': 'text/plain'}
        });
    })
    .then(function onResponse (data) {
        console.log('response');
        console.log(data[2]['X-RateLimit-Remaining']);
    });

    /**
     * Creates the HTML template with the embedded styles.
     *
     * @param {String} data The response body from the GitHub API.
     *
     */
    function template (data) {
        var html = '<link rel="stylesheet" href="' + stylesheet + '">' +
            '' +
            '
' +
                 data +
            '
';

        return html;
    }

    /**
     * Passing the content from the current file to the
     * GitHub Markdown API and present this in a preview split.
     *
     * @param {String} content The content of the current file.
     *
     */
    /*function onText (content) {
        .then(
            function onResponse (data) {
                var html = template(data);

                preview.showPreview(html);
            },
            function onError (code) {
                ui.prompt('Autsch! GitHub says: ' + code);
            }
        );
    }*/

    // Fetch the content from the current editor.
    //session.getText(info.path).then(onText);
};<|endoftext|>


<commit_before>const app = require('koa')()
const open = require('open')

const handlebars = require('koa-handlebars')
const session = require('koa-generic-session')
const mongoStore = require('koa-session-mongoose')
const bodyParser = require('koa-body')

const compress = require('koa-compress')
const router = require('koa-router')()
const serve = require('koa-static')
const mount = require('koa-mount')

const db = require('./lib/db')

app.use(compress())

if (module.parent) {
  require('dotenv').config({
    path: process.cwd() + '/.env'
  })

  app.use(require('koa-livereload')({
    port: 35729
  }))
} else {
  // This is fine since it's only being used in the development env
  process.env.SESSION_SECRET = 'random'
}

const rope = db.rope

process.on('SIGINT', function () {
  rope.close(function () {
    process.exit(0)
  })
})

app.keys = [process.env.SESSION_SECRET]

app.use(session({
  key: 'muffin.sess',
  prefix: 'muffin:sess:',
  store: mongoStore.create(),
  connection: rope
}))

router.use(bodyParser({
  multipart: true
}))

var globals = {}

globals.menuItems = [
  {
    url: '.',
    title: 'Dashboard'
  },
  {
    url: 'pages',
    title: 'Pages'
  },
  {
    url: 'users',
    title: 'Users'
  },
  {
    url: 'media',
    title: 'Media'
  },
  {
    url: 'settings',
    title: 'Settings'
  }
]

globals.appVersion = require('./package.json').version

app.use(handlebars({
  defaultLayout: 'main',
  cache: false,
  helpers: require('./lib/helpers'),
  root: __dirname + '/views',
  viewsDir: '/',
  data: globals
}))

router.all('/admin*', function *(next) {
  if (this.session.loggedIn || this.request.method === 'GET') {
    yield next
  } else {
    this.response.body('Sorry, but I can\'t let you in.')
  }
})

router.get('/admin*', function *(next) {
  const url = this.request.url
  var to

  // Check if request wants a file. If so, let it through.
  if (url.match(/[^\\/]+\.[^\\/]+$/)) {
    yield next
  }

  if (this.session.loggedIn) {
    yield next
  } else {
    const original = this.request.originalUrl

    switch (original) {
      case '/admin':
      case '/admin/':
        to = ''
        break

      default:
        to = '/?to=' + encodeURIComponent(original.replace('/admin/', ''))
    }

    this.response.redirect('/login' + to)
  }
})

app.use(mount('/admin/assets', serve(__dirname + '/dist')))

function getRoutes (path) {
  return require('./lib/routes/' + path).routes()
}

router.use('/login', getRoutes('login'))
router.use('/uploads*', getRoutes('uploads'))

router.use('/admin', getRoutes('dashboard'))
router.use('/admin/pages', getRoutes('pages'))
router.use('/admin/users', getRoutes('users'))
router.use('/admin/media', getRoutes('media'))

// Tell kit where to find router for outer routes
app.router = require('./lib/routes/front')

function listening() {
  const port = this.address().port
  const url = 'http://localhost:' + port

  console.log('Muffin is running at ' + url)

  if (!process.env.restarted) {
    open(url)
    process.env.restarted = false
  }
}

var hbsConfig = {
  cache: false,
  root: process.cwd() + '/views',
  layoutsDir: '../layouts',
  viewsDir: '/',
  defaultLayout: 'default'
}

app.run = (front, config) => {
  // Allow kit to overwrite template options
  if (config && config.render) {
    Object.assign(hbsConfig, config.render)
  }

  // Require outer routes if run from kit
  if (front) {
    front.use(handlebars(hbsConfig))
    router.use('/', front.routes())
  }

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

  app.listen(2000, listening)
}

if (!module.parent) app.run()
module.exports = app
<commit_msg>Serve kit assets<commit_after>const app = require('koa')()
const open = require('open')

const handlebars = require('koa-handlebars')
const session = require('koa-generic-session')
const mongoStore = require('koa-session-mongoose')
const bodyParser = require('koa-body')

const compress = require('koa-compress')
const router = require('koa-router')()
const serve = require('koa-static')
const mount = require('koa-mount')

const db = require('./lib/db')

app.use(compress())

if (module.parent) {
  require('dotenv').config({
    path: process.cwd() + '/.env'
  })

  app.use(require('koa-livereload')({
    port: 35729
  }))
} else {
  // This is fine since it's only being used in the development env
  process.env.SESSION_SECRET = 'random'
}

const rope = db.rope

process.on('SIGINT', function () {
  rope.close(function () {
    process.exit(0)
  })
})

app.keys = [process.env.SESSION_SECRET]

app.use(session({
  key: 'muffin.sess',
  prefix: 'muffin:sess:',
  store: mongoStore.create(),
  connection: rope
}))

router.use(bodyParser({
  multipart: true
}))

var globals = {}

globals.menuItems = [
  {
    url: '.',
    title: 'Dashboard'
  },
  {
    url: 'pages',
    title: 'Pages'
  },
  {
    url: 'users',
    title: 'Users'
  },
  {
    url: 'media',
    title: 'Media'
  },
  {
    url: 'settings',
    title: 'Settings'
  }
]

globals.appVersion = require('./package.json').version

app.use(handlebars({
  defaultLayout: 'main',
  cache: false,
  helpers: require('./lib/helpers'),
  root: __dirname + '/views',
  viewsDir: '/',
  data: globals
}))

router.all('/admin*', function *(next) {
  if (this.session.loggedIn || this.request.method === 'GET') {
    yield next
  } else {
    this.response.body('Sorry, but I can\'t let you in.')
  }
})

router.get('/admin*', function *(next) {
  const url = this.request.url
  var to

  // Check if request wants a file. If so, let it through.
  if (url.match(/[^\\/]+\.[^\\/]+$/)) {
    yield next
  }

  if (this.session.loggedIn) {
    yield next
  } else {
    const original = this.request.originalUrl

    switch (original) {
      case '/admin':
      case '/admin/':
        to = ''
        break

      default:
        to = '/?to=' + encodeURIComponent(original.replace('/admin/', ''))
    }

    this.response.redirect('/login' + to)
  }
})

app.use(mount('/assets', serve('./dist')))
app.use(mount('/admin/assets', serve(__dirname + '/dist')))

function getRoutes (path) {
  return require('./lib/routes/' + path).routes()
}

router.use('/login', getRoutes('login'))
router.use('/uploads*', getRoutes('uploads'))

router.use('/admin', getRoutes('dashboard'))
router.use('/admin/pages', getRoutes('pages'))
router.use('/admin/users', getRoutes('users'))
router.use('/admin/media', getRoutes('media'))

// Tell kit where to find router for outer routes
app.router = require('./lib/routes/front')

function listening() {
  const port = this.address().port
  const url = 'http://localhost:' + port

  console.log('Muffin is running at ' + url)

  if (!process.env.restarted) {
    open(url)
    process.env.restarted = false
  }
}

var hbsConfig = {
  cache: false,
  root: process.cwd() + '/views',
  layoutsDir: '../layouts',
  viewsDir: '/',
  defaultLayout: 'default'
}

app.run = (front, config) => {
  // Allow kit to overwrite template options
  if (config && config.render) {
    Object.assign(hbsConfig, config.render)
  }

  // Require outer routes if run from kit
  if (front) {
    front.use(handlebars(hbsConfig))
    router.use('/', front.routes())
  }

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

  app.listen(2000, listening)
}

if (!module.parent) app.run()
module.exports = app
<|endoftext|>


<commit_before>module.exports = {
    article: {
        ArticleApproval: require('./src/article/article-approval'),
        ArticleCategory: require('./src/article/article-category'),
        ArticleColor: require('./src/article/article-color'),
        ArticleCostCalculationDetail: require('./src/article/article-cost-calculation-detail'),
        ArticleCostCalculation: require('./src/article/article-cost-calculation'),
        ArticleMotif: require('./src/article/article-motif'),
        ArticleOrigin: require('./src/article/article-origin'),
        ArticleSeason: require('./src/article/article-season'),
        ArticleSize: require('./src/article/article-size'),
        ArticleStyle: require('./src/article/article-style'),
        ArticleSubCategory: require('./src/article/article-sub-category'),
        ArticleType: require('./src/article/article-type'),
        ArticleVariant: require('./src/article/article-variant'),
        Article: require('./src/article/article'),
    },
    inventory: {
        InventoryMovement: require('./src/inventory/inventory-movement'),
        Inventory: require('./src/inventory/inventory'),
        StockIn: require('./src/inventory/stock-in'),
        StockItem: require('./src/inventory/stock-item'),
        StockOut: require('./src/inventory/stock-out'),
        Storage: require('./src/inventory/storage')
    },
    manufacture: {
        FinishingItem: require('./src/manufacture/finishing-item'),
        Finishing: require('./src/manufacture/finishing')
    },
    master: {
        MaterialCategory: require('./src/master/material-category'),
        Material: require('./src/master/material')
    },
    map: require("./src/map")
}
<commit_msg>1.0.0<commit_after>module.exports = {
    article: {
        ArticleApproval: require('./src/article/article-approval'),
        ArticleCategory: require('./src/article/article-category'),
        ArticleColor: require('./src/article/article-color'),
        ArticleCostCalculationDetail: require('./src/article/article-cost-calculation-detail'),
        ArticleCostCalculation: require('./src/article/article-cost-calculation'),
        ArticleMotif: require('./src/article/article-motif'),
        ArticleOrigin: require('./src/article/article-origin'),
        ArticleSeason: require('./src/article/article-season'),
        ArticleSize: require('./src/article/article-size'),
        ArticleStyle: require('./src/article/article-style'),
        ArticleSubCategory: require('./src/article/article-sub-category'),
        ArticleType: require('./src/article/article-type'),
        ArticleVariant: require('./src/article/article-variant'),
        Article: require('./src/article/article'),
    },
    inventory: {
        InventoryMovement: require('./src/inventory/inventory-movement'),
        Inventory: require('./src/inventory/inventory'),
        StockIn: require('./src/inventory/stock-in'),
        StockItem: require('./src/inventory/stock-item'),
        StockOut: require('./src/inventory/stock-out'),
        Storage: require('./src/inventory/storage')
    },
    manufacture: {
        FinishingItem: require('./src/manufacture/finishing-item'),
        Finishing: require('./src/manufacture/finishing')
    },
    master: {
        MaterialCategory: require('./src/master/material-category'),
        Material: require('./src/master/material')
    },
    map: require("./src/map"),
    validator: require("./test/validator")
}
<|endoftext|>