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

var LTBR       = require('level-tbr')
var hyperquest = require('hyperquest')
var toPull     = require('stream-to-pull-stream')
var pull       = require('pull-stream')
var split      = require('pull-split')
var csvLine    = require('csv-line')
var url        = require('url')
var qs         = require('querystring')
var http       = require('http')
var stack      = require('stack')
var route      = require('tiny-route')
var periods    = require('time-period').periods
var stringify  = require('pull-stringify')
var query      = require('./query')
var createDb   = require('./db')

var version    = require('./package.json').version

module.exports = function (config) {

  var db = createDb(config)

  var tbr = LTBR(db, function (since) {
    var u = url.format({
        protocol: 'http',
        hostname: config.megaHost,
        port: config.megaPort,
        pathname: '/query',
        search: qs.encode({gt: since})
      })

    console.error('GET', u)
    return pull(
      toPull(hyperquest(u)),
      split(),
      pull.filter(function (e) {
        return e && e.length
      }),
      pull.map(csvLine.decode)
    )
  })

  //load views from the config file.
  //(TODO, post views via http)

  var views = config.views

  for(var name in views) (function (name) {
    var v = views[name]
    if     (v.stats) v = query.stats(v.stats)
    else if(v.count) v = query.count(v.count)
    else
      throw new Error('view may be type "count" or "stats"')

    tbr.addQuery({
      name   : name,
      map    : v.filter,
      reduce : v.reduce
    })
  })(name)

  var qdb = db.sublevel('queries')

  function filter (q, opts) {
    var d = q.dump()
      .filter(function (e) {
        return e.value != null && (opts.period ? e.type === opts.period : true)
      })
    return opts.period ? d[0] : d
  }

  return http.createServer(stack(
    route.get(/^\/view\/(\w+)/, function (req, res, next) {
      var opts = qs.decode(url.parse(req.url).query)
      opts.name = req.params[0]

      try {
        pull(
          tbr.query(opts),
          pull.map(function (d) {
            return {key: d.key[2], value: d.value}
          }),
          opts.lines ? stringify.lines() : stringify(),
          toPull.sink(res)
        )
      } catch (err) {
        return next(err)
      }
    }),
    route.get(/^\/views/, function (req, res, next) {
      res.end(JSON.stringify(Object.keys(tbr.queries), null, 2) + '\n')
    }),
    route.get(/^\/state\/(\w+)/, function (req, res, next) {
      var name = req.params[0]
      var query = tbr.queries[name]
      var opts = qs.decode(url.parse(req.url).query)

      if(!query)
        return next(new Error('unknown query:'+name))
      var data = filter(query, opts)

      res.end(JSON.stringify(data, null, 2) + '\n')
    }),
    route.get(/^\/state/, function (req, res, next) {
      var opts = qs.decode(url.parse(req.url).query)
      var d = {}
      for(var name in tbr.queries) {
        var q = tbr.queries[name]
        if('function' === typeof q.dump)
          d[name] = filter(q, opts)
      }
      res.end(JSON.stringify(d, null, 2) + '\n')
    }),
    route.get(/^\/$/, function (req, res, next) {
      res.end(
        JSON.stringify({
          views: '/views',
          view: '/view/{name}',
          viewState: '/state/{name}',
          allState: '/state'
        }, null, 2) + '\n'
      )

    }),
    route.get(/^\/version$/, function (req, res, next) {
      res.end(version + '\n')
    })
//    route.post(/^\/(count|sum)\/(\w+)\//, function (req, res, next) {
//      var type = req.params[0]
//      var name = req.params[1]
//      console.log(type, name, req.url)
//      var line = csvLine.decode(req.url)
//      res.end('ok')
//    })
  ))

}

if(!module.parent) {
  var config = require('./config')
  var server = module.exports(config)
  server.listen(config.viewPort)
}
<commit_msg>support - in names<commit_after>#! /usr/bin/env node

var LTBR       = require('level-tbr')
var hyperquest = require('hyperquest')
var toPull     = require('stream-to-pull-stream')
var pull       = require('pull-stream')
var split      = require('pull-split')
var csvLine    = require('csv-line')
var url        = require('url')
var qs         = require('querystring')
var http       = require('http')
var stack      = require('stack')
var route      = require('tiny-route')
var periods    = require('time-period').periods
var stringify  = require('pull-stringify')
var query      = require('./query')
var createDb   = require('./db')

var version    = require('./package.json').version

module.exports = function (config) {

  var db = createDb(config)

  var tbr = LTBR(db, function (since) {
    var u = url.format({
        protocol: 'http',
        hostname: config.megaHost,
        port: config.megaPort,
        pathname: '/query',
        search: qs.encode({gt: since})
      })

    console.error('GET', u)
    return pull(
      toPull(hyperquest(u)),
      split(),
      pull.filter(function (e) {
        return e && e.length
      }),
      pull.map(csvLine.decode)
    )
  })

  //load views from the config file.
  //(TODO, post views via http)

  var views = config.views

  for(var name in views) (function (name) {
    var v = views[name]
    if     (v.stats) v = query.stats(v.stats)
    else if(v.count) v = query.count(v.count)
    else
      throw new Error('view may be type "count" or "stats"')

    tbr.addQuery({
      name   : name,
      map    : v.filter,
      reduce : v.reduce
    })
  })(name)

  var qdb = db.sublevel('queries')

  function filter (q, opts) {
    var d = q.dump()
      .filter(function (e) {
        return e.value != null && (opts.period ? e.type === opts.period : true)
      })
    return opts.period ? d[0] : d
  }

  return http.createServer(stack(
    route.get(/^\/view\/([\w-_.]+)/, function (req, res, next) {
      var opts = qs.decode(url.parse(req.url).query)
      opts.name = req.params[0]

      try {
        pull(
          tbr.query(opts),
          pull.map(function (d) {
            return {key: d.key[2], value: d.value}
          }),
          opts.lines ? stringify.lines() : stringify(),
          toPull.sink(res)
        )
      } catch (err) {
        return next(err)
      }
    }),
    route.get(/^\/views/, function (req, res, next) {
      res.end(JSON.stringify(Object.keys(tbr.queries), null, 2) + '\n')
    }),
    route.get(/^\/state\/([\w-_.]+)/, function (req, res, next) {
      var name = req.params[0]
      var query = tbr.queries[name]
      var opts = qs.decode(url.parse(req.url).query)

      if(!query)
        return next(new Error('unknown query:'+name))
      var data = filter(query, opts)

      res.end(JSON.stringify(data, null, 2) + '\n')
    }),
    route.get(/^\/state/, function (req, res, next) {
      var opts = qs.decode(url.parse(req.url).query)
      var d = {}
      for(var name in tbr.queries) {
        var q = tbr.queries[name]
        if('function' === typeof q.dump)
          d[name] = filter(q, opts)
      }
      res.end(JSON.stringify(d, null, 2) + '\n')
    }),
    route.get(/^\/$/, function (req, res, next) {
      res.end(
        JSON.stringify({
          views: '/views',
          view: '/view/{name}',
          viewState: '/state/{name}',
          allState: '/state'
        }, null, 2) + '\n'
      )

    }),
    route.get(/^\/version$/, function (req, res, next) {
      res.end(version + '\n')
    })
//    route.post(/^\/(count|sum)\/(\w+)\//, function (req, res, next) {
//      var type = req.params[0]
//      var name = req.params[1]
//      console.log(type, name, req.url)
//      var line = csvLine.decode(req.url)
//      res.end('ok')
//    })
  ))

}

if(!module.parent) {
  var config = require('./config')
  var server = module.exports(config)
  server.listen(config.viewPort)
}
<|endoftext|>


<commit_before>/**
 * update-copyright <https://github.com/jonschlinkert/update-copyright>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */

var parse = require('parse-copyright');
var extend = require('extend-shallow');
var currentYear = +require('year')();
var jsdiff = require('diff');
var chalk = require('chalk');

module.exports = function update(str, options) {
  var opts = extend({year: currentYear, verbose: true}, options);
  var re = new RegExp('(Copyright[^\\d]*)(20\\d{2})([^\\n]+)', 'i');

  var matches = parse(str);
  console.log(matches)

  // var match = str.match(re) || [];

  // var prefix = opts.prefix || match[1];
  // var author = cleanAuthor(opts.author || match[3]);
  // var prev = opts.prev || match[2] || opts.year;
  // var year = opts.year;

  // var range = (+prev === +year ? year : (prev + '-' + year)).toString();
  // var updated = (prefix + range + formatAuthor(author));
  // var orig = match[0];
  // str = str.replace(orig, updated);

  // var ctx = {};
  // ctx.prefix = prefix;
  // ctx.author = author;
  // ctx.prev = prev;
  // ctx.year = year;

  // ctx.range = range;
  // ctx.updated = updated;
  // ctx.original = orig;
  // render(ctx);

  // if (opts.verbose === true) {
  //   diff(orig, updated);
  //   // console.log(prev + ' => ' + range);
  // }
  return str;
};

function render(context) {
  console.log(context)
}

function diff(a, b) {
  jsdiff.diffChars(a, b).forEach(function (part) {
    var color = part.added
      ? chalk.green
      : (part.removed ? chalk.red : chalk.gray);

    process.stderr.write(color(part.value));
  });
  console.log()
}

function formatAuthor(str) {
  return ', ' + str + '.';
}

var template = '<%= prefix %><%= symbol ? ' ' + symbol + ' ' %><%= date %>, <%= author %>.';
<commit_msg>working implementation<commit_after>/**
 * update-copyright <https://github.com/jonschlinkert/update-copyright>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */

var parseAuthor = require('parse-author');
var parseCopyright = require('parse-copyright');
var updateYear = require('update-year');
var extend = require('extend-shallow');
var omit = require('omit-empty');
var currentYear = +require('year')();
var leven = require('leven');
var jsdiff = require('diff');
var chalk = require('chalk');
var pkg = require('load-pkg');
var _ = require('lodash');

/**
 * Parse a copyright statement and return a new, updated
 * copyright statement.
 *
 * @param  {String} `str`
 * @param  {Object} `options`
 * @return {String}
 */

function updateCopyright (str, options) {
  return parse(str, options).updated;
}

function parse(str, options) {
  var opts = extend({}, options);
  var matches = parseCopyright(str);
  var len = matches.length;
  if (len === 0) { len = 1; }

  var res = '', i = -1;

  while (len--) {
    res += copyright(matches[++i], options);
  }

  if (opts.diff) { diff(str, res); }
  var obj = {};
  obj.original = str;
  obj.matches = matches;
  obj.updated = res;
  return obj;
}

function getAuthor(match) {
  if (!match.author) { return pkg.author; }

  var author = clean(match.author);
  if (pkg.author) {
    if (typeof pkg.author === 'string') {
      pkg.author = clean(parseAuthor(pkg.author).name);
    } else if (typeof pkg.author === 'object') {
      pkg.author = clean(pkg.author.name);
    }
    if (leven(author, pkg.author) < 2) {
      author = pkg.author;
    }
  }
  return author;
}

var template = '<%= prefix %><%= symbol ? (" " + symbol + " ") : "" %><%= years %>, <%= author %>.';

