<commit_before>var utils = require("./utils");
var request = require("request");
var url = require("url");

/**
 * TODO: docs
 *
 * Constructor
 *
 * Takes an object with keys:
 *     token (required)
 *     host (optional, defaults to localhost)
 *     name (optional, defaults to splunk-javascript-logging)
 *     etc.
 */
var SplunkLogger = function(config) {
    this.config = this._initializeConfig(config);
    this.middlewares = [];
};

/**
 * TODO: docs, do we want to add other levels?
 *
 */
SplunkLogger.prototype.levels = {
    info: "info"
};

var defaultConfig = {
    name: "splunk-javascript-logging/0.8.0",
    host: "localhost",
    path: "/services/collector/event/1.0",
    protocol: "https",
    level: SplunkLogger.prototype.levels.info,
    port: 8088
};

var defaultRequestOptions = {
    json: true, // Sets the content-type header to application/json
    strictSSL: false,
    url: defaultConfig.protocol + "://" + defaultConfig.host + ":" + defaultConfig.port + defaultConfig.path
};

/**
 * TODO: docs
 *
 * validates the config, throwing an error if it's horribly wrong
 */
SplunkLogger.prototype._initializeConfig = function(config) {
    // Copy over the instance config
    var ret = {};
    for (var key in this.config) {
        ret[key] = this.config[key];
    }

    if (!config) {
        throw new Error("Config is required.");
    }
    else if (typeof config !== "object") {
        throw new Error("Config must be an object.");
    }
    else if (!config.hasOwnProperty("token")) {
        throw new Error("Config object must have a token.");
    }
    else if (typeof config.token !== "string") {
        throw new Error("Config token must be a string.");
    }
    else {
        // Specifying the url will override host, port, scheme, & path if possible
        if (config.url) {
            var parsed = url.parse(config.url);
            if (parsed.protocol) {
                config.protocol = parsed.protocol.replace(":", "");
            }
            if (parsed.port) {
                config.port = parsed.port;
            }
            if (parsed.hostname && parsed.path) {
                config.host = parsed.hostname;
                config.path = parsed.path;
            }
            else if (parsed.path) {
                // If hostname isn't set, but path is assume path is the host
                config.host = parsed.path;
            }
        }

        // Take the argument's value, then instance value, then the default value
        ret.token = config.token || ret.token;
        ret.name = config.name || ret.name || defaultConfig.name;
        ret.host = config.host || ret.host || defaultConfig.host;
        ret.path = config.path || ret.path || defaultConfig.path;
        ret.protocol = config.protocol || ret.protocol || defaultConfig.protocol;
        ret.level = config.level || ret.level || defaultConfig.level;

        if (!config.hasOwnProperty("port")) {
            ret.port = ret.port || defaultConfig.port;
        }
        else {
            ret.port = parseInt(config.port, 10);
            if (isNaN(ret.port)) {
                throw new Error("Port must be an integer, found: " + ret.port);
            }
        }
        if (ret.port < 1000 || ret.port > 65535) {
            throw new Error("Port must be an integer between 1000 and 65535, found: " + ret.port);
        }
    }
    return ret;
};

/**
 * TODO: docs
 *
 * NOTE: This function calls _initializeConfig
 */
SplunkLogger.prototype._initializeRequestOptions = function(config, options) {
    var ret = {};
    for (var key in defaultRequestOptions) {
        ret[key] = defaultRequestOptions[key];
    }

    // _initializeConfig will throw an error config or this.config is
    //     undefined, or doesn't have at least the token property set
    config = this._initializeConfig(config || this.config);
    options = options || ret;

    ret.url = config.protocol + "://" + config.host + ":" + config.port + config.path;
    ret.json = options.json || ret.json;
    ret.strictSSL = options.strictSSL || ret.strictSSL;
    ret.headers = ret.headers || {};
    ret.headers.Authorization = "Splunk " + config.token;

    return ret;
};

/**
 * TODO: docs
 *
 * Takes the setting object & tries to initialize the
 * config and request options.
 */
SplunkLogger.prototype._initializeSettings = function(settings) {
    if (!settings) {
        throw new Error("Settings argument is required.");
    }
    else if (typeof settings !== "object") {
        throw new Error("Settings argument must be an object.");
    }
    else if (!settings.hasOwnProperty("data")) {
        throw new Error("Settings argument must have the data property set.");
    }

    settings.requestOptions = this._initializeRequestOptions(settings.config, settings.requestOptions);

    return settings;
};

/**
 * TODO: docs
 * Takes anything and puts it in a JS object for the event/1.0 EC format
 *
 * TODO: add metadata to the JSON body
 */
SplunkLogger.prototype._makeBody = function(event) {
    var body = {
        event: event
    };
    return body;
};

/**
 * TODO: docs
 *
 * Adds a middleware function to run before sending the
 * data to Splunk.
 */
SplunkLogger.prototype.use = function(middleware) {
    if (!middleware || typeof middleware !== "function") {
        throw new Error("Middleware must be a function.");
    }
    else {
        this.middlewares.push(middleware);
    }
};

/**
 * TODO: docs
 *
 * Makes an HTTP POST to the configured server.
 * Any config not specified will be
 */
SplunkLogger.prototype._sendEvents = function(settings, callback) {
    // Validate the settings again, right before using them
    settings = this._initializeSettings(settings);

    var token = settings.config.token || this.config.token;
    settings.requestOptions.headers["Authorization"] = "Splunk " + token;
    settings.requestOptions.body = this._makeBody(settings.data);

    request.post(settings.requestOptions, callback);
};

/**
 * TODO: docs
 * Takes config settings, anything, & a callback(err, resp, body)
 *
 */
SplunkLogger.prototype.send = function (settings, callback) {
    // Validate the settings
    settings = this._initializeSettings(settings);

    // TODO: the following should be addressed with _initializeConfig
    // TODO: properly handle config changing "on the fly"
    //     : decide between 3 sources of config (default, this.config & config parameter)
    // Currently, we're ignoring anything set on this.config
    // config = this._initializeConfig(config);
    // settings.config = this._initializeConfig(settings.config);

    // TODO: implement error handling for all middlewares, and _sendEvents

    // Send the data to the first middleware
    var callbacks = this.middlewares;
    callbacks.unshift(function(callback) {
        callback(null, settings);
    });

    // After running all, if any, middlewares send the events
    var that = this;
    utils.chain(callbacks, function(err, settings) {
        that._sendEvents(settings, callback);
    });
};

module.exports = SplunkLogger;<commit_msg>temp commit<commit_after>var utils = require("./utils");
var request = require("request");
var url = require("url");

/**
 * TODO: docs
 * default error handler
 */
function _err(err) {
    console.log("ERROR:", err);
}

/**
 * TODO: docs
 *
 * Constructor
 *
 * Takes an object with keys:
 *     token (required)
 *     host (optional, defaults to localhost)
 *     name (optional, defaults to splunk-javascript-logging)
 *     etc.
 */
var SplunkLogger = function(config) {
    this.config = this._initializeConfig(config);
    this.middlewares = [];
    // this.error = config.err || _err;
};

/**
 * TODO: docs, do we want to add other levels?
 *
 */
SplunkLogger.prototype.levels = {
    info: "info"
};

var defaultConfig = {
    name: "splunk-javascript-logging/0.8.0",
    host: "localhost",
    path: "/services/collector/event/1.0",
    protocol: "https",
    level: SplunkLogger.prototype.levels.info,
    port: 8088
};

var defaultRequestOptions = {
    json: true, // Sets the content-type header to application/json
    strictSSL: false,
    url: defaultConfig.protocol + "://" + defaultConfig.host + ":" + defaultConfig.port + defaultConfig.path
};

/**
 * TODO: docs
 *
 * validates the config, throwing an error if it's horribly wrong
 */
SplunkLogger.prototype._initializeConfig = function(config) {
    // Copy over the instance config
    var ret = {};
    for (var key in this.config) {
        if (this.config.hasOwnProperty(key)){
            ret[key] = this.config[key];
        }
    }

    if (!config) {
        throw new Error("Config is required.");
    }
    else if (typeof config !== "object") {
        throw new Error("Config must be an object.");
    }
    else if (!config.hasOwnProperty("token")) {
        throw new Error("Config object must have a token.");
    }
    else if (typeof config.token !== "string") {
        throw new Error("Config token must be a string.");
    }
    else {
        // Specifying the url will override host, port, scheme, & path if possible
        if (config.url) {
            var parsed = url.parse(config.url);
            if (parsed.protocol) {
                config.protocol = parsed.protocol.replace(":", "");
            }
            if (parsed.port) {
                config.port = parsed.port;
            }
            if (parsed.hostname && parsed.path) {
                config.host = parsed.hostname;
                config.path = parsed.path;
            }
            else if (parsed.path) {
                // If hostname isn't set, but path is assume path is the host
                config.host = parsed.path;
            }
        }

        // Take the argument's value, then instance value, then the default value
        ret.token = config.token || ret.token;
        ret.name = config.name || ret.name || defaultConfig.name;
        ret.host = config.host || ret.host || defaultConfig.host;
        ret.path = config.path || ret.path || defaultConfig.path;
        ret.protocol = config.protocol || ret.protocol || defaultConfig.protocol;
        ret.level = config.level || ret.level || defaultConfig.level;

        if (!config.hasOwnProperty("port")) {
            ret.port = ret.port || defaultConfig.port;
        }
        else {
            ret.port = parseInt(config.port, 10);
            if (isNaN(ret.port)) {
                throw new Error("Port must be an integer, found: " + ret.port);
            }
        }
        if (ret.port < 1000 || ret.port > 65535) {
            throw new Error("Port must be an integer between 1000 and 65535, found: " + ret.port);
        }
    }
    return ret;
};

