<commit_before>"use strict";

/*
 * Static utility methods for RESTBase
 */

var P = require('bluebird');
var util = require('util');
var url = require('url');
var Busboy = require('busboy');
var uuid = require('cassandra-uuid');

var rbUtil = {};

// Optimized URL parsing
var qs = require('querystring');
// Should make it into 0.12, see https://github.com/joyent/node/pull/7878
var SIMPLE_PATH = /^(\/(?!\/)[^\?#\s]*)(?:\?([^#\s]*))?$/;
rbUtil.parseURL = function parseURL (uri) {
    // Fast path for simple path uris
    var fastMatch = SIMPLE_PATH.exec(uri);
    if (fastMatch) {
        return {
            protocol: null,
            slashes: null,
            auth: null,
            host: null,
            port: null,
            hostname: null,
            hash: null,
            search: fastMatch[2] || '',
            pathname: fastMatch[1],
            path: fastMatch[1],
            query: fastMatch[2] && qs.parse(fastMatch[2]) || {},
            href: uri
        };
    } else {
        return url.parse(uri, true);
    }
};

// Parse a POST request into request.body with BusBoy
// Drops file uploads on the floor without creating temporary files
//
// @param {request} HTTP request
// @returns {Promise<>}

function read(req) {
    return new P(function (resolve) {
        var chunks = [];
        req.on('data', function(chunk) {
            chunks.push(chunk);
        });

        req.on('end', function() {
            resolve(Buffer.concat(chunks));
        });
    });
}

rbUtil.parsePOST = function parsePOST(req) {

    var readIt =
        (req.method === 'PUT') ||
        (req.method === 'POST' && req.headers &&
         (/^application\/json/i.test(req.headers['content-type'])
            || !req.headers['content-type']));

    if (readIt) {
        return read(req);
    } else if (req.method !== 'POST') {
        return P.resolve();
    } else {
        // Parse the POST
        return new P(function(resolve) {
            // Parse POST data
            var bboy = new Busboy({
                headers: req.headers,
                // Increase the form field size limit from the 1M default.
                limits: { fieldSize: 15 * 1024 * 1024 }
            });
            var body = {};
            bboy.on('field', function (field, val) {
                body[field] = val;
            });
            bboy.on('finish', function () {
                resolve(body);
            });
            req.pipe(bboy);
        });
    }
};

rbUtil.reverseDomain = function reverseDomain (domain) {
    return domain.toLowerCase().split('.').reverse().join('.');
};

rbUtil.tidFromDate = function tidFromDate(date) {
    if (typeof date === 'object') {
        // convert Date object to numeric milliseconds
        date = date.getTime();
    } else if (typeof date === 'string') {
        // convert date string to numeric milliseconds
        date = Date.parse(date);
    }
    if (isNaN(+date)) {
        throw new Error('Invalid date');
    }
    // Create a new, deterministic timestamp
    return uuid.TimeUuid.fromDate(date,
        0,
        new Buffer([0x01, 0x23, 0x45, 0x67, 0x89, 0xab]),
        new Buffer([0x12, 0x34])).toString();
};

/**
 * Check if a string is a valid timeuuid
 */
rbUtil.isTimeUUID = function (s) {
    return uuid.TimeUuid.test(s);
};

/**
 * Generates a new request ID
 */
rbUtil.generateRequestId = function() {
    return uuid.Uuid.random().toRawString();
};

/*
 * Error instance wrapping HTTP error responses
 *
 * Has the same properties as the original response.
 */
function HTTPError(response) {
    Error.call(this);
    Error.captureStackTrace(this, HTTPError);
    this.name = this.constructor.name;
    this.message = response.status + '';
    if (response.body && response.body.type) {
        this.message += ': ' + response.body.type;
    }

    for (var key in response) {
        this[key] = response[key];
    }
}
util.inherits(HTTPError, Error);

rbUtil.HTTPError = HTTPError;

// Create an etag value of the form
// "<revision>/<tid>"
rbUtil.makeETag = function(rev, tid) {
    return '"' + rev + '/' + tid + '"';
};

// Parse an etag value of the form
// "<revision>/<tid>"
// @param {string} etag
// @return {object} with params rev / tid
rbUtil.parseETag = function(etag) {
    var bits = /^"?([^"\/]+)(?:\/([^"\/]+))"?$/.exec(etag);
    if (bits) {
        return {
            rev: bits[1],
            tid: bits[2],
        };
    } else {
        return null;
    }
};

/***
 * MediaWiki-specific functions
 * TODO: Move them out in a separate file
 ***/

// Store titles as MediaWiki db keys
// @param {string} title
// @return {string} normalised title
rbUtil.normalizeTitle = function(title) {
    return title.replace(/ /g, '_');
};

module.exports = rbUtil;
<commit_msg>Request id in proper form and using the time uuid<commit_after>"use strict";

/*
 * Static utility methods for RESTBase
 */

var P = require('bluebird');
var util = require('util');
var url = require('url');
var Busboy = require('busboy');
var uuid = require('cassandra-uuid').TimeUuid;

var rbUtil = {};

// Optimized URL parsing
var qs = require('querystring');
// Should make it into 0.12, see https://github.com/joyent/node/pull/7878
var SIMPLE_PATH = /^(\/(?!\/)[^\?#\s]*)(?:\?([^#\s]*))?$/;
rbUtil.parseURL = function parseURL (uri) {
    // Fast path for simple path uris
    var fastMatch = SIMPLE_PATH.exec(uri);
    if (fastMatch) {
        return {
            protocol: null,
            slashes: null,
            auth: null,
            host: null,
            port: null,
            hostname: null,
            hash: null,
            search: fastMatch[2] || '',
            pathname: fastMatch[1],
            path: fastMatch[1],
            query: fastMatch[2] && qs.parse(fastMatch[2]) || {},
            href: uri
        };
    } else {
        return url.parse(uri, true);
    }
};

// Parse a POST request into request.body with BusBoy
// Drops file uploads on the floor without creating temporary files
//
// @param {request} HTTP request
// @returns {Promise<>}

function read(req) {
    return new P(function (resolve) {
        var chunks = [];
        req.on('data', function(chunk) {
            chunks.push(chunk);
        });

        req.on('end', function() {
            resolve(Buffer.concat(chunks));
        });
    });
}

rbUtil.parsePOST = function parsePOST(req) {

    var readIt =
        (req.method === 'PUT') ||
        (req.method === 'POST' && req.headers &&
         (/^application\/json/i.test(req.headers['content-type'])
            || !req.headers['content-type']));

    if (readIt) {
        return read(req);
    } else if (req.method !== 'POST') {
        return P.resolve();
    } else {
        // Parse the POST
        return new P(function(resolve) {
            // Parse POST data
            var bboy = new Busboy({
                headers: req.headers,
                // Increase the form field size limit from the 1M default.
                limits: { fieldSize: 15 * 1024 * 1024 }
            });
            var body = {};
            bboy.on('field', function (field, val) {
                body[field] = val;
            });
            bboy.on('finish', function () {
                resolve(body);
            });
            req.pipe(bboy);
        });
    }
};

rbUtil.reverseDomain = function reverseDomain (domain) {
    return domain.toLowerCase().split('.').reverse().join('.');
};

rbUtil.tidFromDate = function tidFromDate(date) {
    if (typeof date === 'object') {
        // convert Date object to numeric milliseconds
        date = date.getTime();
    } else if (typeof date === 'string') {
        // convert date string to numeric milliseconds
        date = Date.parse(date);
    }
    if (isNaN(+date)) {
        throw new Error('Invalid date');
    }
    // Create a new, deterministic timestamp
    return uuid.fromDate(date,
        0,
        new Buffer([0x01, 0x23, 0x45, 0x67, 0x89, 0xab]),
        new Buffer([0x12, 0x34])).toString();
};

/**
 * Check if a string is a valid timeuuid
 */
rbUtil.isTimeUUID = function (s) {
    return uuid.test(s);
};

/**
 * Generates a new request ID
 */
rbUtil.generateRequestId = function() {
    return uuid.now().toString();
};

/*
 * Error instance wrapping HTTP error responses
 *
 * Has the same properties as the original response.
 */
function HTTPError(response) {
    Error.call(this);
    Error.captureStackTrace(this, HTTPError);
    this.name = this.constructor.name;
    this.message = response.status + '';
    if (response.body && response.body.type) {
        this.message += ': ' + response.body.type;
    }

    for (var key in response) {
        this[key] = response[key];
    }
}
util.inherits(HTTPError, Error);

rbUtil.HTTPError = HTTPError;

// Create an etag value of the form
// "<revision>/<tid>"
rbUtil.makeETag = function(rev, tid) {
    return '"' + rev + '/' + tid + '"';
};

// Parse an etag value of the form
// "<revision>/<tid>"
// @param {string} etag
// @return {object} with params rev / tid
rbUtil.parseETag = function(etag) {
    var bits = /^"?([^"\/]+)(?:\/([^"\/]+))"?$/.exec(etag);
    if (bits) {
        return {
            rev: bits[1],
            tid: bits[2],
        };
    } else {
        return null;
    }
};

/***
 * MediaWiki-specific functions
 * TODO: Move them out in a separate file
 ***/

// Store titles as MediaWiki db keys
// @param {string} title
// @return {string} normalised title
rbUtil.normalizeTitle = function(title) {
    return title.replace(/ /g, '_');
};

module.exports = rbUtil;
<|endoftext|>


<commit_before>var path = require('path')
var spawn = require('child_process').spawn

var pairSettings = ['version-string']
var singleSettings = ['file-version', 'product-version', 'icon']

module.exports = function (exe, options, callback) {
  var rcedit = path.resolve(__dirname, '..', 'bin', 'rcedit.exe')
  var args = [exe]

  pairSettings.forEach(function (name) {
    if (options[name] != null) {
      for (var key in options[name]) {
        var value = options[name][key]
        args.push('--set-' + name)
        args.push(key)
        args.push(value)
      }
    }
  })

  singleSettings.forEach(function (name) {
    if (options[name] != null) {
      args.push('--set-' + name)
      args.push(options[name])
    }
  })

  if (process.platform !== 'win32') {
    args.unshift(rcedit)
    rcedit = 'wine'
  }

  var spawnOptions = {}
  spawnOptions.env = Object.create(process.env)
  spawnOptions.env.WINEDEBUG = '-all'

  var child = spawn(rcedit, args, spawnOptions)
  var stderr = ''
  var error = null

  child.on('error', function (err) {
    if (error == null) error = err
  })

  child.stderr.on('data', function (data) {
    stderr += data
  })

  child.on('close', function (code) {
    if (error != null) {
      callback(error)
    } else if (code === 0) {
      callback()
    } else {
      var message = 'rcedit.exe failed with exit code ' + code
      stderr = stderr.trim()
      if (stderr) message += '. ' + stderr
      callback(new Error(message))
    }
  })
}
<commit_msg>Only set WINEDEBUG on non-Windows<commit_after>var path = require('path')
var spawn = require('child_process').spawn

var pairSettings = ['version-string']
var singleSettings = ['file-version', 'product-version', 'icon']

module.exports = function (exe, options, callback) {
  var rcedit = path.resolve(__dirname, '..', 'bin', 'rcedit.exe')
  var args = [exe]

  pairSettings.forEach(function (name) {
    if (options[name] != null) {
      for (var key in options[name]) {
        var value = options[name][key]
        args.push('--set-' + name)
        args.push(key)
        args.push(value)
      }
    }
  })

  singleSettings.forEach(function (name) {
    if (options[name] != null) {
      args.push('--set-' + name)
      args.push(options[name])
    }
  })

  var spawnOptions = {}
  spawnOptions.env = Object.create(process.env)

  if (process.platform !== 'win32') {
    args.unshift(rcedit)
    rcedit = 'wine'
    spawnOptions.env.WINEDEBUG = '-all'
  }

  var child = spawn(rcedit, args, spawnOptions)
  var stderr = ''
  var error = null

  child.on('error', function (err) {
    if (error == null) error = err
  })

  child.stderr.on('data', function (data) {
    stderr += data
  })

  child.on('close', function (code) {
    if (error != null) {
      callback(error)
    } else if (code === 0) {
      callback()
    } else {
      var message = 'rcedit.exe failed with exit code ' + code
      stderr = stderr.trim()
      if (stderr) message += '. ' + stderr
      callback(new Error(message))
    }
  })
}
<|endoftext|>


<commit_before>//处理logo日志
//由于nodejs是单进程单线程的，所以多个请求时，由于时间差。可能造成logo混乱的问题。
//
//使用：
//var logRecord = require('./lib/logger.js');
//
//app.use(logRecord({
//   logdir: path.join(__dirname, 'logs'),
//   exportGlobalLogger:true,
//   env:'development'
// }));
//
//这样就可以 this.logger.log
//
//
var assert = require('assert');
var libLoggerFactory = require('./logger.js');
var util = require('./util.js');

var RECORD;
var libLoggerInstance;

//var ShowError;

var Logdir;
var Env;

var filter = function*(next) {
  //记录基础的请求时间,跳过静态资源
  //参考koa-logger
  var ctx = this;
  var start = new Date;
  var staticExt = /(.js)|(.html)|(.css)|(.ico)/;
  var logsMemory = []; //logs缓存，打log不会真的输出，而是记录

  ctx.logger = libLoggerInstance.generate(logsMemory);

  if (!staticExt.test(this.url)) {
    ctx.logger.log("Started " + ctx.method + "   " + ctx.url + " for " + ctx.ip + "at " + new Date);
    ctx.query && ctx.logger.log("  {{#magenta}}query{{/magenta}}:" + JSON.stringify(ctx.query));
    ctx.request.body && ctx.logger.log("  {{#magenta}}body{{/magenta}}:" + JSON.stringify(ctx.request.body));
  }

  try{
    yield next
  }catch(err){

    this.logger.error(util.error2string(err));
    this.logger.flush();

    //告诉全局的error监控，此错误已经处理过了
    err.hasHandled = true;
    //抛出去 方便其他程序监控
    ctx.throw(err);
  }

  if (staticExt.test(this.url)) return;

  var res = this.res;

  var onfinish = done.bind(null, 'finish');
  var onclose = done.bind(null, 'close');

  res.once('finish', onfinish);
  res.once('close', onclose);

  function done(event) {
    res.removeListener('finish', onfinish);
    res.removeListener('close', onclose);

    ctx.logger.log("Completed in " + util.time(start) + "  " + ctx.status + "\n\n");
    ctx.logger.flush();

  }

}

RECORD = function(app,options) {
  options = options || {};

  Logdir = options.logdir || path.join('./', 'logs');
  Env = options.env || process.env.NODE_ENV || "development";

  libLoggerInstance = libLoggerFactory({
    logdir:Logdir,
    env:Env
  });

  var globalLogger = libLoggerInstance.generate();
  //重置错误消息处理
  //koa 如果发现没有监听error事件，会默认生成一个所有错误打到console的错误处理。
  //我们要重置掉。
  app.on('error',function(err){
    if (!err.hasHandled) {
      globalLogger.error(util.error2string(err));
    }
  })

  //暴露logger到全局
  if (options.exportGlobalLogger) {
    global.logger = globalLogger
  }

  return filter;
}

module.exports = RECORD;<commit_msg>修改静态资源判断<commit_after>//处理logo日志
//由于nodejs是单进程单线程的，所以多个请求时，由于时间差。可能造成logo混乱的问题。
//
//使用：
//var logRecord = require('./lib/logger.js');
//
//app.use(logRecord({
//   logdir: path.join(__dirname, 'logs'),
//   exportGlobalLogger:true,
//   env:'development'
// }));
//
//这样就可以 this.logger.log
//
//
var assert = require('assert');
var libLoggerFactory = require('./logger.js');
var util = require('./util.js');

var RECORD;
var libLoggerInstance;

//var ShowError;

var Logdir;
var Env;

var STATIC_EXT = '(.css)|(.gif)|(.html)|(.ico)|(.jpeg)|(.jpg)|(.js)|(.json)|(.pdf)|(.png)|(.svg)|(.swf)|(.tiff)|(.txt)|(.wav)|(.wma)|(.wmv)|(.xml)';

var filter = function*(next) {
  //记录基础的请求时间,跳过静态资源
  //参考koa-logger
  var ctx = this;
  var start = new Date;
  var logsMemory = []; //logs缓存，打log不会真的输出，而是记录

  ctx.logger = libLoggerInstance.generate(logsMemory);

  //只记录实际的action请求
  if (!STATIC_EXT.test(this.url)) {
    ctx.logger.log("Started " + ctx.method + "   " + ctx.url + " for " + ctx.ip + "at " + new Date);
    ctx.query && ctx.logger.log("  {{#magenta}}query{{/magenta}}:" + JSON.stringify(ctx.query));
    ctx.request.body && ctx.logger.log("  {{#magenta}}body{{/magenta}}:" + JSON.stringify(ctx.request.body));
  }

  try{
    yield next
  }catch(err){

    this.logger.error(util.error2string(err));
    this.logger.flush();

    //告诉全局的error监控，此错误已经处理过了
    err.hasHandled = true;
    //抛出去 方便其他程序监控
    ctx.throw(err);
  }

  //静态资源直接return
  if (STATIC_EXT.test(this.url)) return;

  var res = this.res;

  var onfinish = done.bind(null, 'finish');
  var onclose = done.bind(null, 'close');

  res.once('finish', onfinish);
  res.once('close', onclose);

  function done(event) {
    res.removeListener('finish', onfinish);
    res.removeListener('close', onclose);

    ctx.logger.log("Completed in " + util.time(start) + "  " + ctx.status + "\n\n");
    ctx.logger.flush();

  }

}

RECORD = function(app,options) {
  options = options || {};

  Logdir = options.logdir || path.join('./', 'logs');
  Env = options.env || process.env.NODE_ENV || "development";

  libLoggerInstance = libLoggerFactory({
    logdir:Logdir,
    env:Env
  });

  var globalLogger = libLoggerInstance.generate();
  //重置错误消息处理
  //koa 如果发现没有监听error事件，会默认生成一个所有错误打到console的错误处理。
  //我们要重置掉。
  app.on('error',function(err){
    if (!err.hasHandled) {
      globalLogger.error(util.error2string(err));
    }
  })

  //暴露logger到全局
  if (options.exportGlobalLogger) {
    global.logger = globalLogger
  }

  return filter;
}

module.exports = RECORD;<|endoftext|>


<commit_before>/**
	Client side remote API utilities

  @module Hop
	@submodule Remote
**/

if(typeof Hop=="undefined"){
	var Hop = {};
}

var path = require('path');
var request = require('request');
var querystring = require('querystring');
var url = require('url');
var fs = require('fs');
var util = require('hopjs-common');

var _csrf = null;

var responseHandler=function(err,ahr,data,onComplete){
		if(ahr.headers['x-csrf-token']!=undefined)
			_csrf = ahr.headers['x-csrf-token'];
   	if(ahr.statusCode=="404") return onComplete(null,null);
   	if(ahr.statusCode*1 >= 400) return onComplete(data,null);
		if(err){
      return onComplete(err,null);
    } else {
      return onComplete(null,data);
    }
}

/**
  Use a remote URL to instantiate a client side Javascript implementation of the API

  @param {String} _url
    The URL to use, this can be either the base URL for the website or api.json
  @param {Function} onComplete(err,api)
    The call back which will return an error or the API
	@param {Object} options
		@param  options.ignoreDemands - do not check for missing parameters before calling the API

  @method Hop.remoteAPI
  @static
*/
Hop.remoteAPI=function(_url,onComplete,options){
	options=options||{};

  if(!(/.*\/api.json/.test(_url))){
    var _u = url.parse(_url);
    _url = _u.protocol+"//"+_u.host+"/_hopjs/api.json";
  }

  request.get(_url,{ json:true },function(err,ahr,data){

    if(err) return onComplete(err);
    if(!data) return onComplete("Invalid _url");

    var api = {};

		api.setOAuthAccessToken=function(token){
			api.OAuthAccessToken=token;
		}

		api.setCSRFToken=function(token){
			api._csrf=token;
		}

    api._json=data;
    for(var objName in data.Objects){
      api[objName]={};
      for(var methodName in data.Objects[objName].methods){
        (function(objName,methodName,apiOptions){
                var method = data.Objects[objName].methods[methodName];

                api[objName][methodName]=function(input,onComplete,req){
									input=input||{};
                  var _u = url.parse(_url);
                  var _path = method.fullPath;

                  _path = _u.protocol+"//"+_u.host+_path;

									var _input={};

                  for(var paramName in method.params){
										if(apiOptions.ignoreDemands!==true){
											if(method.params[paramName].demand){
												if(!input || typeof input[paramName]=="undefined")
													return onComplete("Missing parameter '"+paramName+"'");
											}
										}
										if(_path.indexOf(":"+paramName)!=-1){
                    	_path= _path.replace(":"+paramName,input[paramName]);
										} else {
											if(typeof input=="object"  && typeof input[paramName]=="object" && input[paramName]!=null && input[paramName]._fileFromURL){
												var _fileFromUrl = url.parse(input[paramName]._fileFromURL);
												if(!_fileFromUrl.host) _fileFromUrl.host = _u.host;
												if(!_fileFromUrl.protocol) _fileFromUrl.protocol = _u.protocol;
												var _fu = url.format(_fileFromUrl);
												_input[paramName]=request(_fu);
											} else {
												if(typeof input[paramName]!="undefined"){
													_input[paramName]=input[paramName];
												}
											}
										}
                  }
            			//console.log(_input);
                  if(method.method=="get" || method.method=="delete"){
													var qo = {};
													var headers = {};
													if(_csrf!=null || api._csrf)
														headers['X-CSRF-Token']=_csrf || api._csrf;
													if(api.OAuthAccessToken){
														headers['Authorization']='Bearer '+api.OAuthAccessToken;
													}
													util.appendForm({ append:function(name,value) { qo[name]=value; }},_input);
													var query = querystring.stringify(qo);
                          request({ uri: _path+"?"+query, method: method.method, json:true}, function(err,ahr,data){
                            responseHandler(err,ahr,data,onComplete);
                          })
                  } else {

													var headers = {};
													if(_csrf!=null || api._csrf)
														headers['X-CSRF-Token']=_csrf || api._csrf;
													if(api.OAuthAccessToken){
														headers['Authorization']='Bearer '+api.OAuthAccessToken;
													}
													var r = request({uri: _path, method: method.method, json:true, headers: headers, callback: function(err,ahr,data){
                            responseHandler(err,ahr,data,onComplete);
													} });
													if(util.appendForm(undefined,_input)){
														var form = r.form();
														util.appendForm(form,_input);
													}

                  }
                };

        })(objName,methodName,options);
      }
    }
    onComplete(null,api);

  });
}

Hop.remoteAPITestHarness=function(_url,onComplete){
  if(!(/.*\/apitest.js/.test(_url))){
    var _u = url.parse(_url);
    _url = _u.protocol+"//"+_u.host+"/_hopjs/apitest.js";
  }

  request.get(_url,function(err,ahr,data){

    if(err) return onComplete(err);
    if(!data) return onComplete("Invalid url");

    onComplete(null,data.toString());

  });
}

Hop.remoteAPITest=function(_url,onComplete){
  if(!(/.*\/apitest.json/.test(_url))){
    var _u = url.parse(_url);
    _url = _u.protocol+"//"+_u.host+"/_hopjs/apitest.json";
  }

  request.get(_url,function(err,ahr,data){

    if(err) return onComplete(err);
    if(!data) return onComplete("Invalid url");

    onComplete(null,data);

  });
}

module.exports=Hop;
<commit_msg>Continued attempting to work around issues with request<commit_after>/**
	Client side remote API utilities

  @module Hop
	@submodule Remote
**/

if(typeof Hop=="undefined"){
	var Hop = {};
}

var path = require('path');
var request = require('hopjs-request');
var querystring = require('querystring');
var url = require('url');
var fs = require('fs');
var util = require('hopjs-common');

var _csrf = null;

var responseHandler=function(err,ahr,data,onComplete){
		if(ahr.headers['x-csrf-token']!=undefined)
			_csrf = ahr.headers['x-csrf-token'];
   	if(ahr.statusCode=="404") return onComplete(null,null);
   	if(ahr.statusCode*1 >= 400) return onComplete(data,null);
		if(err){
      return onComplete(err,null);
    } else {
      return onComplete(null,data);
    }
}

/**
  Use a remote URL to instantiate a client side Javascript implementation of the API

  @param {String} _url
    The URL to use, this can be either the base URL for the website or api.json
  @param {Function} onComplete(err,api)
    The call back which will return an error or the API
	@param {Object} options
		@param  options.ignoreDemands - do not check for missing parameters before calling the API

  @method Hop.remoteAPI
  @static
*/
Hop.remoteAPI=function(_url,onComplete,options){
	options=options||{};

  if(!(/.*\/api.json/.test(_url))){
    var _u = url.parse(_url);
    _url = _u.protocol+"//"+_u.host+"/_hopjs/api.json";
  }

  request.get(_url,{ json:true },function(err,ahr,data){

    if(err) return onComplete(err);
    if(!data) return onComplete("Invalid _url");

    var api = {};

		api.setOAuthAccessToken=function(token){
			api.OAuthAccessToken=token;
		}

		api.setCSRFToken=function(token){
			api._csrf=token;
		}

    api._json=data;
    for(var objName in data.Objects){
      api[objName]={};
      for(var methodName in data.Objects[objName].methods){
        (function(objName,methodName,apiOptions){
                var method = data.Objects[objName].methods[methodName];

                api[objName][methodName]=function(input,onComplete,req){
									input=input||{};
                  var _u = url.parse(_url);
                  var _path = method.fullPath;

                  _path = _u.protocol+"//"+_u.host+_path;

									var _input={};

                  for(var paramName in method.params){
										if(apiOptions.ignoreDemands!==true){
											if(method.params[paramName].demand){
												if(!input || typeof input[paramName]=="undefined")
													return onComplete("Missing parameter '"+paramName+"'");
											}
										}
										if(_path.indexOf(":"+paramName)!=-1){
                    	_path= _path.replace(":"+paramName,input[paramName]);
										} else {
											if(typeof input=="object"  && typeof input[paramName]=="object" && input[paramName]!=null && input[paramName]._fileFromURL){
												var _fileFromUrl = url.parse(input[paramName]._fileFromURL);
												if(!_fileFromUrl.host) _fileFromUrl.host = _u.host;
												if(!_fileFromUrl.protocol) _fileFromUrl.protocol = _u.protocol;
												var _fu = url.format(_fileFromUrl);
												_input[paramName]=request(_fu);
											} else {
												if(typeof input[paramName]!="undefined"){
													_input[paramName]=input[paramName];
												}
											}
										}
                  }
            			//console.log(_input);
                  if(method.method=="get" || method.method=="delete"){
													var qo = {};
													var headers = {};
													if(_csrf!=null || api._csrf)
														headers['X-CSRF-Token']=_csrf || api._csrf;
													if(api.OAuthAccessToken){
														headers['Authorization']='Bearer '+api.OAuthAccessToken;
													}
													util.appendForm({ append:function(name,value) { qo[name]=value; }},_input);
													var query = querystring.stringify(qo);
                          request({ uri: _path+"?"+query, method: method.method, json:true}, function(err,ahr,data){
                            responseHandler(err,ahr,data,onComplete);
                          })
                  } else {

													var headers = {};
													if(_csrf!=null || api._csrf)
														headers['X-CSRF-Token']=_csrf || api._csrf;
													if(api.OAuthAccessToken){
														headers['Authorization']='Bearer '+api.OAuthAccessToken;
													}
													var r = request({uri: _path, method: method.method, json:true, headers: headers, callback: function(err,ahr,data){
                            responseHandler(err,ahr,data,onComplete);
													} });
													if(util.appendForm(undefined,_input)){
														var form = r.form();
														util.appendForm(form,_input);
													}

                  }
                };

        })(objName,methodName,options);
      }
    }
    onComplete(null,api);

  });
}

Hop.remoteAPITestHarness=function(_url,onComplete){
  if(!(/.*\/apitest.js/.test(_url))){
    var _u = url.parse(_url);
    _url = _u.protocol+"//"+_u.host+"/_hopjs/apitest.js";
  }

  request.get(_url,function(err,ahr,data){

    if(err) return onComplete(err);
    if(!data) return onComplete("Invalid url");

    onComplete(null,data.toString());

  });
}

Hop.remoteAPITest=function(_url,onComplete){
  if(!(/.*\/apitest.json/.test(_url))){
    var _u = url.parse(_url);
    _url = _u.protocol+"//"+_u.host+"/_hopjs/apitest.json";
  }

  request.get(_url,function(err,ahr,data){

    if(err) return onComplete(err);
    if(!data) return onComplete("Invalid url");

    onComplete(null,data);

  });
}

module.exports=Hop;
<|endoftext|>


<commit_before>var request = require('request');
var http    = require('http');
var path    = require('path');
var os      = require('os');
var unzip   = require('unzip2');
var mkdirp  = require('mkdirp');
var rimraf  = require('rimraf');
var fs      = require('fs');
var crypto  = require('crypto');
var config  = require('./config');

if (config.get().proxy) {
  request = request.defaults({
    'proxy':config.proxy
  });
}

exports.download = function(done) {

  var src = source();
  var url = 'https://github.com/' + src.user + '/' + src.repo + '/archive/' + src.branch + '.zip';
  var target = path.join(os.tmpdir(), 'tldr');
  var inside = path.join(target, src.repo + '-' + src.branch);

  rimraf.sync(target);
  mkdirp.sync(target);

  var extractor = unzip.Extract({path: target});
  extractor.on('error', done);
  extractor.on('finish', function() {
    done(null, inside);
  });

  var req = request.get({
    url: url,
    headers: {'User-Agent' : 'tldr-node-client'}
  });

  req.on('error', done);
  req.pipe(extractor);

}

function source() {
  var parts  = config.get().repository.split('#');
  var github = parts[0].match(/^(.*)\/(.*)$/);
  return {
    user: github[1],
    repo: github[2],
    branch: parts[1] || 'master'
  };

}
<commit_msg>Fix #12, #19: download pages zip archive from tldr-pages.github.io static site instead of Github API<commit_after>var request = require('request');
var http    = require('http');
var path    = require('path');
var os      = require('os');
var unzip   = require('unzip2');
var mkdirp  = require('mkdirp');
var rimraf  = require('rimraf');
var fs      = require('fs');
var crypto  = require('crypto');
var config  = require('./config');

if (config.get().proxy) {
  request = request.defaults({
    'proxy':config.proxy
  });
}

exports.download = function(done) {
  var src = source();
  var url = 'http://tldr-pages.github.io/assets/tldr.zip';
  var target = path.join(os.tmpdir(), 'tldr');

  rimraf.sync(target);
  mkdirp.sync(target);

  var extractor = unzip.Extract({path: target});
  extractor.on('error', done);
  extractor.on('finish', function() {
    done(null, target);
  });

  var req = request.get({
    url: url,
    headers: {'User-Agent' : 'tldr-node-client'}
  });

  req.on('error', done);
  req.pipe(extractor);

}

function source() {
  var parts  = config.get().repository.split('#');
  var github = parts[0].match(/^(.*)\/(.*)$/);
  return {
    user: github[1],
    repo: github[2],
    branch: parts[1] || 'master'
  };

}
<|endoftext|>


<commit_before>'use strict';

var crypto = require('crypto');
var util = require('util');
var rest = require('wreck');

var _ = require('./functions');

var Stash = require('./stash');

const CONTENT_TYPE = 'application/json';

/**
 * An in-memory representation of a node in our network.
 * @param       {Object} initial - Target object.
 * @constructor
 */
function Remote (init) {
  this['@data'] = init || {};
  this.clock = 0;
  this.stack = [];
  this.known = {};
  this.init();
}

util.inherits(Remote, require('./vector'));

Remote.prototype.enumerate = async function () {
  var self = this;
  var options = await self._OPTIONS('/');

  if (!options) {
    console.log('nothing:', options);
    return [];
  }

  options.resources = options.resources.map(function(r) {
    return {
      name: r.name,
      description: r.description,
      // TODO: remove lodash
      components: _.merge({
        query: 'maki-resource-query',
        get: 'maki-resource-get'
      }, r.components),
      routes: r.routes,
      attributes: r.attributes,
      names: r.names,
    }
  });

  return options.resources;
}

/**
 * HTTP GET against the configured Authority.
 * @param  {String} path - HTTP Path to request.
 * @param  {Object} params - Map of parameters to supply.
 * @return {Mixed}        [description]
 */
Remote.prototype._GET = async function (key, params) {
  var self = this;
  var host = self['@data'].host;
  var url = 'https://' + host + key;

  var request = rest.request('GET', url, {
    headers: {
      'Accept': CONTENT_TYPE
    }
  });

  try {
    var response = await request;
    var result = await rest.read(response, {
      json: true
    });
  } catch (e) {
    console.error('[REMOTE]', e);
  }

  return result;
};

/**
 * HTTP OPTIONS on the configured Authority.
 * @param  {String} path - HTTP Path to request.
 * @param  {Object} params - Map of parameters to supply.
 * @return {Object} - Full description of remote resource.
 */
Remote.prototype._OPTIONS = async function (key, params) {
  var self = this;
  var host = self['@data'].host;
  var url = 'https://' + host + key;

  var request = rest.request('OPTIONS', url, {
    headers: {
      'Accept': CONTENT_TYPE
    }
  });

  try {
    var response = await request;
    var result = await rest.read(response, {
      json: true
    });
  } catch (e) {
    console.error('[REMOTE]', e);
  }

  return result;
};

module.exports = Remote;
<commit_msg>Clarify Remote flow<commit_after>'use strict';

var crypto = require('crypto');
var util = require('util');
var rest = require('wreck');

var _ = require('./functions');

var Stash = require('./stash');

const CONTENT_TYPE = 'application/json';

/**
 * An in-memory representation of a node in our network.
 * @param       {Object} initial - Target object.
 * @constructor
 */
function Remote (init) {
  this['@data'] = init || {};
  this.clock = 0;
  this.stack = [];
  this.known = {};
  this.init();
}

util.inherits(Remote, require('./vector'));

Remote.prototype.enumerate = async function () {
  var self = this;
  var options = await self._OPTIONS('/');

  if (!options) {
    console.log('nothing:', options);
    return [];
  }

  options.resources = options.resources.map(function(r) {
    return {
      name: r.name,
      description: r.description,
      // TODO: remove lodash
      components: _.merge({
        query: 'maki-resource-query',
        get: 'maki-resource-get'
      }, r.components),
      routes: r.routes,
      attributes: r.attributes,
      names: r.names,
    }
  });

  return options.resources;
}

/**
 * HTTP GET against the configured Authority.
 * @param  {String} path - HTTP Path to request.
 * @param  {Object} params - Map of parameters to supply.
 * @return {Mixed}        [description]
 */
Remote.prototype._GET = async function (key, params) {
  var self = this;
  var host = self['@data'].host;
  var url = 'https://' + host + key;

  try {
    var response = await rest.request('GET', url, {
      headers: {
        'Accept': CONTENT_TYPE
      }
    });
    var result = await rest.read(response, {
      json: true
    });
  } catch (e) {
    console.error('[REMOTE]', 'exception:', e);
  }

  return result;
};

/**
 * HTTP OPTIONS on the configured Authority.
 * @param  {String} path - HTTP Path to request.
 * @param  {Object} params - Map of parameters to supply.
 * @return {Object} - Full description of remote resource.
 */
Remote.prototype._OPTIONS = async function (key, params) {
  var self = this;
  var host = self['@data'].host;
  var url = 'https://' + host + key;

  try {
    var response = await rest.request('OPTIONS', url, {
      headers: {
        'Accept': CONTENT_TYPE
      }
    });
    var result = await rest.read(response, {
      json: true
    });
  } catch (e) {
    console.error('[REMOTE]', 'exception:', e);
  }

  return result;
};

module.exports = Remote;
<|endoftext|>


<commit_before>'use strict';

var pathUtil = require('path');
var fs = require('./utils/fs');
var validate = require('./utils/validate');
var inspect = require('./inspect');
var list = require('./list');

var validateInput = function (methodName, path) {
  var methodSignature = methodName + '([path])';
  validate.argument(methodSignature, 'path', path, ['string', 'undefined']);
};

var generateUnknownEtityUnderPathError = function (path) {
  return new Error("Can't remove " + path + ' The path is not file nor directory');
};

// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------

var removeSync = function (path) {
  // First check what we have on given path.
  var inspectedFile = inspect.sync(path, { symlinks: 'report' });
  if (inspectedFile === undefined) {
    // The path already doesn't exits. Nothing to do here.
  } else if (inspectedFile.type === 'dir') {
    // Must delete everything inside the directory first.
    list.sync(path).forEach(function (filename) {
      removeSync(pathUtil.join(path, filename));
    });
    // Everything inside directory has been removed,
    // it's safe now do go for the directory itself.
    fs.rmdirSync(path);
  } else if (inspectedFile.type === 'file' || inspectedFile.type === 'symlink') {
    fs.unlinkSync(path);
  } else {
    throw generateUnknownEtityUnderPathError(path);
  }
};

// ---------------------------------------------------------
// Async
// ---------------------------------------------------------

var removeAsync = function (path) {
  return new Promise(function (resolve, reject) {
    // First check what we have on given path.
    inspect.async(path).then(function (inspectedFile) {
      if (inspectedFile === undefined) {
        // The path already doesn't exits. Nothing to do here.
        resolve();
      } else if (inspectedFile.type === 'dir') {
        // Must delete everything inside the directory first.
        list.async(path).then(function (filenamesInsideDir) {
          var promises = filenamesInsideDir.map(function (filename) {
            return removeAsync(pathUtil.join(path, filename));
          });
          return Promise.all(promises);
        })
        .then(function () {
          // Everything inside directory has been removed,
          // it's safe now do go for the directory itself.
          return fs.rmdir(path);
        })
        .then(resolve, reject);
      } else if (inspectedFile.type === 'file' || inspectedFile.type === 'symlink') {
        fs.unlink(path).then(resolve, reject);
      } else {
        reject(generateUnknownEtityUnderPathError(path));
      }
    });
  });
};

// ---------------------------------------------------------
// API
// ---------------------------------------------------------

exports.validateInput = validateInput;
exports.sync = removeSync;
exports.async = removeAsync;
<commit_msg>More performant remove<commit_after>'use strict';

var pathUtil = require('path');
var fs = require('./utils/fs');
var validate = require('./utils/validate');
var list = require('./list');

var validateInput = function (methodName, path) {
  var methodSignature = methodName + '([path])';
  validate.argument(methodSignature, 'path', path, ['string', 'undefined']);
};

// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------

var removeSync = function (path) {
  try {
    // Assume the path is a file and just try to remove it.
    fs.unlinkSync(path);
  } catch (err) {
    if (err.code === 'EPERM') {
      // Must delete everything inside the directory first.
      list.sync(path).forEach(function (filename) {
        removeSync(pathUtil.join(path, filename));
      });
      // Everything inside directory has been removed,
      // it's safe now do go for the directory itself.
      fs.rmdirSync(path);
    } else if (err.code === 'ENOENT') {
      // File already doesn't exist. We're done.
    } else {
      // Something unexpected happened. Rethrow original error.
      throw err;
    }
  }
};

// ---------------------------------------------------------
// Async
// ---------------------------------------------------------

var removeAsync = function (path) {
  return new Promise(function (resolve, reject) {
    // Assume the path is a file and just try to remove it.
    fs.unlink(path)
    .then(resolve)
    .catch(function (err) {
      if (err.code === 'EPERM') {
        // It's not a file, it's a directory.
        // Must delete everything inside first.
        list.async(path).then(function (filenamesInsideDir) {
          var promises = filenamesInsideDir.map(function (filename) {
            return removeAsync(pathUtil.join(path, filename));
          });
          return Promise.all(promises);
        })
        .then(function () {
          // Everything inside directory has been removed,
          // it's safe now to go for the directory itself.
          return fs.rmdir(path);
        })
        .then(resolve, reject);
      } else if (err.code === 'ENOENT') {
        // File already doesn't exist. We're done.
        resolve();
      } else {
        // Something unexpected happened. Rethrow original error.
        reject(err);
      }
    });
  });
};

// ---------------------------------------------------------
// API
// ---------------------------------------------------------

exports.validateInput = validateInput;
exports.sync = removeSync;
exports.async = removeAsync;
<|endoftext|>


<commit_before>/*
  Module dependencies
*/
var _ = require('underscore');
var utils = require('./utils');

var encode = utils.encode;

/*
  Boolean Attributes
*/
var rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i;

/*
  Format attributes
*/
var formatAttrs = function(attributes) {
  if (!attributes) return;

  var output = '',
      value;

  // Loop through the attributes
  for (var key in attributes) {
    value = attributes[key];
    if (output) {
      output += ' ';
    }

    if (!value && (rboolean.test(key) || key === '/')) {
      output += key;
    } else {
      output += key + '="' + encode(value) + '"';
    }
  }

  return output;
};

/*
  Self-enclosing tags (stolen from node-htmlparser)
*/
var singleTag = {
  area: 1,
  base: 1,
  basefont: 1,
  br: 1,
  col: 1,
  frame: 1,
  hr: 1,
  img: 1,
  input: 1,
  isindex: 1,
  link: 1,
  meta: 1,
  param: 1,
  embed: 1,
  include: 1,
  'yield': 1
};

/*
  Tag types from htmlparser
*/
var tagType = {
  tag: 1,
  script: 1,
  link: 1,
  style: 1,
  template: 1
};

var render = module.exports = function(dom, opts) {
  if (!Array.isArray(dom) && !dom.cheerio) dom = [dom];
  opts = opts || {};

  var output = '',
      xmlMode = opts.xmlMode;

  _.each(dom, function(elem) {
    var isTag = tagType[elem.type];

    var pushVal;
    if (isTag)
      pushVal = renderTag(elem, xmlMode);
    else if (elem.type === 'directive')
      pushVal = renderDirective(elem);
    else if (elem.type === 'comment')
      pushVal = renderComment(elem);
    else if (elem.type === 'cdata')
      pushVal = renderCdata(elem);
    else
      pushVal = renderText(elem);

    if (elem.children)
      pushVal += render(elem.children, opts);

    if (isTag && (!singleTag[elem.name] || xmlMode)) {
      if (!isClosedTag(elem, xmlMode)) {
        pushVal += '</' + elem.name + '>';
      }
    }

    // Push rendered DOM node
    output += pushVal;
  });

  return output;
};

var isClosedTag = function(elem, xmlMode){
  return (xmlMode && (!elem.children || elem.children.length === 0));
};

var renderTag = function(elem, xmlMode) {
  var tag = '<' + elem.name,
      attribs = formatAttrs(elem.attribs);

  if (attribs) {
    tag += ' ' + attribs;
  }

  if (isClosedTag(elem, xmlMode)) {
    tag += '/';
  }

  return tag + '>';
};

var renderDirective = function(elem) {
  return '<' + elem.data + '>';
};

var renderText = function(elem) {
  return elem.data || '';
};

var renderCdata = function(elem) {
  var text = '';

  if (elem.children) {
    _.each(elem.children, function(cdata) {
      text += '<![CDATA['+cdata.data+']]>';
    });
  }

  return text;
};

var renderComment = function(elem) {
  return '<!--' + elem.data + '-->';
};

// module.exports = $.extend(exports);
<commit_msg>don't loop through cdata children array<commit_after>/*
  Module dependencies
*/
var _ = require('underscore');
var utils = require('./utils');

var encode = utils.encode;

/*
  Boolean Attributes
*/
var rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i;

/*
  Format attributes
*/
var formatAttrs = function(attributes) {
  if (!attributes) return;

  var output = '',
      value;

  // Loop through the attributes
  for (var key in attributes) {
    value = attributes[key];
    if (output) {
      output += ' ';
    }

    if (!value && (rboolean.test(key) || key === '/')) {
      output += key;
    } else {
      output += key + '="' + encode(value) + '"';
    }
  }

  return output;
};

/*
  Self-enclosing tags (stolen from node-htmlparser)
*/
var singleTag = {
  area: 1,
  base: 1,
  basefont: 1,
  br: 1,
  col: 1,
  frame: 1,
  hr: 1,
  img: 1,
  input: 1,
  isindex: 1,
  link: 1,
  meta: 1,
  param: 1,
  embed: 1,
  include: 1,
  'yield': 1
};

/*
  Tag types from htmlparser
*/
var tagType = {
  tag: 1,
  script: 1,
  link: 1,
  style: 1,
  template: 1
};

var render = module.exports = function(dom, opts) {
  if (!Array.isArray(dom) && !dom.cheerio) dom = [dom];
  opts = opts || {};

  var output = '',
      xmlMode = opts.xmlMode;

  _.each(dom, function(elem) {
    var isTag = tagType[elem.type];

    var pushVal;
    if (isTag)
      pushVal = renderTag(elem, xmlMode);
    else if (elem.type === 'directive')
      pushVal = renderDirective(elem);
    else if (elem.type === 'comment')
      pushVal = renderComment(elem);
    else if (elem.type === 'cdata')
      pushVal = renderCdata(elem);
    else
      pushVal = renderText(elem);

    if (elem.children && elem.type !== 'cdata')
      pushVal += render(elem.children, opts);

    if (isTag && (!singleTag[elem.name] || xmlMode)) {
      if (!isClosedTag(elem, xmlMode)) {
        pushVal += '</' + elem.name + '>';
      }
    }

    // Push rendered DOM node
    output += pushVal;
  });

  return output;
};

var isClosedTag = function(elem, xmlMode){
  return (xmlMode && (!elem.children || elem.children.length === 0));
};

var renderTag = function(elem, xmlMode) {
  var tag = '<' + elem.name,
      attribs = formatAttrs(elem.attribs);

  if (attribs) {
    tag += ' ' + attribs;
  }

  if (isClosedTag(elem, xmlMode)) {
    tag += '/';
  }

  return tag + '>';
};

var renderDirective = function(elem) {
  return '<' + elem.data + '>';
};

var renderText = function(elem) {
  return elem.data || '';
};

var renderCdata = function(elem) {
  var text = '';

  if (elem.children) {
    _.each(elem.children, function(cdata) {
      text += '<![CDATA['+cdata.data+']]>';
    });
  }

  return text;
};

var renderComment = function(elem) {
  return '<!--' + elem.data + '-->';
};

// module.exports = $.extend(exports);
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
    Path = require('path'),
    log = require('./log'),
    mkdirp = require('mkdirp'),
    _ = require('lodash'),
    async = require('async'),
    cons = require('consolidate');

function template(config, source, done) {
    var tpl = Path.join(config.templatePath, source.attributes.template || config.template),
        engine = Path.extname(tpl).slice(1),
        locals = null;

    if (!cons[engine]) throw 'Unknown template engine: ' + engine;

    log.info('Rendering %s > %s', source.relative, source.target);

    locals = _.extend({
        config: config,
        content: source.body,
    }, source.attributes);

    cons[engine](tpl, locals, function(err, html) {
        fs.writeFile(source.target, html, done);
    });
}

function write(config, source, next) {
    mkdirp.sync(Path.dirname(source.target));

    if (source.body)
        return template(config, source, next);

    log.info('Linking %s > %s', source.relative, source.target);

    return fs.unlink(source.target, function() {
        return fs.link(source.source, source.target, next);
    });
}

module.exports = function render(config, done) {
    async.each(config.sources, _.partial(write, config), done);
};
<commit_msg>remove public before overwriting it<commit_after>'use strict';

var fs = require('fs'),
    Path = require('path'),
    log = require('./log'),
    mkdirp = require('mkdirp'),
    _ = require('lodash'),
    rmdir = require('rmdir'),
    async = require('async'),
    cons = require('consolidate');

function template(config, source, done) {
    var tpl = Path.join(config.templatePath, source.attributes.template || config.template),
        engine = Path.extname(tpl).slice(1),
        locals = null;

    if (!cons[engine]) throw 'Unknown template engine: ' + engine;

    log.info('Rendering %s > %s', source.relative, source.target);

    locals = _.extend({
        config: config,
        content: source.body,
    }, source.attributes);

    cons[engine](tpl, locals, function(err, html) {
        fs.writeFile(source.target, html, done);
    });
}

function write(config, source, next) {
    mkdirp.sync(Path.dirname(source.target));

    return fs.unlink(source.target, function() {
        if (source.type == 'markdown')
            return template(config, source, next);

        log.info('Linking %s > %s', source.relative, source.target);

        return fs.link(source.source, source.target, next);
    });
}

module.exports = function render(config, done) {
    rmdir(config.target, function(err) {
        if (err) throw err;
        async.each(config.sources, _.partial(write, config), done);
    });

};
<|endoftext|>


<commit_before>/* globals state, createObj, findObjs, getObj, getAttrByName, sendChat, on, log, Campaign, playerIsGM, spawnFx,
 spawnFxBetweenPoints, filterObjs, randomInteger */
'use strict';
const _ = require('underscore');

// noinspection JSUnusedLocalSymbols
module.exports = class Roll20Wrapper {

  getState(module) {
    if (!state[module]) {
      state[module] = {};
    }
    return state[module];
  }

  createObj(type, attributes) {
    return createObj(type, attributes);
  }

  findObjs(attributes) {
    return findObjs(attributes);
  }

  filterObjs(attributes) {
    return filterObjs(attributes);
  }

  getObj(type, id) {
    return getObj(type, id);
  }

  getOrCreateObj(type, attributes) {
    const newAttributes = _.extend(_.clone(attributes), { type });
    const existing = this.findObjs(newAttributes);
    switch (existing.length) {
      case 0:
        return this.createObj(type, newAttributes);
      case 1:
        return existing[0];
      default:
        throw new Error(`Asked for a single ${type} but more than 1 was found matching attributes: ` +
          `${JSON.stringify(attributes)}`);
    }
  }

  getAttrByName(character, attrName, valueType) {
    return getAttrByName(character, attrName, valueType);
  }

  checkCharacterFlag(character, flag) {
    const value = this.getAttrByName(character, flag);
    switch (typeof value) {
      case 'boolean':
        return value;
      case 'number':
        return !!value;
      default:
        return value === '1' || value === 'on';
    }
  }

  getAttrObjectByName(character, attrName) {
    const attr = this.findObjs({ type: 'attribute', characterid: character, name: attrName });
    return attr && attr.length > 0 ? attr[0] : null;
  }

  getOrCreateAttr(characterId, attrName) {
    return this.getOrCreateObj('attribute', { characterid: characterId, name: attrName });
  }

  setAttrByName(characterId, attrName, value) {
    this.getOrCreateAttr(characterId, attrName).set('current', value);
  }

  processAttrValue(characterId, attrName, cb) {
    const attribute = this.getOrCreateAttr(characterId, attrName);
    attribute.set('current', cb(attribute.get('current')));
  }

  getRepeatingSectionAttrs(characterId, sectionName) {
    const prefix = `repeating_${sectionName}`;
    return _.filter(this.findObjs({ type: 'attribute', characterid: characterId }),
      attr => attr.get('name').indexOf(prefix) === 0);
  }

  getRepeatingSectionItemIdsByName(characterId, sectionName) {
    const re = new RegExp(`repeating_${sectionName}_([^_]+)_name$`);
    return _.reduce(this.getRepeatingSectionAttrs(characterId, sectionName),
      (lookup, attr) => {
        const match = attr.get('name').match(re);
        if (match) {
          lookup[attr.get('current').toLowerCase()] = match[1];
        }
        return lookup;
      }, {});
  }

  getCurrentPage(playerId) {
    let pageId;
    if (this.playerIsGM(playerId)) {
      pageId = this.getObj('player', playerId).get('lastpage');
    }
    else {
      pageId = this.getCampaign().get('playerspecificpages')[playerId] || this.getCampaign().get('playerpageid');
    }

    return pageId ? this.getObj('page', pageId) : null;
  }

  spawnFx(pointsArray, fxType, pageId) {
    switch (pointsArray.length) {
      case 1:
        spawnFx(pointsArray[0].x, pointsArray[0].y, fxType, pageId);
        break;
      case 2:
        spawnFxBetweenPoints(pointsArray[0], pointsArray[1], fxType, pageId);
        break;
      default:
        throw new Error('Wrong number of points supplied to spawnFx: $$$', pointsArray);
    }
  }

  playerIsGM(playerId) {
    return playerIsGM(playerId);
  }

  getCampaign() {
    return Campaign(); // eslint-disable-line
  }

  sendChat(sendAs, message, callback, options) {
    return sendChat(sendAs, message, callback, options);
  }

  on(event, callback) {
    return on(event, callback);
  }

  randomInteger(max) {
    return randomInteger(max);
  }

  log(msg) {
    return log(msg);
  }
};

<commit_msg>Change processAttrVal to return the new value<commit_after>/* globals state, createObj, findObjs, getObj, getAttrByName, sendChat, on, log, Campaign, playerIsGM, spawnFx,
 spawnFxBetweenPoints, filterObjs, randomInteger */
'use strict';
const _ = require('underscore');

// noinspection JSUnusedLocalSymbols
module.exports = class Roll20Wrapper {

  getState(module) {
    if (!state[module]) {
      state[module] = {};
    }
    return state[module];
  }

  createObj(type, attributes) {
    return createObj(type, attributes);
  }

  findObjs(attributes) {
    return findObjs(attributes);
  }

  filterObjs(attributes) {
    return filterObjs(attributes);
  }

  getObj(type, id) {
    return getObj(type, id);
  }

  getOrCreateObj(type, attributes) {
    const newAttributes = _.extend(_.clone(attributes), { type });
    const existing = this.findObjs(newAttributes);
    switch (existing.length) {
      case 0:
        return this.createObj(type, newAttributes);
      case 1:
        return existing[0];
      default:
        throw new Error(`Asked for a single ${type} but more than 1 was found matching attributes: ` +
          `${JSON.stringify(attributes)}`);
    }
  }

  getAttrByName(character, attrName, valueType) {
    return getAttrByName(character, attrName, valueType);
  }

  checkCharacterFlag(character, flag) {
    const value = this.getAttrByName(character, flag);
    switch (typeof value) {
      case 'boolean':
        return value;
      case 'number':
        return !!value;
      default:
        return value === '1' || value === 'on';
    }
  }

  getAttrObjectByName(character, attrName) {
    const attr = this.findObjs({ type: 'attribute', characterid: character, name: attrName });
    return attr && attr.length > 0 ? attr[0] : null;
  }

  getOrCreateAttr(characterId, attrName) {
    return this.getOrCreateObj('attribute', { characterid: characterId, name: attrName });
  }

  setAttrByName(characterId, attrName, value) {
    this.getOrCreateAttr(characterId, attrName).set('current', value);
  }

  processAttrValue(characterId, attrName, cb) {
    const attribute = this.getOrCreateAttr(characterId, attrName);
    const newVal = cb(attribute.get('current'));
    attribute.set('current', newVal);
    return newVal;
  }

  getRepeatingSectionAttrs(characterId, sectionName) {
    const prefix = `repeating_${sectionName}`;
    return _.filter(this.findObjs({ type: 'attribute', characterid: characterId }),
      attr => attr.get('name').indexOf(prefix) === 0);
  }

  getRepeatingSectionItemIdsByName(characterId, sectionName) {
    const re = new RegExp(`repeating_${sectionName}_([^_]+)_name$`);
    return _.reduce(this.getRepeatingSectionAttrs(characterId, sectionName),
      (lookup, attr) => {
        const match = attr.get('name').match(re);
        if (match) {
          lookup[attr.get('current').toLowerCase()] = match[1];
        }
        return lookup;
      }, {});
  }

  getCurrentPage(playerId) {
    let pageId;
    if (this.playerIsGM(playerId)) {
      pageId = this.getObj('player', playerId).get('lastpage');
    }
    else {
      pageId = this.getCampaign().get('playerspecificpages')[playerId] || this.getCampaign().get('playerpageid');
    }

    return pageId ? this.getObj('page', pageId) : null;
  }

  spawnFx(pointsArray, fxType, pageId) {
    switch (pointsArray.length) {
      case 1:
        spawnFx(pointsArray[0].x, pointsArray[0].y, fxType, pageId);
        break;
      case 2:
        spawnFxBetweenPoints(pointsArray[0], pointsArray[1], fxType, pageId);
        break;
      default:
        throw new Error('Wrong number of points supplied to spawnFx: $$$', pointsArray);
    }
  }

  playerIsGM(playerId) {
    return playerIsGM(playerId);
  }

  getCampaign() {
    return Campaign(); // eslint-disable-line
  }

  sendChat(sendAs, message, callback, options) {
    return sendChat(sendAs, message, callback, options);
  }

  on(event, callback) {
    return on(event, callback);
  }

  randomInteger(max) {
    return randomInteger(max);
  }

  log(msg) {
    return log(msg);
  }
};

<|endoftext|>


<commit_before>'use strict';

var authConfiguration = require('../lib/authConfiguration'),
    Cookies = require('cookies'),
    routes = require('./routes');

module.exports = function (appRouter) {
  var routes = authConfiguration.strategyRoutes(function (err, user) {
    (new Cookies(this.req, this.res)).set('signin', 'true', {
      httpOnly: false,
      expires: new Date(new Date().getTime() + this.req.session.cookie.maxAge)
    });

    this.res.redirect('/');
  }), route;
  for (route in routes) {
    console.log(route);
    appRouter.get(route, routes[route]);
  }

  appRouter.get('/status', function () {
    this.res.writeHead(200, { 'Content-Type': 'application/json' });
    this.res.write(JSON.stringify({ signedIn: this.req.isAuthenticated(), user: this.req.user }));
    this.res.end();
  });

  function writeJSON (type, content) {
    this.writeHead(type == 'success' ? 200 : type, {
      'Content-Type': 'application/json'
    });

    if (!content) content = {};
    else if (typeof content == 'string') content = { error: content };
    content.success = type == 'sucess';

    this.write(JSON.stringify(content));
    this.end();
  }

  appRouter.post('/signout', function () {
    this.req.logOut();

    (new Cookies(this.req, this.res)).set('signin');

    writeJSON.call(this.res, 'success');
  });

  // appRouter.mount(routes);
};
<commit_msg>Remove console.log<commit_after>'use strict';

var authConfiguration = require('../lib/authConfiguration'),
    Cookies = require('cookies'),
    routes = require('./routes');

module.exports = function (appRouter) {
  var routes = authConfiguration.strategyRoutes(function (err, user) {
    (new Cookies(this.req, this.res)).set('signin', 'true', {
      httpOnly: false,
      expires: new Date(new Date().getTime() + this.req.session.cookie.maxAge)
    });

    this.res.redirect('/');
  }), route;
  for (route in routes) {
    appRouter.get(route, routes[route]);
  }

  appRouter.get('/status', function () {
    this.res.writeHead(200, { 'Content-Type': 'application/json' });
    this.res.write(JSON.stringify({ signedIn: this.req.isAuthenticated(), user: this.req.user }));
    this.res.end();
  });

  function writeJSON (type, content) {
    this.writeHead(type == 'success' ? 200 : type, {
      'Content-Type': 'application/json'
    });

    if (!content) content = {};
    else if (typeof content == 'string') content = { error: content };
    content.success = type == 'sucess';

    this.write(JSON.stringify(content));
    this.end();
  }

  appRouter.post('/signout', function () {
    this.req.logOut();

    (new Cookies(this.req, this.res)).set('signin');

    writeJSON.call(this.res, 'success');
  });

  // appRouter.mount(routes);
};
<|endoftext|>


<commit_before>Router.configure({
    layoutTemplate: "layout",
    loadingTemplate: "loading",
    waitOn: function(){
        return Meteor.subscribe("posts")
    }
});

Router.map(function(){
    this.route('postsList', {path: '/'})
    this.route('postPage', {
        path: "/posts/:_id",
        data: function(){ return Posts.findOne(this.params._id) }
    })
})
<commit_msg>sentinel before router<commit_after>Router.configure({
    layoutTemplate: "layout",
    loadingTemplate: "loading",
    waitOn: function(){
        return Meteor.subscribe("posts")
    }
});

Router.map(function(){
    this.route('postsList', {path: '/'})
    this.route('postPage', {
        path: "/posts/:_id",
        data: function(){ return Posts.findOne(this.params._id) }
    })
    this.route('postSubmit', {
        path: "/submit"
    })
})

//this is refers to
var requireLogin = function() {
    if (! Meteor.user()) {
        this.render('accessDenied')
        this.stop()
    }
}

Router.before(requireLogin, {only: 'postSubmit'})
<|endoftext|>


<commit_before>Router.route("/", {
	name: "home",
	template: "home"
});<commit_msg>Define routes to templates<commit_after>Router.route("/", {
	name: "gamelist",
	template: "gamelist",
	waitOn: function() {
		return Meteor.subscribe("gameList");
	}
});

Router.route("/game/:_id", {
	name: "game",
	template: "game",
	waitOn: function() {
		return Meteor.subscribe("gameData", this.params._id);
	},
	data: function() {
		return Games.findOne(this.params._id);
	}
});<|endoftext|>


<commit_before>Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound',
    waitOn: function () {
        return Meteor.subscribe('notifications');
    }
});

var requireLogin = function () {
    if (!Meteor.user()) {
        if (Meteor.loggingIn()) {
            this.render(this.loadingTemplate);
        } else {
            this.render('accessDenied');
        }
    } else {
        this.next();
    }
};

if (Meteor.isClient) {
    Router.onBeforeAction('dataNotFound', {only: 'postPage'});
    Router.onBeforeAction(requireLogin, {only: 'postSubmit'});
}

Router.route('/', {
    name: 'home',
    controller: NewPostsController
});

Router.route('/new/:postsLimit?', {name: 'newPosts'});

Router.route('/best/:postsLimit?', {name: 'bestPosts'});

Router.route('/posts/:_id', {
    name: 'postPage',
    waitOn: function () {
        return [
            Meteor.subscribe('singlePost', this.params._id),
            Meteor.subscribe('comments', this.params._id)
        ];
    },
    data: function () {
        return Posts.findOne(this.params._id);
    }
});

Router.route('/posts/:_id/edit', {
    name: 'postEdit',
    waitOn: function () {
        return Meteor.subscribe('singlePost', this.params._id);
    },
    data: function () {
        return Posts.findOne(this.params._id);
    }
});

Router.route('/submit', {name: 'postSubmit'});

Router.route('/feed.xml', {
    where: 'server',
    name: 'rss',
    action: function () {
        var feed = new RSS({
            title: 'New Microscope Posts',
            description: "the latest posts from Microscope, the smallest news aggregator."
        });

        Posts.find({}, {sort: {submitted: -1}, limit: 20}).forEach(function (post) {
            feed.item({
                title: post.title,
                description: post.body,
                author: post.author,
                date: post.submitted,
                url: '/posts/' + post._id
            });
        });

        this.response.write(feed.xml());
        this.response.end();
    }
});

Router.route('/api/posts', {
    where: 'server',
    name: 'apiPosts',
    action: function () {
        var parameters = this.request.query,
            // if parameter limit exists, take that value, else 20
            limit = !!parameters.limit ? parseInt(parameters.limit) : 20,
            data = Posts.find({}, {limit: limit, fields: {title: 1, author: 1, url: 1, submitted: 1}}).fetch();

        this.response.write(JSON.stringify(data));
        this.response.end();
    }
});
<commit_msg>api show single post<commit_after>Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound',
    waitOn: function () {
        return Meteor.subscribe('notifications');
    }
});

var requireLogin = function () {
    if (!Meteor.user()) {
        if (Meteor.loggingIn()) {
            this.render(this.loadingTemplate);
        } else {
            this.render('accessDenied');
        }
    } else {
        this.next();
    }
};

if (Meteor.isClient) {
    Router.onBeforeAction('dataNotFound', {only: 'postPage'});
    Router.onBeforeAction(requireLogin, {only: 'postSubmit'});
}

Router.route('/', {
    name: 'home',
    controller: NewPostsController
});

Router.route('/new/:postsLimit?', {name: 'newPosts'});

Router.route('/best/:postsLimit?', {name: 'bestPosts'});

Router.route('/posts/:_id', {
    name: 'postPage',
    waitOn: function () {
        return [
            Meteor.subscribe('singlePost', this.params._id),
            Meteor.subscribe('comments', this.params._id)
        ];
    },
    data: function () {
        return Posts.findOne(this.params._id);
    }
});

Router.route('/posts/:_id/edit', {
    name: 'postEdit',
    waitOn: function () {
        return Meteor.subscribe('singlePost', this.params._id);
    },
    data: function () {
        return Posts.findOne(this.params._id);
    }
});

Router.route('/submit', {name: 'postSubmit'});

Router.route('/feed.xml', {
    where: 'server',
    name: 'rss',
    action: function () {
        var feed = new RSS({
            title: 'New Microscope Posts',
            description: "the latest posts from Microscope, the smallest news aggregator."
        });

        Posts.find({}, {sort: {submitted: -1}, limit: 20}).forEach(function (post) {
            feed.item({
                title: post.title,
                description: post.body,
                author: post.author,
                date: post.submitted,
                url: '/posts/' + post._id
            });
        });

        this.response.write(feed.xml());
        this.response.end();
    }
});

Router.route('/api/posts', {
    where: 'server',
    name: 'apiPosts',
    action: function () {
        var parameters = this.request.query,
            // if parameter limit exists, take that value, else 20
            limit = !!parameters.limit ? parseInt(parameters.limit) : 20,
            data = Posts.find({}, {limit: limit, fields: {title: 1, author: 1, url: 1, submitted: 1}}).fetch();

        this.response.write(JSON.stringify(data));
        this.response.end();
    }
});

Router.route('/api/posts/:_id', {
    where: 'server',
    name: 'apiPost',
    action: function () {
        var post = Posts.findOne(this.params._id);

        if (post) {
            this.response.write(JSON.stringify(post));
        } else {
            this.response.writeHead(404, {'Content-Type': 'text/html'});
            this.response.write('Post not found.');
        }
        this.response.end();
    }
});
<|endoftext|>


<commit_before>// Insert router into filesystem if it's not present

var fs = require('fs.extra');

exports.create = function() {
  var destRoot, routeSrc, routeDest;

  destRoot = 'both/';
  routeSrc = templatePath + 'router/routes.js';
  routeDest = destRoot + 'routes.js';

  fs.mkdirsSync(destRoot);

  // bail if router already exists
  if (fs.existsSync(destRoot + 'routes.js')) return;

  fs.copy(routeSrc, routeDest, function (err) {
    if (err) {
      console.log(err);
      return;
    }
    console.log('  Created both/routes.js');
  });

};

<commit_msg>document router.js<commit_after>var fs = require('fs.extra');

/** Insert router.js into user's /both/controller/ folder
 *  If file already exists, do not overwrite.
 *  Copy router.js from templates to user's project.
 * @api public
 */
exports.create = function() {
  var destRoot, routeSrc, routeDest;

  destRoot = 'both/';
  routeSrc = templatePath + 'router/routes.js';
  routeDest = destRoot + 'routes.js';

  // create both folder if it doesn't already exisit
  fs.mkdirsSync(destRoot);

  // bail if router already exists
  if (fs.existsSync(destRoot + 'routes.js')) return;

  // copy router.js from templates/ to project/both/controllers
  fs.copy(routeSrc, routeDest, function (err) {
    if (err) {
      console.log(err);
      return;
    }
    console.log('  Created both/routes.js');
  });

};

<|endoftext|>


<commit_before>var debug = require('debug')('router');
var util = require('util');
var emit = require('events').EventEmitter.prototype.emit;
var slice = Array.prototype.slice;

module.exports = Router;

/**
 * Binds a function to the socket.io socket #onevent method and pushes the
 * event through middleware.
 *
 * @return Router
 */

function Router () {
  if (!(this instanceof Router)) return new Router();

  function router (socket, cb) {
    debug('router socket.id %s typeof cb %s', socket ? socket.id : null, typeof cb);
    router.middleware(socket, cb);
  }

  router.__proto__ = Router.prototype;

  var index = 0;

  /**
   * Inc the index
   *
   * @return Number
   */

  router.index = function () {
    return index++;
  };

  /**
   * The middleware function
   *
   * @api private
   * @param {Socket} socket
   * @param {function} cb
   */

  router.middleware = function (socket, cb) {
    debug('middleware socket.id %s typeof cb %s', socket.id, typeof cb);
    if ('function' != typeof socket.onevent || socket.onevent !== router.onEvent) {
      debug('the socket does not have the onEvent method attached yet');
      if (socket.onevent && socket.onevent.router) {
        debug('the socket\'s onevent method is an onEvent method that has a router so lets attach to it');
        socket.onevent.router.use(router);
      }
      else {
        debug('the onevent method is NOT a router method');
        socket.onevent = router.onEvent;
      }
    }
    cb();
  };

  /**
   * Handles the packet and pushes it through the middleware.
   * When invoked "this" will be the socket.
   *
   * @api private
   * @param {Object} packet
   */

  router.onEvent = function (packet) {

    var args = packet.data || [];

    if (null != packet.id) {
      args.push(this.ack(packet.id));
    }

    router.onRoute(null, this, args);

  };

  /*
   * This will allow the onEvent method to chain it self when attaching
   * multiple routers side by side. e.g.
   * var io = require('socket.io')(3000);
   * io.use(Router());
   * io.use(Router());
   */
  router.onEvent.router = router;

  /**
   * Pushes the socket and arguments through the middleware
   *
   * @api private
   * @param {Error} err *optional
   * @param {Socket} socket
   * @param {Array} args
   * @param {Function} cb
   */

  router.onRoute = function (err, socket, args, cb) {

    debug('onRoute err? %s socket.id %s args?', util.isError(err), (socket ? socket.id : null),  args);

    socket = router.decorate(socket, function (emit, args) { debug('done callled'); emit.apply(socket, args); });

    var i = 0, path = router.getPath(args.length ? args[0] : '*'), len = path.length;

    debug('got path the length is %s', len);

    debug('about to call "step" for the first time passing %s for err', err);

    (function step (err) {

      debug('current step %s of %s', i+1, len);

      function next (err) {
        debug('next called err? %s', util.isError(err));
        if (++i >= len) {
          debug('last step');
          if (err) {
            debug('has err');
            if ('function' === typeof cb) {
              debug('cb is function');
              cb(err, socket, args);
            }
            else {
              debug('default which is to call emit on the socket');
              emit.apply(socket, ['error', args]);
            }
          }
          else {
            debug('no err');
            if ('function' === typeof cb) {
              debug('cb is function');
              cb(null, socket, args);
            }
            else {
              debug('default which is to call emit on the socket');
              emit.apply(socket, args);
            }
          }
        }
        else {
          debug('calling step');
          step(err);
        }
      }

      var fn = path[i];
      if (!fn) return next();

      debug('typeof fn? %s', typeof fn);

      try {
        if (err) {
          debug('we have an error');
          if (fn.length >= 4) {
            debug('the fn.length is >= 4');
            if (fn instanceof Router) {
              debug('we have a router instance');
              fn.onRoute(err, socket, args, next);
            }
            else {
              debug('we have a regular function');
              fn(err, socket, args, next);
            }
          }
          else {
            debug('fn is not an erorr handler call next %s', typeof next);
            next(err);
          }
        }
        else {
          debug('we do not have an error');
          debug('fn %s', fn);
          if (fn.length >= 4) {
            debug('the fn.length is >= 4');
            if (fn instanceof Router) {
              debug('we have a router instance');
              fn.onRoute(null, socket, args, next);
            }
            else {
              debug('we have a regular function call next %s', typeof next);
              next();
            }
          }
          else {
            if (fn instanceof Router) {
              debug('we have a router instance');
              fn.onRoute(null, socket, args, next);
            }
            else {
              debug('fn is normal invoke it socket.id %s args %s typeof next %s', (socket ? socket.id : null), args, typeof next);
              fn(socket, args, next);
            }
          }
        }
      }
      catch(e) {
        debug('caught error %s', e);
        debug('the fn causing problems', fn);
        console.log(e.stack);
        next(e);
      }

    })(err);

  };

  debug('router instanceof Router? %s', router instanceof Router);

  return router;

};

/**
 * Decorates the socket's emit function to call the passed done method
 *
 * @api private
 * @param {Socket} socket
 * @param {function} done
 * @return Socket
 */

Router.prototype.decorate = function (socket, done) {
  debug('decorate socket.id %s typeof done %s', socket.id, typeof done);
  var emit = socket.emit;

  debug('is the "emit" on socket.id %s wrapped? %s', socket.id, (emit.wrapped ? true : false));

  // prevent double wrapping
  if (emit.wrapped) return socket;

  socket.emit = function () {
    done(emit, slice.call(arguments));
  };

  debug('"emit" on socket.id %s is now wrapped', socket.id);
  socket.emit.wrapped = true;

  return socket;
};

/**
 * Gets the routing path given the name
 *
 * @api private
 * @param {String} name
 * @return Array
 */

Router.prototype.getPath = function (name) {
  debug('get path %s', name);
  name = name || '*';
  var points = [].concat(this.fns(name));
  if (name !== '*') {
    points = points.concat(this.fns());
  }
  var fns = [];
  points
    .sort(function (a, b) {
      return a[0] - b[0];
    })
    .forEach(function (point) {
      fns.push(point[1]);
    });
  return fns;
};

/**
 * Use this method to attach handlers, and other routers
 *
 * @api public
 * @param {mixed} Either a string and one of either a [function, or array of functions, or a Router]
 * @return Router
 */

Router.prototype.use = function () {
  if (!arguments.length) throw new Error('expecting at least one parameter');
  var args = slice.call(arguments);
  debug('use called %s', args);
  var name = typeof args[0] === 'string' ? args.shift() : '*';
  debug('the name %s', name);
  if (!args.length) throw new Error('we have the name, but need a handler');
  var fns = this.fns(name);
  var self = this;
  var i, arg, type;
  for (i=0; i<args.length; i++) {
    arg = args[i];
    if (util.isArray(arg)) return self.use.apply(self, arg);
    type = typeof arg;
    debug('typeof arg %s', type);
    if ('function' !== type) return;
    debug('arg instanceof Router? %s', arg instanceof Router);
    fns[fns.length] = [self.index(), arg];
  }
  return this;
};

/**
 * An alias to the `use` method.
 *
 * @api public
 * @param {mixed} Either a string, function, or array of functions
 * @return Router
 */

Router.prototype.on = Router.prototype.use;

/**
 * Gets the functions given the name.  Name will default to '*'
 *
 * @api private
 * @param {string} name
 * @return Array
 */

Router.prototype.fns = function (name) {
  name = name || '*';
  if (!this._fns) {
    this._fns = {};
  }
  if (!this._fns[name]) {
    this._fns[name] = [];
  }
  return this._fns[name];
};
<commit_msg>renamed to error<commit_after>var debug = require('debug')('router');
var util = require('util');
var emit = require('events').EventEmitter.prototype.emit;
var slice = Array.prototype.slice;

module.exports = Router;

/**
 * Binds a function to the socket.io socket #onevent method and pushes the
 * event through middleware.
 *
 * @return Router
 */

function Router () {
  if (!(this instanceof Router)) return new Router();

  function router (socket, cb) {
    debug('router socket.id %s typeof cb %s', socket ? socket.id : null, typeof cb);
    router.middleware(socket, cb);
  }

  router.__proto__ = Router.prototype;

  var index = 0;

  /**
   * Inc the index
   *
   * @return Number
   */

  router.index = function () {
    return index++;
  };

  /**
   * The middleware function
   *
   * @api private
   * @param {Socket} socket
   * @param {function} cb
   */

  router.middleware = function (socket, cb) {
    debug('middleware socket.id %s typeof cb %s', socket.id, typeof cb);
    if ('function' != typeof socket.onevent || socket.onevent !== router.onEvent) {
      debug('the socket does not have the onEvent method attached yet');
      if (socket.onevent && socket.onevent.router) {
        debug('the socket\'s onevent method is an onEvent method that has a router so lets attach to it');
        socket.onevent.router.use(router);
      }
      else {
        debug('the onevent method is NOT a router method');
        socket.onevent = router.onEvent;
      }
    }
    cb();
  };

  /**
   * Handles the packet and pushes it through the middleware.
   * When invoked "this" will be the socket.
   *
   * @api private
   * @param {Object} packet
   */

  router.onEvent = function (packet) {

    var args = packet.data || [];

    if (null != packet.id) {
      args.push(this.ack(packet.id));
    }

    router.onRoute(null, this, args);

  };

  /*
   * This will allow the onEvent method to chain it self when attaching
   * multiple routers side by side. e.g.
   * var io = require('socket.io')(3000);
   * io.use(Router());
   * io.use(Router());
   */
  router.onEvent.router = router;

  /**
   * Pushes the socket and arguments through the middleware
   *
   * @api private
   * @param {Error} err *optional
   * @param {Socket} socket
   * @param {Array} args
   * @param {Function} cb
   */

  router.onRoute = function (err, socket, args, cb) {

    debug('onRoute err? %s socket.id %s args?', util.isError(err), (socket ? socket.id : null),  args);

    socket = router.decorate(socket, function (emit, args) { debug('done callled'); emit.apply(socket, args); });

    var i = 0, path = router.getPath(args.length ? args[0] : '*'), len = path.length;

    debug('got path the length is %s', len);

    debug('about to call "step" for the first time passing %s for err', err);

    (function step (err) {

      debug('current step %s of %s', i+1, len);

      function next (err) {
        debug('next called err? %s', util.isError(err));
        if (++i >= len) {
          debug('last step');
          if (err) {
            debug('has err');
            if ('function' === typeof cb) {
              debug('cb is function');
              cb(err, socket, args);
            }
            else {
              debug('default which is to call emit on the socket');
              emit.apply(socket, ['error', args]);
            }
          }
          else {
            debug('no err');
            if ('function' === typeof cb) {
              debug('cb is function');
              cb(null, socket, args);
            }
            else {
              debug('default which is to call emit on the socket');
              emit.apply(socket, args);
            }
          }
        }
        else {
          debug('calling step');
          step(err);
        }
      }

      var fn = path[i];
      if (!fn) return next();

      debug('typeof fn? %s', typeof fn);

      try {
        if (err) {
          debug('we have an error');
          if (fn.length >= 4) {
            debug('the fn.length is >= 4');
            if (fn instanceof Router) {
              debug('we have a router instance');
              fn.onRoute(err, socket, args, next);
            }
            else {
              debug('we have a regular function');
              fn(err, socket, args, next);
            }
          }
          else {
            debug('fn is not an erorr handler call next %s', typeof next);
            next(err);
          }
        }
        else {
          debug('we do not have an error');
          debug('fn %s', fn);
          if (fn.length >= 4) {
            debug('the fn.length is >= 4');
            if (fn instanceof Router) {
              debug('we have a router instance');
              fn.onRoute(null, socket, args, next);
            }
            else {
              debug('we have a regular function call next %s', typeof next);
              next();
            }
          }
          else {
            if (fn instanceof Router) {
              debug('we have a router instance');
              fn.onRoute(null, socket, args, next);
            }
            else {
              debug('fn is normal invoke it socket.id %s args %s typeof next %s', (socket ? socket.id : null), args, typeof next);
              fn(socket, args, next);
            }
          }
        }
      }
      catch(e) {
        debug('caught error %s', e);
        debug('the fn causing problems', fn);
        console.error(e.stack);
        next(e);
      }

    })(err);

  };

  debug('router instanceof Router? %s', router instanceof Router);

  return router;

};

/**
 * Decorates the socket's emit function to call the passed done method
 *
 * @api private
 * @param {Socket} socket
 * @param {function} done
 * @return Socket
 */

Router.prototype.decorate = function (socket, done) {
  debug('decorate socket.id %s typeof done %s', socket.id, typeof done);
  var emit = socket.emit;

  debug('is the "emit" on socket.id %s wrapped? %s', socket.id, (emit.wrapped ? true : false));

  // prevent double wrapping
  if (emit.wrapped) return socket;

  socket.emit = function () {
    done(emit, slice.call(arguments));
  };

  debug('"emit" on socket.id %s is now wrapped', socket.id);
  socket.emit.wrapped = true;

  return socket;
};

/**
 * Gets the routing path given the name
 *
 * @api private
 * @param {String} name
 * @return Array
 */

Router.prototype.getPath = function (name) {
  debug('get path %s', name);
  name = name || '*';
  var points = [].concat(this.fns(name));
  if (name !== '*') {
    points = points.concat(this.fns());
  }
  var fns = [];
  points
    .sort(function (a, b) {
      return a[0] - b[0];
    })
    .forEach(function (point) {
      fns.push(point[1]);
    });
  return fns;
};

/**
 * Use this method to attach handlers, and other routers
 *
 * @api public
 * @param {mixed} Either a string and one of either a [function, or array of functions, or a Router]
 * @return Router
 */

Router.prototype.use = function () {
  if (!arguments.length) throw new Error('expecting at least one parameter');
  var args = slice.call(arguments);
  debug('use called %s', args);
  var name = typeof args[0] === 'string' ? args.shift() : '*';
  debug('the name %s', name);
  if (!args.length) throw new Error('we have the name, but need a handler');
  var fns = this.fns(name);
  var self = this;
  var i, arg, type;
  for (i=0; i<args.length; i++) {
    arg = args[i];
    if (util.isArray(arg)) return self.use.apply(self, arg);
    type = typeof arg;
    debug('typeof arg %s', type);
    if ('function' !== type) return;
    debug('arg instanceof Router? %s', arg instanceof Router);
    fns[fns.length] = [self.index(), arg];
  }
  return this;
};

/**
 * An alias to the `use` method.
 *
 * @api public
 * @param {mixed} Either a string, function, or array of functions
 * @return Router
 */

Router.prototype.on = Router.prototype.use;

/**
 * Gets the functions given the name.  Name will default to '*'
 *
 * @api private
 * @param {string} name
 * @return Array
 */

Router.prototype.fns = function (name) {
  name = name || '*';
  if (!this._fns) {
    this._fns = {};
  }
  if (!this._fns[name]) {
    this._fns[name] = [];
  }
  return this._fns[name];
};
<|endoftext|>


<commit_before>Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    waitOn: function() { return Meteor.subscribe('posts'); }
});

Router.map(function () {
    this.route('postsList', { path: '/' });
    this.route('postPage', {
        path: '/posts/:_id',
        data: function() { return Posts.findOne(this.params._id); }
    });
    this.route('postNew', { path: '/new' });
});

var checkAuthentication = function() {
    if (!Meteor.user()) {
        this.render('accessDenied');
        this.stop();
    }
};

Router.before(checkAuthentication, { only: 'postNew' });<commit_msg>fixing router before hook and changing postPage route<commit_after>Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    waitOn: function() { return Meteor.subscribe('posts'); }
});

Router.map(function () {
    this.route('postsList', { path: '/' });
    this.route('postPage', {
        path: '/posts/show/:_id',
        data: function() { return Posts.findOne(this.params._id); }
    });
    this.route('postNew', { path: '/posts/new' });
});

var checkAuthentication = function() {
    if (!Meteor.user()) {
        this.render('accessDenied');
    } else {
        this.next();
    }
};

Router.onBeforeAction(checkAuthentication, { only: 'postNew' });<|endoftext|>