function copyright(match, options) {
  var defaults = {year: currentYear, prefix: 'Copyright', symbol: '(c)'};
  var opts = extend({verbose: true, template: template}, options);
  var ctx = extend(defaults, omit(match));
  ctx.author = opts.author || getAuthor(ctx);
  ctx.years = opts.year || updateYear(ctx.dateRange || currentYear.toString());
  return _.template(opts.template)(ctx);
}

function diff(a, b) {
  jsdiff.diffChars(a, b).forEach(function (part) {
    var color = part.added
      ? chalk.green
      : (part.removed ? chalk.red : chalk.gray);

    process.stderr.write(color(part.value));
  });
  console.log();
}

function clean(str) {
  return str.replace(/^\W+|\W+$/g, '');
}

module.exports = updateCopyright;
module.exports.parse = parse;
<|endoftext|>


<commit_before>/**
 * The main module to run the linters.
 */
var async = require("async");
var less = require("less");
var postcss = require("postcss");
var sourceMap = require("source-map");

var abcLint = require("./lib/abc-lint");
var overqualifiedLint = require("./lib/overqualified-lint");
var nestingLint = require("./lib/nesting-lint");

const CSS_LINTERS = [overqualifiedLint];
const LESS_LINTERS = [abcLint, nestingLint];

module.exports = function(code) {
    var errors = [];
    function reportError(error) {
        errors.push(error);
    }

    function runLessLinters(done) {
        less.parse(code, function(err, ast) {
            if (err) {
                return done(err);
            }

            LESS_LINTERS.forEach(function(linter) {
                linter(code, ast, reportError);
            });

            done();
        });
    }

    function runCSSLinters(done) {
        var options = {
            sourceMap: {
                outputSourceFiles: true,
            },
        };

        less.render(code, options, function(err, result) {
            if (err) {
                return done(err);
            }

            // Establish a SourceMapConsumer to point to the original less
            var smc = new sourceMap.SourceMapConsumer(result.map);
            var ast = postcss.parse(result.css);
            CSS_LINTERS.forEach(function(linter) {
                linter(ast, smc, reportError);
            });

            done();
        });
    }

    // Run the linter groups in parallel
    async.parallel([runLessLinters, runCSSLinters], function(err) {
        if (err) {
            console.log(err);
            process.exit(1);
        }

        // Report any errors
        if (errors.length) {
            errors.forEach(function(error) {
                console.log(error);
            });

            process.exit(1);
        }
    });
};
<commit_msg>error message for parsing error<commit_after>/**
 * The main module to run the linters.
 */
var async = require("async");
var less = require("less");
var postcss = require("postcss");
var sourceMap = require("source-map");

var abcLint = require("./lib/abc-lint");
var overqualifiedLint = require("./lib/overqualified-lint");
var nestingLint = require("./lib/nesting-lint");

const CSS_LINTERS = [overqualifiedLint];
const LESS_LINTERS = [abcLint, nestingLint];

module.exports = function(code) {
    var errors = [];
    function reportError(error) {
        errors.push(error);
    }

    function runLessLinters(done) {
        less.parse(code, function(err, ast) {
            if (err) {
                return done(err);
            }

            LESS_LINTERS.forEach(function(linter) {
                linter(code, ast, reportError);
            });

            done();
        });
    }

    function runCSSLinters(done) {
        var options = {
            sourceMap: {
                outputSourceFiles: true,
            },
        };

        less.render(code, options, function(err, result) {
            if (err) {
                return done(err);
            }

            // Establish a SourceMapConsumer to point to the original less
            var smc = new sourceMap.SourceMapConsumer(result.map);
            var ast = postcss.parse(result.css);
            CSS_LINTERS.forEach(function(linter) {
                linter(ast, smc, reportError);
            });

            done();
        });
    }

    // Run the linter groups in parallel
    async.parallel([runLessLinters, runCSSLinters], function(err) {
        if (err) {
            // Parsing error
            var location = "(" + err.line + ":" + err.column + ")";
            console.log("Error parsing: unrecognized input " + location);
            process.exit(1);
        }

        // Report any errors
        if (errors.length) {
            errors.forEach(function(error) {
                console.log(error);
            });

            process.exit(1);
        }
    });
};
<|endoftext|>


<commit_before>var Steam = require('steam');
var SteamID = require('steamid');
var AppDirectory = require('appdirectory');
var FileStorage = require('file-manager');
var fs = require('fs');

require('util').inherits(SteamUser, require('events').EventEmitter);

module.exports = SteamUser;

SteamUser.Steam = Steam;
SteamUser.ECurrencyCode = require('./resources/ECurrencyCode.js');
SteamUser.CurrencyData = require('./resources/CurrencyData.js');
SteamUser.EMachineIDType = require('./resources/EMachineIDType.js');

try {
	SteamUser.Steam.servers = require('./resources/servers.json');
} catch(e) {
	// It's okay if it isn't there
}

function SteamUser(client, options) {
	this.client = client ? client : new Steam.SteamClient();
	this.steamID = null;

	// Account info
	this.limitations = null;
	this.vac = null;
	this.wallet = null;
	this.emailInfo = null;
	this.licenses = null;

	// Friends and users info
	this.users = {};
	this.groups = {};
	this.chats = {};
	this.myFriends = {};
	this.myGroups = {};
	this.myFriendGroups = {};

	this._sentry = null;

	var appdir = new AppDirectory({
		"appName": "node-steamuser",
		"appAuthor": "doctormckay"
	});

	this.options = options || {};

	var defaultOptions = {
		"dataDirectory": process.env.OPENSHIFT_DATA_DIR ? process.env.OPENSHIFT_DATA_DIR + "/node-steamuser" : appdir.userData(),
		"autoRelogin": true,
		"singleSentryfile": false,
		"promptSteamGuardCode": true,
		"machineIdType": SteamUser.EMachineIDType.AccountNameGenerated,
		"machineIdFormat": ["SteamUser Hash BB3 {account_name}", "SteamUser Hash FF2 {account_name}", "SteamUser Hash 3B3 {account_name}"],
		"debug": false
	};

	for(var i in defaultOptions) {
		if(!defaultOptions.hasOwnProperty(i)) {
			continue;
		}

		if(typeof this.options[i] === 'undefined') {
			this.options[i] = defaultOptions[i];
		}
	}

	this.storage = new FileStorage(this.options.dataDirectory);

	this.client.on('message', this._handleMessage.bind(this));

	var self = this;
	this.client.on('error', function(e) {
		if(!self.steamID) {
			return; // We've already handled this
		}

		if(self.options.autoRelogin) {
			self.emit('disconnected', Steam.EResult.RemoteDisconnect);
			self.steamID = null;
			self.logOn(true);
		} else {
			e.eresult = Steam.EResult.RemoteDisconnect;
			self.emit('error', e);
			self.steamID = null;
		}
	});

	this.client.on('servers', function(servers) {
		self.storage.writeFile('servers.json', JSON.stringify(servers, null, "\t"));
		if(!client) {
			// It's an internal client, so we know that our Steam has an up-to-date server list
			Steam['__SteamUserServersSet__'] = true;
		}
	});
}

SteamUser.prototype.setOption = function(option, value) {
	this.options[option] = value;

	// Handle anything that needs to happen when particular options update
	switch(option) {
		case 'dataDirectory':
			this.storage.directory = value;
			break;
	}
};

SteamUser.prototype.setOptions = function(options) {
	for(var i in options) {
		if(!options.hasOwnProperty(i)) {
			continue;
		}

		this.setOption(i, options[i]);
	}
};

require('./components/messages.js');
require('./components/logon.js');
require('./components/sentry.js');
require('./components/web.js');
require('./components/notifications.js');
require('./components/apps.js');
require('./components/account.js');
require('./components/gameservers.js');
require('./components/utility.js');
require('./components/trading.js');
require('./components/friends.js');
require('./components/chat.js');
require('./components/twofactor.js');

/**
 * Called when the request completes.
 * @callback SteamUser~genericEResultCallback
 * @param {EResult} eresult - The result of the operation
 */
<commit_msg>Remove unused dependencies<commit_after>var Steam = require('steam');
var AppDirectory = require('appdirectory');
var FileStorage = require('file-manager');

require('util').inherits(SteamUser, require('events').EventEmitter);

module.exports = SteamUser;

SteamUser.Steam = Steam;
SteamUser.ECurrencyCode = require('./resources/ECurrencyCode.js');
SteamUser.CurrencyData = require('./resources/CurrencyData.js');
SteamUser.EMachineIDType = require('./resources/EMachineIDType.js');

try {
	SteamUser.Steam.servers = require('./resources/servers.json');
} catch(e) {
	// It's okay if it isn't there
}

function SteamUser(client, options) {
	this.client = client ? client : new Steam.SteamClient();
	this.steamID = null;

	// Account info
	this.limitations = null;
	this.vac = null;
	this.wallet = null;
	this.emailInfo = null;
	this.licenses = null;

	// Friends and users info
	this.users = {};
	this.groups = {};
	this.chats = {};
	this.myFriends = {};
	this.myGroups = {};
	this.myFriendGroups = {};

	this._sentry = null;

	var appdir = new AppDirectory({
		"appName": "node-steamuser",
		"appAuthor": "doctormckay"
	});

	this.options = options || {};

	var defaultOptions = {
		"dataDirectory": process.env.OPENSHIFT_DATA_DIR ? process.env.OPENSHIFT_DATA_DIR + "/node-steamuser" : appdir.userData(),
		"autoRelogin": true,
		"singleSentryfile": false,
		"promptSteamGuardCode": true,
		"machineIdType": SteamUser.EMachineIDType.AccountNameGenerated,
		"machineIdFormat": ["SteamUser Hash BB3 {account_name}", "SteamUser Hash FF2 {account_name}", "SteamUser Hash 3B3 {account_name}"],
		"debug": false
	};

	for(var i in defaultOptions) {
		if(!defaultOptions.hasOwnProperty(i)) {
			continue;
		}

		if(typeof this.options[i] === 'undefined') {
			this.options[i] = defaultOptions[i];
		}
	}

	this.storage = new FileStorage(this.options.dataDirectory);

	this.client.on('message', this._handleMessage.bind(this));

	var self = this;
	this.client.on('error', function(e) {
		if(!self.steamID) {
			return; // We've already handled this
		}

		if(self.options.autoRelogin) {
			self.emit('disconnected', Steam.EResult.RemoteDisconnect);
			self.steamID = null;
			self.logOn(true);
		} else {
			e.eresult = Steam.EResult.RemoteDisconnect;
			self.emit('error', e);
			self.steamID = null;
		}
	});

	this.client.on('servers', function(servers) {
		self.storage.writeFile('servers.json', JSON.stringify(servers, null, "\t"));
		if(!client) {
			// It's an internal client, so we know that our Steam has an up-to-date server list
			Steam['__SteamUserServersSet__'] = true;
		}
	});
}

SteamUser.prototype.setOption = function(option, value) {
	this.options[option] = value;

	// Handle anything that needs to happen when particular options update
	switch(option) {
		case 'dataDirectory':
			this.storage.directory = value;
			break;
	}
};

SteamUser.prototype.setOptions = function(options) {
	for(var i in options) {
		if(!options.hasOwnProperty(i)) {
			continue;
		}

		this.setOption(i, options[i]);
	}
};