/**
 * TODO: docs
 *
 * NOTE: This function calls _initializeConfig
 */
SplunkLogger.prototype._initializeRequestOptions = function(config, options) {
    var ret = {};
    for (var key in defaultRequestOptions) {
        if (defaultRequestOptions.hasOwnProperty(key)) {
            ret[key] = defaultRequestOptions[key];
        }
    }

    // _initializeConfig will throw an error config or this.config is
    //     undefined, or doesn't have at least the token property set
    config = this._initializeConfig(config || this.config);
    options = options || ret;

    ret.url = config.protocol + "://" + config.host + ":" + config.port + config.path;
    ret.json = options.hasOwnProperty("json") ? options.json : ret.json;
    ret.strictSSL = options.strictSSL || ret.strictSSL;
    ret.headers = options.headers || {};
    ret.headers.Authorization = "Splunk " + config.token;

    return ret;
};

/**
 * TODO: docs
 *
 * Takes the setting object & tries to initialize the
 * config and request options.
 */
SplunkLogger.prototype._initializeSettings = function(settings) {
    if (!settings) {
        throw new Error("Settings argument is required.");
    }
    else if (typeof settings !== "object") {
        throw new Error("Settings argument must be an object.");
    }
    else if (!settings.hasOwnProperty("data")) {
        throw new Error("Settings argument must have the data property set.");
    }

    settings.requestOptions = this._initializeRequestOptions(settings.config, settings.requestOptions);

    return settings;
};

/**
 * TODO: docs
 * Takes anything and puts it in a JS object for the event/1.0 EC format
 *
 * TODO: add metadata to the JSON body
 */
SplunkLogger.prototype._makeBody = function(event) {
    var body = {
        event: event
    };
    return body;
};

/**
 * TODO: docs
 *
 * Adds a middleware function to run before sending the
 * data to Splunk.
 */
SplunkLogger.prototype.use = function(middleware) {
    if (!middleware || typeof middleware !== "function") {
        throw new Error("Middleware must be a function.");
    }
    else {
        this.middlewares.push(middleware);
    }
};

/**
 * TODO: docs
 *
 * Makes an HTTP POST to the configured server.
 * Any config not specified will be set to the default configuration.
 */
SplunkLogger.prototype._sendEvents = function(settings, callback) {
    // Validate the settings again, right before using them
    settings = this._initializeSettings(settings);

    var token = settings.config.token || this.config.token;
    settings.requestOptions.headers["Authorization"] = "Splunk " + token;
    settings.requestOptions.body = this._makeBody(settings.data);

    request.post(settings.requestOptions, callback);
};

/**
 * TODO: docs
 * Takes config settings, anything, & a callback(err, resp, body)
 *
 */
SplunkLogger.prototype.send = function (settings, callback) {
    // Validate the settings
    settings = this._initializeSettings(settings);

    // TODO: the following should be addressed with _initializeConfig
    // TODO: properly handle config changing "on the fly"
    //     : decide between 3 sources of config (default, this.config & config parameter)
    // Currently, we're ignoring anything set on this.config
    // config = this._initializeConfig(config);
    // settings.config = this._initializeConfig(settings.config);

    // TODO: implement error handling for all middlewares, and _sendEvents

    // Send the data to the first middleware
    var callbacks = this.middlewares;
    callbacks.unshift(function(callback) {
        callback(null, settings);
    });

    // After running all, if any, middlewares send the events
    var that = this;
    utils.chain(callbacks, function(err, settings) {
        // if (err) {
        //     that.error(err);
        // }
        // else {
            that._sendEvents(settings, callback);
        // }
    });
};

module.exports = SplunkLogger;<|endoftext|>


<commit_before>module.exports = WSKey;

function WSKey (key, secret, options) {
    if ( !(this instanceof WSKey) ) return new WSKey(key, secret, options);

    this.key = key;
    this.secret = secret;
    this.opt = options || {};

    this.addUser(this.opt.user);

    this.time = this.nonce = null;
}

WSKey.prototype.addUser = function(user) {
    this.user = (user && user.principalID && user.principalIDNS) ? user : {};
}

WSKey.prototype.hasUser = function() {
    return this.user && this.user.principalID && this.user.principalIDNS;
}

WSKey.prototype.HMACSignature = function (method, url, options) {
    var options = options || this.opt || {}
      , user = options.user
      , norm = this._normalizeRequest(method, url, options)
      , sig
      ;

    sig = 'http://www.worldcat.org/wskey/v2/hmac/v1'
        + ' clientId="' + this.key + '",'
        + ' timestamp="' + this.time + '",'
        + ' nonce="' + this.nonce + '",'
        + ' signature="' + createHMACDigest(norm, this.secret) + '"'
        ;

    if ( user ) {
      sig += ', principalID="' + user.principalID + '"'
          +  ', principalIDNS="' + user.principalIDNS + '"'
          ;
    }

    this.time = this.nonce = null;

    return sig;
}

WSKey.prototype._normalizeRequest = function (method, reqUrl, options) {
    var url = require('url')
      , parsedSigUrl = url.parse('https://www.oclc.org/wskey')
      , parsedReqUrl = url.parse(reqUrl)
      , qs = parsedReqUrl.query

      , sigPort = parsedSigUrl.protocol === 'https:' ? 443 : 80

      , options = options || this.opt || {}
      , time = options._debug ? options._debug.time : (new Date()).getTime().toString().substr(0, 10)
      , nonce = options._debug ? options._debug.nonce : createNonce()
      , bodyHash = options._debug ? options._debug.bodyHash : (options.bodyHash || '')

      , query, normalized
      ;

    this.time = time;
    this.nonce = nonce;

    if ( qs ) {
      query = qs.split('&').sort().join('\n');
      query = query.replace(/[^\s%\=]/g, function(match) { return encodeURIComponent(match); });
    }

    normalized = [
        this.key,
        this.time,
        this.nonce,
        bodyHash,
        method.toUpperCase(),
        parsedSigUrl.host,
        sigPort,
        parsedSigUrl.path
    ];

    if ( query ) normalized.push(query);

    return normalized.join('\n') + '\n';
}

function createHMACDigest(normalized, secret) {
    var crypto = require('crypto')
      , hmac = crypto.createHmac('sha256', secret)
      ;

    hmac.update(normalized);
    return hmac.digest('base64');
};

function createNonce () {
    return Math.ceil(
            (new Date()).getMilliseconds()
            * Math.random()
            * 1000000
           );
}<commit_msg>overhaul + add requestAccessToken<commit_after>module.exports = WSKey;

function WSKey (key, secret, user) {
    if ( !(this instanceof WSKey) ) return new WSKey(key, secret, user);

    this.key = key;
    this.secret = secret;

    this.addUser(user)

    this.time = this.nonce = null;
}

WSKey.prototype.addUser = function(user) {
    this.user = isUser(user) ? user : {};
}

WSKey.prototype.hasUser = function() {
    return isUser(this.user);
}

WSKey.prototype.removeUser = function() {
    this.user = {}
}

WSKey.prototype.requestAccessToken = function(authInstID, contextInstID, user, scope, cb) {
  var request = require('request');
  var opts = {};

  // variation 1: authInstID is contextInstID
  // requestAccessToken(authInstId, user, scope, cb)
  if (typeof scope === 'function') {
    cb = scope
    scope = user
    user = contextInstID
    contextInstID = authInstID
  }

  // variation 2: authInstID is contextInstID + no user specified
  // requestAccessToken(authInstId, scope, cb)
  else if ( typeof user === 'function' ) {
    cb = user;
    scope = contextInstID;
    contextInstID = authInstID;
    user = this.user;
  }

  // variation 3: opts object + callback
  // requestAccessToken({ ... }, cb );
  else if ( typeof authInstID === 'object' ) {
    opts = authInstID;
    cb = typeof contextInstID === 'function' ? contextInstID : noop;
    authInstID = opts.authenticatingInstitutionID || opts.contextInstitutionID;
    contextInstID = opts.contextInstitutionID || authInstID;
    scope = opts.scope || [];
    user = opts.user || this.user || {};
  }

  if ( typeof scope === 'string' ) scope = [scope]

  var url, tokenResponse;

  url = 'https://authn.sd00.worldcat.org/oauth2/accessToken?grant_type=client_credentials'
      + '&authenticatingInstitutionId=' + authInstID
      + '&contextInstitutionId=' + contextInstID
      + '&scope=' + scope.join(' ')
      ;

  request.post(
    url,
    {
      headers: {
        'Authorization': this.HMACSignature('POST', url),
        'Accept': 'application/json'
      }
    },
    function(err, resp, body) {
      if (err) return cb(err, null);

      body = JSON.parse(body);

      if (body.code) return cb(Error(body.message), null);

      return cb(err, body, 'Bearer: ' + body.access_token);
    })
}

WSKey.prototype.HMACSignature = function (method, url, user, _debug) {
    // lousy check for debug vs. user
    if ( !_debug ) {
      if ( isUser(user) ) {
        _debug = {};
      } else {
        _debug = user;
        user = null;
      }
    }

    if ( !user && this.hasUser() ) user = this.user;

    var norm = this._normalizeRequest(method, url, _debug || {})
      , sig
      ;

    sig = 'http://www.worldcat.org/wskey/v2/hmac/v1'
        + ' clientId="' + this.key + '",'
        + ' timestamp="' + this.time + '",'
        + ' nonce="' + this.nonce + '",'
        + ' signature="' + createHMACDigest(norm, this.secret) + '"'
        ;

    if ( user ) {
      sig += ', principalID="' + user.principalID + '"'
          +  ', principalIDNS="' + user.principalIDNS + '"'
          ;
    }

    this.time = this.nonce = null;

    return sig;
}

WSKey.prototype._normalizeRequest = function (method, reqUrl, _debug) {
    var url = require('url')
      , parsedSigUrl = url.parse('https://www.oclc.org/wskey')
      , parsedReqUrl = url.parse(reqUrl)
      , qs = parsedReqUrl.query

      , sigPort = parsedSigUrl.protocol === 'https:' ? 443 : 80

      , _debug = _debug || {}
      , time = _debug.time || (new Date()).getTime().toString().substr(0, 10)
      , nonce = _debug.nonce || createNonce()
      , bodyHash = _debug.bodyHash || ''

      , query, normalized
      ;

    this.time = time;
    this.nonce = nonce;

    if ( qs ) {
      query = qs.split('&').sort().join('\n');
      query = query.replace(/[^\s%\=]/g, function(match) { return encodeURIComponent(match); });
    }

    normalized = [
        this.key,
        this.time,
        this.nonce,
        bodyHash,
        method.toUpperCase(),
        parsedSigUrl.host,
        sigPort,
        parsedSigUrl.path
    ];

    if ( query ) normalized.push(query);

    return normalized.join('\n') + '\n';
}

function createHMACDigest(normalized, secret) {
    var crypto = require('crypto')
      , hmac = crypto.createHmac('sha256', secret)
      ;

    hmac.update(normalized);
    return hmac.digest('base64');
};

function createNonce() {
    return Math.ceil(
            (new Date()).getMilliseconds()
            * Math.random()
            * 1000000
           );
}

function isUser(user) {
  if ( user === undefined ) return false;
  if ( typeof user !== 'object' ) return false;
  if ( !user.principalID || !user.principalIDNS ) return false;
  return true;
}

function noop() {}
<|endoftext|>


<commit_before>var parseRoute = require('./parseRoute'),
    url = require('url');

function addRoute(seaLion, route, handler){
    if(handler == null || typeof handler === 'object' && !~Object.keys(handler).length){
        throw 'A route handler must be a function or an object with at least one key';
    }

    if(typeof handler === 'function'){
        handler = {
            any: handler
        };
    }

    if(!seaLion._routes[route]){
        seaLion._routes[route] = {};
    }

    for(var key in handler){
        seaLion._routes[route][key] = handler[key];
    }

    if(route in seaLion._rules){
        return;
    }

    seaLion._rules[route] = parseRoute(route);
}

function getValidMethod(handler, method){
    return handler[method.toLowerCase()] || handler[method.toUpperCase()] || handler.any;
}

function SeaLion(routes){
    this._rules = {};
    this._routes = {};

    this.add(routes);
}
SeaLion.prototype.add = function(routes){
    for(var key in routes){
        addRoute(this, key, routes[key]);
    }
};
SeaLion.prototype.match = function(pathname, method){
    var seaLion = this,
        ruleKeys = Object.keys(this._rules),
        matches = [];

    for(var i = 0; i < ruleKeys.length; i++){
        var match = this._rules[ruleKeys[i]](pathname);

        if(match){
            matches.push(match);
        }
    }

    var sorted = matches.sort(function(a,b) {
            return Object.keys(b.tokens).length - Object.keys(a.tokens).length;
        });

    while(sorted.length){
        var possibleMatch = sorted.pop(),
            possibleHandler = seaLion._routes[possibleMatch.route];

        if(typeof possibleHandler === 'function' || getValidMethod(possibleHandler, method)){
            return possibleMatch;
        }
    }

};
SeaLion.prototype.createHandler = function(){
    var seaLion = this;
    return function(request, response){
        var pathname = url.parse(request.url).pathname,
            match = seaLion.match(pathname, request.method);

        if(!match){
            return seaLion.notFound(request, response);
        }

        var handler = seaLion._routes[match.route];

        if(typeof handler !== 'function'){
            handler = getValidMethod(handler, request.method) || seaLion.methodNotAllowed;
        }

        try{
            handler(request, response, match.tokens);
        }catch(error){
            seaLion.error(request, response, error);
        }
    };
};
SeaLion.prototype.notFound = function(request, response) {
    var body = '404: The server has not found anything matching the Request-URI.';
    response.writeHead(404, { 'Content-Length': body.length, 'Content-Type': 'text/plain' });
    response.end(body);

    console.log('404: ' + request.url);
};
SeaLion.prototype.methodNotAllowed = function(request, response) {
    var body = '405: The method specified in the Request-Line is not allowed for the resource identified by the Request-URI.';
    response.writeHead(405, { 'Content-Length': body.length, 'Content-Type': 'text/plain' });
    response.end(body);

    console.log('405: url: ' + request.url + ' verb: ' + request.method);
};
SeaLion.prototype.error = function(request, response, error) {
    if(!error){
        error = 'Internal Server Error. The server encountered an unexpected condition which prevented it from fulfilling the request.';
    }

    console.error('Error accessing: ' + request.method + ' ' + request.url, error.stack || error.message || error);

    var body =
        'An exception was thrown while accessing: ' + request.method + ' ' + request.url + '\n' +
        'Exception: ' + (error.message || error);

    response.writeHead(500, { 'Content-Length': body.length, 'Content-Type': 'text/plain' });
    response.end(body);
};

module.exports = SeaLion;<commit_msg>Use default order when route sorting results in the same value<commit_after>var parseRoute = require('./parseRoute'),
    url = require('url');

function addRoute(seaLion, route, handler){
    if(handler == null || typeof handler === 'object' && !~Object.keys(handler).length){
        throw 'A route handler must be a function or an object with at least one key';
    }

    if(typeof handler === 'function'){
        handler = {
            any: handler
        };
    }

    if(!seaLion._routes[route]){
        seaLion._routes[route] = {};
    }

    for(var key in handler){
        seaLion._routes[route][key] = handler[key];
    }

    if(route in seaLion._rules){
        return;
    }

    seaLion._rules[route] = parseRoute(route);
}

function getValidMethod(handler, method){
    return handler[method.toLowerCase()] || handler[method.toUpperCase()] || handler.any;
}

function SeaLion(routes){
    this._rules = {};
    this._routes = {};

    this.add(routes);
}
SeaLion.prototype.add = function(routes){
    for(var key in routes){
        addRoute(this, key, routes[key]);
    }
};
SeaLion.prototype.match = function(pathname, method){
    var seaLion = this,
        ruleKeys = Object.keys(this._rules),
        matches = [];

    for(var i = 0; i < ruleKeys.length; i++){
        var match = this._rules[ruleKeys[i]](pathname);

        if(match){
            matches.push(match);
        }
    }

    var sorted = matches.sort(function(a,b) {
            return Object.keys(a.tokens).length - Object.keys(b.tokens).length;
        });

    while(sorted.length){
        var possibleMatch = sorted.shift(),
            possibleHandler = seaLion._routes[possibleMatch.route];

        if(typeof possibleHandler === 'function' || getValidMethod(possibleHandler, method)){
            return possibleMatch;
        }
    }

};
SeaLion.prototype.createHandler = function(){
    var seaLion = this;
    return function(request, response){
        var pathname = url.parse(request.url).pathname,
            match = seaLion.match(pathname, request.method);

        if(!match){
            return seaLion.notFound(request, response);
        }

        var handler = seaLion._routes[match.route];

        if(typeof handler !== 'function'){
            handler = getValidMethod(handler, request.method) || seaLion.methodNotAllowed;
        }

        try{
            handler(request, response, match.tokens);
        }catch(error){
            seaLion.error(request, response, error);
        }
    };
};
SeaLion.prototype.notFound = function(request, response) {
    var body = '404: The server has not found anything matching the Request-URI.';
    response.writeHead(404, { 'Content-Length': body.length, 'Content-Type': 'text/plain' });
    response.end(body);

    console.log('404: ' + request.url);
};
SeaLion.prototype.methodNotAllowed = function(request, response) {
    var body = '405: The method specified in the Request-Line is not allowed for the resource identified by the Request-URI.';
    response.writeHead(405, { 'Content-Length': body.length, 'Content-Type': 'text/plain' });
    response.end(body);

    console.log('405: url: ' + request.url + ' verb: ' + request.method);
};
SeaLion.prototype.error = function(request, response, error) {
    if(!error){
        error = 'Internal Server Error. The server encountered an unexpected condition which prevented it from fulfilling the request.';
    }

    console.error('Error accessing: ' + request.method + ' ' + request.url, error.stack || error.message || error);

    var body =
        'An exception was thrown while accessing: ' + request.method + ' ' + request.url + '\n' +
        'Exception: ' + (error.message || error);

    response.writeHead(500, { 'Content-Length': body.length, 'Content-Type': 'text/plain' });
    response.end(body);
};

module.exports = SeaLion;<|endoftext|>


<commit_before>var fire_list = [];
var fire_count = 0;

var pointlight_list = [];
var smoke_list = [];
var smoke_and_light_count = 0;

var fire;
var fireWidth = -1;
var fireHeight = -1;
var fireDepth = -1;
var sliceSpacing = -1;

var clock = new THREE.Clock();

function initFire() {
    fire = new VolumetricFire(
        fireWidth,
        fireHeight,
        fireDepth,
        sliceSpacing,
        camera
    );

    // Feuer wird für die animate Funktion in ein Array gelegt
    fire_list.push(fire);
    fire_count++;
}