require('./components/messages.js');
require('./components/logon.js');
require('./components/sentry.js');
require('./components/web.js');
require('./components/notifications.js');
require('./components/apps.js');
require('./components/account.js');
require('./components/gameservers.js');
require('./components/utility.js');
require('./components/trading.js');
require('./components/friends.js');
require('./components/chat.js');
require('./components/twofactor.js');

/**
 * Called when the request completes.
 * @callback SteamUser~genericEResultCallback
 * @param {EResult} eresult - The result of the operation
 */
<|endoftext|>


<commit_before>'use strict';

var MongooseError = require('mongoose/lib/error');
var mongooseModelSave = require('mongoose/lib/model').prototype.save;
var Promise = require('promise');

var errorRegex = /index:\s*(?:.+?\.\$)?(\S*)\s*dup key:\s*\{(.*?)\}/;
var indexesCache = {};

/**
 * Check if given error is an unique error
 *
 * @param {Object} err Error to test
 * @return {bool} True if it is an unique error
 */
function isUniqueError(err) {
    return err && err.name === 'MongoError' &&
        (err.code === 11000 || err.code === 11001);
}

/**
 * Retrieve index information using collection#indexInformation
 * or previously cached data
 *
 * @param {Object} collection Mongoose collection
 * @return {Promise} Resolved with index information data
 */
function getIndexes(collection) {
    return new Promise(function (resolve, reject) {
        if (indexesCache[collection.name]) {
            resolve(indexesCache[collection.name]);
            return;
        }

        collection.indexInformation(function (dbErr, indexes) {
            if (dbErr) {
                reject(dbErr);
                return;
            }

            indexesCache[collection.name] = indexes;
            resolve(indexes);
        });
    });
}

/**
 * Beautify an E11000 or 11001 (unique constraint fail) Mongo error
 * by turning it into a validation error
 *
 * @param {MongoError} err Error to process
 * @param {Object} model Model associated to the document
 * @param {Object} messages Map fields to unique error messages
 * @return {Promise} Resolved with the beautified error message
 */
function beautify(error, model, messages) {
    var matches, indexName, rawValues, valueRegex;

    return new Promise(function (resolve, reject) {
        // get index name from the error message
        matches = errorRegex.exec(error.message);

        if (!matches) {
            reject(new Error(
                'mongoose-beautiful-unique-validation error: ' +
                'Unrecognized error pattern. The error has not ' +
                'been processed.'
            ));
            return;
        }

        indexName = matches[1], rawValues = matches[2].trim() + ',';
        valueRegex = /\s*:\s*(\S*),/g;

        // look for the index contained in the MongoDB error
        getIndexes(model.collection).then(function (indexes) {
            var index = indexes[indexName];

            if (!index) {
                reject(new Error(
                    'mongoose-beautiful-unique-validation error: ' +
                    'could not find index "' + indexName + '" among ' +
                    'the collection\'s indexes'
                ));
                return;
            }

            var createdError = new MongooseError.ValidationError(model);

            // populate validation error with the index's fields
            index.forEach(function (item) {
                var value = valueRegex.exec(rawValues)[1],
                    path = item[0], props;

                // the value is parsed directly from the error
                // string. We try to guess the value type (in a basic way)
                if (value[0] === '"' || value[0] === "'") {
                    value = value.substr(1, value.length - 2);
                } else if (!isNaN(value)) {
                    value = parseFloat(value);
                }

                props = {
                    type: 'Duplicate value',
                    path: path,
                    value: value
                };

                if (typeof messages[path] === 'string') {
                    props.message = messages[path];
                }

                createdError.errors[item[0]] =
                    new MongooseError.ValidatorError(props);
            });

            resolve(createdError);
        }).catch(reject);
    });
}

module.exports = function (schema) {
    var tree = schema.tree, key, messages = {};

    // fetch error messages defined in the "unique" field,
    // store them for later use and replace them with true
    for (key in tree) {
        if (tree.hasOwnProperty(key)) {
            if (tree[key] && tree[key].unique) {
                messages[key] = tree[key].unique;
                tree[key].unique = true;
            }
        }
    }

    schema._indexes.forEach(function (index) {
        if (index[0] && index[1] && index[1].unique) {
            Object.keys(index[0]).forEach(function (indexKey) {
                messages[indexKey] = index[1].unique;
            });

            index[1].unique = true;
        }
    });

    /**
     * Save the schema in the database, beautify any
     * unique error produced in the process
     *
     * @param {Object} [options] Options for #save
     * @param {bool} [options.safe] Overrides schema's safe option
     * @param {bool} [options.validateBeforeSave] Set to false to save without validating
     * @param {bool} [options.beautifyUnique] Set to false to disable beautifying unique errors
     * @param {function} [callback] Callback called with any error and the document
     * @return {Promise} If no callback was provided, resolved with the
     * document and fails if any error was produced
     */
    schema.methods.save = function (options, callback) {
        var that = this;

        // default arguments
        if (typeof options === 'function') {
            callback = options;
            options = {};
        }

        if (options === undefined) {
            options = {};
        }

        if (typeof callback !== 'function') {
            callback = function () {};
        }

        var beautifyUnique = options.beautifyUnique !== false;

        return new Promise(function (resolve, reject) {
            mongooseModelSave.call(that, options, function (err, document, numAffected) {
                // we have a native E11000/11001 error, lets beautify it
                if (isUniqueError(err) && beautifyUnique) {
                    beautify(err, that, messages).then(function (beautifiedErr) {
                        // successfully beautified the error
                        reject(beautifiedErr);
                        callback(beautifiedErr);
                    }).catch(function (beautifyingErr) {
                        // the error could not be beautified. Warn about
                        // it and pass on the normal error
                        console.warn(beautifyingErr);
                        reject(err);
                        callback(err);
                    });
                    return;
                }

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

                resolve(document);
                callback(null, document, numAffected);
            });
        });
    };

    /**
     * Deprecated, use #save instead
     */
    schema.methods.trySave = function (callback) {
        // /!\ Deprecation warning
        console.warn(
            'mongoose-beautiful-unique-validation: Model#trySave() is ' +
            'deprecated, use Model#save() instead. To disable ' +
            'beautifying on plugged-in models, set the "beautifyUnique" ' +
            'option to false in this function\'s arguments'
        );

        return this.save({}, callback);
    };
};
<commit_msg>Fix regex to handle spaced fields<commit_after>'use strict';

var MongooseError = require('mongoose/lib/error');
var mongooseModelSave = require('mongoose/lib/model').prototype.save;
var Promise = require('promise');

var errorRegex = /index:\s*(?:.+?\.\$)?(.*?)\s*dup key:\s*\{(.*?)\}/;
var indexesCache = {};

/**
 * Check if given error is an unique error
 *
 * @param {Object} err Error to test
 * @return {bool} True if it is an unique error
 */
function isUniqueError(err) {
    return err && err.name === 'MongoError' &&
        (err.code === 11000 || err.code === 11001);
}

/**
 * Retrieve index information using collection#indexInformation
 * or previously cached data
 *
 * @param {Object} collection Mongoose collection
 * @return {Promise} Resolved with index information data
 */
function getIndexes(collection) {
    return new Promise(function (resolve, reject) {
        if (indexesCache[collection.name]) {
            resolve(indexesCache[collection.name]);
            return;
        }

        collection.indexInformation(function (dbErr, indexes) {
            if (dbErr) {
                reject(dbErr);
                return;
            }

            indexesCache[collection.name] = indexes;
            resolve(indexes);
        });
    });
}

/**
 * Beautify an E11000 or 11001 (unique constraint fail) Mongo error
 * by turning it into a validation error
 *
 * @param {MongoError} err Error to process
 * @param {Object} model Model associated to the document
 * @param {Object} messages Map fields to unique error messages
 * @return {Promise} Resolved with the beautified error message
 */
function beautify(error, model, messages) {
    var matches, indexName, rawValues, valueRegex;

    return new Promise(function (resolve, reject) {
        // get index name from the error message
        matches = errorRegex.exec(error.message);

        if (!matches) {
            reject(new Error(
                'mongoose-beautiful-unique-validation error: ' +
                'Unrecognized error pattern. The error has not ' +
                'been processed.'
            ));
            return;
        }

        indexName = matches[1], rawValues = matches[2].trim() + ',';
        valueRegex = /\s*:\s*(\S*),/g;

        // look for the index contained in the MongoDB error
        getIndexes(model.collection).then(function (indexes) {
            var index = indexes[indexName];

            if (!index) {
                reject(new Error(
                    'mongoose-beautiful-unique-validation error: ' +
                    'could not find index "' + indexName + '" among ' +
                    'the collection\'s indexes'
                ));
                return;
            }

            var createdError = new MongooseError.ValidationError(model);

            // populate validation error with the index's fields
            index.forEach(function (item) {
                var value = valueRegex.exec(rawValues)[1],
                    path = item[0], props;

                // the value is parsed directly from the error
                // string. We try to guess the value type (in a basic way)
                if (value[0] === '"' || value[0] === "'") {
                    value = value.substr(1, value.length - 2);
                } else if (!isNaN(value)) {
                    value = parseFloat(value);
                }

                props = {
                    type: 'Duplicate value',
                    path: path,
                    value: value
                };

                if (typeof messages[path] === 'string') {
                    props.message = messages[path];
                }

                createdError.errors[item[0]] =
                    new MongooseError.ValidatorError(props);
            });

            resolve(createdError);
        }).catch(reject);
    });
}

module.exports = function (schema) {
    var tree = schema.tree, key, messages = {};

    // fetch error messages defined in the "unique" field,
    // store them for later use and replace them with true
    for (key in tree) {
        if (tree.hasOwnProperty(key)) {
            if (tree[key] && tree[key].unique) {
                messages[key] = tree[key].unique;
                tree[key].unique = true;
            }
        }
    }

    schema._indexes.forEach(function (index) {
        if (index[0] && index[1] && index[1].unique) {
            Object.keys(index[0]).forEach(function (indexKey) {
                messages[indexKey] = index[1].unique;
            });

            index[1].unique = true;
        }
    });

    /**
     * Save the schema in the database, beautify any
     * unique error produced in the process
     *
     * @param {Object} [options] Options for #save
     * @param {bool} [options.safe] Overrides schema's safe option
     * @param {bool} [options.validateBeforeSave] Set to false to save without validating
     * @param {bool} [options.beautifyUnique] Set to false to disable beautifying unique errors
     * @param {function} [callback] Callback called with any error and the document
     * @return {Promise} If no callback was provided, resolved with the
     * document and fails if any error was produced
     */
    schema.methods.save = function (options, callback) {
        var that = this;

        // default arguments
        if (typeof options === 'function') {
            callback = options;
            options = {};
        }

        if (options === undefined) {
            options = {};
        }

        if (typeof callback !== 'function') {
            callback = function () {};
        }

        var beautifyUnique = options.beautifyUnique !== false;

        return new Promise(function (resolve, reject) {
            mongooseModelSave.call(that, options, function (err, document, numAffected) {
                // we have a native E11000/11001 error, lets beautify it
                if (isUniqueError(err) && beautifyUnique) {
                    beautify(err, that, messages).then(function (beautifiedErr) {
                        // successfully beautified the error
                        reject(beautifiedErr);
                        callback(beautifiedErr);
                    }).catch(function (beautifyingErr) {
                        // the error could not be beautified. Warn about
                        // it and pass on the normal error
                        console.warn(beautifyingErr);
                        reject(err);
                        callback(err);
                    });
                    return;
                }

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

                resolve(document);
                callback(null, document, numAffected);
            });
        });
    };

    /**
     * Deprecated, use #save instead
     */
    schema.methods.trySave = function (callback) {
        // /!\ Deprecation warning
        console.warn(
            'mongoose-beautiful-unique-validation: Model#trySave() is ' +
            'deprecated, use Model#save() instead. To disable ' +
            'beautifying on plugged-in models, set the "beautifyUnique" ' +
            'option to false in this function\'s arguments'
        );

        return this.save({}, callback);
    };
};
<|endoftext|>


<commit_before><commit_msg>removed code to fix ui-slider triggering geocomp button borders<commit_after><|endoftext|>


<commit_before>var restify = require('restify');
var unirest = require('unirest');
var stats = { 'status' : 'pending', 'servers' : {} };

var Status = {
  servers: [
    "dallas.api.bukget.org",
    "paris.api.bukget.org"
  ],

  versions: {
    "v3": {
      "pl": "/3/plugins",
      "plb": "/3/plugins/bukkit",
      "pd": "/3/plugins/bukkit/pvp-arena",
      "pdl": "/3/plugins/bukkit/pvp-arena/latest",
      "pdr": "/3/plugins/bukkit/pvp-arena/release",
      "pdb": "/3/plugins/bukkit/pvp-arena/beta",
      "pda": "/3/plugins/bukkit/pvp-arena/alpha",
      "cl": "/3/categories",
      "cpl": "/3/categories/Admin Tools",
      "al": "/3/authors",
      "apl": "/3/authors/NuclearW",
      "se": "/3/search/versions.type/=/Alpha?sort=-popularity.daily"
    },

    "v2": {
      "plb": "/2/bukkit/plugins",
      "pd": "/2/bukkit/plugin/pvp-arena",
      "pdl": "/2/bukkit/plugin/pvp-arena/latest",
      "cl": "/2/categories",
      "cpl": "/2/bukkit/category/Admin Tools",
      "al": "/2/authors",
      "apl": "/2/bukkit/author/NuclearW",
      "se": "/2/search/version/type/=/Alpha?sort=-popularity.daily"
    },

    "v1": {
      "pl": "/1/plugins",
      "pd": "/1/plugin/pvp-arena",
      "pdl": "/1/plugin/pvp-arena/latest",
      "cl": "/1/categories",
      "cpl": "/1/categories/Admin Tools",
      "al": "/1/authors",
      "apl": "/1/author/NuclearW",
      "se": "/1/search/slug/like/pvp-arena"
    }
  }
};

Status.call = function (server, uri, callback) {
  var url = "http://" + server + uri;

	unirest.get(url).headers({ 'User-Agent': 'BukGet-Monitor' }).timeout(20000).end(function (response) {
		if (response.error) {
			return callback(false, response.error);
		}

		return callback(true);
	});
};

Status.check = function () {
  for (var server in Status.servers) {
  	(function request (server) {
		  for (var version in Status.versions) {
		    (function request (version) {
		      var sections = Status.versions[version];
		      var errors = 0;
		      var called = 0;
		      var length = Object.keys(sections).length;

		      for (var section in sections) {
		        (function request (section) {
		          var path = sections[section];

		          return Status.call(server, path, function (status, error) {
		            called++;
		            errors += (error == 'ETIMEDOUT' || !status ? 1 : 0);
		            stats['servers'][server][version][section] = (error == 'ETIMEDOUT' ? 'warning' : (status ? 'ok' : 'down'));
		            if (called === length && version === 'v3') {
		              var status = "ok";

		              if (errors > 3) {
		                status = "down";
		              } else if (errors) {
		                status = "warning";
		              }

		              stats.status = status;
		            }

		            return;
		          });
		        })(section);
		      }
		    })(version);
		  }
		})(Status.servers[server]);
	}

  return;
};

for (var server in Status.servers) {
	stats['servers'][Status.servers[server]] = {};
	for (var version in Status.versions) {
		stats['servers'][Status.servers[server]][version] = {};
	}
}

Status.check();

setInterval(function() {
	Status.check();
}, 1000 * 60);

setInterval(function() {
	unirest.get('http://bukget-monitor.herokuapp.com').end(function (response) {});
}, 1000 * 60 * 20);

var app = restify.createServer();

app.use(restify.jsonp());

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/', function (req, res, next) {
	res.send(stats);
});

app.listen(process.env.PORT || 5000);<commit_msg>Pre-fill dict for order<commit_after>var restify = require('restify');
var unirest = require('unirest');
var stats = { 'status' : 'pending', 'servers' : {} };

var Status = {
  servers: [
    "dallas.api.bukget.org",
    "paris.api.bukget.org"
  ],

  versions: {
    "v3": {
      "pl": "/3/plugins",
      "plb": "/3/plugins/bukkit",
      "pd": "/3/plugins/bukkit/pvp-arena",
      "pdl": "/3/plugins/bukkit/pvp-arena/latest",
      "pdr": "/3/plugins/bukkit/pvp-arena/release",
      "pdb": "/3/plugins/bukkit/pvp-arena/beta",
      "pda": "/3/plugins/bukkit/pvp-arena/alpha",
      "cl": "/3/categories",
      "cpl": "/3/categories/Admin Tools",
      "al": "/3/authors",
      "apl": "/3/authors/NuclearW",
      "se": "/3/search/versions.type/=/Alpha?sort=-popularity.daily"
    },

    "v2": {
      "plb": "/2/bukkit/plugins",
      "pd": "/2/bukkit/plugin/pvp-arena",
      "pdl": "/2/bukkit/plugin/pvp-arena/latest",
      "cl": "/2/categories",
      "cpl": "/2/bukkit/category/Admin Tools",
      "al": "/2/authors",
      "apl": "/2/bukkit/author/NuclearW",
      "se": "/2/search/version/type/=/Alpha?sort=-popularity.daily"
    },

    "v1": {
      "pl": "/1/plugins",
      "pd": "/1/plugin/pvp-arena",
      "pdl": "/1/plugin/pvp-arena/latest",
      "cl": "/1/categories",
      "cpl": "/1/categories/Admin Tools",
      "al": "/1/authors",
      "apl": "/1/author/NuclearW",
      "se": "/1/search/slug/like/pvp-arena"
    }
  }
};

Status.call = function (server, uri, callback) {
  var url = "http://" + server + uri;

	unirest.get(url).headers({ 'User-Agent': 'BukGet-Monitor' }).timeout(20000).end(function (response) {
		if (response.error) {
			return callback(false, response.error);
		}

		return callback(true);
	});
};

Status.check = function () {
  for (var server in Status.servers) {
  	(function request (server) {
		  for (var version in Status.versions) {
		    (function request (version) {
		      var sections = Status.versions[version];
		      var errors = 0;
		      var called = 0;
		      var length = Object.keys(sections).length;

		      for (var section in sections) {
		        (function request (section) {
		          var path = sections[section];

		          return Status.call(server, path, function (status, error) {
		            called++;
		            errors += (error == 'ETIMEDOUT' || !status ? 1 : 0);
		            stats['servers'][server][version][section] = (error == 'ETIMEDOUT' ? 'warning' : (status ? 'ok' : 'down'));
		            if (called === length && version === 'v3') {
		              var status = "ok";

		              if (errors > 3) {
		                status = "down";
		              } else if (errors) {
		                status = "warning";
		              }

		              stats.status = status;
		            }

		            return;
		          });
		        })(section);
		      }
		    })(version);
		  }
		})(Status.servers[server]);
	}

  return;
};

for (var server in Status.servers) {
	stats['servers'][Status.servers[server]] = {};
	for (var version in Status.versions) {
		stats['servers'][Status.servers[server]][version] = {};
		for (var section in Status.versions[version]) {
			stats['servers'][Status.servers[server]][version][section] = "pending";
		}
	}
}

Status.check();

setInterval(function() {
	Status.check();
}, 1000 * 60);

setInterval(function() {
	unirest.get('http://bukget-monitor.herokuapp.com').end(function (response) {});
}, 1000 * 60 * 20);

var app = restify.createServer();

app.use(restify.jsonp());

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/', function (req, res, next) {
	res.send(stats);
});

app.listen(process.env.PORT || 5000);<|endoftext|>