function addFire(x, y, z, width, height, depth, spacing) {

    // Compare to last used fire
    if (fireWidth != width || fireHeight != height || fireDepth != depth || sliceSpacing != spacing) {

        var exists = false;

        // Check if the fire exists in the Array. If it does use the existing one.
        for (i = 0; i < fire_count; i++) {
            if (fire_list[i]._width == width && fire_list[i]._height == height &&
                fire_list[i]._depth == depth && fire_list[i]._sliceSpacing == spacing) {
                fire = fire_list[i];
                exists = true;
                break;
            }
        }

        if (exists == false) {
            //Create new fire
            fireWidth = width;
            fireHeight = height;
            fireDepth = depth;
            sliceSpacing = spacing;
            initFire();
        }
    }

    var pointlight = new THREE.PointLight(0xff9933, 1, 1.5);
    pointlight.position.set(x, y + 1, z);
    scene.add(pointlight);

    var fmesh = fire.mesh.clone();
    scene.add(fmesh);
    fmesh.position.set(x, y + fireHeight / 2, z);

    var smoke = addSmoke(x, y, z);

    // Push smoke und light in Array
    pointlight_list.push(pointlight);
    smoke_list.push(smoke);
    smoke_and_light_count++;

}

function addSmallFire(x, y, z) {
    addFire(x, y, z, 1.5, 2, 1.5, 0.5);
}

function animateFire() {

    requestAnimationFrame(animateFire);

    var elapsed = clock.getElapsedTime();

    // update alle fire Objekte aus dem Array
    for (i = 0; i < fire_count; i++) {
        fire_list[i].update(elapsed);
    }

    // update alle smoke und pointlights
    for (j = 0; j < smoke_and_light_count; j++) {

        pointlight_list[j].intensity = Math.sin(elapsed * 30) * 0.25 + 3;

        smoke_list[j].material.uniforms.time.value = clock.getElapsedTime();
    }
}
<commit_msg>Transparent collision box for fire<commit_after>var fire_list = [];
var fire_count = 0;

var pointlight_list = [];
var smoke_list = [];
var smoke_and_light_count = 0;

var fire;
var fireWidth = -1;
var fireHeight = -1;
var fireDepth = -1;
var sliceSpacing = -1;

var clock = new THREE.Clock();

function initFire() {
    fire = new VolumetricFire(
        fireWidth,
        fireHeight,
        fireDepth,
        sliceSpacing,
        camera
    );

    // Feuer wird für die animate Funktion in ein Array gelegt
    fire_list.push(fire);
    fire_count++;
}

function addFire(x, y, z, width, height, depth, spacing) {

    // Compare to last used fire
    if (fireWidth != width || fireHeight != height || fireDepth != depth || sliceSpacing != spacing) {

        var exists = false;

        // Check if the fire exists in the Array. If it does use the existing one.
        for (i = 0; i < fire_count; i++) {
            if (fire_list[i]._width == width && fire_list[i]._height == height &&
                fire_list[i]._depth == depth && fire_list[i]._sliceSpacing == spacing) {
                fire = fire_list[i];
                exists = true;
                break;
            }
        }

        if (exists == false) {
            //Create new fire
            fireWidth = width;
            fireHeight = height;
            fireDepth = depth;
            sliceSpacing = spacing;
            initFire();
        }
    }

    var pointlight = new THREE.PointLight(0xff9933, 1, 1.5);
    pointlight.position.set(x, y + 1, z);
    scene.add(pointlight);

    var fmesh = fire.mesh.clone();
    scene.add(fmesh);
    fmesh.position.set(x, y + fireHeight / 2, z);

    var geometry = new THREE.BoxGeometry( fireWidth, fireHeight, fireDepth);
    var material = new THREE.MeshBasicMaterial( {color: 0x00ff00,opacity: 1} );
    var cube = new THREE.Mesh( geometry, material );
    cube.position.set(x,y,z);
    terrain.push( cube );

    var smoke = addSmoke(x, y, z);

    // Push smoke und light in Array
    pointlight_list.push(pointlight);
    smoke_list.push(smoke);
    smoke_and_light_count++;

}

function addSmallFire(x, y, z) {
    addFire(x, y, z, 1.5, 2, 1.5, 0.5);
}

function animateFire() {

    requestAnimationFrame(animateFire);

    var elapsed = clock.getElapsedTime();

    // update alle fire Objekte aus dem Array
    for (i = 0; i < fire_count; i++) {
        fire_list[i].update(elapsed);
    }

    // update alle smoke und pointlights
    for (j = 0; j < smoke_and_light_count; j++) {

        pointlight_list[j].intensity = Math.sin(elapsed * 30) * 0.25 + 3;

        smoke_list[j].material.uniforms.time.value = clock.getElapsedTime();
    }
}
<|endoftext|>


<commit_before>import { server } from './server'