<commit_before>;(function( exports ){

	var publisher 	  = pubsub(),
		attribute 	  = 'data-component',
		selector  	  = '['+attribute+']';

	function jails( name, mixin ){
		jails.components[ name ] = mixin;
	}

	jails.events 	 = events();
	jails.components = {};
	jails.publish 	 = publisher.publish;
	jails.subscribe  = publisher.subscribe;

	jails.start = function( ctx ){
		ctx = ctx || document.documentElement;
		each(ctx.querySelectorAll(selector), scan, true);
	};

	jails.destroy = function( ctx, query ){

		ctx = ctx || document.documentElement;
		query = query || selector;

		each(ctx.querySelectorAll( query ), function( node ){
			(node.__eventHandlers[':destroy'] || function(){}).call( node, node );
			node.__events = null;
			node.__eventHandlers = null;
			node.j = null;
		}, true);
	};

	jails.component = function( name, node, fn ){

		var data = {}, init = function(){};

		var base = {

			elm 		:node,
			subscribe 	:publisher.subscribe,
			publish   	:publisher.publish,

			on :function( ev, callback ){
				jails.events.on( node, ev, callback );
			},

			off :function( ev, callback ){
				jails.events.off( node, ev, callback );
			},

			init :function( callback ){
				init = callback;
			},

			props :function( key ){
				data.props = data.props || properties( node );
				return key? data.props[key] : data.props;
			},

			annotations :function( key ){
				data.annotations = data.annotations || annotations( node )[ name ] || {};
				return key? data.annotations[key] : data.annotations;
			},

			set( n, f ){
				node.j[name].methods[n] = f;
			},

			get :function( n, query ){
				return function(){
					var args   = Array.from( arguments );
					var method = args.shift();
					query = query? '[data-component*='+n+']' + query : '[data-component*='+n+']';
					each( node.querySelectorAll(query), function( el ){
						if( el.j && method in el.j[n].methods )
							el.j[n].methods[method].apply(null, args);
						if( node.matches(query) )
							node.j[n].methods[method].apply(null, args);
					});
				}
			},

			emit( n, params ){
				var p = node.parentNode, ev = ':' + n;
				while( p ){
					if( p.j ){
						Object.keys(p.j).forEach(function( name ){
							if( p.__eventHandlers[ev] ){
								p.__eventHandlers[ev].call( node, node, params );
							}
						});
					}
					p = p.parentNode;
				}
			}
		};

		fn( base, node, base.props );
		init( base );
	};

	function annotations( node ){

		let ann = {}, comment;

		comment = node.previousSibling;
		comment = comment && comment.nodeType == 8? comment :comment? comment.previousSibling : null;

		if( comment && comment.nodeType == 8 ){
			comment.data.replace(/@([a-zA-z0-9-\/]*)(?:\((.*)\))?/g, function( text, component, param ){
				ann[component] = new Function('return '+ param)();
			});
		}

		return ann;
	}

	function scan( node ){
		var components = node.getAttribute(attribute).split(/\s/);
		each( components, mount(node) );
	}

	function mount( node ){
		return function( name ){
			if( name in jails.components ){
				node.j = node.j || {};
				node.j[name] = { methods :{} };
				jails.component( name, node, jails.components[name] );
			}
		};
	}

	function properties( node ){
		var props = { data:{} };
		each( node.attributes, propset(props) );
		return props;
	}

	function propset( acc ){
		return function( item ){
			var value, name = item.name.split(/data\-/);
			try{ value = item.value in window? item.value :(new Function('return '+ item.value))(); }
			catch(err){ value = item.value; }

			if( name[1] ) acc.data[name.pop().replace(/-([a-z])/g, upper)] = value;
			else acc[item.name] = value;
			return acc;
		};
	}

	function upper(m, string){
		return string.toUpperCase();
	}

	function each( list, callback, reverse ){
		list = reverse? Array.from( list ).reverse() : list;
		for( var i = 0, len = list.length; i < len; i ++ )
			callback( list[i], i, list );
	}

	function events(){

		function Ev(type, params) {
			var e = document.createEvent(type);
			params = params || {};
			e.initEvent(type, params.bubbles || false, params.cancelable || false, params.detail || null);
			return e;
		}

		function handler(node, ev){
			return function(e){
				var args = arguments;
				node.__events[ev].forEach(function(cb){ cb.apply(this, args); });
			};
		}

		function delegate( callback ){
			return function(){
				var element = this;
				var args = arguments;
				Object.keys(callback).forEach( function(key){
					if( element.matches( key ) )
						callback[key].apply(element, args);
				});
			};
		}

		return {

			on :function( node, ev, callback ){

				node.__eventHandlers = node.__eventHandlers || {};
				node.__events = node.__events || {};

				if( !node.__eventHandlers[ev] ){
					var cb = callback.call? handler(node, ev) : delegate(callback);
					node.__eventHandlers[ev] = cb;
					node.addEventListener( ev, cb, (ev == 'focus' || ev == 'blur') );
				}
				if( callback.call ){
					node.__events[ev] = (node.__events[ev] || []).concat(callback);
				}else{
					Object.keys(callback).forEach(function(key){
						(node.__events[ev] || []).concat(callback).concat( callback[key] );
					});
				}
			},

			off :function(el, ev, fn){
				if( fn && el.__events[ev] && el.__events[ev].length )
					el.__events[ev] = (el.__events[ev] || []).filter(function(cb){ return cb != fn; });
				else
					el.removeEventListener(ev, el.__eventHandlers[ev], false);
			},

			trigger :function(el, name, args){
				try{
					el.dispatchEvent( new Ev( name, { bubbles :true, detail :args } ) );
				}catch(e){
					el.dispatchEvent( new CustomEvent( name, { bubbles :true, detail :args } ) );
				}
			}
		};
	}

	function pubsub( topics, async ){

		topics = {};
		async  = {};

		return {
			publish :function( name, params ){
				if( !(name in topics) )
					async[name] = params;
				else
					each( topics[name], function( topic ){ topic( params ); });
			},
			subscribe :function( name, method ){
				topics[name] = topics[name] || [];
				topics[name].push( method );
				if( name in async )
					each( topics[name], function( topic ){ topic( async[name] ); });
				return function(){
					topics[name] = topics[name].filter(function( topic ){
						return topic == method;
					});
				};
			}
		};
	}

	// UMD export
	if ( typeof define === 'function' && define.amd ) {
		define(function () { return jails; });
	} else if ( typeof module !== 'undefined' && module.exports ){
		module.exports = jails;
	} else {
		exports.jails = jails;
	}
})( window );
<commit_msg>Fix on delegate() method<commit_after>;(function( exports ){

	var publisher 	  = pubsub(),
		attribute 	  = 'data-component',
		selector  	  = '['+attribute+']';

	function jails( name, mixin ){
		jails.components[ name ] = mixin;
	}

	jails.events 	 = events();
	jails.components = {};
	jails.publish 	 = publisher.publish;
	jails.subscribe  = publisher.subscribe;

	jails.start = function( ctx ){
		ctx = ctx || document.documentElement;
		each(ctx.querySelectorAll(selector), scan, true);
	};

	jails.destroy = function( ctx, query ){

		ctx = ctx || document.documentElement;
		query = query || selector;

		each(ctx.querySelectorAll( query ), function( node ){
			(node.__eventHandlers[':destroy'] || function(){}).call( node, node );
			node.__events = null;
			node.__eventHandlers = null;
			node.j = null;
		}, true);
	};

	jails.component = function( name, node, fn ){

		var data = {}, init = function(){};

		var base = {

			elm 		:node,
			subscribe 	:publisher.subscribe,
			publish   	:publisher.publish,

			on :function( ev, callback ){
				jails.events.on( node, ev, callback );
			},

			off :function( ev, callback ){
				jails.events.off( node, ev, callback );
			},

			init :function( callback ){
				init = callback;
			},

			props :function( key ){
				data.props = data.props || properties( node );
				return key? data.props[key] : data.props;
			},

			annotations :function( key ){
				data.annotations = data.annotations || annotations( node )[ name ] || {};
				return key? data.annotations[key] : data.annotations;
			},

			set( n, f ){
				node.j[name].methods[n] = f;
			},

			get :function( n, query ){
				return function(){
					var args   = Array.from( arguments );
					var method = args.shift();
					query = query? '[data-component*='+n+']' + query : '[data-component*='+n+']';
					each( node.querySelectorAll(query), function( el ){
						if( el.j && method in el.j[n].methods )
							el.j[n].methods[method].apply(null, args);
						if( node.matches(query) )
							node.j[n].methods[method].apply(null, args);
					});
				}
			},

			emit( n, params ){
				var p = node.parentNode, ev = ':' + n;
				while( p ){
					if( p.j ){
						Object.keys(p.j).forEach(function( name ){
							if( p.__eventHandlers[ev] ){
								p.__eventHandlers[ev].call( node, node, params );
							}
						});
					}
					p = p.parentNode;
				}
			}
		};

		fn( base, node, base.props );
		init( base );
	};

	function annotations( node ){

		let ann = {}, comment;

		comment = node.previousSibling;
		comment = comment && comment.nodeType == 8? comment :comment? comment.previousSibling : null;

		if( comment && comment.nodeType == 8 ){
			comment.data.replace(/@([a-zA-z0-9-\/]*)(?:\((.*)\))?/g, function( text, component, param ){
				ann[component] = new Function('return '+ param)();
			});
		}

		return ann;
	}

	function scan( node ){
		var components = node.getAttribute(attribute).split(/\s/);
		each( components, mount(node) );
	}

	function mount( node ){
		return function( name ){
			if( name in jails.components ){
				node.j = node.j || {};
				node.j[name] = { methods :{} };
				jails.component( name, node, jails.components[name] );
			}
		};
	}

	function properties( node ){
		var props = { data:{} };
		each( node.attributes, propset(props) );
		return props;
	}

	function propset( acc ){
		return function( item ){
			var value, name = item.name.split(/data\-/);
			try{ value = item.value in window? item.value :(new Function('return '+ item.value))(); }
			catch(err){ value = item.value; }

			if( name[1] ) acc.data[name.pop().replace(/-([a-z])/g, upper)] = value;
			else acc[item.name] = value;
			return acc;
		};
	}

	function upper(m, string){
		return string.toUpperCase();
	}

	function each( list, callback, reverse ){
		list = reverse? Array.from( list ).reverse() : list;
		for( var i = 0, len = list.length; i < len; i ++ )
			callback( list[i], i, list );
	}

	function events(){

		function Ev(type, params) {
			var e = document.createEvent(type);
			params = params || {};
			e.initEvent(type, params.bubbles || false, params.cancelable || false, params.detail || null);
			return e;
		}

		function handler(node, ev){
			return function(e){
				var args = arguments;
				node.__events[ev].forEach(function(cb){ cb.apply(this, args); });
			};
		}

		function delegate( callback ){
			return function(e){
				var element = this,
					args    = arguments,
					target  = e.target || e;
				Object.keys(callback).forEach( function(key){
					if( target.matches( key ) )
						callback[key].apply(element, args);
				});
			};
		}

		return {

			on :function( node, ev, callback ){

				node.__eventHandlers = node.__eventHandlers || {};
				node.__events = node.__events || {};

				if( !node.__eventHandlers[ev] ){
					var cb = callback.call? handler(node, ev) : delegate(callback);
					node.__eventHandlers[ev] = cb;
					node.addEventListener( ev, cb, (ev == 'focus' || ev == 'blur') );
				}
				if( callback.call ){
					node.__events[ev] = (node.__events[ev] || []).concat(callback);
				}else{
					Object.keys(callback).forEach(function(key){
						(node.__events[ev] || []).concat(callback).concat( callback[key] );
					});
				}
			},

			off :function(el, ev, fn){
				if( fn && el.__events[ev] && el.__events[ev].length )
					el.__events[ev] = (el.__events[ev] || []).filter(function(cb){ return cb != fn; });
				else
					el.removeEventListener(ev, el.__eventHandlers[ev], false);
			},

			trigger :function(el, name, args){
				try{
					el.dispatchEvent( new Ev( name, { bubbles :true, detail :args } ) );
				}catch(e){
					el.dispatchEvent( new CustomEvent( name, { bubbles :true, detail :args } ) );
				}
			}
		};
	}

	function pubsub( topics, async ){

		topics = {};
		async  = {};

		return {
			publish :function( name, params ){
				if( !(name in topics) )
					async[name] = params;
				else
					each( topics[name], function( topic ){ topic( params ); });
			},
			subscribe :function( name, method ){
				topics[name] = topics[name] || [];
				topics[name].push( method );
				if( name in async )
					each( topics[name], function( topic ){ topic( async[name] ); });
				return function(){
					topics[name] = topics[name].filter(function( topic ){
						return topic == method;
					});
				};
			}
		};
	}

	// UMD export
	if ( typeof define === 'function' && define.amd ) {
		define(function () { return jails; });
	} else if ( typeof module !== 'undefined' && module.exports ){
		module.exports = jails;
	} else {
		exports.jails = jails;
	}
})( window );
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');

var gutil = require('gulp-util');
var through = require('through2');