server()
  .then(() => process.on('SIGINT', () => process.exit(0))
  .catch(e => console.log(e))
<commit_msg>fix: Index File (#95)<commit_after>import { server } from './server'

server()
  .then(() => process.on('SIGINT', () => process.exit(0)))
  .catch(e => console.log(e))
<|endoftext|>


<commit_before>import { matcherHint, printExpected, printReceived } from 'jest-matcher-utils';
import getType from "jest-get-type";

exports const toBeType = (received, argument) => {
	const type = getType(received);
	const pass = type === expected;
	const message = pass
		? () =>
			matcherHint('.not.toBeType', 'value', 'type') +
			'\n\n' +
			`Expected value to be of type:\n` +
			`  ${printExpected(expected)}\n` +
			`Received:\n` +
			`  ${printReceived(received)}\n`
		: () =>
			matcherHint('.toBeType', 'value', 'type') +
			'\n\n' +
			`Expected value to be of type:\n` +
			`  ${printExpected(expected)}\n` +
			`Received:\n` +
			`  ${printReceived(received)}\n` +
			`type:\n` +
			`  ${printReceived(type)}`;

	return { pass, message }
};

const wrapped = {
	toBeType
};

export const extend = (expect) => {
	expect.extend(wrapped);
};

export default wrapped;
<commit_msg>fix exports -> export<commit_after>import { matcherHint, printExpected, printReceived } from 'jest-matcher-utils';
import getType from "jest-get-type";

export const toBeType = (received, argument) => {
	const type = getType(received);
	const pass = type === expected;
	const message = pass
		? () =>
			matcherHint('.not.toBeType', 'value', 'type') +
			'\n\n' +
			`Expected value to be of type:\n` +
			`  ${printExpected(expected)}\n` +
			`Received:\n` +
			`  ${printReceived(received)}\n`
		: () =>
			matcherHint('.toBeType', 'value', 'type') +
			'\n\n' +
			`Expected value to be of type:\n` +
			`  ${printExpected(expected)}\n` +
			`Received:\n` +
			`  ${printReceived(received)}\n` +
			`type:\n` +
			`  ${printReceived(type)}`;

	return { pass, message }
};

const wrapped = {
	toBeType
};

export const extend = (expect) => {
	expect.extend(wrapped);
};

export default wrapped;
<|endoftext|>


<commit_before>/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */

'use strict';

const exec = require('child_process').exec;
const fs = require('fs');

const removeBom = (text) => {
    return text.replace(/^\uFEFF/, '');
};

exec('git tag --contains HEAD', function (err, stdout, stderr) {
    if (err) {
        console.error(err);
        return;
    }

    if (stdout) {
        console.log(stdout);
    }
    if (stderr) {
        console.log(stderr);
    }

    let matchResult = /^v(.+)$/gm.exec(stdout);
    if (matchResult === null) {
        console.log('PrepareToPublishTask: no tags found, skip package.json update.');
        return;
    }
    const version = matchResult[1];

    console.log(`PrepareToPublishTask: There are tags on the build that match the version pattern. Updating package.json with version ${version}...`);
    let packageJson = JSON.parse(removeBom(fs.readFileSync(`${__dirname}/package.json`, 'utf8')));
    packageJson.version = version;
    fs.writeFileSync(`${__dirname}/package.json`, JSON.stringify(packageJson, null, '    '), 'utf8');
});
<commit_msg>polish npm publishing<commit_after>/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint no-console: 0 */

'use strict';

const exec = require('child_process').exec;
const fs = require('fs');

const removeBom = (text) => {
    return text.replace(/^\uFEFF/, '');
};

exec('git tag --contains HEAD', function (err, stdout, stderr) {
    if (err) {
        console.error(err);
        return;
    }

    if (stdout) {
        console.log(stdout);
    }
    if (stderr) {
        console.log(stderr);
    }

    let matchResult = /^v(.+)$/gm.exec(stdout);
    if (matchResult === null) {
        console.log('PrepareToPublishTask: no tags found, skip package.json update.');
        return;
    }
    const version = matchResult[1];

    console.log(`PrepareToPublishTask: There is a tag that matches the version pattern. Updating package.json with version ${version}...`);
    let packageJson = JSON.parse(removeBom(fs.readFileSync(`${__dirname}/package.json`, 'utf8')));
    packageJson.version = version;
    fs.writeFileSync(`${__dirname}/package.json`, JSON.stringify(packageJson, null, '  '), 'utf8');
    console.log(`Updated.`);
});
<|endoftext|>


<commit_before>var BracketValidator = require('bracket-validator');
var BracketData = require('bracket-data');
var _bind = require('lodash/function/bind');
var _each = require('lodash/collection/forEach');
var _map = require('lodash/collection/map');
var _uniq = require('lodash/array/uniq');
var _some = require('lodash/collection/some');
var _contains = require('lodash/collection/contains');
var _isArray = require('lodash/lang/isArray');
var _cloneDeep = require('lodash/lang/cloneDeep');
var _extend = require('lodash/object/assign');
var _isPlainObject = require('lodash/lang/isPlainObject');
var bracketData;

var getResult = {
    totalScore: function (result) {
        if (result.status !== 'correct') return 0;

        var scoringSystem = bracketData.scoring[result.type];

        if (typeof scoringSystem === 'undefined') throw new Error('There is no scoring system: ' + result.type);

        if (_isArray(scoringSystem) && typeof scoringSystem[0] === 'number' && scoringSystem.length === initialValues.rounds().length) {
            // The scoring system is an array of numbers that is equal to the number of rounds
            // So we return the value for the current round
            return scoringSystem[result.roundIndex] * 10;
        } else if (_isArray(scoringSystem) && _isArray(scoringSystem[0]) && scoringSystem.length === initialValues.rounds().length && scoringSystem[0].length === bracketData.constants.TEAMS_PER_REGION) {
            // The scoring system is an array of arrays. There is one array for each round
            // and each sub-array has one value for each seed. So we return the value for the current round+seed
            return scoringSystem[result.roundIndex][result.seed - 1] * 10;
        } else if (typeof scoringSystem === 'number') {
            return scoringSystem * 10;
        }

        throw new Error('Cant do anything with scoring system: ' + result.type);
    },
    diff: function (options) {
        if (options.status === 'incorrect') {
            if (options.diff) {
                options.diff[options.regionId].rounds[options.roundIndex][options.gameIndex].correct = false;
                options.diff[options.regionId].rounds[options.roundIndex][options.gameIndex].shouldBe = options.masterGame;
            }
            options.eliminated.push(options.game.fromRegion + options.game.seed);
        } else if (options.status === 'correct') {
            if (options.diff) {
                options.diff[options.regionId].rounds[options.roundIndex][options.gameIndex].correct = true;
            }
        } else if (options.status === 'unplayed' && _contains(options.eliminated, options.game.fromRegion + options.game.seed)) {
            if (options.diff) {
                options.diff[options.regionId].rounds[options.roundIndex][options.gameIndex].eliminated = true;
            }
        } else if (options.status === 'unplayed' && options.pprMethods.length && options.getScoreResult) {
            _each(options.pprMethods, function (pprMethod) {
                options.results[pprMethod] += this.totalScore({
                    roundIndex: options.trueRoundIndex,
                    status: 'correct',
                    seed: options.game.seed,
                    type: pprMethod.replace('PPR', '')
                });
            }, this);
        }
    },
    rounds: function (options) {
        options.rounds[options.roundIndex] += (options.status === 'correct' ? 1 : 0);
    }
};

var initialValues = {
    rounds: function () {
        var teamCount = bracketData.constants.TEAMS_PER_REGION * bracketData.constants.REGION_COUNT;
        var rounds = [];
        while (teamCount > 1) {
            rounds.push(0);
            teamCount = teamCount / 2;
        }
        return rounds;
    },
    diff: function (entry) { return _cloneDeep(entry); },
};

function Scorer(options) {
    bracketData = new BracketData({
        sport: options.sport,
        year: options.year,
        props: ['constants', 'scoring', 'bracket']
    });

    // Create convenience methods
    _each(_extend(bracketData.scoring, options.scoring || {}), function (system, key) {
        this[key + 'PPR'] = _bind(this.score, this, [key + 'PPR']);
        this[key] = _bind(this.score, this, [key]);
    }, this);

    this.entryValidator = new BracketValidator({year: options.year, sport: options.sport});
    this.masterValidator = new BracketValidator({year: options.year, sport: options.sport});

    return this.reset(options);
}

Scorer.prototype.reset = function (options) {
    if (options.entry) {
        if (Array.isArray(options.entry)) {
            this.validatedEntry = options.entry.map(function (entry) {
                if (typeof entry === 'string') {
                    return this.entryValidator.validate(entry);
                } else {
                    return _extend({}, entry, {
                        score: this.entryValidator.validate(entry.bracket),
                    });
                }
            }, this);
        } else {
            this.validatedEntry = this.entryValidator.validate(options.entry);
        }
    }
    if (options.master) {
        this.validatedMaster = this.masterValidator.validate(options.master);
    }
    return this;
};

// Default convenience methods
Scorer.prototype.diff = function (options) {
    return this.score(['diff'], options);
};

Scorer.prototype.rounds = function (options) {
    return this.score(['rounds'], options);
};

// Generic score method
Scorer.prototype.score = function (methods, options) {
    if (_isPlainObject(methods) && (methods.entry || methods.master) && !options) {
        options = methods;
    }

    options && this.reset(options);

    if (typeof methods === 'string') {
        methods = [methods];
    } else if (!methods || !_isArray(methods)) {
        methods = ['rounds'];
    }

    if (Array.isArray(this.validatedEntry)) {
        return this.validatedEntry.map(function (entry) {
            if (entry.score) {
                return _extend({}, entry, {
                    score: this._roundLoop(entry.score, methods)
                });
            } else {
                return this._roundLoop(entry, methods);
            }
        }, this);
    } else {
        return this._roundLoop(this.validatedEntry, methods);
    }
};

Scorer.prototype._roundLoop = function (entry, methods) {
    var results = {};
    var eliminatedTeams = [];
    var pprMethods = [];
    _each(methods, function (method) {
        if (method.indexOf('PPR') > -1) pprMethods.push(method);
        results[method] = initialValues[method] ? initialValues[method](entry) : 0;
    }, this);

    _each(entry, function (region, regionId) {
        var isFinal = regionId === bracketData.constants.FINAL_ID;
        _each(region.rounds, function (games, roundIndex) {
            var trueRoundIndex = (isFinal ? bracketData.constants.REGION_COUNT + roundIndex : roundIndex) - 1;
            var getScoreResult = roundIndex > 0;
            var getDiffResult = getScoreResult || isFinal;
            if (getScoreResult || getDiffResult) {
                _each(games, function (game, gameIndex) {
                    var masterGame = this.validatedMaster[regionId].rounds[roundIndex][gameIndex];
                    var status;

                    // Set the status of the result
                    if (masterGame === null) {
                        status = 'unplayed';
                    } else if (game.name === masterGame.name) {
                        status = 'correct';
                    } else {
                        status = 'incorrect';
                    }

                    // The diff methods needs to be called to get the diff result or any PPR results
                    var callableMethods;
                    var hasDiff = _contains(methods, 'diff');
                    var hasPPR = _some(methods, function (m) { return m.indexOf('PPR') > -1; });
                    // But we should only call it once
                    if (hasDiff || hasPPR) {
                        callableMethods = _uniq(_map(methods, function (m) {
                            return m.indexOf('PPR') > -1 ? 'diff' : m;
                        }));
                    }
                    // Process method for each result
                    _each(callableMethods || methods, function (method) {
                        if (method === 'rounds' && getScoreResult) {
                            getResult[method]({
                                rounds: results.rounds,
                                roundIndex: trueRoundIndex,
                                status: status
                            });
                        } else if (method === 'diff') {
                            getResult.diff({
                                diff: results.diff,
                                regionId: regionId,
                                roundIndex: roundIndex,
                                trueRoundIndex: trueRoundIndex,
                                gameIndex: gameIndex,
                                game: game,
                                status: status,
                                eliminated: eliminatedTeams,
                                masterGame: masterGame,
                                pprMethods: pprMethods,
                                results: results,
                                getScoreResult: getScoreResult
                            });
                        } else if (getScoreResult) {
                            results[method] += getResult.totalScore({
                                roundIndex: trueRoundIndex,
                                status: status,
                                seed: game.seed,
                                type: method
                            });
                        }
                    }, this);
                }, this);
            }
        }, this);
    }, this);

    // Any total score is a number and we multipled by 10 originally to support tenth place decimals
    _each(results, function (val, key, list) {
        if (typeof val === 'number') {
            list[key] = val / 10;
        }
    });

    return methods.length === 1 ? results[methods[0]] : results;
};

module.exports = Scorer;
<commit_msg>fix state outside scope<commit_after>var BracketValidator = require('bracket-validator');
var BracketData = require('bracket-data');
var _bind = require('lodash/function/bind');
var _each = require('lodash/collection/forEach');
var _map = require('lodash/collection/map');
var _uniq = require('lodash/array/uniq');
var _some = require('lodash/collection/some');
var _contains = require('lodash/collection/contains');
var _isArray = require('lodash/lang/isArray');
var _cloneDeep = require('lodash/lang/cloneDeep');
var _extend = require('lodash/object/assign');
var _isPlainObject = require('lodash/lang/isPlainObject');

var getResult = {
    totalScore: function (bd, result) {
        if (result.status !== 'correct') return 0;

        var scoringSystem = bd.scoring[result.type];

        if (typeof scoringSystem === 'undefined') throw new Error('There is no scoring system: ' + result.type);

        if (_isArray(scoringSystem) && typeof scoringSystem[0] === 'number' && scoringSystem.length === initialValues.rounds(bd).length) {
            // The scoring system is an array of numbers that is equal to the number of rounds
            // So we return the value for the current round
            return scoringSystem[result.roundIndex] * 10;
        } else if (_isArray(scoringSystem) && _isArray(scoringSystem[0]) && scoringSystem.length === initialValues.rounds(bd).length && scoringSystem[0].length === bd.constants.TEAMS_PER_REGION) {
            // The scoring system is an array of arrays. There is one array for each round
            // and each sub-array has one value for each seed. So we return the value for the current round+seed
            return scoringSystem[result.roundIndex][result.seed - 1] * 10;
        } else if (typeof scoringSystem === 'number') {
            return scoringSystem * 10;
        }

        throw new Error('Cant do anything with scoring system: ' + result.type);
    },
    diff: function (bd, options) {
        if (options.status === 'incorrect') {
            if (options.diff) {
                options.diff[options.regionId].rounds[options.roundIndex][options.gameIndex].correct = false;
                options.diff[options.regionId].rounds[options.roundIndex][options.gameIndex].shouldBe = options.masterGame;
            }
            options.eliminated.push(options.game.fromRegion + options.game.seed);
        } else if (options.status === 'correct') {
            if (options.diff) {
                options.diff[options.regionId].rounds[options.roundIndex][options.gameIndex].correct = true;
            }
        } else if (options.status === 'unplayed' && _contains(options.eliminated, options.game.fromRegion + options.game.seed)) {
            if (options.diff) {
                options.diff[options.regionId].rounds[options.roundIndex][options.gameIndex].eliminated = true;
            }
        } else if (options.status === 'unplayed' && options.pprMethods.length && options.getScoreResult) {
            _each(options.pprMethods, function (pprMethod) {
                options.results[pprMethod] += this.totalScore(bd, {
                    roundIndex: options.trueRoundIndex,
                    status: 'correct',
                    seed: options.game.seed,
                    type: pprMethod.replace('PPR', '')
                });
            }, this);
        }
    },
    rounds: function (options) {
        options.rounds[options.roundIndex] += (options.status === 'correct' ? 1 : 0);
    }
};

var initialValues = {
    rounds: function (bd) {
        var teamCount = bd.constants.TEAMS_PER_REGION * bd.constants.REGION_COUNT;
        var rounds = [];
        while (teamCount > 1) {
            rounds.push(0);
            teamCount = teamCount / 2;
        }
        return rounds;
    },
    diff: function (entry) { return _cloneDeep(entry); },
};

function Scorer(options) {
    this.bracketData = new BracketData({
        sport: options.sport,
        year: options.year,
        props: ['constants', 'scoring', 'bracket']
    });

    // Create convenience methods
    _each(_extend(this.bracketData.scoring, options.scoring || {}), function (system, key) {
        this[key + 'PPR'] = _bind(this.score, this, [key + 'PPR']);
        this[key] = _bind(this.score, this, [key]);
    }, this);

    this.entryValidator = new BracketValidator({year: options.year, sport: options.sport});
    this.masterValidator = new BracketValidator({year: options.year, sport: options.sport});

    return this.reset(options);
}

Scorer.prototype.reset = function (options) {
    if (options.entry) {
        if (Array.isArray(options.entry)) {
            this.validatedEntry = options.entry.map(function (entry) {
                if (typeof entry === 'string') {
                    return this.entryValidator.validate(entry);
                } else {
                    return _extend({}, entry, {
                        score: this.entryValidator.validate(entry.bracket),
                    });
                }
            }, this);
        } else {
            this.validatedEntry = this.entryValidator.validate(options.entry);
        }
    }
    if (options.master) {
        this.validatedMaster = this.masterValidator.validate(options.master);
    }
    return this;
};

// Default convenience methods
Scorer.prototype.diff = function (options) {
    return this.score(['diff'], options);
};

Scorer.prototype.rounds = function (options) {
    return this.score(['rounds'], options);
};

// Generic score method
Scorer.prototype.score = function (methods, options) {
    if (_isPlainObject(methods) && (methods.entry || methods.master) && !options) {
        options = methods;
    }

    options && this.reset(options);

    if (typeof methods === 'string') {
        methods = [methods];
    } else if (!methods || !_isArray(methods)) {
        methods = ['rounds'];
    }

    if (Array.isArray(this.validatedEntry)) {
        return this.validatedEntry.map(function (entry) {
            if (entry.score) {
                return _extend({}, entry, {
                    score: this._roundLoop(entry.score, methods)
                });
            } else {
                return this._roundLoop(entry, methods);
            }
        }, this);
    } else {
        return this._roundLoop(this.validatedEntry, methods);
    }
};

Scorer.prototype._roundLoop = function (entry, methods) {
    var results = {};
    var self = this;
    var eliminatedTeams = [];
    var pprMethods = [];
    _each(methods, function (method) {
        if (method.indexOf('PPR') > -1) pprMethods.push(method);
        if (method === 'rounds') {
            results[method] = initialValues.rounds(self.bracketData);
        } else {
            results[method] = initialValues[method] ? initialValues[method](entry) : 0;
        }
    }, this);

    _each(entry, function (region, regionId) {
        var isFinal = regionId === self.bracketData.constants.FINAL_ID;
        _each(region.rounds, function (games, roundIndex) {
            var trueRoundIndex = (isFinal ? self.bracketData.constants.REGION_COUNT + roundIndex : roundIndex) - 1;
            var getScoreResult = roundIndex > 0;
            var getDiffResult = getScoreResult || isFinal;
            if (getScoreResult || getDiffResult) {
                _each(games, function (game, gameIndex) {
                    var masterGame = this.validatedMaster[regionId].rounds[roundIndex][gameIndex];
                    var status;

                    // Set the status of the result
                    if (masterGame === null) {
                        status = 'unplayed';
                    } else if (game.name === masterGame.name) {
                        status = 'correct';
                    } else {
                        status = 'incorrect';
                    }

                    // The diff methods needs to be called to get the diff result or any PPR results
                    var callableMethods;
                    var hasDiff = _contains(methods, 'diff');
                    var hasPPR = _some(methods, function (m) { return m.indexOf('PPR') > -1; });
                    // But we should only call it once
                    if (hasDiff || hasPPR) {
                        callableMethods = _uniq(_map(methods, function (m) {
                            return m.indexOf('PPR') > -1 ? 'diff' : m;
                        }));
                    }
                    // Process method for each result
                    _each(callableMethods || methods, function (method) {
                        if (method === 'rounds' && getScoreResult) {
                            getResult[method]({
                                rounds: results.rounds,
                                roundIndex: trueRoundIndex,
                                status: status
                            });
                        } else if (method === 'diff') {
                            getResult.diff(self.bracketData, {
                                diff: results.diff,
                                regionId: regionId,
                                roundIndex: roundIndex,
                                trueRoundIndex: trueRoundIndex,
                                gameIndex: gameIndex,
                                game: game,
                                status: status,
                                eliminated: eliminatedTeams,
                                masterGame: masterGame,
                                pprMethods: pprMethods,
                                results: results,
                                getScoreResult: getScoreResult
                            });
                        } else if (getScoreResult) {
                            results[method] += getResult.totalScore(self.bracketData, {
                                roundIndex: trueRoundIndex,
                                status: status,
                                seed: game.seed,
                                type: method
                            });
                        }
                    }, this);
                }, this);
            }
        }, this);
    }, this);

    // Any total score is a number and we multipled by 10 originally to support tenth place decimals
    _each(results, function (val, key, list) {
        if (typeof val === 'number') {
            list[key] = val / 10;
        }
    });

    return methods.length === 1 ? results[methods[0]] : results;
};

module.exports = Scorer;
<|endoftext|>


<commit_before>function getValorComp(vComponete){
	var fComponentej = "#"+vComponete;
	return $(fComponentej).val();
}

function getValorTabela(vComp, vColuna){

	var fRetorno = null;

	$('#'+vComp+' tbody').on('click', 'tr', function () {
		var fValor  = $('td', this).eq(vColuna).text();

		fRetorno = fValor;

	} );

	return fRetorno;

}

function divConfirma(vMsg) {
	 bootbox.confirm(vMsg, function(result) {
        return result;
    });
};

function CarregarJS(vURL){

	var script = document.createElement('script');
	script.src = vURL;
	document.body.appendChild(script);

}

function fecharForm(){
	window.close();
}

function ocultarComp(vComp){
	$("#"+vComp).hide();
}

function alterarClass(vComp, vClasse){
	document.getElementById(vComp).className = vClasse;
}

function maiuscula(vComp, vVerifica){

	if(String(vVerifica)=='T'){

		fComp = vComp.value.toUpperCase();
		vComp.value = uCase;

	}
}

function exibirComp(vComp, vVisivel){

	if(vComp == null||vVisivel == null){}else{

		var fComp = "#"+vComp;
		//Exibir
		if(vVisivel){
			$(fComp).show();
		}
		//Ocultar
		if(vVisivel==false){
			$(fComp).hide();
		}
	}
}

function alterarValorComp(vComp, vValor){
	if(vComp != null||vValor != null){
		document.getElementById(vComp).value=vValor;
	}
}

function getVisivel(vComp){

	var fRetorno = false
    var fComp = "#"+vComp;

	if($(fComp).is(':visible')){
		fRetorno = true;
	}

	return fRetorno;
}

function princ_focarComp(vComp){

	document.getElementById(vComp).focus();
}

function princ_apenasLeitura(vComp, vVerifica){

    var fComp = "#"+vComp;

    $(fComp).prop('readonly', vVerifica);
}

function princ_ocultarComp(vComp){
	$("#"+vComp).hide();
}

function princ_extraiScript(texto){

	var ini = 0;
	while (ini!=-1){

		ini = texto.indexOf('<script', ini);

		if (ini >=0){

			ini = texto.indexOf('>', ini) + 1;

			var fim = texto.indexOf('</script>', ini);

			codigo = texto.substring(ini,fim);
			novo = document.createElement("script")
			novo.text = codigo;
			document.body.appendChild(novo)
		}
	}
}

function princ_openAjax() {

	var ajax;

	try{
	    ajax = new XMLHttpRequest(); // XMLHttpRequest para Firefox, Safari, dentre outros.
	}catch(ee){
	    try{
	        ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o Internet Explorer
	    }catch(e){
	        try{
	            ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o Internet Explorer
	        }catch(E){
	            ajax = false;
	        }
	    }
	}
	return ajax;
}

function princ_excAjax(vComp, vUrl){
		var vRenderiza = document.getElementById(vComp);
        var ajax = princ_openAjax(); // Inicia o Ajax.
        ajax.open("GET", vUrl, true);
        ajax.onreadystatechange = function()
        {
            if(ajax.readyState == 1) // Quando estiver carregando, exibe: carregando...
            {
            	vRenderiza.innerHTML = "Atualizando...";
            }
            if(ajax.readyState == 4) // Quando estiver tudo pronto.
            {
                if(ajax.status == 200)
                {
                    var resultado = ajax.responseText;
                    vRenderiza.innerHTML = resultado;
                    princ_extraiScript(resultado);
                }
                  else
                  {
                	  vRenderiza.innerHTML = "Erro Ajax";
                  }
            }
        }
        ajax.send(null); // submete
}

function princ_excAjaxJson(vUrl, funcao){
  var ajax = princ_openAjax(); // Inicia o Ajax.
  ajax.open("GET", vUrl, true);
  ajax.onreadystatechange = function()
  {
      if(ajax.readyState == 1) // Quando estiver carregando, exibe: carregando...
      {
      	vRenderiza.innerHTML = "Carregando...";
      }
      if(ajax.readyState == 4) // Quando estiver tudo pronto.
      {
          if(ajax.status == 200)
          {
						funcao(JSON.parse(ajax.responseText));
          }
            else
            {
          	  console.log("erro");
            }
      }
  }
  ajax.send(null); // submete
}

function princ_obterValorComp(vComp){

		var fComponentej = "#"+vComp;
		return $(fComponentej).val();

}

function princ_alterarValorComp(vComp, vValor){

	var fComp = "#"+vComp;

	if(vComp == null||vValor == null){}else{

		if($(fComp).tagName == "TEXTAREA"){

			$(fComp).jqteVal(vValor);

		}else{
			if($(fComp).tagName == "SELECT"){

				$(fComp+" option:selected").removeAttr("selected");

				$(fComp+' option[value="' + vValor + '"]').attr({ selected : "selected" });

			}else{
				if($(fComp).type == "checkbox"){

					if(vValor=="true"){
						$(fComp).attr('checked',true);
						document.getElementById(vComp).value=vValor;

					}else{
						$(fComp).removeAttr('checked');
						document.getElementById(vComp).value=vValor;

					}

				}else{
					document.getElementById(vComp).value=vValor;
				}

			}

		}

	}
}

function princ_desabilitarComp(vComp, vVerifica){

	var fComponentej = "#"+vComp;
	if(vVerifica){

		$(fComponentej).addClass("disabled");

	}else{

		$(fComponentej).removeClass("disabled");
	}

}

function princ_desabilitarComp_Mate(vComp, vVerifica){

	var fComponentej = "#"+vComp;
	if(vVerifica){

		$(fComponentej).attr("disabled");

	}else{

		$(fComponentej).removeAttr("disabled");
	}

}

function setCheck(vComp){

	var fValor = princ_obterValorComp(vComp);

	if(fValor == "true"){

		princ_alterarValorComp(vComp, "false");

	}else{

		princ_alterarValorComp(vComp, "true");

	}

}

function princ_ocultarComp2(vComp,vVerifica){

	if(vVerifica){
		$("#"+vComp).hide();
	}else{
		$("#"+vComp).show();
	}

}

function princ_confirma(vMsg) {
	 bootbox.confirm(vMsg, function(result) {
       return result;
   });
};

function princ_estaVisivel(vComp){

	var fRetorno = false
    var fComp = "#"+vComp;

	if($(fComp).is(':visible')){
		fRetorno = true;
	}

	return fRetorno;
}

function princ_abrirPopUp(vUrl, vWidth, vHeight){

	window.open (vUrl,"mywindow","menubar=1,resizable=1,width="+vWidth+",height="+vHeight);
}

function princ_obterIp(vUrl){

	var fUrl = String(vUrl);

	var fPosicaoIni = fUrl.indexOf("//");
	fUrl = fUrl.substring((fPosicaoIni + 2), fUrl.length);

	var fPosicaoFim = fUrl.indexOf(":");
	var fIp = fUrl.substring(0, fPosicaoFim);

	return fIp;

}

function princ_formata_data(vData){

	var fData = "";

	if(vData != null){
		var data = new Date(vData);
     var dia = data.getDate();
     if (dia.toString().length == 1)
       dia = "0"+dia;
     var mes = data.getMonth()+1;
     if (mes.toString().length == 1)
       mes = "0"+mes;
     var ano = data.getFullYear();
		 //tempo
		 var hora    = data.getHours();
		 var minutos = data.getMinutes();
		 if(minutos < 10){
			 minutos = "0"+minutos;
		 }
		 var segunds = data.getSeconds();
		 if(segunds < 10){
			 segunds = "0"+segunds;
		 }
     return dia+"/"+mes+"/"+ano+" "+hora+":"+minutos+":"+segunds;
	}

}
function princ_limparSelect(vComp){
	document.getElementById(vComp).options.length = 0;
}

function princ_execAjaxJquery(vUrl){

	var fRetorno = false;

	$.ajax({
	     type: "POST",
	     url: vUrl,
	     dataType: "json",
	     success: function(json){
	    	 fRetorno = true;
	     }
	  });

	return fRetorno;
}

function princ_execAjaxJqueryRet(vUrl, vComp){

	$.ajax({
	     type: "POST",
	     url: vUrl,
	     dataType: "html",
	     success: function(dado){

	    	 $("#"+vComp).html(dado);

	     }
	  });
}

function princ_limparGrade(vComp){

	$("#"+vComp+" tbody tr").remove();

}

function princ_limparDiv(vComp){
	 document.getElementById(vComp).innerHTML="";
}

//Máscaras
$(".masc-data").mask("99/99/9999");
$(".masc-cpf").mask("999-999-999-99");
<commit_msg>Starting removing jquery dependency<commit_after>function getValorComp(vComponete){
	var fComponentej = "#"+vComponete;
	return $(fComponentej).val();
}

function getValorTabela(vComp, vColuna){

	var fRetorno = null;

	$('#'+vComp+' tbody').on('click', 'tr', function () {
		var fValor  = $('td', this).eq(vColuna).text();

		fRetorno = fValor;

	} );

	return fRetorno;

}

function divConfirma(vMsg) {
	 bootbox.confirm(vMsg, function(result) {
        return result;
    });
};

function CarregarJS(vURL){

	var script = document.createElement('script');
	script.src = vURL;
	document.body.appendChild(script);

}

function fecharForm(){
	window.close();
}

function ocultarComp(vComp){
	$("#"+vComp).hide();
}

function alterarClass(vComp, vClasse){
	document.getElementById(vComp).className = vClasse;
}

function maiuscula(vComp, vVerifica){

	if(String(vVerifica)=='T'){

		fComp = vComp.value.toUpperCase();
		vComp.value = uCase;

	}
}

function princ_exibirComp(vComp, vVisivel){
	if(vComp != null||vVisivel != null){
		if(vVisivel){
			document.getElementById(vComp).style.display = "block";
		}
		if(!vVisivel){
			document.getElementById(vComp).style.display = "none";
		}
	}
}

function alterarValorComp(vComp, vValor){
	if(vComp != null||vValor != null){
		document.getElementById(vComp).value=vValor;
	}
}

function getVisivel(vComp){

	var fRetorno = false
    var fComp = "#"+vComp;

	if($(fComp).is(':visible')){
		fRetorno = true;
	}

	return fRetorno;
}

function princ_focarComp(vComp){

	document.getElementById(vComp).focus();
}

function princ_apenasLeitura(vComp, vVerifica){

    var fComp = "#"+vComp;

    $(fComp).prop('readonly', vVerifica);
}

function princ_ocultarComp(vComp){
	$("#"+vComp).hide();
}

function princ_extraiScript(texto){

	var ini = 0;
	while (ini!=-1){

		ini = texto.indexOf('<script', ini);

		if (ini >=0){

			ini = texto.indexOf('>', ini) + 1;

			var fim = texto.indexOf('</script>', ini);

			codigo = texto.substring(ini,fim);
			novo = document.createElement("script")
			novo.text = codigo;
			document.body.appendChild(novo)
		}
	}
}

function princ_openAjax() {

	var ajax;

	try{
	    ajax = new XMLHttpRequest(); // XMLHttpRequest para Firefox, Safari, dentre outros.
	}catch(ee){
	    try{
	        ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o Internet Explorer
	    }catch(e){
	        try{
	            ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o Internet Explorer
	        }catch(E){
	            ajax = false;
	        }
	    }
	}
	return ajax;
}

function princ_excAjax(vComp, vUrl){
		var vRenderiza = document.getElementById(vComp);
        var ajax = princ_openAjax(); // Inicia o Ajax.
        ajax.open("GET", vUrl, true);
        ajax.onreadystatechange = function()
        {
            if(ajax.readyState == 1) // Quando estiver carregando, exibe: carregando...
            {
            	vRenderiza.innerHTML = "Atualizando...";
            }
            if(ajax.readyState == 4) // Quando estiver tudo pronto.
            {
                if(ajax.status == 200)
                {
                    var resultado = ajax.responseText;
                    vRenderiza.innerHTML = resultado;
                    princ_extraiScript(resultado);
                }
                  else
                  {
                	  vRenderiza.innerHTML = "Erro Ajax";
                  }
            }
        }
        ajax.send(null); // submete
}

function princ_excAjaxJson(vUrl, funcao){
  var ajax = princ_openAjax(); // Inicia o Ajax.
  ajax.open("GET", vUrl, true);
  ajax.onreadystatechange = function()
  {
      if(ajax.readyState == 1) // Quando estiver carregando, exibe: carregando...
      {
      	vRenderiza.innerHTML = "Carregando...";
      }
      if(ajax.readyState == 4) // Quando estiver tudo pronto.
      {
          if(ajax.status == 200)
          {
						funcao(JSON.parse(ajax.responseText));
          }
            else
            {
          	  console.log("erro");
            }
      }
  }
  ajax.send(null); // submete
}

function princ_obterValorComp(vComp){
	return document.getElementById(vComp).value;
}

function princ_alterarValorComp(vComp, vValor){

	var fComp = "#"+vComp;

	if(vComp == null||vValor == null){}else{

		if($(fComp).tagName == "TEXTAREA"){

			$(fComp).jqteVal(vValor);

		}else{
			if($(fComp).tagName == "SELECT"){

				$(fComp+" option:selected").removeAttr("selected");

				$(fComp+' option[value="' + vValor + '"]').attr({ selected : "selected" });

			}else{
				if($(fComp).type == "checkbox"){

					if(vValor=="true"){
						$(fComp).attr('checked',true);
						document.getElementById(vComp).value=vValor;

					}else{
						$(fComp).removeAttr('checked');
						document.getElementById(vComp).value=vValor;

					}

				}else{
					document.getElementById(vComp).value=vValor;
				}

			}

		}

	}
}

function princ_desabilitarComp(vComp, vVerifica){
	if(vVerifica){
		document.getElementById(vComp).disabled = true;
	}else{
		document.getElementById(vComp).disabled = false;
	}
}

function princ_desabilitarComp_Mate(vComp, vVerifica){

	var fComponentej = "#"+vComp;
	if(vVerifica){

		$(fComponentej).attr("disabled");

	}else{

		$(fComponentej).removeAttr("disabled");
	}

}

function setCheck(vComp){

	var fValor = princ_obterValorComp(vComp);

	if(fValor == "true"){

		princ_alterarValorComp(vComp, "false");

	}else{

		princ_alterarValorComp(vComp, "true");

	}

}

function princ_ocultarComp2(vComp,vVerifica){

	if(vVerifica){
		$("#"+vComp).hide();
	}else{
		$("#"+vComp).show();
	}

}

function princ_confirma(vMsg) {
	 bootbox.confirm(vMsg, function(result) {
       return result;
   });
};

function princ_estaVisivel(vComp){

	var fRetorno = false
    var fComp = "#"+vComp;

	if($(fComp).is(':visible')){
		fRetorno = true;
	}

	return fRetorno;
}

function princ_abrirPopUp(vUrl, vWidth, vHeight){

	window.open (vUrl,"mywindow","menubar=1,resizable=1,width="+vWidth+",height="+vHeight);
}

function princ_obterIp(vUrl){

	var fUrl = String(vUrl);

	var fPosicaoIni = fUrl.indexOf("//");
	fUrl = fUrl.substring((fPosicaoIni + 2), fUrl.length);

	var fPosicaoFim = fUrl.indexOf(":");
	var fIp = fUrl.substring(0, fPosicaoFim);

	return fIp;

}

function princ_formata_data(vData){

	var fData = "";

	if(vData != null){
		var data = new Date(vData);
     var dia = data.getDate();
     if (dia.toString().length == 1)
       dia = "0"+dia;
     var mes = data.getMonth()+1;
     if (mes.toString().length == 1)
       mes = "0"+mes;
     var ano = data.getFullYear();
		 //tempo
		 var hora    = data.getHours();
		 var minutos = data.getMinutes();
		 if(minutos < 10){
			 minutos = "0"+minutos;
		 }
		 var segunds = data.getSeconds();
		 if(segunds < 10){
			 segunds = "0"+segunds;
		 }
     return dia+"/"+mes+"/"+ano+" "+hora+":"+minutos+":"+segunds;
	}

}
function princ_limparSelect(vComp){
	document.getElementById(vComp).options.length = 0;
}

function princ_execAjaxJquery(vUrl){

	var fRetorno = false;

	$.ajax({
	     type: "POST",
	     url: vUrl,
	     dataType: "json",
	     success: function(json){
	    	 fRetorno = true;
	     }
	  });

	return fRetorno;
}

function princ_execAjaxJqueryRet(vUrl, vComp){

	$.ajax({
	     type: "POST",
	     url: vUrl,
	     dataType: "html",
	     success: function(dado){

	    	 $("#"+vComp).html(dado);

	     }
	  });
}

function princ_limparGrade(vComp){

	$("#"+vComp+" tbody tr").remove();

}

function princ_limparDiv(vComp){
	 document.getElementById(vComp).innerHTML="";
}

function princ_loadJS (url){
	var scriptTag = document.createElement('script');
	scriptTag.src = url;
	document.body.appendChild(scriptTag);
};

function princ_loadSelect(comp, data){
	if(data.length > 0){
    for (var i=0; i < data.length; i++){
      console.log(data[i].guiche);

      var x = document.getElementById("checkin.fkguiche");
      var c = document.createElement("option");
      c.text = data[i].guiche;
      c.value = data[i].pkguiche;
      x.options.add(c, x.options.length + 1);

    }
  }else{
    console.log("limpar grade");
  }
}

//Máscaras
$(".masc-data").mask("99/99/9999");
$(".masc-cpf").mask("999-999-999-99");
<|endoftext|>


<commit_before>if (require.resolve('./lib/cli').endsWith('es')) {
  require('@babel/register')(require('./babel.config'))
}
require('./lib/cli')
require('./app')
<commit_msg>fix: crash on startup<commit_after>try {
  require('./lib/cli')
} catch (e) {
  require('@babel/register')(require('./babel.config'))
  require('./lib/cli')
} finally {
  require('./app')
}
<|endoftext|>


<commit_before>module.exports = require('./lib/ware');
<commit_msg>refactor ware<commit_after>'use strict';

/**
 *  Module dependencies.
 */

var debug = require('debug')('ware');
var Emitter = require('events').EventEmitter;
var compose = require('koa-compose');
var co = require('co');

/**
 * slice() reference.
 */

var slice = Array.prototype.slice;

/**
 *  Ware prototype.
 */

var w = Ware.prototype;

/**
 *  Expose `Ware`.
 */

exports = module.exports = Ware;

/**
 *  Initialize a new `Ware` manager.
 *
 *  @api public
 */

function Ware () {
  if (!(this instanceof Ware)) return new Ware;
  this.env = process.env.NODE_ENV || 'development';
  this.outputErrors = 'test' != this.env;
  this.on('error', this.onerror);
  this.fns = [];
  this.context = Object.create(null);
}

/**
 * Inherit from `Emitter.prototype`.
 */

Ware.prototype.__proto__ = Emitter.prototype;

/**
 *  Use the given middleware `fn`.
 *
 *  @param {GeneratorFunction} fn
 *  @return {Ware} self
 *  @api public
 */

w.use = function (fn) {
  debug('use %s', fn._name || fn.name || '-');
  this.fns.push(fn);
  return this;
};

/**
 *  Run through the middleware with the given `args` and optional `callback`.
 *
 *  @param {Mixed} args...
 *  @param {Function} callback (optional)
 *  @return {Ware}
 *  @api public
 */

w.run = function () {
  debug('run');
  var self = this;
  var mw = [].concat(this.fns);
  var args = slice.call(arguments);
  var last = args[args.length - 1];
  var callback = 'function' === typeof last ? last : null;
  if (callback) args.pop();
  mw.push(callback || noop);
  var gen = compose(mw);
  var fn = co(gen);
  var ctx = Object.create(this.context);
  ctx.input = args;
  ctx.onerror = function (err) {
    if (!err) return;
    self.emit('error', err);
  };
  fn.call(ctx, ctx.onerror);
  return this;
};

/**
 * Default error handler.
 *
 * @param {Error} err
 * @api private
 */

w.onerror = function(err){
  if (!this.outputErrors) return;
  console.error(err.stack);
};

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

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


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

//environment variables
var env = proccess.env;
var port = env.PORT || 5000;
var mailgun = require('mailgun-js')({
  apiKey: env.MAILGUN_API_KEY,
  domain: env.MAILGUN_DOMAIN,
});
var inboundMessageEndpoint = env.ENDPOINT_SECRET;

//setup express
app.set('port', port);

app.post(inboundMessageEndpoint, function(request, response) {
  console.log(request.body);
  console.log(request.query);
});

app.listen(app.get('port'), function() {
  console.log('Running; port = ', app.get('port'));
});

//UTILITIES---------------------------------------------------------------------
<commit_msg>add response to inbound mail endpoint so it doesnt hang<commit_after>var express = require('express');
var app = express();

//environment variables
var env = proccess.env;
var port = env.PORT || 5000;
var mailgun = require('mailgun-js')({
  apiKey: env.MAILGUN_API_KEY,
  domain: env.MAILGUN_DOMAIN,
});
var inboundMessageEndpoint = env.ENDPOINT_SECRET;

//setup express
app.set('port', port);

app.post(inboundMessageEndpoint, function(request, response) {
  console.log(request.body);
  console.log(request.query);
  response.send('got it.');
});

app.listen(app.get('port'), function() {
  console.log('Running; port = ', app.get('port'));
});

//UTILITIES---------------------------------------------------------------------
<|endoftext|>