var jsReg = /<\s*script\s+.*src\s*=\s*["|']([^"']+)[^>]*><\s*\/\s*script\s*>/gim;
var cssReg = /<\s*link\s+.*href\s*=\s*["|']([^"']+)[^>]*>/gim;
var imgReg = /url\s*\(\s*['|"]?([^'")]+)['|"]?\s*\)/gim;
var base64Reg = /^data:image\/([^;]+);base64,/;

var isCss = function(str) {
    if (!str) return false;
    return /rel\s*=\s*["|']stylesheet["|']/.test(String(str));
};
var isHTTP = function(str) {
    if (!str) return false;
    return /^https?:/.test(String(str));
};
var isBase64 = function(str) {
    if (!str) return false;
    return base64Reg.test(str);
};

module.exports = function(option) {
    option = option || {};
    option.root = option.root || {};
    option.dir = option.dir || './dist';

    function getNewUrl(url, ext) {
        var paths = url.split('/');
        var filename = paths.pop();

        ext = ext || filename.split('.').pop();

        var prefix = option.root[ext] || '';
        prefix && (prefix[prefix.length - 1] === '/' || (prefix += '/'));

        paths.unshift(option.dir);

        var dir = path.resolve.apply(null, paths);

        try {
            var files = fs.readdirSync(dir);
            filename = filename.split('.');

            var newUrl = url;
            files.some(function(item) {
                item = item.split('.');
                if (filename[0] === item[0] && filename[filename.length - 1] === item[item.length - 1]) {
                    paths.shift();
                    newUrl = prefix + paths.join('/') + '/' + item.join('.');
                    return true;
                }
            });

            return newUrl;
        } catch (e) {
            return url;
        }
    }

    return through.obj(function(file, enc, fn) {
        if (file.isNull()) return fn(null, file);

        if (file.isStream()) return fn(new gutil.PluginError('gulp-cdn-replace', 'Streaming is not supported'));

        // Buffer
        var contents = file.contents.toString();
        contents = contents.replace(jsReg, function(match, url) {
                isHTTP(url) || (match = match.replace(/src\s*=\s*["|']([^"'>]+)["|']/, 'src="' + getNewUrl(url, 'js') + '"'));
                return match;
            })
            .replace(cssReg, function(match, url) {
                isHTTP(url) || (isCss(match) && (match = match.replace(/href\s*=\s*["|']([^"']+)["|']/, 'href="' + getNewUrl(url, 'css') + '"')));
                return match;
            })
            .replace(imgReg, function(match, url) {
                isHTTP(url) || isBase64(url) || (match = match.replace(/url\s*\(\s*['|"]?([^'")]+)['|"]?\s*\)/, 'url("' + getNewUrl(url, 'css') + '")'));
                return match;
            });

        file.contents = new Buffer(contents);
        this.push(file);

        fn(null);
    });
};<commit_msg>add image's src replace<commit_after>'use strict';

var fs = require('fs');
var path = require('path');

var gutil = require('gulp-util');
var through = require('through2');

var jsReg = /<\s*script\s+.*src\s*=\s*["|']([^"']+)[^>]*><\s*\/\s*script\s*>/gim;
var cssReg = /<\s*link\s+.*href\s*=\s*["|']([^"']+)[^>]*>/gim;
var imageReg = /<\s*img\s+.*src\s*=\s*["|']([^"']+)[^>]*>/gim;
var imgReg = /url\s*\(\s*['|"]?([^'")]+)['|"]?\s*\)/gim;
var base64Reg = /^data:image\/([^;]+);base64,/;

var isCss = function(str) {
    if (!str) return false;
    return /rel\s*=\s*["|']stylesheet["|']/.test(String(str));
};
var isHTTP = function(str) {
    if (!str) return false;
    return /^https?:/.test(String(str));
};
var isBase64 = function(str) {
    if (!str) return false;
    return base64Reg.test(str);
};

module.exports = function(option) {
    option = option || {};
    option.root = option.root || {};
    option.dir = option.dir || './dist';

    function getNewUrl(url, ext) {
        var paths = url.split('/');
        var filename = paths.pop();

        ext = ext || filename.split('.').pop();

        var prefix = option.root[ext] || '';
        prefix && (prefix[prefix.length - 1] === '/' || (prefix += '/'));

        paths.unshift(option.dir);

        var dir = path.resolve.apply(null, paths);

        try {
            var files = fs.readdirSync(dir);
            filename = filename.split('.');

            var newUrl = url;
            files.some(function(item) {
                item = item.split('.');
                if (filename[0] === item[0] && filename[filename.length - 1] === item[item.length - 1]) {
                    paths.shift();
                    newUrl = prefix + paths.join('/') + '/' + item.join('.');
                    return true;
                }
            });

            return newUrl;
        } catch (e) {
            return url;
        }
    }

    return through.obj(function(file, enc, fn) {
        if (file.isNull()) return fn(null, file);

        if (file.isStream()) return fn(new gutil.PluginError('gulp-cdn-replace', 'Streaming is not supported'));

        // Buffer
        var contents = file.contents.toString();
        contents = contents.replace(jsReg, function(match, url) {
                isHTTP(url) || (match = match.replace(/src\s*=\s*["|']([^"'>]+)["|']/, 'src="' + getNewUrl(url, 'js') + '"'));
                return match;
            })
            .replace(imageReg, function(match, url) {
                isHTTP(url) || (match = match.replace(/src\s*=\s*["|']([^"'>]+)["|']/, 'src="' + getNewUrl(url, 'image') + '"'));
                return match;
            })
            .replace(cssReg, function(match, url) {
                isHTTP(url) || (isCss(match) && (match = match.replace(/href\s*=\s*["|']([^"']+)["|']/, 'href="' + getNewUrl(url, 'css') + '"')));
                return match;
            })
            .replace(imgReg, function(match, url) {
                isHTTP(url) || isBase64(url) || (match = match.replace(/url\s*\(\s*['|"]?([^'")]+)['|"]?\s*\)/, 'url("' + getNewUrl(url, 'css') + '")'));
                return match;
            });

        file.contents = new Buffer(contents);
        this.push(file);

        fn(null);
    });
};<|endoftext|>


<commit_before>"use strict";
var t0 = Date.now();
if (process.env.NODE_ENV === "dev") {
    // Load local env variables
    require("./env");
}

const express = require("express"),
    bodyParser = require('body-parser'),
    xhub = require('express-x-hub'),
    Controller = require("./lib/controller");

function logArgs() {
    var args = arguments;
    process.nextTick(function() {
        console.log.apply(console, args);
    });
}

function logResult(r, action) {
    var err = r.error;

    // We're all good. Log outcome and exit.
    if (!err) {
        logArgs(`${r.id}: ${ action }`);
        logArgs(r);
        return;
    }

    // These are well understood error paths.
    // They shouldn't trigger error messages.
    // Log and exit.
    if (err.noConfig || err.prMerged || err.raceCondition) {
        logArgs(`${r.id}: ${ action } (${err.message})`);
        return;
    }

    // Those are reall issues.
    // Log in details
    logArgs(`${r.id}: ${ action } (${err.name}: ${err.message})`);
    if (r.errorRenderingErrorMsg) {
        logArgs(`    Additionally, triggered the following error while attempting to render the error msg to the client:
    errorRenderingErrorMsg.name}: ${r.errorRenderingErrorMsg.message}`);
    }
    if (err.data) { logArgs(err.data) };
    if (err.stack && process.env.DISPLAY_STACK_TRACES == "yes") { logArgs(err.stack) };
    logArgs(r);
}

const controller = new Controller();

const STARTUP_QUEUE = process.env.STARTUP_QUEUE;
if (STARTUP_QUEUE) {
    try {
        let queue = JSON.parse(STARTUP_QUEUE);
        if (queue && queue.length && typeof queue[0].id == "string") {
            logArgs(`Processing queue : ${ STARTUP_QUEUE }`);
            function next() {
                var r = queue.pop();
                if (r) {
                    logArgs(`Processing queue : ${ r.id }`);
                    controller.handlePullRequest(r).then(r => logResult(r, "startup-queue"), logArgs).then(next);
                } else {
                    logArgs("Startup queue processed");
                }
            }
            next();
        } else {
            throw new Error();
        }
    } catch (e) {
        logArgs(`Malformed queue ${STARTUP_QUEUE}`);
    }
} else {
    logArgs("No startup queue present");
}

var app = express();
app.use(xhub({ algorithm: 'sha1', secret: process.env.GITHUB_SECRET }));

app.post('/github-hook', function (req, res, next) {
    if (process.env.NODE_ENV != 'production' || req.isXHubValid()) {
        res.send(new Date().toISOString());
        var payload = req.body;
        if (payload.issue_comment) {
            logArgs("comment", JSON.stringify(payload, null, 4));
        } else if (payload.pull_request) {
            if (payload.sender && payload.sender.login == "pr-preview[bot]") {
                logArgs("skipping auto-generated changes");
            } else {
                let action = payload.action
                switch(action) {
                    case "opened":
                    case "edited":
                    case "reopened":
                    case "synchronize":
                        controller.queuePullRequest(payload).then(r => logResult(r, action), logArgs);
                }
            }
        } else {
            logArgs("Unknown request", JSON.stringify(payload, null, 4));
        }
    } else {
        logArgs("Unverified request", req);
    }
    next();
});

app.post('/config', bodyParser.urlencoded({ extended: false }), function (req, res, next) {
    let params = req.body;
    controller[params.validate ? "getUrl" : "pullRequestUrl"](req.body)
        .then(
            url => res.redirect(url),
            err => {
                res.status(400).send({ error: err.message });
                logArgs(`${err.name}: ${err.message}\n${err.stack}`);
            }
        ).then(_ => next(), _ => next());
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
    console.log("Express server listening on port %d in %s mode", port, app.settings.env);
    console.log("App started in", (Date.now() - t0) + "ms.");
});
<commit_msg>Add comment<commit_after>"use strict";
var t0 = Date.now();
if (process.env.NODE_ENV === "dev") {
    // Load local env variables
    require("./env");
}

const express = require("express"),
    bodyParser = require('body-parser'),
    xhub = require('express-x-hub'),
    Controller = require("./lib/controller");

function logArgs() {
    var args = arguments;
    process.nextTick(function() {
        console.log.apply(console, args);
    });
}

function logResult(r, action) {
    var err = r.error;

    // We're all good. Log outcome and exit.
    if (!err) {
        logArgs(`${r.id}: ${ action }`);
        logArgs(r);
        return;
    }

    // These are well understood error paths.
    // They shouldn't trigger error messages.
    // Log and exit.
    if (err.noConfig || err.prMerged || err.raceCondition) {
        logArgs(`${r.id}: ${ action } (${err.message})`);
        return;
    }

    // Those are reall issues.
    // Log in details
    logArgs(`${r.id}: ${ action } (${err.name}: ${err.message})`);
    if (r.errorRenderingErrorMsg) {
        logArgs(`    Additionally, triggered the following error while attempting to render the error msg to the client:
    errorRenderingErrorMsg.name}: ${r.errorRenderingErrorMsg.message}`);
    }
    if (err.data) { logArgs(err.data) };
    if (err.stack && process.env.DISPLAY_STACK_TRACES == "yes") { logArgs(err.stack) };
    logArgs(r);
}

const controller = new Controller();

const STARTUP_QUEUE = process.env.STARTUP_QUEUE;
if (STARTUP_QUEUE) {
    try {
        let queue = JSON.parse(STARTUP_QUEUE);
        if (queue && queue.length && typeof queue[0].id == "string") {
            logArgs(`Processing queue : ${ STARTUP_QUEUE }`);
            function next() {
                var r = queue.pop();
                if (r) {
                    logArgs(`Processing queue : ${ r.id }`);
                    controller.handlePullRequest(r).then(r => logResult(r, "startup-queue"), logArgs).then(next);
                } else {
                    logArgs("Startup queue processed");
                }
            }
            next();
        } else {
            throw new Error();
        }
    } catch (e) {
        logArgs(`Malformed queue ${STARTUP_QUEUE}`);
    }
} else {
    logArgs("No startup queue present");
}

var app = express();
app.use(xhub({ algorithm: 'sha1', secret: process.env.GITHUB_SECRET }));

app.post('/github-hook', function (req, res, next) {
    if (process.env.NODE_ENV != 'production' || req.isXHubValid()) {
        res.send(new Date().toISOString());
        var payload = req.body;
        if (payload.issue_comment) { // Depends on increased app permission
            logArgs("comment", JSON.stringify(payload, null, 4));
        } else if (payload.pull_request) {
            if (payload.sender && payload.sender.login == "pr-preview[bot]") {
                logArgs("skipping auto-generated changes");
            } else {
                let action = payload.action
                switch(action) {
                    case "opened":
                    case "edited":
                    case "reopened":
                    case "synchronize":
                        controller.queuePullRequest(payload).then(r => logResult(r, action), logArgs);
                }
            }
        } else {
            logArgs("Unknown request", JSON.stringify(payload, null, 4));
        }
    } else {
        logArgs("Unverified request", req);
    }
    next();
});

app.post('/config', bodyParser.urlencoded({ extended: false }), function (req, res, next) {
    let params = req.body;
    controller[params.validate ? "getUrl" : "pullRequestUrl"](req.body)
        .then(
            url => res.redirect(url),
            err => {
                res.status(400).send({ error: err.message });
                logArgs(`${err.name}: ${err.message}\n${err.stack}`);
            }
        ).then(_ => next(), _ => next());
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
    console.log("Express server listening on port %d in %s mode", port, app.settings.env);
    console.log("App started in", (Date.now() - t0) + "ms.");
});
<|endoftext|>


<commit_before>function inputComparator (a, b) {
  return a.txId.localeCompare(b.txId) || a.vout - b.vout
}

function outputComparator (a, b) {
  return a.value - b.value || a.script.compare(b.script)
}

function sortInputs (inputs) {
  return inputs.concat().sort(inputComparator)
}

function sortOutputs (outputs) {
  return outputs.concat().sort(outputComparator)
}

module.exports = {
  sortInputs: sortInputs,
  sortOutputs: sortOutputs
}
<commit_msg>add inline comments<commit_after>// Previous transaction hashes (in reversed byte-order) are to be sorted in ascending order, lexicographically.
// In the event of two matching transaction hashes, the respective previous output indices will be compared by their integer value, in ascending order.
// If the previous output indices match, the inputs are considered equal.
function inputComparator (a, b) {
  return a.txId.localeCompare(b.txId) || a.vout - b.vout
}

// Transaction output amounts (as 64-bit unsigned integers) are to be sorted in ascending order.
// In the event of two matching output amounts, the respective output scriptPubKeys (as a byte-array) will be compared lexicographically, in ascending order.
// If the scriptPubKeys match, the outputs are considered equal.
function outputComparator (a, b) {
  return a.value - b.value || a.script.compare(b.script)
}

function sortInputs (inputs) {
  return inputs.concat().sort(inputComparator)
}

function sortOutputs (outputs) {
  return outputs.concat().sort(outputComparator)
}

module.exports = {
  sortInputs: sortInputs,
  sortOutputs: sortOutputs
}
<|endoftext|>


<commit_before>module.exports = require('./dist/index');<commit_msg>Updating minified file path<commit_after>module.exports = require('./dist/react-swipeable-tabs');<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var _ = require('underscore');
var Promise = require('bluebird');

var eventTree = function () {
    return {
        hash: {}
        , funcs: []
    };
};

var chainExecutions = function () {
    var ps = _.toArray(arguments);

    var execution = Promise.reduce(ps, function (called, p) {
        var result = p();
        if (result.isPending()) {
            return result.then(function (fcalled) {
                return called || fcalled;
            });
        }
        else {
            if (result.isRejected()) {
                return result;
            }
            else {
                return Promise.resolve(called || result.value());
            }
        }
    }, false);
    return execution;
};

var addCallback = function (route, tree, cb) {
    var head = _.head(route);
    if (!tree.hash.hasOwnProperty(head)) {
        tree.hash[head] = eventTree();
    }

    if (route.length > 1) {
        return addCallback(_.rest(route), tree.hash[head], cb);
    }
    else if (route.length === 1) {
        tree.hash[head].funcs.push(cb);
    }
};

var execTree = function (tree, msg) {
    if (!tree || (tree.funcs.length === 0)) {
        return Promise.resolve(false);
    }
    var funcs = tree.funcs;
    var execution = Promise.reduce(funcs, function (called, f) {
        return f(msg);
    }, false);
    if (execution.isPending()) {
        return execution.then(true);
    }
    else {
        if (execution.isRejected()) {
            return execution;
        }
        else {
            return Promise.resolve(true);
        }
    }
};

var applySubTrees = function (tree, method) {
    return Promise.map(_.pairs(tree.hash)
                       , function (kv) {
                           if (kv[0] === '**') {
                               return false;
                           }
                           else {
                               return method(kv[1]);
                           }
                       }, {concurrency: 1});
};

var execAll = function (tree, msg) {
    return chainExecutions(
        function () {
            return execTree(tree, msg);
        }
        , function () {
            return applySubTrees(tree, function (subtree) {
                return execAll(subtree, msg);
            });
        }
    );
};

var execMatch = function (target, tree, msg) {
    if (!tree) {
        return Promise.resolve(false);
    }
    var targetTree = tree.hash.hasOwnProperty(target) && tree.hash[target];
    if (!targetTree) {
        return Promise.resolve(false);
    }
    var doubleStarTree = targetTree.hash['**'];
    return Promise.join(execTree(targetTree, msg)
                        , execTree(doubleStarTree, msg))
        .then(_.any);
};

var noExecution = function () {
    return Promise.resolve(false);
};

var execCallbacks = function (route, tree, msg) {
    if (!tree) {
        return noExecution();
    }
    var head = _.head(route);
    if (head === '**') {
        return execAll(tree, msg);
    }
    else if (route.length > 1) {
        var rest = _.rest(route);
        if (head === '*') {
            return applySubTrees(tree, function (subtree) {
                return Promise.join(execTree(subtree.hash['**'], msg)
                                    , execCallbacks(rest, subtree, msg))
                    .then(_.any);
            });
        }
        else {
            var matchTree = tree.hash.hasOwnProperty(head) && tree.hash[head];
            return chainExecutions(function () {
                return execTree(tree.hash['*'] && tree.hash['*'].hash['**'], msg);
            }, function () {
                return execTree(matchTree && matchTree.hash['**'], msg);
            }, function () {
                return execCallbacks(rest, tree.hash['*'], msg);
            }, function () {
                return execCallbacks(rest, matchTree, msg);
            });
        }
    }
    else if (route.length === 1) {
        if (head === '*') {
            return applySubTrees(tree, function (subtree) {
                return execTree(subtree, msg);
            })
                .then(_.any);
        }
        else {
            return chainExecutions(function () {
                return execMatch('*', tree, msg);
            }, function () {
                return execMatch(head, tree, msg);
            });
        }
    }
    else {
        return noExecution();
    }
};

var filterFuncs = function (funcs, f) {
    if (f) {
        return _.filter(funcs, function (func) {
            return func.listener !== f;
        });
    }
    else {
        return [];
    }
};

var emptyTree = function (tree) {
    return tree.funcs.length === 0
        && _.isEmpty(tree.hash);
};

var deleteIfEmpty = function (target, hash) {
    if (emptyTree(hash[target])) {
        delete hash[target];
    }
};

var removeFunc = function (tree, f) {
    tree.funcs = filterFuncs(tree.funcs, f);
};

var removeCallback = function (route, tree, f) {
    var head = _.head(route);
    if (route.length > 1) {
        var rest = _.rest(route);
        if (head === '*') {
            return _.each(tree.hash, function (subtree, subhead) {
                if (subhead !== '**') {
                    removeCallback(rest, subtree, f);
                    deleteIfEmpty(subhead, tree.hash);
                }
            });
        }
        else if (tree.hash.hasOwnProperty(head)) {
            removeCallback(_.rest(route), tree.hash[head], f);
            deleteIfEmpty(head, tree.hash);
        }
    }
    else if (route.length === 1) {
        if (head === '**')  {
            removeFunc(tree, f);
            _.each(tree.hash, function (subtree, subhead) {
                removeCallback(route, subtree, f);
                deleteIfEmpty(subhead, tree.hash);
            });
        }
        if (head === '*') {
            _.each(tree.hash, function (subtree, subhead) {
                removeFunc(subtree, f);
                deleteIfEmpty(subhead, tree.hash);
            });
        }
        else if (tree.hash.hasOwnProperty(head)) {
            removeFunc(tree.hash[head], f);
            deleteIfEmpty(head, tree.hash);
        }
    }
};

var adaptCallback = function (cb) {
    var f;
    if (cb.length === 2) {
        f = Promise.promisify(cb);
    }
    else {
        f = function (msg) {
            cb(msg);
            return Promise.resolve(false);
        };
    }
    f.listener = cb;
    return f;
};

var EventEmitter = function () {
    this._eventTree = eventTree();
};

_.extend(EventEmitter.prototype, {
    on: function (route, cb) {
        return addCallback(route, this._eventTree, adaptCallback(cb));
    }
    , emit: function (route, msg) {
        var _this = this;
        return chainExecutions(
            function () {
                return execTree(_this._eventTree.hash['**'], msg);
            }
            , function () {
                return execCallbacks(route, _this._eventTree, msg);
            });
    }
    , removeListener: function (route, f) {
        removeCallback(route, this._eventTree, f);
    }
    , once: function (route, cb) {
        var _this = this;
        var f = adaptCallback(cb);
        var g = function (msg) {
            _this.removeListener(route, cb);
            return f(msg);
        };
        g.listener = cb;
        return addCallback(route, this._eventTree, g);
    }
    , removeAllListeners: function (route) {
        if (route[0] === '**') {
            this._eventTree = eventTree();
        }
        else {
            removeCallback(route, this._eventTree);
        }
    }
});

module.exports = {
    EventEmitter: EventEmitter
};
<commit_msg>Satisfy string route constraints.<commit_after>/*jslint node: true */
"use strict";

var _ = require('underscore');
var Promise = require('bluebird');

var eventTree = function () {
    return {
        hash: {}
        , funcs: []
    };
};

var chainExecutions = function () {
    var ps = _.toArray(arguments);

    var execution = Promise.reduce(ps, function (called, p) {
        var result = p();
        if (result.isPending()) {
            return result.then(function (fcalled) {
                return called || fcalled;
            });
        }
        else {
            if (result.isRejected()) {
                return result;
            }
            else {
                return Promise.resolve(called || result.value());
            }
        }
    }, false);
    return execution;
};

var addCallback = function (route, tree, cb) {
    var head = _.head(route);
    if (!tree.hash.hasOwnProperty(head)) {
        tree.hash[head] = eventTree();
    }

    if (route.length > 1) {
        return addCallback(_.rest(route), tree.hash[head], cb);
    }
    else if (route.length === 1) {
        tree.hash[head].funcs.push(cb);
    }
};

var execTree = function (tree, msg) {
    if (!tree || (tree.funcs.length === 0)) {
        return Promise.resolve(false);
    }
    var funcs = tree.funcs;
    var execution = Promise.reduce(funcs, function (called, f) {
        return f(msg);
    }, false);
    if (execution.isPending()) {
        return execution.then(true);
    }
    else {
        if (execution.isRejected()) {
            return execution;
        }
        else {
            return Promise.resolve(true);
        }
    }
};

var applySubTrees = function (tree, method) {
    return Promise.map(_.pairs(tree.hash)
                       , function (kv) {
                           if (kv[0] === '**') {
                               return false;
                           }
                           else {
                               return method(kv[1]);
                           }
                       }, {concurrency: 1});
};

var execAll = function (tree, msg) {
    return chainExecutions(
        function () {
            return execTree(tree, msg);
        }
        , function () {
            return applySubTrees(tree, function (subtree) {
                return execAll(subtree, msg);
            });
        }
    );
};

var execMatch = function (target, tree, msg) {
    if (!tree) {
        return Promise.resolve(false);
    }
    var targetTree = tree.hash.hasOwnProperty(target) && tree.hash[target];
    if (!targetTree) {
        return Promise.resolve(false);
    }
    var doubleStarTree = targetTree.hash['**'];
    return Promise.join(execTree(targetTree, msg)
                        , execTree(doubleStarTree, msg))
        .then(_.any);
};

var noExecution = function () {
    return Promise.resolve(false);
};

var execCallbacks = function (route, tree, msg) {
    if (!tree) {
        return noExecution();
    }
    var head = _.head(route);
    if (head === '**') {
        return execAll(tree, msg);
    }
    else if (route.length > 1) {
        var rest = _.rest(route);
        if (head === '*') {
            return applySubTrees(tree, function (subtree) {
                return Promise.join(execTree(subtree.hash['**'], msg)
                                    , execCallbacks(rest, subtree, msg))
                    .then(_.any);
            });
        }
        else {
            var matchTree = tree.hash.hasOwnProperty(head) && tree.hash[head];
            return chainExecutions(function () {
                return execTree(tree.hash['*'] && tree.hash['*'].hash['**'], msg);
            }, function () {
                return execTree(matchTree && matchTree.hash['**'], msg);
            }, function () {
                return execCallbacks(rest, tree.hash['*'], msg);
            }, function () {
                return execCallbacks(rest, matchTree, msg);
            });
        }
    }
    else if (route.length === 1) {
        if (head === '*') {
            return applySubTrees(tree, function (subtree) {
                return execTree(subtree, msg);
            })
                .then(_.any);
        }
        else {
            return chainExecutions(function () {
                return execMatch('*', tree, msg);
            }, function () {
                return execMatch(head, tree, msg);
            });
        }
    }
    else {
        return noExecution();
    }
};

var filterFuncs = function (funcs, f) {
    if (f) {
        return _.filter(funcs, function (func) {
            return func.listener !== f;
        });
    }
    else {
        return [];
    }
};

var emptyTree = function (tree) {
    return tree.funcs.length === 0
        && _.isEmpty(tree.hash);
};

var deleteIfEmpty = function (target, hash) {
    if (emptyTree(hash[target])) {
        delete hash[target];
    }
};

var removeFunc = function (tree, f) {
    tree.funcs = filterFuncs(tree.funcs, f);
};

var removeCallback = function (route, tree, f) {
    var head = _.head(route);
    if (route.length > 1) {
        var rest = _.rest(route);
        if (head === '*') {
            return _.each(tree.hash, function (subtree, subhead) {
                if (subhead !== '**') {
                    removeCallback(rest, subtree, f);
                    deleteIfEmpty(subhead, tree.hash);
                }
            });
        }
        else if (tree.hash.hasOwnProperty(head)) {
            removeCallback(_.rest(route), tree.hash[head], f);
            deleteIfEmpty(head, tree.hash);
        }
    }
    else if (route.length === 1) {
        if (head === '**')  {
            removeFunc(tree, f);
            _.each(tree.hash, function (subtree, subhead) {
                removeCallback(route, subtree, f);
                deleteIfEmpty(subhead, tree.hash);
            });
        }
        if (head === '*') {
            _.each(tree.hash, function (subtree, subhead) {
                removeFunc(subtree, f);
                deleteIfEmpty(subhead, tree.hash);
            });
        }
        else if (tree.hash.hasOwnProperty(head)) {
            removeFunc(tree.hash[head], f);
            deleteIfEmpty(head, tree.hash);
        }
    }
};

var adaptCallback = function (cb) {
    var f;
    if (cb.length === 2) {
        f = Promise.promisify(cb);
    }
    else {
        f = function (msg) {
            cb(msg);
            return Promise.resolve(false);
        };
    }
    f.listener = cb;
    return f;
};

var EventEmitter = function (options) {
    options = _.defaults({}, options, {
        delimiter: '/'
    });
    this._eventTree = eventTree();
    this.delimiter = options.delimiter;
};

_.extend(EventEmitter.prototype, {
    parseRoute: function (route) {
        if (_.isString(route))  {
            return route.split(this.delimiter);
        }
        else {
            return route;
        }
    }
    , on: function (route, cb) {
        route = this.parseRoute(route);
        return addCallback(route, this._eventTree, adaptCallback(cb));
    }
    , emit: function (route, msg) {
        var _this = this;
        route = this.parseRoute(route);
        return chainExecutions(
            function () {
                return execTree(_this._eventTree.hash['**'], msg);
            }
            , function () {
                return execCallbacks(route, _this._eventTree, msg);
            });
    }
    , removeListener: function (route, f) {
        route = this.parseRoute(route);
        removeCallback(route, this._eventTree, f);
    }
    , once: function (route, cb) {
        route = this.parseRoute(route);
        var _this = this;
        var f = adaptCallback(cb);
        var g = function (msg) {
            _this.removeListener(route, cb);
            return f(msg);
        };
        g.listener = cb;
        return addCallback(route, this._eventTree, g);
    }
    , removeAllListeners: function (route) {
        route = this.parseRoute(route);
        if (route[0] === '**') {
            this._eventTree = eventTree();
        }
        else {
            removeCallback(route, this._eventTree);
        }
    }
});

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


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

var existsSync = require('exists-sync');
var chalk = require('chalk');

module.exports = {
  name: 'ember-cli-template-lint',

  _findHtmlbarsPreprocessor: function(registry) {
    var plugins = registry.load('template');

    return plugins.filter(function(plugin) {
      return plugin.name === 'ember-cli-htmlbars';
    })[0];
  },

  _monkeyPatch_EmberDeprecate: function(htmlbarsCompilerPreprocessor) {
    var addonContext = this;
    var originalHtmlbarsOptions = htmlbarsCompilerPreprocessor._addon.htmlbarsOptions;
    var logToNodeConsole = this.project.config(process.env.EMBER_ENV).logTemplateLintToConsole;

    htmlbarsCompilerPreprocessor._addon.htmlbarsOptions = function() {
      var options = originalHtmlbarsOptions.apply(this, arguments);
      var originalDeprecate = options.templateCompiler._Ember.deprecate;

      options.templateCompiler._Ember.deprecate = function(message, test, options) {
        var noDeprecation;

        if (typeof test === "function") {
          noDeprecation = test();
        } else {
          noDeprecation = test;
        }

        if (!noDeprecation) {
          addonContext._deprecations.push({
            message: JSON.stringify(message),
            test: !!test,
            options: JSON.stringify(options)
          });
        }

        if (logToNodeConsole) {
          return originalDeprecate.apply(this, arguments);
        }
      };

      return options;
    };
  },

  setupPreprocessorRegistry: function(type, registry) {
    if (type === 'parent') {
      var htmlbarsCompilerPreprocessor = this._findHtmlbarsPreprocessor(registry);

      this._monkeyPatch_EmberDeprecate(htmlbarsCompilerPreprocessor);
    }

    var plugins = require('./ext/plugins');
    for (var name in plugins) {
      registry.add('htmlbars-ast-plugin', {
        name: name,
        plugin: plugins[name](this)
      });
    }
  },

  loadConfig: function() {
    var defaultConfig  = this.project.root + '/.template-lintrc';
    var overrideConfig = process.env['TEMPLATE_LINTRC'];
    var config = overrideConfig || defaultConfig
    if(existsSync(config)) {
      return require(config);
    } else {
      return {};
    }
  },

  logLintingError: function(pluginName, moduleName, message) {
    this.ui.writeLine(message.yellow);
  },

  init: function() {
    this._deprecations = [];
  },

  lintTree: function(type, tree) {
    var ui = this.ui;
    var TemplateLinter = require('./generate-deprecations-tree');

    return new TemplateLinter(this);
  }
};
<commit_msg>Use chalk methods instead of prototype extension.<commit_after>/* jshint node: true */
'use strict';

var existsSync = require('exists-sync');
var chalk = require('chalk');

module.exports = {
  name: 'ember-cli-template-lint',

  _findHtmlbarsPreprocessor: function(registry) {
    var plugins = registry.load('template');

    return plugins.filter(function(plugin) {
      return plugin.name === 'ember-cli-htmlbars';
    })[0];
  },

  _monkeyPatch_EmberDeprecate: function(htmlbarsCompilerPreprocessor) {
    var addonContext = this;
    var originalHtmlbarsOptions = htmlbarsCompilerPreprocessor._addon.htmlbarsOptions;
    var logToNodeConsole = this.project.config(process.env.EMBER_ENV).logTemplateLintToConsole;

    htmlbarsCompilerPreprocessor._addon.htmlbarsOptions = function() {
      var options = originalHtmlbarsOptions.apply(this, arguments);
      var originalDeprecate = options.templateCompiler._Ember.deprecate;

      options.templateCompiler._Ember.deprecate = function(message, test, options) {
        var noDeprecation;

        if (typeof test === "function") {
          noDeprecation = test();
        } else {
          noDeprecation = test;
        }

        if (!noDeprecation) {
          addonContext._deprecations.push({
            message: JSON.stringify(message),
            test: !!test,
            options: JSON.stringify(options)
          });
        }

        if (logToNodeConsole) {
          return originalDeprecate.apply(this, arguments);
        }
      };

      return options;
    };
  },

  setupPreprocessorRegistry: function(type, registry) {
    if (type === 'parent') {
      var htmlbarsCompilerPreprocessor = this._findHtmlbarsPreprocessor(registry);

      this._monkeyPatch_EmberDeprecate(htmlbarsCompilerPreprocessor);
    }

    var plugins = require('./ext/plugins');
    for (var name in plugins) {
      registry.add('htmlbars-ast-plugin', {
        name: name,
        plugin: plugins[name](this)
      });
    }
  },

  loadConfig: function() {
    var defaultConfig  = this.project.root + '/.template-lintrc';
    var overrideConfig = process.env['TEMPLATE_LINTRC'];
    var config = overrideConfig || defaultConfig
    if(existsSync(config)) {
      return require(config);
    } else {
      return {};
    }
  },

  logLintingError: function(pluginName, moduleName, message) {
    this.ui.writeLine(chalk.yellow(message));
  },

  init: function() {
    this._deprecations = [];
  },

  lintTree: function(type, tree) {
    var ui = this.ui;
    var TemplateLinter = require('./generate-deprecations-tree');

    return new TemplateLinter(this);
  }
};
<|endoftext|>