<|start_filename|>bin/game-server/node_modules/mqtt/test/old/connection.test.js<|end_filename|>
/*global describe, it, beforeEach */

var assert = require('assert'),
  should = require('should');

var protocol = require('../../lib/protocol'),
  Connection = require('../../lib/connection'),
  make_tester = require('./tester');

var tester = make_tester();
var connection = new Connection(tester);

function make_protocol_type_case(type) {
  return it('#' + type, function () {
    var method = connection[type];
    method.should.be.a('function');
  });
}


describe.skip("Connection", function () {

  describe("should have functions for", function () {
    var typenum;
    for (typenum in protocol.types) {
      if (protocol.types.hasOwnProperty(typenum)) {
        make_protocol_type_case.call(this, protocol.types[typenum]);
      }
    }
  });


  describe("should emit on stream event", function () {
    beforeEach(function () {
      this.tester = make_tester();
      this.connection = new Connection(this.tester);
    });

    it("close", function (done) {
      this.connection.on('close', done);
      this.tester.do_emit('close');
    });

    it("error", function (done) {
      this.connection.on('error', function (err) {
        should.exist(err);
        err.should.be.instanceOf(Error);
        done();
      });
      this.tester.do_emit('error', new Error("fake test one"));
    });

  });
});


<|start_filename|>bin/game-server/node_modules/mqtt-connection/lib/generateStream.js<|end_filename|>

var through   = require('through2')
  , generate  = require('mqtt-packet').generate
  , empty     = new Buffer(0)

function generateStream() {
  var stream  = through.obj(process)

  function process(chunk, enc, cb) {
    var packet = empty;

    try {
      packet = generate(chunk)
    } catch(err) {
      this.emit('error', err)
      return;
    }

    this.push(packet)
    cb()
  }

  return stream
}

module.exports = generateStream;


<|start_filename|>bin/game-server/node_modules/pomelo-admin/node_modules/pomelo-scheduler/lib/cronTriggerDecoder.js<|end_filename|>
var decoder = module.exports;
decoder.decodeCronTime = decodeCronTime;

var timer = {
  second: -1,
  min: -1,
  hour: -1,
  dom: -1,
  month: -1,
  dow: -1,
  executeTime: -1
}

var limit = [[0,59],[0,59],[0,24],[1,31],[1,12],[0,6]];

function nexExcuteTime(time, timer){
  //add 1s to the time so it must be the next time
  time += 1000;
  var date = new Date(time);
  var nextTime = new Date(time);

  outmost:
  while(true){
    if(!timeMatch(date.getMonth(), timer.month)){
      var nextMonth = nextTime(date.getMonth(), timer.month);
      if(nextMonth < date.getMonth()){
        date.setYear(date.getYear()+1);
      }
      date.setMonth(nextMonth);
      
      date.setDate(1);
      date.setHours(0);        
      date.setMinutes(0);
      date.setSeconds(0);
    }
      
    if(!timeMatch(date.getDate(), timer.dom)){
      do{
        var nextDom = nextTime(date.getDate(), timer.dom);
    
        //If the date is in the next month, add month
        if(nextDom <= date.getDate()){
          date.setMonth(date.getMonth() + 1);
          continue outmost;
        }
       
        //If the date exceed the limit, add month
         var domLimit = getDomLimit();
        if(nexDom > domLimit){
           date.setMonth(date.getMonth() + 1);
          continue outmost;
        }
 
         date.setDate(nextDom);
      }while(!timeMatch(date.getDay(), timer.dow));
     
      date.setHours(0);        
      date.setMinutes(0);
      date.setSeconds(0); 
    }
    
    if(!timeMatch(date.getHours(), timer.hour)){
      var nextHour = nextTime(date.getHours(), timer.hour);
     
      if(nextHour <= date.getHours()){
         date.setDate(date.getDate() + 1);
         continue;
      }
      
      date.setHours(nextHour);
      date.setMinutes(0);
      date.setSeconds(0);
    }
    
    if(!timeMatch(date.getMinutes(), timer.minute)){
      var nextMinute = nextTime(date.getMinutes(), timer.minute);
     
      if(nextMinute <= date.getMinutes()){
         date.setHours(date.getHours() + 1);
         continue;
      }
      
      date.setMinutes(nextMinute);
      date.setSeconds(0);
    }
    
    if(!timeMatch(date.getSeconds(), timer.seconde)){
      var nextSecond = nextTime(date.getSeconds(), timer.seconde);
     
      if(nextSecond <= date.getSeconds()){
         date.setMinutes()(date.getMinutes() + 1);
         continue;
      }
      
      date.setSeconds(nextSecond);
    }
    
    break;
  }
  
  return date.getTime();
}

/**
 * return the next match time of the given value
 */
function nextTime(value, cronTime){
  if(typeof(cronTime) == 'number'){
    if(cronTime == -1)
      return value + 1;
    else
      return cronTime;
  }else if(typeof(cronTime) == 'array'){
    if(value < arr[0] || value > arr[arr.length -1])
      return arr[0];
    
    for(var i = 0; i < arr.length; i++)
      if(value < arr[i])
        return arr[i];
  }
  
  return null;
}

function timeMatch(value, cronTime){
   if(tyeof(cronTime) == 'number'){
    if(cronTime == -1)
      return true;
    if(value == cronTime)
      return true;
    return false;
  }else if(typeof(cronTime) == 'array'){
    if(value < arr[0] || value > arr[arr.length -1])
      return false;
    
    for(var i = 0; i < arr.length; i++)
      if(value == arr[i])
        return true;
        
    return false;
  }
  
  return null;
}

function getDomLimit(year, month){
  var date = new Date(year, month, 0);
  
  return date.getDate();
}

function decodeCronTime(cronTime){
  var timers = cronTime.split(/\s+/);
  
  if(timers.length != 6){
    return null;
  }
  
  for(var i = 0; i < timers.length; i++){
    timers[i] = (decodeTimeStr(timers[i]));
    
    if(!checkNum(timers[i], limit[i][0], limit[i][1])){
      return null;
    }
  }
  
  return timers;
}

function decodeTimeStr(timeStr){  
  var result = {};
  var arr = [];
  
  if(timeStr=='*'){
    return -1;
  }else if(timeStr.search(',')>0){
    var timeStrArray = timeStr.split(',');
    for(var i = 0; i < timeStrArray.length; i++){
      var time = timeStrArray[i];
      if(time.match(/^\d+-\d+$/)){
        decodeRangeTime(result, time);
      }else if(!isNaN(timeStrArray[i]))
        result[i] = time;
      else
        return null;
    }
  }else if(timeStr.match(/^\d+-\d+$/)){
    decodeRangeTime(result, time);
  }else if(!isNaN(timeStr)){
    result[timeStr] = timeStr;
  }else{
    return null;
  }  
  
  for(var key in result)
    arr.push(result[key]);
      
  arr.sort();
  
  return arr;
}

function decodeRangeTime(map, timeStr){
  var times = timeStr.split('-');
  
  if(times[0] > times[1])
    return null;
  for(var i = times[0]; i <= times[1]; i++)
    map[i] = i;
}

function checkNum(nums, min, max){
  if(nums == null)
    return false;
    
  if(nums == -1)
    return true;
  
  for(var i = 0; i < nums.length; i++){
    if(nums[i]<min || nums[i]>max)
      return false;
  }
  
  return true;
}

<|start_filename|>node_modules/mocha/lib/cli/run-helpers.js<|end_filename|>
'use strict';

/**
 * Helper scripts for the `run` command
 * @see module:lib/cli/run
 * @module
 * @private
 */

const fs = require('fs');
const path = require('path');
const ansi = require('ansi-colors');
const debug = require('debug')('mocha:cli:run:helpers');
const minimatch = require('minimatch');
const Context = require('../context');
const Mocha = require('../mocha');
const utils = require('../utils');

const cwd = (exports.cwd = process.cwd());

/**
 * Exits Mocha when tests + code under test has finished execution (default)
 * @param {number} code - Exit code; typically # of failures
 * @ignore
 * @private
 */
const exitMochaLater = code => {
  process.on('exit', () => {
    process.exitCode = Math.min(code, 255);
  });
};

/**
 * Exits Mocha when Mocha itself has finished execution, regardless of
 * what the tests or code under test is doing.
 * @param {number} code - Exit code; typically # of failures
 * @ignore
 * @private
 */
const exitMocha = code => {
  const clampedCode = Math.min(code, 255);
  let draining = 0;

  // Eagerly set the process's exit code in case stream.write doesn't
  // execute its callback before the process terminates.
  process.exitCode = clampedCode;

  // flush output for Node.js Windows pipe bug
  // https://github.com/joyent/node/issues/6247 is just one bug example
  // https://github.com/visionmedia/mocha/issues/333 has a good discussion
  const done = () => {
    if (!draining--) {
      process.exit(clampedCode);
    }
  };

  const streams = [process.stdout, process.stderr];

  streams.forEach(stream => {
    // submit empty write request and wait for completion
    draining += 1;
    stream.write('', done);
  });

  done();
};

/**
 * Hide the cursor.
 * @ignore
 * @private
 */
const hideCursor = () => {
  process.stdout.write('\u001b[?25l');
};

/**
 * Show the cursor.
 * @ignore
 * @private
 */
const showCursor = () => {
  process.stdout.write('\u001b[?25h');
};

/**
 * Stop cursor business
 * @private
 */
const stop = () => {
  process.stdout.write('\u001b[2K');
};

/**
 * Coerce a comma-delimited string (or array thereof) into a flattened array of
 * strings
 * @param {string|string[]} str - Value to coerce
 * @returns {string[]} Array of strings
 * @private
 */
exports.list = str =>
  Array.isArray(str) ? exports.list(str.join(',')) : str.split(/ *, */);

/**
 * `require()` the modules as required by `--require <require>`
 * @param {string[]} requires - Modules to require
 * @private
 */
exports.handleRequires = (requires = []) => {
  requires.forEach(mod => {
    let modpath = mod;
    if (fs.existsSync(mod, {cwd}) || fs.existsSync(`${mod}.js`, {cwd})) {
      modpath = path.resolve(mod);
      debug(`resolved ${mod} to ${modpath}`);
    }
    require(modpath);
    debug(`loaded require "${mod}"`);
  });
};

/**
 * Smash together an array of test files in the correct order
 * @param {Object} [opts] - Options
 * @param {string[]} [opts.extension] - File extensions to use
 * @param {string[]} [opts.spec] - Files, dirs, globs to run
 * @param {string[]} [opts.exclude] - Files, dirs, globs to exclude
 * @param {boolean} [opts.recursive=false] - Find files recursively
 * @param {boolean} [opts.sort=false] - Sort test files
 * @returns {string[]} List of files to test
 * @private
 */
exports.handleFiles = ({
  exclude = [],
  extension = [],
  file = [],
  recursive = false,
  sort = false,
  spec = []
} = {}) => {
  let files = [];
  const unmatched = [];
  spec.forEach(arg => {
    let newFiles;
    try {
      newFiles = utils.lookupFiles(arg, extension, recursive);
    } catch (err) {
      if (err.code === 'ERR_MOCHA_NO_FILES_MATCH_PATTERN') {
        unmatched.push({message: err.message, pattern: err.pattern});
        return;
      }

      throw err;
    }

    if (typeof newFiles !== 'undefined') {
      if (typeof newFiles === 'string') {
        newFiles = [newFiles];
      }
      newFiles = newFiles.filter(fileName =>
        exclude.every(pattern => !minimatch(fileName, pattern))
      );
    }

    files = files.concat(newFiles);
  });

  if (!files.length) {
    // give full message details when only 1 file is missing
    const noneFoundMsg =
      unmatched.length === 1
        ? `Error: No test files found: ${JSON.stringify(unmatched[0].pattern)}` // stringify to print escaped characters raw
        : 'Error: No test files found';
    console.error(ansi.red(noneFoundMsg));
    process.exit(1);
  } else {
    // print messages as an warning
    unmatched.forEach(warning => {
      console.warn(ansi.yellow(`Warning: ${warning.message}`));
    });
  }

  const fileArgs = file.map(filepath => path.resolve(filepath));
  files = files.map(filepath => path.resolve(filepath));

  // ensure we don't sort the stuff from fileArgs; order is important!
  if (sort) {
    files.sort();
  }

  // add files given through --file to be ran first
  files = fileArgs.concat(files);
  debug('files (in order): ', files);
  return files;
};

/**
 * Give Mocha files and tell it to run
 * @param {Mocha} mocha - Mocha instance
 * @param {Options} [opts] - Options
 * @param {string[]} [opts.files] - List of test files
 * @param {boolean} [opts.exit] - Whether or not to force-exit after tests are complete
 * @returns {Runner}
 * @private
 */
exports.singleRun = (mocha, {files = [], exit = false} = {}) => {
  mocha.files = files;
  return mocha.run(exit ? exitMocha : exitMochaLater);
};

/**
 * Run Mocha in "watch" mode
 * @param {Mocha} mocha - Mocha instance
 * @param {Object} [opts] - Options
 * @param {string[]} [opts.extension] - List of extensions to watch
 * @param {string|RegExp} [opts.grep] - Grep for test titles
 * @param {string} [opts.ui=bdd] - User interface
 * @param {string[]} [files] - Array of test files
 * @private
 */
exports.watchRun = (
  mocha,
  {extension = ['js'], grep = '', ui = 'bdd', files = []} = {}
) => {
  let runner;

  console.log();
  hideCursor();
  process.on('SIGINT', () => {
    showCursor();
    console.log('\n');
    process.exit(130);
  });

  const watchFiles = utils.files(cwd, extension);
  let runAgain = false;

  const loadAndRun = () => {
    try {
      mocha.files = files;
      runAgain = false;
      runner = mocha.run(() => {
        runner = null;
        if (runAgain) {
          rerun();
        }
      });
    } catch (e) {
      console.log(e.stack);
    }
  };

  const purge = () => {
    watchFiles.forEach(Mocha.unloadFile);
  };

  loadAndRun();

  const rerun = () => {
    purge();
    stop();
    if (!grep) {
      mocha.grep(null);
    }
    mocha.suite = mocha.suite.clone();
    mocha.suite.ctx = new Context();
    mocha.ui(ui);
    loadAndRun();
  };

  utils.watch(watchFiles, () => {
    runAgain = true;
    if (runner) {
      runner.abort();
    } else {
      rerun();
    }
  });
};

/**
 * Actually run tests
 * @param {Mocha} mocha - Mocha instance
 * @param {Object} [opts] - Options
 * @param {boolean} [opts.watch=false] - Enable watch mode
 * @param {string[]} [opts.extension] - List of extensions to watch
 * @param {string|RegExp} [opts.grep] - Grep for test titles
 * @param {string} [opts.ui=bdd] - User interface
 * @param {boolean} [opts.exit=false] - Force-exit Mocha when tests done
 * @param {string[]} [files] - Array of test files
 * @private
 */
exports.runMocha = (
  mocha,
  {watch = false, extension = ['js'], grep = '', ui = 'bdd', exit = false} = {},
  files = []
) => {
  if (watch) {
    exports.watchRun(mocha, {extension, grep, ui, files});
  } else {
    exports.singleRun(mocha, {files, exit});
  }
};

/**
 * Used for `--reporter` and `--ui`.  Ensures there's only one, and asserts
 * that it actually exists.
 * @todo XXX This must get run after requires are processed, as it'll prevent
 * interfaces from loading.
 * @param {Object} opts - Options object
 * @param {string} key - Resolvable module name or path
 * @param {Object} [map] - An object perhaps having key `key`
 * @private
 */
exports.validatePlugin = (opts, key, map = {}) => {
  if (Array.isArray(opts[key])) {
    throw new TypeError(`"--${key} <${key}>" can only be specified once`);
  }

  const unknownError = () => new Error(`Unknown "${key}": ${opts[key]}`);

  if (!map[opts[key]]) {
    try {
      opts[key] = require(opts[key]);
    } catch (err) {
      if (err.code === 'MODULE_NOT_FOUND') {
        // Try to load reporters from a path (absolute or relative)
        try {
          opts[key] = require(path.resolve(process.cwd(), opts[key]));
        } catch (err) {
          throw unknownError();
        }
      } else {
        throw unknownError();
      }
    }
  }
};


<|start_filename|>bin/game-server/node_modules/pomelo-logger/index.js<|end_filename|>
module.exports = require('./lib/logger');

<|start_filename|>bin/game-server/node_modules/bops/test/join.js<|end_filename|>
var test = require('tape')
  , binary = require('../index')

test('test that join works as expected', function(assert) {
  var tmp1 = binary.create(16)
    , tmp2 = binary.create(16)
    , tmp3
    , cur

  for(var i = 0, len = 16; i < len; ++i) {
    binary.writeUInt8(tmp1, Math.random() * 0xFF & 0xFF, i)
    binary.writeUInt8(tmp2, Math.random() * 0xFF & 0xFF, i) 
  }

  tmp3 = binary.join([tmp1, tmp2])
  cur = tmp1

  for(var i = 0, j = 0, len = 32; i < len; ++i, ++j) {
    if(j !== 0 && j % 16 === 0) {
      cur = tmp2
      j = 0
    }
    assert.equal(
      binary.readUInt8(tmp3, i)
    , binary.readUInt8(cur, j)
    )
  }

  assert.end()
})


<|start_filename|>bin/game-server/node_modules/mqtt/lib/browser.js<|end_filename|>

var MqttClient = require('./client')
  , MqttConnection = require('./connection');

module.exports.MqttClient = MqttClient;
module.exports.MqttConnection = MqttConnection;


<|start_filename|>node_modules/mocha/lib/reporters/doc.js<|end_filename|>
'use strict';
/**
 * @module Doc
 */
/**
 * Module dependencies.
 */

var Base = require('./base');
var utils = require('../utils');
var constants = require('../runner').constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
var EVENT_SUITE_END = constants.EVENT_SUITE_END;

/**
 * Expose `Doc`.
 */

exports = module.exports = Doc;

/**
 * Constructs a new `Doc` reporter instance.
 *
 * @public
 * @class
 * @memberof Mocha.reporters
 * @extends Mocha.reporters.Base
 * @param {Runner} runner - Instance triggers reporter actions.
 * @param {Object} [options] - runner options
 */
function Doc(runner, options) {
  Base.call(this, runner, options);

  var indents = 2;

  function indent() {
    return Array(indents).join('  ');
  }

  runner.on(EVENT_SUITE_BEGIN, function(suite) {
    if (suite.root) {
      return;
    }
    ++indents;
    console.log('%s<section class="suite">', indent());
    ++indents;
    console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
    console.log('%s<dl>', indent());
  });

  runner.on(EVENT_SUITE_END, function(suite) {
    if (suite.root) {
      return;
    }
    console.log('%s</dl>', indent());
    --indents;
    console.log('%s</section>', indent());
    --indents;
  });

  runner.on(EVENT_TEST_PASS, function(test) {
    console.log('%s  <dt>%s</dt>', indent(), utils.escape(test.title));
    var code = utils.escape(utils.clean(test.body));
    console.log('%s  <dd><pre><code>%s</code></pre></dd>', indent(), code);
  });

  runner.on(EVENT_TEST_FAIL, function(test, err) {
    console.log(
      '%s  <dt class="error">%s</dt>',
      indent(),
      utils.escape(test.title)
    );
    var code = utils.escape(utils.clean(test.body));
    console.log(
      '%s  <dd class="error"><pre><code>%s</code></pre></dd>',
      indent(),
      code
    );
    console.log('%s  <dd class="error">%s</dd>', indent(), utils.escape(err));
  });
}

Doc.description = 'HTML documentation';


<|start_filename|>bin/game-server/node_modules/pomelo-admin/lib/util/profileProxy.js<|end_filename|>
var fs = require('fs');

var HeapProfileType = 'HEAP';
var CPUProfileType = 'CPU';

var Proxy = function(){
	this.profiles = {
		HEAP: {},
		CPU: {}
	};

	this.isProfilingCPU = false;
};

module.exports = Proxy;

var pro = Proxy.prototype;

pro.enable = function(id, params, clientId, agent) {
	this.sendResult(id,{
		result : true
	}, clientId, agent);
};

pro.causesRecompilation = function(id, params, clientId, agent) {
	this.sendResult(id,{
		result: false
	}, clientId, agent);
};

pro.isSampling = function(id, params, clientId, agent) {
	this.sendResult(id,{
		result: true
	}, clientId, agent);
};

pro.hasHeapProfiler = function(id, params, clientId, agent) {
	this.sendResult(id,{
		result: true
	}, clientId, agent);
};

pro.getProfileHeaders = function(id, params, clientId, agent) {
	var headers = [];
	for (var type in this.profiles) {
		for (var profileId in this.profiles[type]) {
			var profile = this.profiles[type][profileId];
			headers.push({
				title: profile.title,
				uid: profile.uid,
				typeId: type
			});
		}
	}
	this.sendResult(id, {
		headers: headers
	}, clientId, agent);
};

pro.takeHeapSnapshot = function(id, params, clientId, agent) {
	var uid = params.uid;

	agent.notifyById(uid, 'profiler', {type: 'heap', action: 'start', uid: uid, clientId: clientId});

	this.sendEvent({
		method: 'Profiler.addProfileHeader', 
		params: {header: {title: uid, uid: uid, typeId: HeapProfileType}}
	}, clientId, agent);
	this.sendResult(id, {}, clientId, agent);
};

pro.takeSnapCallBack = function (data) {
	var uid = data.params.uid || 0;
	var snapShot = this.profiles[HeapProfileType][uid];
	if (!snapShot || snapShot.finish) {
		snapShot = {};
		snapShot.data = [];
		snapShot.finish = false;
		snapShot.uid = uid;
		snapShot.title = uid;
	}
	if (data.method === 'Profiler.addHeapSnapshotChunk') {
		var chunk = data.params.chunk;
		snapShot.data.push(chunk);
	} else {
		snapShot.finish = true;
	}
	this.profiles[HeapProfileType][uid] = snapShot;
};

pro.getProfile = function(id, params, clientId, agent) {
	var profile = this.profiles[params.type][params.uid];
	var self = this;
	if (!profile || !profile.finish) {
		var timerId = setInterval(function() {
			profile = self.profiles[params.type][params.uid];
			if (!!profile) {
				clearInterval(timerId);
				self.asyncGet(id, params, profile, clientId, agent);
			}
		}, 5000);
	} else {
		this.asyncGet(id,params, profile, clientId, agent);
	}
};

pro.asyncGet = function(id, params, snapshot, clientId, agent) {
	var uid = params.uid;
	if (params.type === HeapProfileType) {
		for (var index in snapshot.data) {
			var chunk = snapshot.data[index];
			this.sendEvent({method: 'Profiler.addHeapSnapshotChunk', params: {uid: uid, chunk: chunk}}, clientId, agent);
		}
		this.sendEvent({method: 'Profiler.finishHeapSnapshot', params: {uid: uid}}, clientId, agent);
		this.sendResult(id, {profile: {title: snapshot.title, uid: uid, typeId: HeapProfileType}}, clientId, agent);
	} else if (params.type === CPUProfileType) {
		this.sendResult(id,{
			profile: {
				title: snapshot.title,
				uid: uid,
				typeId: CPUProfileType,
				head: snapshot.data.head,
				bottomUpHead: snapshot.data.bottomUpHead
			}
		}, clientId, agent);
	}
};

pro.clearProfiles = function(id, params) {
	this.profiles.HEAP = {};
	this.profiles.CPU = {};
	//profiler.deleteAllSnapshots();
	//profiler.deleteAllProfiles();
};

pro.sendResult = function(id, res, clientId, agent){
	agent.notifyClient(clientId, 'profiler', JSON.stringify({id: id, result: res}));
};

pro.sendEvent = function(res, clientId, agent){
	agent.notifyClient(clientId, 'profiler', JSON.stringify(res));
};

pro.start = function(id, params, clientId, agent) {
	var uid = params.uid;

	agent.notifyById(uid, 'profiler', {type: 'CPU', action: 'start', uid: uid, clientId: clientId});
	this.sendEvent({method: 'Profiler.setRecordingProfile', params: {isProfiling: true}}, clientId, agent);
	this.sendResult(id, {}, clientId, agent);
};

pro.stop = function(id, params, clientId, agent) {
	var uid = params.uid;
	agent.notifyById(uid, 'profiler', {type: 'CPU', action: 'stop', uid: uid, clientId: clientId});
	this.sendResult(id, {}, clientId, agent);
};

pro.stopCallBack = function(res, clientId, agent) {
	var uid = res.msg.uid;
	var profiler = this.profiles[CPUProfileType][uid];
	if (!profiler || profiler.finish){
		profiler = {};
		profiler.data = null;
		profiler.finish = true;
		profiler.typeId = CPUProfileType;
		profiler.uid = uid;
		profiler.title = uid;
	}
	profiler.data = res;
	this.profiles[CPUProfileType][uid] = profiler;
	this.sendEvent({
		method: 'Profiler.addProfileHeader', 
		params: {header: {title: profiler.title, uid: uid, typeId: CPUProfileType}}
	}, clientId, agent);
};

<|start_filename|>bin/game-server/node_modules/pomelo-admin/sample/client.js<|end_filename|>
var MonitorConsole = require('../lib/consoleService');
var TestModule = require('./module');
var port = 3300;
// var host = '192.168.131.1';
var host = 'localhost';

var opts = {
	id: 'test-server-1',
	type: 'test',
	host: host,
	port: port,
	info: {
		id: 'test-server-1',
		host: host,
		port: 4300
	}
}

var monitorConsole = MonitorConsole.createMonitorConsole(opts);
var module = TestModule();
monitorConsole.register(TestModule.moduleId, module);

monitorConsole.start(function() {

})

<|start_filename|>bin/game-server/node_modules/mqtt/test/helpers/server_process.js<|end_filename|>
var server = require('../../lib/mqtt').createServer(function (client) {
  client.on('connect', function () {
    client.connack({ returnCode : 0 });
  });
}).listen(3000, 'localhost');



<|start_filename|>node_modules/blanket/src/adapters/yui-blanket.js<|end_filename|>
(function() {

    if(!YUI) {
        throw new Exception("YUI does not exist in global namespace!");
    }

    YUI.add('blanket', function (Y) {
        var TestRunner = Y.Test.Runner;

        TestRunner.subscribe(TestRunner.COMPLETE_EVENT,function(data){
            var res = data.results;
            blanket.onTestDone(res.total, res.failed === 0 && (res.passed+res.ignored) === res.total);
        });

        TestRunner.subscribe(TestRunner.BEGIN_EVENT,function(){
            blanket.setupCoverage();
        });

        TestRunner.subscribe(TestRunner.TEST_CASE_COMPLETE_EVENT,function(){
            blanket.onTestsDone();
        });

        TestRunner.subscribe(TestRunner.TEST_SUITE_BEGIN_EVENT,function(){
            blanket.onModuleStart();
        });

        TestRunner.subscribe(TestRunner.TEST_CASE_BEGIN_EVENT,function(){
            blanket.onTestStart();
        });
    },'0.0.1',{
        requires :['test']
    });
})();

<|start_filename|>node_modules/blanket/bower.json<|end_filename|>
{
  "name": "blanket",
  "version": "1.1.7",
  "main": [
    "./dist/qunit/blanket.js"
  ],
  "homepage": "https://github.com/alex-seville/blanket",
  "authors": [
    "Alex-Seville <<EMAIL>>"
  ],
  "description": "blanket.js is a simple code coverage library for javascript",
  "moduleType": [
    "amd",
    "globals",
    "node"
  ],
  "keywords": [
    "code-coverage",
    "coverage",
    "unit",
    "test"
  ],
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ]
}


<|start_filename|>bin/game-server/node_modules/mqtt/test/old/tls.test.js<|end_filename|>
/*global describe, it, before */


var assert = require('assert'),
  should = require('should');

var servers = require('./helpers/server'),
  mqtt = require('..');

var KEY = __dirname + '/helpers/tls-key.pem';
var CERT = __dirname + '/helpers/tls-cert.pem';

var options = {
  keyPath: KEY,
  certPath: CERT,
  rejectUnauthorized : false
};

var PORT = (process.env.PORT || 1883) + 1; //port collides with other tests so +1

describe("SecureClient", function () {
  before(function () {
    this.server = servers.init_secure_server(PORT, KEY, CERT);
  });

  it("should connect", function (done) {
    var client = mqtt.createSecureClient(PORT, 'localhost', options);

    client.on('connect', function (packet) {
      done();
    });
    client.on('error', function (err) {
      should.not.exist(err);
      done();
    });

  });
});


<|start_filename|>bin/game-server/node_modules/mqtt-packet/numbers.js<|end_filename|>
'use strict'

var Buffer = require('safe-buffer').Buffer
var max = 65536
var cache = {}

function generateBuffer (i) {
  var buffer = Buffer.allocUnsafe(2)
  buffer.writeUInt8(i >> 8, 0)
  buffer.writeUInt8(i & 0x00FF, 0 + 1)

  return buffer
}

function generateCache () {
  for (var i = 0; i < max; i++) {
    cache[i] = generateBuffer(i)
  }
}

module.exports = {
  cache: cache,
  generateCache: generateCache,
  generateNumber: generateBuffer
}


<|start_filename|>bin/game-server/node_modules/mqtt/test/auth_utils.js<|end_filename|>
var should = require('should');

var utils = require('../lib/auth_utils');


describe('Authentication Utils', function () {

  it('should extract username from a auth attribute', function(){
    var auth = 'user', opts = {};
    utils.parseAuthOptions(auth, opts);
    opts.should.have.property('username', 'user');
  });

  it('should extract username and password from a auth attribute', function(){
    var auth = 'user:pass', opts = {};
    utils.parseAuthOptions(auth, opts);
    opts.should.have.property('username', 'user');
    opts.should.have.property('password', '<PASSWORD>');
  });

});


<|start_filename|>bin/game-server/node_modules/pomelo/lib/pushSchedulers/buffer.js<|end_filename|>
var utils = require('../util/utils');
var DEFAULT_FLUSH_INTERVAL = 20;

var Service = function(app, opts) {
  if (!(this instanceof Service)) {
    return new Service(app, opts);
  }

  opts = opts || {};
  this.app = app;
  this.flushInterval = opts.flushInterval || DEFAULT_FLUSH_INTERVAL;
  this.sessions = {};   // sid -> msg queue
  this.tid = null;
};

module.exports = Service;

Service.prototype.start = function(cb) {
  this.tid = setInterval(flush.bind(null, this), this.flushInterval);
  process.nextTick(function() {
    utils.invokeCallback(cb);
  });
};

Service.prototype.stop = function(force, cb) {
  if(this.tid) {
    clearInterval(this.tid);
    this.tid = null;
  }
  process.nextTick(function() {
    utils.invokeCallback(cb);
  });
};

Service.prototype.schedule = function(reqId, route, msg, recvs, opts, cb) {
  opts = opts || {};
  if(opts.type === 'broadcast') {
    doBroadcast(this, msg, opts.userOptions);
  } else {
    doBatchPush(this, msg, recvs);
  }

  process.nextTick(function() {
    utils.invokeCallback(cb);
  });
};

var doBroadcast = function(self, msg, opts) {
  var channelService = self.app.get('channelService');
  var sessionService = self.app.get('sessionService');

  if(opts.binded) {
    sessionService.forEachBindedSession(function(session) {
      if(channelService.broadcastFilter &&
         !channelService.broadcastFilter(session, msg, opts.filterParam)) {
        return;
      }

      enqueue(self, session, msg);
    });
  } else {
    sessionService.forEachSession(function(session) {
      if(channelService.broadcastFilter &&
          !channelService.broadcastFilter(session, msg, opts.filterParam)) {
        return;
      }

      enqueue(self, session, msg);
    });
  }
};

var doBatchPush = function(self, msg, recvs) {
  var sessionService = self.app.get('sessionService');
  var session;
  for(var i=0, l=recvs.length; i<l; i++) {
    session = sessionService.get(recvs[i]);
    if(session) {
      enqueue(self, session, msg);
    }
  }
};

var enqueue = function(self, session, msg) {
  var queue = self.sessions[session.id];
  if(!queue) {
    queue = self.sessions[session.id] = [];
    session.once('closed', onClose.bind(null, self));
  }

  queue.push(msg);
};

var onClose = function(self, session) {
  delete self.sessions[session.id];
};

var flush = function(self) {
  var sessionService = self.app.get('sessionService');
  var queue, session;
  for(var sid in self.sessions) {
    session = sessionService.get(sid);
    if(!session) {
      continue;
    }

    queue = self.sessions[sid];
    if(!queue || queue.length === 0) {
      continue;
    }

    session.sendBatch(queue);
    self.sessions[sid] = [];
  }
};


<|start_filename|>bin/game-server/node_modules/pomelo-scheduler/node_modules/log4js/lib/appenders/dateFile.js<|end_filename|>
"use strict";
var streams = require('../streams')
, layouts = require('../layouts')
, path = require('path')
, os = require('os')
, eol = os.EOL || '\n'
, openFiles = [];

//close open files on process exit.
process.on('exit', function() {
  openFiles.forEach(function (file) {
    file.end();
  });
});

/**
 * File appender that rolls files according to a date pattern.
 * @filename base filename.
 * @pattern the format that will be added to the end of filename when rolling,
 *          also used to check when to roll files - defaults to '.yyyy-MM-dd'
 * @layout layout function for log messages - defaults to basicLayout
 */
function appender(filename, pattern, alwaysIncludePattern, layout) {
  layout = layout || layouts.basicLayout;

  var logFile = new streams.DateRollingFileStream(
    filename, 
    pattern, 
    { alwaysIncludePattern: alwaysIncludePattern }
  );
  openFiles.push(logFile);
  
  return function(logEvent) {
    logFile.write(layout(logEvent) + eol, "utf8");
  };

}

function configure(config, options) {
  var layout;
  
  if (config.layout) {
    layout = layouts.layout(config.layout.type, config.layout);
  }
  
  if (!config.alwaysIncludePattern) {
    config.alwaysIncludePattern = false;
  }
  
  if (options && options.cwd && !config.absolute) {
    config.filename = path.join(options.cwd, config.filename);
  }

  return appender(config.filename, config.pattern, config.alwaysIncludePattern, layout);
}

exports.appender = appender;
exports.configure = configure;


<|start_filename|>bin/game-server/node_modules/bops/create.js<|end_filename|>
module.exports = create

var Buffer = require('buffer').Buffer

function create(size) {
  return new Buffer(size)
}


<|start_filename|>bin/game-server/node_modules/mqtt/test/old/mqtt.client.test.js<|end_filename|>
/*global describe, it */

var assert = require('assert'),
  should = require('should');

var mqtt = require('../lib/mqtt'),
  Connection = require('../../lib/connection');

describe.skip("Mqtt.createClient", function () {

  it("should return Connection", function () {
    var client = mqtt.createClient();
    client.should.be.instanceOf(Connection);
  });

  it("should callback error if not able to connect", function (done) {
    //use a non existing IP and default port
    var client = mqtt.createClient('127.0.0.3', false, function (err) {
      should.exist(err);
      err.should.be.instanceOf(Error);
      done();
    });
  });

  it("should callback with client if success", function (done) {
    var client = mqtt.createClient(function (err, c) {
      should.not.exist(err, "make sure you have a running server on the defaultPort");
      should.exist(c);
      c.should.be.instanceOf(Connection);
      done();
    });
  });

});


<|start_filename|>bin/game-server/node_modules/dequeue/lib/index.js<|end_filename|>
exports = module.exports = require("./dequeue")

<|start_filename|>bin/game-server/node_modules/bops/write.js<|end_filename|>
var Buffer = require('buffer').Buffer

var proto = {}
  , rex = /write.+/
  , buildFn

buildFn = function(key) {
  var code = '' +
    'return buf.' + key + '(' + ['a', 'b', 'c'].join(',' ) + ')'

  return new Function(['buf', 'a', 'b', 'c'], code)
}

module.exports = proto

for(var key in Buffer.prototype) {
  if(rex.test(key)) {
    proto[key] = buildFn(key)
  }
}


<|start_filename|>bin/game-server/node_modules/mqtt/test/connection.js<|end_filename|>
/**
 * Testing requires
 */
var should = require('should')
  , Stream = require('./util').TestStream;

/**
 * Units under test
 */
var Connection = require('../lib/connection');


describe('Connection', function() {
  beforeEach(function () {
    var that = this;
    this.stream = new Stream();
    this.conn = this.stream.pipe(new Connection());
  });

  describe('parsing', require('./connection.parse.js'));
  describe('transmission', require('./connection.transmit.js'));
  describe('miscellaneous', function() {
    it('should reset packet state before firing callbacks', function(done) {
      var fixture = [
        16, 18, // Header 
        0, 6, // Protocol id length
        77, 81, 73, 115, 100, 112, // Protocol id
        3, // Protocol version
        0, // Connect flags 
        0, 30, // Keepalive 
        0, 4, //Client id length 
        116, 101, 115, 116 // Client id
      ];

      this.stream.write(new Buffer(fixture));
      this.conn.on('connect', function(packet) {
        this.packet.should.eql({});
        done();
      });
    });

    describe('set encoding', function () {
      it('should emit a buffer as payload', function(done) {
        var expected = {
          cmd: "publish",
          retain: false,
          qos: 0,
          dup: false,
          length: 10,
          topic: "test",
          payload: "test"
        };

        var fixture = [
          48, 10, // Header 
          0, 4, // Topic length
          116, 101, 115, 116, // Topic (test)
          116, 101, 115, 116 // Payload (test)
        ];

        this.conn.setPacketEncoding('binary');

        this.stream.write(new Buffer(fixture));

        this.conn.once('publish', function(packet) {
          Buffer.isBuffer(packet.payload).should.be.ok
          done();
        });
      });
    });
    it('should emit a string as payload', function(done) {
      this.conn.setPacketEncoding('utf8');
      var expected = {
        cmd: "publish",
        retain: false,
        qos: 0,
        dup: false,
        length: 10,
        topic: "test",
        payload: "test"
      };

      var fixture = [
        48, 10, // Header
        0, 4, // Topic length
        116, 101, 115, 116, // Topic (test)
        116, 101, 115, 116 // Payload (test)
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('publish', function(packet) {
        packet.payload.should.equal('test');
        done();
      });
    });
  });
});


<|start_filename|>bin/game-server/node_modules/bops/test/create.js<|end_filename|>
var test = require('tape')
  , binary = require('../index')

test('create works as expected', function(assert) {
  var len = Math.random() * 0xFF & 0xFF
  len += 1
  assert.equal(binary.create(len).length, len)
  assert.end()
})


<|start_filename|>bin/game-server/node_modules/bops/subarray.js<|end_filename|>
module.exports = function(source, from, to) {
  return arguments.length === 2 ?
    source.slice(from) :
    source.slice(from, to)
}


<|start_filename|>bin/game-server/node_modules/stream-pkg/Makefile<|end_filename|>
MOCHA_OPTS=
TESTS = test/*
REPORTER = dot
TIMEOUT = 5000

test:
	@./node_modules/.bin/mocha \
		--reporter $(REPORTER) --timeout $(TIMEOUT) $(TESTS) \
		$(MOCHA_OPTS)

test-cov: lib-cov
	@STREAM_PKG_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html

lib-cov:
	@jscoverage lib lib-cov

clean:
	rm -f coverage.html
	rm -fr lib-cov

.PHONY: test clean

<|start_filename|>bin/game-server/node_modules/pomelo/test/remote/channelRemote.js<|end_filename|>
var should = require('should');
var pomelo = require('../../');
var remote = require('../../lib/common/remote/frontend/channelRemote');
var SessionService = require('../../lib/common/service/sessionService');
var ChannelService = require('../../lib/common/service/channelService');
var countDownLatch = require('../../lib/util/countDownLatch');
var MockChannelManager = require('../manager/mockChannelManager');


var mockBase = process.cwd() + '/test';

var WAIT_TIME = 200;

describe('channel remote test', function() {
  describe('#pushMessage', function() {
    it('should push message the the specified clients', function(done) {
      var sids = [1, 2, 3, 4, 5, 6];
      var uids = [11, 12, 13];
      var frontendId = 'frontend-server-id';
      var mockRoute = 'mock-route-string';
      var mockMsg = {msg: 'some test msg'};
      var invokeCount = 0;
      var invokeUids = [];

      var sessionService = new SessionService();
      sessionService.sendMessageByUid = function(uid, msg) {
        mockMsg.should.eql(msg);
        invokeCount++;
        invokeUids.push(uid);
      };

      var session;
      for(var i=0, l=sids.length, j=0; i<l; i++) {
        session = sessionService.create(sids[i], frontendId);
        if(i % 2) {
          sessionService.bind(session.id, uids[j]);
          j++;
        }
      }

      var app = pomelo.createApp({base: mockBase});
      app.components.__connector__ = {
        send: function(reqId, route, msg, recvs, opts, cb) {
          app.components.__pushScheduler__.schedule(reqId, route, msg, recvs, opts, cb);
        }
      };
      app.components.__connector__.connector = {};
      app.components.__pushScheduler__ = {
        schedule: function(reqId, route, msg, recvs, opts, cb) {
          mockMsg.should.eql(msg);
          invokeCount += recvs.length;
          var sess;
          for(var i=0; i<recvs.length; i++) {
            sess = sessionService.get(recvs[i]);
            if(sess) {
              invokeUids.push(sess.uid);
            }
          }
          cb();
        }
      };
      app.set('sessionService', sessionService);
      var channelRemote = remote(app);
      channelRemote.pushMessage(mockRoute, mockMsg, uids, {isPush: true}, function() {
        invokeCount.should.equal(uids.length);
        invokeUids.length.should.equal(uids.length);
        for(var i=0, l=uids.length; i<l; i++) {
          invokeUids.should.include(uids[i]);
        }
        done();
      });
    });
  });

  describe('#broadcast', function() {
    it('should broadcast to all the client connected', function(done) {
      var sids = [1, 2, 3, 4, 5];
      var uids = [11, 12, 13, 14, 15];
      var frontendId = 'frontend-server-id';
      var mockRoute = 'mock-route-string';
      var mockMsg = {msg: 'some test msg'};
      var invokeCount = 0;

      var sessionService = new SessionService();
      var channelService = new ChannelService();

      var session;
      for(var i=0, l=sids.length; i<l; i++) {
        session = sessionService.create(sids[i], frontendId);
        if(i % 2) {
          session.bind(uids[i]);
        }
      }

      var app = pomelo.createApp({base: mockBase});
      app.components.__connector__ = {
        send: function(reqId, route, msg, recvs, opts, cb) {
          app.components.__pushScheduler__.schedule(reqId, route, msg, recvs, opts, cb);
        }
      };
      app.components.__connector__.connector = {};
      app.components.__pushScheduler__ = {
        schedule: function(reqId, route, msg, recvs, opts, cb) {
          invokeCount++;
          mockMsg.should.eql(msg);
          should.exist(opts);
          should.equal(opts.type, 'broadcast');
          cb();
        }
      };
      app.set('sessionService', sessionService);
      app.set('channelService', channelService);
      var channelRemote = remote(app);
      channelRemote.broadcast(mockRoute, mockMsg, {type: 'broadcast'}, function() {
        invokeCount.should.equal(1);
        done();
      });
    });

    it('should broadcast to all the binded client connected', function(done) {
      var sids = [1, 2, 3, 4, 5, 6];
      var uids = [11, 12, 13];
      var frontendId = 'frontend-server-id';
      var mockRoute = 'mock-route-string';
      var mockMsg = {msg: 'some test msg'};
      var invokeCount = 0;
      var invokeUids = [];

      var sessionService = new SessionService();
      var channelService = new ChannelService();

      var session;
      for(var i=0, l=sids.length, j=0; i<l; i++) {
        session = sessionService.create(sids[i], frontendId);
        if(i % 2) {
          session.bind(uids[j]);
          j++;
        }
      }

      var app = pomelo.createApp({base: mockBase});
      app.components.__connector__ = {
        send: function(reqId, route, msg, recvs, opts, cb) {
          app.components.__pushScheduler__.schedule(reqId, route, msg, recvs, opts, cb);
        }
      };
      app.components.__connector__.connector = {};
      app.components.__pushScheduler__ = {
        schedule: function(reqId, route, msg, recvs, opts, cb) {
          invokeCount++;
          mockMsg.should.eql(msg);
          should.exist(opts);
          should.equal(opts.type, 'broadcast');
          true.should.equal(opts.userOptions.binded);
          cb();
        }
      };
      app.set('sessionService', sessionService);
      app.set('channelService', channelService);
      var channelRemote = remote(app);
      channelRemote.broadcast(mockRoute, mockMsg, {type: 'broadcast', userOptions: {binded: true}}, function() {
        invokeCount.should.equal(1);
        done();
      });
    });
  });
});


<|start_filename|>bin/game-server/node_modules/pomelo-protobuf/test/stringBufferTest.js<|end_filename|>

function joinTest(num){

	var arr = [];
	for(var i = 0; i < num; i++)
		arr.push(i + '');

	var start = Date.now();
	var str = '';

	for(var i = 0; i < num; i++){
		str += arr[i];
	}

	var end = Date.now();
	var time1 = end - start;

	start = Date.now();
	var arr = [];
	for(var i = 0; i < num; i++){
		arr.push(arr[i]);
	}
	var str1 = arr.join();
	end = Date.now();
	var time2 = end - start;

	console.log('test count : %j, \ncost 1 : %j, \ncost 2 : %j', num, time1, time2);
}

joinTest(100);
joinTest(50000);
joinTest(100000);
joinTest(200000);
//joinTest(500000);

<|start_filename|>bin/game-server/node_modules/bearcat-buffer/test/bufferTest.js<|end_filename|>
var OutBuffer = require('../lib/outBuffer');
var InBuffer = require('../lib/inBuffer');

var outBuffer = new OutBuffer();

var case1 = [1, '1', 'aaa', 1.2, {
	a: 1
}, new Buffer('aaa'), -1, 0, null, NaN, undefined];

var case2 = [-100];

var o = {
	id: 4,
	frontendId: 'connector-server-1',
	uid: 210073,
	settings: {}
};

var case3 = [100, 'aaa', o];

var case4 = ["user", 220062, {
	"oid": 210087,
	"name": "",
	"gender": 1,
	"create_tm": 0,
	"create_ip": "127.0.0.1",
	"honor": 0,
	"gold_cur": 0,
	"gold_total": 0,
	"online_tm": 0,
	"timestamp": 0,
	"level": 1,
	"scene": "{\"userForce\":1100024}",
	"id": 220062
}];

var case5 = [null, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 174, 1111111111111111]];

var case6 = 0;

var value = case5;

var num = 1;
for (var i = 0; i < num; i++) {
	outBuffer.writeObject(value);
	// outBuffer.writeObject(case1);

	var buf = outBuffer.getBuffer();
	console.log(buf)
	console.log(buf.length);

	var inBuffer = new InBuffer(buf);
	var obj = inBuffer.readObject();

	console.log(obj)
}

<|start_filename|>bin/game-server/node_modules/stream-pkg/lib/composer.js<|end_filename|>
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var DEFAULT_MAX_LENGTH = -1;  // default max package size: unlimited
var LEFT_SHIFT_BITS = 1 << 7;

var ST_LENGTH = 1;  // state that we should read length
var ST_DATA = 2;  // state that we should read data
var ST_ERROR = 3;  // state that something wrong has happened

var Composer = function(opts) {
  EventEmitter.call(this);

  opts = opts || {};
  this.maxLength = opts.maxLength || DEFAULT_MAX_LENGTH;

  this.offset = 0;
  this.left = 0;
  this.length = 0;
  this.buf = null;

  this.state = ST_LENGTH;
};

module.exports = Composer;

util.inherits(Composer, EventEmitter);

var pro = Composer.prototype;

/**
 * Compose data into package.
 *
 * @param  {String|Buffer}  data data that would be composed.
 * @return {Buffer}        compose result in Buffer.
 */
pro.compose = function(data) {
  if(typeof data === 'string') {
    data = new Buffer(data, 'utf-8');
  }

  if(!(data instanceof Buffer)) {
    throw new Error('data should be an instance of String or Buffer');
  }

  if(data.length === 0) {
    throw new Error('data should not be empty.');
  }

  if(this.maxLength > 0 && data.length > this.maxLength) {
    throw new Error('data length exceeds the limitation:' + this.maxLength);
  }

  var lsize = calLengthSize(data.length);
  var buf = new Buffer(lsize + data.length);
  fillLength(buf, data.length, lsize);
  data.copy(buf, lsize);

  return buf;
};

/**
 * Feed data into composer. It would emit the package by an event when the package finished.
 *
 * @param  {Buffer} data   next chunk of data read from stream.
 * @param  {Number} offset (Optional) offset index of the data Buffer. 0 by default.
 * @param  {Number} end    (Optional) end index (not includ) of the data Buffer. data.lenght by default.
 * @return {Void}
 */
pro.feed = function(data, offset, end) {
  if(!data) {
    return;
  }

  if(this.state === ST_ERROR) {
    throw new Error('compose in error state, reset it first');
  }

  offset = offset || 0;
  end = end || data.length;
  while(offset < end) {
    if(this.state === ST_LENGTH) {
      offset = this._readLength(data, offset, end);
    }

    if(this.state === ST_DATA) {
      offset = this._readData(data, offset, end);
    }

    if(this.state === ST_ERROR) {
      break;
    }
  }
};

/**
 * Reset composer to the init status.
 */
pro.reset = function() {
  this.state = ST_LENGTH;
  this.buf = null;
  this.length = 0;
  this.offset = 0;
  this.left = 0;
};

// read length part of package
pro._readLength = function(data, offset, end) {
  var b, i, length = this.length, finish;
  for(i=0; i<end; i++) {
    b = data.readUInt8(i + offset);
    length *= LEFT_SHIFT_BITS;    // left shift only within 32 bits
    length += (b & 0x7f);

    if(this.maxLength > 0 && length > this.maxLength) {
      this.state = ST_ERROR;
      this.emit('length_limit', this, data, offset);
      return -1;
    }

    if(!(b & 0x80)) {
      i++;
      finish = true;
      break;
    }
  }

  this.length = length;

  if(finish) {
    this.state = ST_DATA;
    this.offset = 0;
    this.left = this.length;
    this.buf = new Buffer(this.length);
  }
  return i + offset;
};

// read data part of package
pro._readData = function(data, offset, end) {
  var left = end - offset;
  var size = Math.min(left, this.left);
  data.copy(this.buf, this.offset, offset, offset + size);
  this.left -= size;
  this.offset += size;

  if(this.left === 0) {
    var buf = this.buf;
    this.reset();
    this.emit('data', buf);
  }

  return offset + size;
};

var calLengthSize = function(length) {
  var res = 0;
  while(length > 0) {
    length >>>= 7;
    res++;
  }

  return res;
};

var fillLength = function(buf, data, size) {
  var offset = size - 1, b;
  for(; offset >= 0; offset--) {
    b = data % LEFT_SHIFT_BITS;
    if(offset < size - 1) {
      b |= 0x80;
    }
    buf.writeUInt8(b, offset);
    data >>>= 7;
  }
};

<|start_filename|>bin/game-server/node_modules/pomelo-admin/sample/server.js<|end_filename|>
var MasterConsole = require('../lib/consoleService');
var TestModule = require('./module');
var port = 3300;
var host = 'localhost';

var opts = {
	port: port,
	master: true
}

var masterConsole = MasterConsole.createMasterConsole(opts);
var module = TestModule();
masterConsole.register(TestModule.moduleId, module);

masterConsole.start(function() {

})

<|start_filename|>bin/game-server/node_modules/base64-js/test/runner.js<|end_filename|>
(function () {
	'use strict';

	var b64 = require('../lib/b64'),
		checks = [
			'a',
			'aa',
			'aaa',
			'hi',
			'hi!',
			'hi!!',
			'sup',
			'sup?',
			'sup?!'
		],
		res;

	res = checks.some(function (check) {
		var b64Str,
			arr,
			arr2,
			str,
			i,
			l;

		arr2 = [];
		for (i = 0, l = check.length; i < l; i += 1) {
			arr2.push(check.charCodeAt(i));
		}
		b64Str = b64.fromByteArray(arr2);

		arr = b64.toByteArray(b64Str);
		arr2 = [];
		for (i = 0, l = arr.length; i < l; i += 1) {
			arr2.push(String.fromCharCode(arr[i]));
		}
		str = arr2.join('');
		if (check !== str) {
			console.log('Fail:', check);
			console.log('Base64:', b64Str);
			return true;
		}
	});

	if (res) {
		console.log('Test failed');
	} else {
		console.log('All tests passed!');
	}
}());


<|start_filename|>node_modules/blanket/src/qunit/qunit.js<|end_filename|>
(function(){
if (typeof QUnit !== 'undefined'){
    //check to make sure requirejs is completed before we start the test runner
    var allLoaded = function() {
        return window.QUnit.config.queue.length > 0 && blanket.noConflict().requireFilesLoaded();
    };

    if (!QUnit.config.urlConfig[0].tooltip){
        //older versions we run coverage automatically
        //and we change how events are binded
        QUnit.begin=function(){
            blanket.noConflict().setupCoverage();
        };
        
        QUnit.done=function(failures, total) {
            blanket.noConflict().onTestsDone();
        };
        QUnit.moduleStart=function( details ) {
            blanket.noConflict().onModuleStart();
        };
        QUnit.testStart=function( details ) {
            blanket.noConflict().onTestStart();
        };
        QUnit.testDone=function( details ) {
            blanket.noConflict().onTestDone(details.total,details.passed);
        };
        blanket.beforeStartTestRunner({
            condition: allLoaded,
            callback: QUnit.start
        });
    }else{
        QUnit.config.urlConfig.push({
            id: "coverage",
            label: "Enable coverage",
            tooltip: "Enable code coverage."
        });
    
        if ( QUnit.urlParams.coverage || blanket.options("autoStart") ) {
            QUnit.begin(function(){
                blanket.noConflict().setupCoverage();
            });
            
            QUnit.done(function(failures, total) {
                blanket.noConflict().onTestsDone();
            });
            QUnit.moduleStart(function( details ) {
                blanket.noConflict().onModuleStart();
            });
            QUnit.testStart(function( details ) {
                blanket.noConflict().onTestStart();
            });
            QUnit.testDone(function( details ) {
                blanket.noConflict().onTestDone(details.total,details.passed);
            });
            blanket.noConflict().beforeStartTestRunner({
                condition: allLoaded,
                callback: function(){
                    if (!(blanket.options("existingRequireJS") && !blanket.options("autoStart"))){
                        QUnit.start();
                    }
                }
            });
        }else{
            if (blanket.options("existingRequireJS")){ requirejs.load = _blanket.utils.oldloader; }
            blanket.noConflict().beforeStartTestRunner({
                condition: allLoaded,
                callback: function(){
                    if (!(blanket.options("existingRequireJS") && !blanket.options("autoStart"))){
                        QUnit.start();
                    }
                },
                coverage:false
            });
        }
    }
}
})();

<|start_filename|>bin/game-server/node_modules/bops/from.js<|end_filename|>
var Buffer = require('buffer').Buffer

module.exports = function(source, encoding) {
  return new Buffer(source, encoding)
}


<|start_filename|>bin/game-server/node_modules/mqtt/lib/client.js<|end_filename|>
/**
 * Module dependencies
 */
var Connection = require('./connection')
  , events = require('events')
  , util = require('util')
  , crypto = require('crypto');

/**
 * Default options
 */
var defaultConnectOptions = {
  keepalive: 60,
  protocolId: 'MQIsdp',
  protocolVersion: 3,
  reconnectPeriod: 1000,
  clean: true,
  encoding: 'utf8'
};

var defaultId = function() {
  return 'mqttjs_' + crypto.randomBytes(8).toString('hex');
};

var nop = function(){};

/**
 * MqttClient constructor
 *
 * @param {Stream} stream - stream
 * @param {Object} [options] - connection options
 * (see Connection#connect)
 */
var MqttClient = module.exports =
function MqttClient(streamBuilder, options) {
  var that = this;

  if (!(this instanceof MqttClient)) {
    return new MqttClient(streamBuilder, options);
  }

  this.options = options || {};

  // Defaults
  for(var k in defaultConnectOptions) {
    if ('undefined' === typeof this.options[k]) {
      this.options[k] = defaultConnectOptions[k];
    } else {
      this.options[k] = options[k];
    }
  }

  this.options.clientId = this.options.clientId || defaultId();

  this.streamBuilder = streamBuilder;

  this._setupStream();

  // Ping timer, setup in _setupPingTimer
  this.pingTimer = null;
  // Is the client connected?
  this.connected = false;
  // Packet queue
  this.queue = [];
  // Are we intentionally disconnecting?
  this.disconnecting = false;
  // Reconnect timer
  this.reconnectTimer = null;
  // MessageIDs starting with 1
  this.nextId = Math.floor(Math.random() * 65535);

  // Inflight messages
  this.inflight = {
    puback: {},
    pubrec: {},
    pubcomp: {},
    suback: {},
    unsuback: {}
  };

  // Incoming messages
  this.incoming = {
    pubrel: {}
  };

  // Mark connected on connect
  this.on('connect', function() {
    this.connected = true;
  });

  // Mark disconnected on stream close
  this.on('close', function() {
    this.connected = false;
  });

  // Setup ping timer
  this.on('connect', this._setupPingTimer);

  // Send queued packets
  this.on('connect', function() {
    var queue = that.queue
      , length = queue.length;

    for (var i = 0; i < length; i += 1) {
      that._sendPacket(
        queue[i].type,
        queue[i].packet,
        queue[i].cb
      );
    }
    that.queue = [];
  });


  // Clear ping timer
  this.on('close', function () {
    if (that.pingTimer !== null) {
      clearInterval(that.pingTimer);
      that.pingTimer = null;
    }
  });

  // Setup reconnect timer on disconnect
  this.on('close', function() {
    that._setupReconnect();
  });

  events.EventEmitter.call(this);
};
util.inherits(MqttClient, events.EventEmitter);

/**
 * setup the event handlers in the inner stream.
 *
 * @api private
 */
MqttClient.prototype._setupStream = function() {
  var that = this;

  this._clearReconnect();

  this.stream = this.streamBuilder();

  // MqttConnection
  this.conn = this.stream.pipe(new Connection());

  // Set encoding of incoming publish payloads
  if (this.options.encoding) {
    this.conn.setPacketEncoding(this.options.encoding);
  }

  // Suppress connection errors
  this.stream.on('error', nop)

  // Echo stream close
  this.stream.on('close', this.emit.bind(this, 'close'));

  // Send a connect packet on stream connect
  this.stream.on('connect', function () {
    that.conn.connect(that.options);
  });

  this.stream.on('secureConnect', function () {
    that.conn.connect(that.options);
  });

  // Handle incoming publish
  this.conn.on('publish', function (packet) {
    that._handlePublish(packet);
  });

  // one single handleAck function
  var handleAck = function (packet) {
    that._handleAck(packet);
  };

  // Handle incoming acks
  var acks = ['puback', 'pubrec', 'pubcomp', 'suback', 'unsuback'];

  acks.forEach(function (event) {
    that.conn.on(event, handleAck);
  });

  // Handle outgoing acks
  this.conn.on('pubrel', function (packet) {
    that._handlePubrel(packet);
  });

  // Handle connack
  this.conn.on('connack', function (packet) {
    that._handleConnack(packet);
  });

  // Handle pingresp
  this.conn.on('pingresp', function (packet) {
    that._handlePingresp(packet);
  });

  // Echo connection errors
  this.conn.on('error', this.emit.bind(this, 'error'));
};

/**
 * publish - publish <message> to <topic>
 *
 * @param {String} topic - topic to publish to
 * @param {String, Buffer} message - message to publish
 * @param {Object} [opts] - publish options, includes:
 *    {Number} qos - qos level to publish on
 *    {Boolean} retain - whether or not to retain the message
 * @param {Function} [callback] - function(err){}
 *    called when publish succeeds or fails
 * @returns {MqttClient} this - for chaining
 * @api public
 *
 * @example client.publish('topic', 'message');
 * @example
 *     client.publish('topic', 'message', {qos: 1, retain: true});
 * @example client.publish('topic', 'message', console.log);
 */
MqttClient.prototype.publish =
function(topic, message, opts, callback) {
  var packet;

  // .publish(topic, payload, cb);
  if ('function' === typeof opts) {
    callback = opts;
    opts = null;
  }

  // Default opts
  if(!opts) opts = {qos: 0, retain: false};

  callback = callback || nop;

  packet = {
    topic: topic,
    payload: message,
    qos: opts.qos,
    retain: opts.retain,
    messageId: this._nextId()
  };

  this._sendPacket('publish', packet, function () {
    switch (opts.qos) {
      case 0:
        // Immediately callback
        callback();
        break;
      case 1:
        // Add to puback callbacks
        this.inflight.puback[packet.messageId] = callback;
        break;
      case 2:
        // Add to pubrec callbacks
        this.inflight.pubrec[packet.messageId] = callback;
        break;
      default:
        break;
    }
  });

  return this;
};

/**
 * subscribe - subscribe to <topic>
 *
 * @param {String, Array} topic - topic(s) to subscribe to
 * @param {Object} [opts] - subscription options, includes:
 *    {Number} qos - subscribe qos level
 * @param {Function} [callback] - function(err, granted){} where:
 *    {Error} err - subscription error (none at the moment!)
 *    {Array} granted - array of {topic: 't', qos: 0}
 * @returns {MqttClient} this - for chaining
 * @api public
 * @example client.subscribe('topic');
 * @example client.subscribe('topic', {qos: 1});
 * @example client.subscribe('topic', console.log);
 */
MqttClient.prototype.subscribe =
function(topic, opts, callback) {
  var subs = [];

  // .subscribe('topic', callback)
  if ('function' === typeof opts) {
    callback = opts;
    opts = null;
  }

  // Defaults
  opts = opts || {qos: 0};
  callback = callback || nop;

  if ('string' === typeof topic) {
    subs.push({topic: topic, qos: opts.qos});
  } else if ('object' === typeof topic) {
    // TODO: harder array check
    for (var i = 0; i < topic.length; i += 1) {
      var t = topic[i];
      subs.push({topic: t, qos: opts.qos});
    }
  } else {
    // Error!
  }

  var packet = {
    subscriptions: subs,
    qos: 1,
    retain: false,
    dup: false,
    messageId: this._nextId()
  };

  this._sendPacket('subscribe', packet, function () {
    this.inflight.suback[packet.messageId] = {
      callback: callback,
      packet: packet
    };
  });

  return this;
};

/**
 * unsubscribe - unsubscribe from topic(s)
 *
 * @param {String, Array} topic - topics to unsubscribe from
 * @param {Function} [callback] - callback fired on unsuback
 * @returns {MqttClient} this - for chaining
 * @api public
 * @example client.unsubscribe('topic');
 * @example client.unsubscribe('topic', console.log);
 */
MqttClient.prototype.unsubscribe = function(topic, callback) {
  callback = callback || nop;
  var packet = {messageId: this._nextId()};

  if ('string' === typeof topic) {
    packet.unsubscriptions = [topic];
  } else if ('object' === typeof topic && topic.length) {
    packet.unsubscriptions = topic;
  }

  this._sendPacket('unsubscribe', packet, function () {
    this.inflight.unsuback[packet.messageId] = callback;
  });

  return this;
};

/**
 * end - close connection
 *
 * @returns {MqttClient} this - for chaining
 * @api public
 */
MqttClient.prototype.end = function() {
  this.disconnecting = true;
  if (!this.connected) {
    this.once('connect', this._cleanUp.bind(this));
  } else {
    this._cleanUp();
  }

  return this;
};

/**
 * _reconnect - implement reconnection
 * @api privateish
 */
MqttClient.prototype._reconnect = function() {

  this.emit('reconnect');

  if (this.conn) {
    this.conn.removeAllListeners();
    delete this.conn;
  }

  this._setupStream();
};

/**
 * _setupReconnect - setup reconnect timer
 */
MqttClient.prototype._setupReconnect = function() {
  var that = this;

  if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
    this.emit('offline');
    that.reconnectTimer = setInterval(function () {
      that._reconnect();
    }, that.options.reconnectPeriod);
  }
};

/**
 * _clearReconnect - clear the reconnect timer
 */
MqttClient.prototype._clearReconnect = function() {
  if (this.reconnectTimer) {
    clearInterval(this.reconnectTimer);
    this.reconnectTimer = false;
  }
};


/**
 * _cleanUp - clean up on connection end
 * @api private
 */
MqttClient.prototype._cleanUp = function(forced) {
  this.conn.disconnect();
  if (forced) {
    this.stream.destroy();
  } else {
    this.stream.end();
  }
  if (this.pingTimer !== null) {
    clearInterval(this.pingTimer);
    this.pingTimer = null;
  }
};

/**
 * _sendPacket - send or queue a packet
 * @param {String} type - packet type (see `protocol`)
 * @param {Object} packet - packet options
 * @param {Function} cb - callback when the packet is sent
 * @api private
 */

MqttClient.prototype._sendPacket = function(type, packet, cb) {
  if (this.connected) {
    this.conn[type](packet);
    if (cb) cb.call(this);
  } else {
    this.queue.push({type: type, packet: packet, cb: cb});
  }
};

/**
 * _setupPingTimer - setup the ping timer
 *
 * @api private
 */
MqttClient.prototype._setupPingTimer = function() {
  var that = this;

  if (!this.pingTimer && this.options.keepalive) {
    this.pingResp = true;
    this.pingTimer = setInterval(function () {
        that._checkPing();
    }, this.options.keepalive * 600);
  }
};

/**
 * _checkPing - check if a pingresp has come back, and ping the server again
 *
 * @api private
 */
MqttClient.prototype._checkPing = function () {
  if (this.pingResp) {
    this.pingResp = false;
    this.conn.pingreq();
  } else {
    // do a forced cleanup since socket will be in bad shape
    this._cleanUp(true);
  }
};

/**
 * _handlePingresp - handle a pingresp
 *
 * @api private
 */
MqttClient.prototype._handlePingresp = function () {
  this.pingResp = true;
};

/**
 * _handleConnack
 *
 * @param {Object} packet
 * @api private
 */

MqttClient.prototype._handleConnack = function(packet) {
  var rc = packet.returnCode;

  // TODO: move to protocol
  var errors = [
    '',
    'Unacceptable protocol version',
    'Identifier rejected',
    'Server unavailable',
    'Bad username or password',
    'Not authorized'
  ];

  if (rc === 0) {
    this.emit('connect');
  } else if (rc > 0) {
    this.emit('error',
        new Error('Connection refused: ' + errors[rc]));
  }
};

/**
 * _handlePublish
 *
 * @param {Object} packet
 * @api private
 */

MqttClient.prototype._handlePublish = function(packet) {
  var topic = packet.topic
    , message = packet.payload
    , qos = packet.qos
    , mid = packet.messageId
    , retain = packet.retain;

  switch (qos) {
    case 0:
      this.emit('message', topic, message, packet);
      break;
    case 1:
      this.conn.puback({messageId: mid});
      this.emit('message', topic, message, packet);
      break;
    case 2:
      this.conn.pubrec({messageId: mid});
      this.incoming.pubrel[mid] = packet;
      break;
    default:
      break;
  }
};

/**
 * _handleAck
 *
 * @param {Object} packet
 * @api private
 */

MqttClient.prototype._handleAck = function(packet) {
  var mid = packet.messageId
    , type = packet.cmd
    , cb = this.inflight[type][mid];

  if (!cb) {
    // Server sent an ack in error, ignore it.
    return;
  }

  // Process
  switch (type) {
    case 'puback':
      // Callback - we're done
      cb();
      break;
    case 'pubrec':
      // Pubrel and add to pubcomp list
      this.conn.pubrel(packet);
      this.inflight.pubcomp[mid] = cb;
      break;
    case 'pubcomp':
      // Callback - we're done
      cb();
      break;
    case 'suback':
      // TODO: RIDICULOUS HACK, PLEASE FIX
      var origSubs = cb.packet.subscriptions
        , cb = cb.callback
        , granted = packet.granted;

      for (var i = 0; i < granted.length; i += 1) {
        origSubs[i].qos = granted[i];
      }
      cb(null, origSubs);
      break;
    case 'unsuback':
      cb();
      break;
    default:
      // code
  }

  // Remove from queue
  delete this.inflight[type][mid];
};

/**
 * _handlePubrel
 *
 * @param {Object} packet
 * @api private
 */

MqttClient.prototype._handlePubrel = function(packet) {
  var mid = packet.messageId
    , pub = this.incoming.pubrel[mid];

  if (!pub) this.emit('error', new Error('Unknown message id'));
  this.conn.pubcomp({messageId: mid});
  this.emit('message', pub.topic, pub.payload, pub);
};

/**
 * _nextId
 */
MqttClient.prototype._nextId = function() {
  var id = this.nextId++;
  // Ensure 16 bit unsigned int:
  if (id === 65535) {
    this.nextId = 1;
  }
  return id;
};


<|start_filename|>bin/game-server/node_modules/pomelo-protobuf/lib/constant.js<|end_filename|>
module.exports = {
	TYPES : {
		uInt32 : 0,
		sInt32 : 0,
		int32 : 0,
		double : 1,
		string : 2,
		message : 2,
		float : 5
	}
}

<|start_filename|>bin/game-server/node_modules/pomelo-loader/test/mock-remote/area/whoAmIService.js<|end_filename|>
/**
 * Mock remote service
 */
module.exports = function(app) {
	return {
		doService: function(cb) {
			cb(null, app.id);
		}, 
		name: 'whoAmIRemote'
	};
};

<|start_filename|>bin/game-server/node_modules/bops/typedarray/mapped.js<|end_filename|>
var proto
  , map

module.exports = proto = {}

map = typeof WeakMap === 'undefined' ? null : new WeakMap

proto.get = !map ? no_weakmap_get : get

function no_weakmap_get(target) {
  return new DataView(target.buffer, 0)
}

function get(target) {
  var out = map.get(target.buffer)
  if(!out) {
    map.set(target.buffer, out = new DataView(target.buffer, 0))
  }
  return out
}


<|start_filename|>bin/game-server/node_modules/pomelo-protobuf/test/client/encoderTest.js<|end_filename|>
var should = require('should');
var encoder = require('../../lib/client/protobuf').codec;

describe('client encoder test', function(){
	describe('float test for 10000 times', function(){
		for(var i = 0; i < 10000; i++){
			var float = Math.random();

			var bytes = encoder.encodeFloat(float);
			var result = encoder.decodeFloat(bytes, 0);

			var diff = Math.abs(float-result);
			//console.log('float : %j, result : %j, diff : %j', float, result, diff);
			diff.should.below(0.0000001);

		}
	});

	describe('double test for 10000 times', function(){
		for(var i = 0; i < 10000; i++){
			var double = Math.random();

			var bytes = encoder.encodeDouble(double);
			var result = encoder.decodeDouble(bytes, 0);

			double.should.equal(result);
		}
	});

	describe('utf8 encode & decode test, use 1000 * 1000 test case', function(){
		var num = 1000;
		var limit = 1000;
		for(var i = 0; i < num; i++){
			var strLength = Math.ceil(Math.random()*limit);
			var arr = [];
			for(var j = 0; j < strLength; j++){
				arr.push(Math.floor(Math.random()*65536));
			}
			//arr = [ 58452, 127, 38641, 25796, 20652, 19237 ];

			var str = String.fromCharCode.apply(null, arr);

			//console.log('old arr : %j', arr);

			var length = encoder.byteLength(str);
			var buffer = new ArrayBuffer(length);
			var bytes = new Uint8Array(buffer);

			var offset = encoder.encodeStr(bytes, 0, str);
			//console.log('encode over, offset : %j, length : %j, str length : %j', offset, length, str.length);
			//console.log(bytes);
			length.should.equal.offset;

			var result = encoder.decodeStr(bytes, 0, length);


			str.length.should.equal(result.length);
			var flag = true;
			for(var m = 0; m < str.length; m++){
				if(str.charCodeAt(m) != result.charCodeAt(m)){
					console.log('error ! origin : %j, result : %j, code : %j, code 1 : %j', str, result, str.charCodeAt(m), result.charCodeAt(m));
					console.log(arr);
					flag = false;
				}
			}

			if(!flag)return;
			//console.log('str : %j, bytes : %j, result : %j', str, bytes, result);
		}
	});

	describe('string decode speed test', function(){
		var array = [];
		var length = 100000;
		for(var i = 0; i < length; i++,array.push(0));
		var start = Date.now();
		var str = '';
		for(var j = 0; j < length; ){
			str += String.fromCharCode.apply(null, array.slice(j, j+10000));
			j += 10000;
		}
		//var str = String.fromCharCode.apply(null, array);
		var end = Date.now();

		console.log('cost time with fromCharCode method : %j, length : %j', end-start, str.length);

		start = Date.now();
		str = '';
		for(var i = 0; i < length; i++){
			str += array[i];
		}
		end = Date.now();

		console.log('cost time by add string: %j, length : %j', end-start, str.length);
	});
});

<|start_filename|>bin/game-server/node_modules/mqtt/examples/client/simple-subscribe.js<|end_filename|>
var mqtt = require('../..')
  , client = mqtt.createClient();

client.subscribe('presence');
client.on('message', function(topic, message) {
  console.log(message);
});


<|start_filename|>bin/game-server/node_modules/pomelo/gruntfile.js<|end_filename|>
'use strict';

module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');

  var src = ['test/manager/taskManager.js', 'test/filters/*.js', 
  'test/remote/*.js', 'test/service/*.js', 'test/modules/*.js', 'test/util/*.js', 'test/*.js'];

  // Project configuration.
  grunt.initConfig({
    mochaTest: {
       test: {
        options: {
          reporter: 'spec',
          timeout: 5000,
          require: 'coverage/blanket'
        },
        src: src
      },
      coverage: {
        options: {
          reporter: 'html-cov',
          quiet: true,
          captureFile: 'coverage.html'
        },
        src: src
      }
    },
    clean: {
      "coverage.html" : {
        src: ['coverage.html']
      }
    },
    jshint: {
      all: ['lib/*']
    }
  });

  // Default task.
  grunt.registerTask('default', ['clean', 'mochaTest', 'jshint']);
};

<|start_filename|>bin/game-server/node_modules/bearcat-buffer/lib/util/codec.js<|end_filename|>
var Codec = {};

/**
 * [encode an uInt32, return a array of bytes]
 * @param  {[integer]} num
 * @return {[array]}
 */
Codec.encodeUInt32 = function(num) {
	var n = parseInt(num);
	if (isNaN(n) || n < 0) {
		return null;
	}

	var result = [];
	do {
		var tmp = n % 128;
		var next = Math.floor(n / 128);

		if (next !== 0) {
			tmp = tmp + 128;
		}
		result.push(tmp);
		n = next;
	} while (n !== 0);

	return result;
};

/**
 * [encode a sInt32, return a byte array]
 * @param  {[sInt32]} num  The sInt32 need to encode
 * @return {[array]} A byte array represent the integer
 */
Codec.encodeSInt32 = function(num) {
	var n = parseInt(num);
	if (isNaN(n)) {
		return null;
	}
	n = n < 0 ? (Math.abs(n) * 2 - 1) : n * 2;

	return Codec.encodeUInt32(n);
};

Codec.decodeUInt32 = function(bytes) {
	var n = 0;

	for (var i = 0; i < bytes.length; i++) {
		var m = parseInt(bytes[i]);
		n = n + ((m & 0x7f) * Math.pow(2, (7 * i)));
		if (m < 128) {
			return n;
		}
	}

	return n;
};

Codec.decodeSInt32 = function(bytes) {
	var n = this.decodeUInt32(bytes);
	var flag = ((n % 2) === 1) ? -1 : 1;

	n = ((n % 2 + n) / 2) * flag;

	return n;
};

module.exports = Codec;

<|start_filename|>bin/game-server/node_modules/pomelo/lib/filters/rpc/rpcLog.js<|end_filename|>
/**
 * Filter for rpc log.
 * Record used time for remote process call.
 */
var rpcLogger = require('pomelo-logger').getLogger('rpc-log', __filename);
var utils = require('../../util/utils');

module.exports = function() {
  return new Filter();
};

var Filter = function () {
}; 

Filter.prototype.name = 'rpcLog';

/**
 * Before filter for rpc
 */

Filter.prototype.before = function(serverId, msg, opts, next) {
  opts = opts||{};
  opts.__start_time__ = Date.now();
  next();
};

/**
 * After filter for rpc
 */
Filter.prototype.after = function(serverId, msg, opts, next) {
  if(!!opts && !!opts.__start_time__) {
    var start = opts.__start_time__;
    var end = Date.now();
    var timeUsed = end - start;
    var log = {
      route: msg.service,
      args: msg.args,
      time: utils.format(new Date(start)),
      timeUsed: timeUsed
    };
    rpcLogger.info(JSON.stringify(log));
  }
  next();
};


<|start_filename|>bin/game-server/node_modules/to-utf8/test.js<|end_filename|>
var test = require('tape')
  , toUTF8 = require('./index')

test('works as expected', function(assert) {
  var input = ['11000010', '10100010'].map(function(x) { return parseInt(x, 2) })
  assert.equal(toUTF8(input), '\u00a2')
  assert.end() 
})

test('works the same as buffer.toString(utf8)', function(assert) {
  var buf = new Buffer('淾淾淾 hello world 淾淾 yep ƒuu 淾', 'utf8')
  assert.equal(toUTF8(buf), buf.toString('utf8'))
  assert.end()
})


<|start_filename|>bin/game-server/node_modules/bops/test/is.js<|end_filename|>
var test = require('tape')
  , binary = require('../index')

test('is works', function(assert) {
  var yes = binary.from("Hello")
    , no = "World"
    , never = { weird: true }
    , noway = [ 42 ]
  
  assert.equal(binary.is(yes), true)
  assert.equal(binary.is(no), false)
  assert.equal(binary.is(never), false)
  assert.equal(binary.is(noway), false)
  assert.end()
})


<|start_filename|>bin/game-server/node_modules/bops/test/subarray.js<|end_filename|>
var test = require('tape')
  , binary = require('../index')

test('subarray works as expected', function(assert) {
  var tmp1 = binary.create(16)
    , tmp2

  for(var i = 0, len = 16; i < len; ++i) {
    binary.writeUInt8(tmp1, Math.random() * 0xFF & 0xFF, i)
  }

  tmp2 = binary.subarray(tmp1, 4)
  binary.writeUInt8(tmp2, 255, 0)

  assert.equal(binary.readUInt8(tmp1, 4), 255)
  assert.end()
})


<|start_filename|>bin/game-server/node_modules/date-format/test/parse-test.js<|end_filename|>
'use strict';

require('should');
var dateFormat = require('../lib');

describe('dateFormat.parse', function() {
  it('should require a pattern', function() {
    (function() { dateFormat.parse() }).should.throw(/pattern must be supplied/);
    (function() { dateFormat.parse(null) }).should.throw(/pattern must be supplied/);
    (function() { dateFormat.parse('') }).should.throw(/pattern must be supplied/);
  });

  describe('with a pattern that has no replacements', function() {
    it('should return a new date when the string matches', function() {
      dateFormat.parse('cheese', 'cheese').should.be.a.Date()
    });

    it('should throw if the string does not match', function() {
      (function() {
        dateFormat.parse('cheese', 'biscuits');
      }).should.throw(/String 'biscuits' could not be parsed as 'cheese'/);
    });
  });

  describe('with a full pattern', function() {
    var pattern = 'yyyy-MM-dd hh:mm:ss.SSSO';

    it('should return the correct date if the string matches', function() {
      var testDate = new Date();
      testDate.setFullYear(2018);
      testDate.setMonth(8);
      testDate.setDate(13);
      testDate.setHours(18);
      testDate.setMinutes(10);
      testDate.setSeconds(12);
      testDate.setMilliseconds(392);
      testDate.getTimezoneOffset = function() { return 600; };

      dateFormat.parse(pattern, '2018-09-13 08:10:12.392+1000').getTime().should.eql(testDate.getTime());
    });

    it('should throw if the string does not match', function() {
      (function() {
        dateFormat.parse(pattern, 'biscuits')
      }).should.throw(/String 'biscuits' could not be parsed as 'yyyy-MM-dd hh:mm:ss.SSSO'/);
    });
  });

  describe('with a partial pattern', function() {
    var testDate = new Date();
    dateFormat.now = function() { return testDate; };

    function verifyDate(actual, expected) {
      actual.getFullYear().should.eql(expected.year || testDate.getFullYear());
      actual.getMonth().should.eql(expected.month || testDate.getMonth());
      actual.getDate().should.eql(expected.day || testDate.getDate());
      actual.getHours().should.eql(expected.hours || testDate.getHours());
      actual.getMinutes().should.eql(expected.minutes || testDate.getMinutes());
      actual.getSeconds().should.eql(expected.seconds || testDate.getSeconds());
      actual.getMilliseconds().should.eql(expected.milliseconds || testDate.getMilliseconds());
    }

    it('should return a date with missing values defaulting to current time', function() {
      var date = dateFormat.parse('yyyy-MM', '2015-09');
      verifyDate(date, { year: 2015, month: 8 });
    });

    it('should handle variations on the same pattern', function() {
      var date = dateFormat.parse('MM-yyyy', '09-2015');
      verifyDate(date, { year: 2015, month: 8 });

      date = dateFormat.parse('yyyy MM', '2015 09');
      verifyDate(date, { year: 2015, month: 8 });

      date = dateFormat.parse('MM, yyyy.', '09, 2015.');
      verifyDate(date, { year: 2015, month: 8 });
    });

    it('should match all the date parts', function() {
      var date = dateFormat.parse('dd', '21');
      verifyDate(date, { day: 21 });

      date = dateFormat.parse('hh', '12');
      verifyDate(date, { hours: 12 });

      date = dateFormat.parse('mm', '34');
      verifyDate(date,  { minutes: 34 });

      date = dateFormat.parse('ss', '59');
      verifyDate(date, { seconds: 59 });

      date = dateFormat.parse('ss.SSS', '23.452');
      verifyDate(date, { seconds: 23, milliseconds: 452 });

      date = dateFormat.parse('hh:mm O', '05:23 +1000');
      verifyDate(date, { hours: 15, minutes: 23 });

      date = dateFormat.parse('hh:mm O', '05:23 -200');
      verifyDate(date, { hours: 3, minutes: 23 });

      date = dateFormat.parse('hh:mm O', '05:23 +0930');
      verifyDate(date, { hours: 14, minutes: 53 });
    });
  });

  describe('with a date formatted by this library', function() {
    var testDate = new Date();
    testDate.setUTCFullYear(2018);
    testDate.setUTCMonth(8);
    testDate.setUTCDate(13);
    testDate.setUTCHours(18);
    testDate.setUTCMinutes(10);
    testDate.setUTCSeconds(12);
    testDate.setUTCMilliseconds(392);

    it('should format and then parse back to the same date', function() {
      dateFormat.parse(
        dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT,
        dateFormat(dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT, testDate)
      ).should.eql(testDate);

      dateFormat.parse(
        dateFormat.ISO8601_FORMAT,
        dateFormat(dateFormat.ISO8601_FORMAT, testDate)
      ).should.eql(testDate);

      dateFormat.parse(
        dateFormat.DATETIME_FORMAT,
        dateFormat(dateFormat.DATETIME_FORMAT, testDate)
      ).should.eql(testDate);

      dateFormat.parse(
        dateFormat.ABSOLUTETIME_FORMAT,
        dateFormat(dateFormat.ABSOLUTETIME_FORMAT, testDate)
      ).should.eql(testDate);
    });

  });
});


<|start_filename|>bin/game-server/node_modules/mqtt-connection/lib/writeToStream.js<|end_filename|>
var stream        = require('stream')
  , writeToStream = require('mqtt-packet').writeToStream
  , duplexify     = require('duplexify')

function generateStream() {
  var input = new stream.Writable({ objectMode: true, write: write })
    , output = new stream.PassThrough()
    , transform = duplexify(input, output, { objectMode: true })

  function write(chunk, enc, cb) {
    try {
      writeToStream(chunk, output)
    } catch(err) {
      this.emit('error', err)
    }

    cb()
  }

  return transform
}

module.exports = generateStream;


<|start_filename|>bin/game-server/node_modules/mqtt/examples/server/redis.js<|end_filename|>
var mqtt = require('../..')
  , redis = require('redis');

mqtt.createServer(function(err, client) {
  client.p = redis.createClient(null, null, {no_ready_check: true});
  client.s = redis.createClient(null, null, {no_ready_check: true});

  client.on('connect', function(packet) {
    client.connack({returnCode: 0});
  });

  client.on('subscribe', function(packet) {
    var granted = [];
    for (var i = 0; i < packet.subscriptions.length; i++) {
      var sub = packet.subscriptions[i]
      granted.push(sub.qos);

      client.s.psubscribe(
        sub.topic
          .replace(/\+/g, '[^/]')
          .replace(/\#/g, '*')
      );
    }

    client.suback({messageId: packet.messageId, granted: granted});
  });
  client.on('publish', function(packet) {
    client.p.publish(packet.topic, packet.payload);
  });
  client.on('pingreq', function(packet) {
    client.pingresp();
  });
  client.on('close', function() {
    client.p.end();
    client.s.end();
  });
  client.s.on('pmessage', function(pattern, channel, message) {
    client.publish({topic: channel, payload: message});
  });
  client.on('disconnect', function(packet) {
    client.stream.end();
  });
  client.on('error', function(e) {
    client.stream.end();
    console.log(e);
  });
}).listen(process.argv[2] || 1883);



<|start_filename|>bin/game-server/node_modules/pomelo/test/mock-plugin/components/mockPlugin.js<|end_filename|>
module.exports = function(app, opts) {
  var service = {name: 'mockPlugin'};
  return service;
};

<|start_filename|>bin/game-server/node_modules/pomelo-loader/Makefile<|end_filename|>
SRC = $(shell find lib -type f -name "*.js")
TESTS = test/*
REPORTER = spec
TIMEOUT = 5000

test:
	@./node_modules/.bin/mocha \
		--reporter $(REPORTER) --timeout $(TIMEOUT) $(TESTS)

test-cov: lib-cov
	@JSCOV=1 $(MAKE) test REPORTER=html-cov > coverage.html && open coverage.html

lib-cov:
	@rm -rf ./$@
	@jscoverage lib $@

clean:
	rm -rf lib-cov
	rm -f coverage.html

.PHONY: test test-cov


<|start_filename|>bin/game-server/node_modules/pomelo-protocol/index.js<|end_filename|>
module.exports = require('./lib/protocol');

<|start_filename|>bin/game-server/node_modules/mqtt/lib/auth_utils.js<|end_filename|>
/**
 * Parse the auth attribute and merge username and password in the options object.
 *
 * @param {String} [auth] auth attribute of a url.
 * @param {Object} [opts] object to merge the auth attributes into.
 */
module.exports.parseAuthOptions = function(auth, opts) {
  if(auth){
    var matches = auth.match(/^(.+):(.+)$/);
    if(matches) {
      opts.username = matches[1];
      opts.password = matches[2];
    } else {
      opts.username = auth;
    }
  }
};

<|start_filename|>bin/game-server/node_modules/bops/test/read.js<|end_filename|>
var test = require('tape')
  , binary = require('../index')

test('read works as expected', function(assert) {
  var tests = {
      readUInt8:      [binary.from([16]), 16]
    , readInt8:       [binary.from([16]), 16]
    , readInt8:       [binary.from([0xff]), -1]
    , readInt8:       [binary.from([0x80]), -128]
    , readUInt16LE:   [binary.from([0xCF, 0xAF]), 45007]
    , readUInt32LE:   [binary.from([0xAF, 0, 0, 0xCF]), 3472883887]
    , readInt16LE:    [binary.from([0xCF, 0xAF]), -20529]
    , readInt32LE:    [binary.from([0xCF, 0, 0, 0xCF]), -822083377]
    , readFloatLE:    [binary.from([0xCF, 0xAF, 0xDA, 0x02]), 3.213313024388152e-37]
    , readDoubleLE:   [binary.from([0xcf, 0xaf, 0xda, 0x02, 0x00, 0x01, 0x2f, 0x44])
                      , 285960563508654870000]
    , readUInt16BE:   [binary.from([0xCF, 0xAF]), 53167]
    , readUInt32BE:   [binary.from([0xAF, 0, 0, 0xCF]), 2936013007]
    , readInt16BE:    [binary.from([0xCF, 0xAF]), -12369]
    , readInt32BE:    [binary.from([0xAF, 0, 0, 0xCF]), -1358954289]
    , readFloatBE:    [binary.from([0xCF, 0xAF, 0xDA, 0x02]), -5900600320]
    , readDoubleBE:   [binary.from([0xcf, 0xaf, 0xda, 0x02, 0x00, 0x01, 0x2f, 0x44]), -7.203442384910198e+75]
  }

  for(var key in tests) {
    var buf = tests[key][0]
      , expect = tests[key][1]

    assert.equal(binary[key](buf, 0), expect)
  }
  assert.end()
})


<|start_filename|>bin/game-server/node_modules/node-bignumber/example.js<|end_filename|>
var rsa = require("./lib/rsa");
var key = new rsa.Key();

var message = "All your bases are belong to us.";
console.log("Message:\n"+message+"\n");

// Generate a key
key.generate(1024, "10001");
console.log("Key:\n");
console.log("n:" + key.n.toString(16));
console.log("e:" + key.e.toString(16));
console.log("d:" + key.d.toString(16));
console.log("\n");

// Encrypt
var encrypted = key.encrypt(message);
console.log("Encrypted:\n" + rsa.linebrk(encrypted, 64) + "\n" );

// Decrypt
var decrypted = key.decrypt(encrypted);
console.log("Decrypted:" + rsa.linebrk(decrypted, 64) + "\n");

var sig = key.signString(message, "sha256");
console.log("String signature: \n" + rsa.linebrk(sig, 64));

var pubkey = new rsa.Key();
pubkey.n = key.n;
pubkey.e = key.e;

var verified = pubkey.verifyString(message, sig);

console.log("Verfied: " + verified);

<|start_filename|>bin/game-server/node_modules/pomelo-protobuf/test/client/rootMsgTest.js<|end_filename|>
var protobuf = require('../../lib/client/protobuf');
var encoder = protobuf.encoder;
var decoder = protobuf.decoder;
var codec = protobuf.codec;
var parser = require('../../lib/parser');
var util = require('../../lib/util');
var should = require('should');
var tc = require('../rootMsgTC');

describe('msgEncoderTest', function(){

	var protos = parser.parse(require('../rootMsg.json'));

	protobuf.init({encoderProtos:protos, decoderProtos:protos});

	describe('protobufTest', function(){
		for(var route in tc){
			var msg = tc[route];

			console.log('====================');
			console.log(route);

			var buffer = protobuf.encode(route, msg);

			console.log(msg);
			console.log(buffer.length);

			var decodeMsg = protobuf.decode(route, buffer);

			console.log(decodeMsg);
			console.log('====================');

			util.equal(msg, decodeMsg).should.equal(true);
		}
	});
});

<|start_filename|>bin/game-server/node_modules/pomelo/lib/connectors/udpconnector.js<|end_filename|>
var net = require('net');
var util = require('util');
var dgram = require("dgram");
var utils = require('../util/utils');
var Constants = require('../util/constants');
var UdpSocket = require('./udpsocket');
var Kick = require('./commands/kick');
var Handshake = require('./commands/handshake');
var Heartbeat = require('./commands/heartbeat');
var protocol = require('pomelo-protocol');
var Package = protocol.Package;
var Message = protocol.Message;
var coder = require('./common/coder');
var EventEmitter = require('events').EventEmitter;

var curId = 1;

var Connector = function(port, host, opts) {
  if (!(this instanceof Connector)) {
    return new Connector(port, host, opts);
  }

  EventEmitter.call(this);
  this.opts = opts || {};
  this.type = opts.udpType || 'udp4';
  this.handshake = new Handshake(opts);
  if(!opts.heartbeat) {
    opts.heartbeat = Constants.TIME.DEFAULT_UDP_HEARTBEAT_TIME;
    opts.timeout = Constants.TIME.DEFAULT_UDP_HEARTBEAT_TIMEOUT;
  }
  this.heartbeat = new Heartbeat(utils.extends(opts, {disconnectOnTimeout: true}));
  this.clients = {};
  this.host = host;
  this.port = port;
};

util.inherits(Connector, EventEmitter);

module.exports = Connector;

Connector.prototype.start = function(cb) {
  var self = this;
  this.tcpServer = net.createServer();
  this.socket = dgram.createSocket(this.type, function(msg, peer) {
    var key = genKey(peer);
    if(!self.clients[key]) {
      var udpsocket = new UdpSocket(curId++, self.socket, peer);
      self.clients[key] = udpsocket;

      udpsocket.on('handshake',
      self.handshake.handle.bind(self.handshake, udpsocket));

      udpsocket.on('heartbeat',
      self.heartbeat.handle.bind(self.heartbeat, udpsocket));

      udpsocket.on('disconnect',
      self.heartbeat.clear.bind(self.heartbeat, udpsocket.id));

      udpsocket.on('disconnect', function() {
        delete self.clients[genKey(udpsocket.peer)];
      });

      udpsocket.on('closing', Kick.handle.bind(null, udpsocket));

      self.emit('connection', udpsocket);
    }
  });

  this.socket.on('message', function(data, peer) {
    var socket = self.clients[genKey(peer)];
    if(!!socket) {
      socket.emit('package', data);
    }
  });

  this.socket.on('error', function(err) {
    logger.error('udp socket encounters with error: %j', err.stack);
    return;
  });

  this.socket.bind(this.port, this.host);
  this.tcpServer.listen(this.port);
  process.nextTick(cb);
};

Connector.decode = Connector.prototype.decode = coder.decode;

Connector.encode = Connector.prototype.encode = coder.encode;

Connector.prototype.stop = function(force, cb) {
  this.socket.close();
  process.nextTick(cb);
};

var genKey = function(peer) {
  return peer.address + ":" + peer.port;
};

<|start_filename|>bin/game-server/node_modules/bops/test/index.js<|end_filename|>
require('./copy')
require('./create')
require('./from')
require('./join')
require('./read')
require('./subarray')
require('./to')
require('./write')


<|start_filename|>bin/game-server/node_modules/mqtt/benchmarks/bombing.js<|end_filename|>
#! /usr/bin/env node

var mqtt = require('../');
var client = mqtt.createClient(1883, "localhost", { clean: true });

var sent = 0;
var interval = 5000;

function count() {
  console.log("sent/s", sent / interval * 1000);
  sent = 0;
  setTimeout(count, interval);
}

function publish() {
  sent++;
  client.publish("test", "payload");
  setImmediate(publish);
}

client.on("connect", function() {
  publish();
  count();
});

client.on("error", function() {
  console.log("reconnect!");
  client.stream.end();
});


<|start_filename|>bin/game-server/node_modules/pomelo/index.js<|end_filename|>
module.exports = require('./lib/pomelo');

<|start_filename|>bin/game-server/node_modules/pomelo-protobuf/test/case1.json<|end_filename|>
{
	"ls": {
		"message MS": {
			"optional Status status": 2,
			"message Status": {
				"repeated string table_cards": 13
			}
		},
		"required MS s": 1
	}
}

<|start_filename|>bin/game-server/node_modules/date-format/lib/index.js<|end_filename|>
'use strict';

function padWithZeros(vNumber, width) {
    var numAsString = vNumber.toString();
    while (numAsString.length < width) {
        numAsString = '0' + numAsString;
    }
    return numAsString;
}

function addZero(vNumber) {
    return padWithZeros(vNumber, 2);
}

/**
 * Formats the TimeOffset
 * Thanks to http://www.svendtofte.com/code/date_format/
 * @private
 */
function offset(timezoneOffset) {
    var os = Math.abs(timezoneOffset);
    var h = String(Math.floor(os / 60));
    var m = String(os % 60);
    if (h.length === 1) {
        h = '0' + h;
    }
    if (m.length === 1) {
        m = '0' + m;
    }
    return timezoneOffset < 0 ? '+' + h + m : '-' + h + m;
}

function datePart(date, displayUTC, part) {
  return displayUTC ? date['getUTC' + part]() : date['get' + part]();
}

function asString(format, date) {
    if (typeof format !== 'string') {
        date = format;
        format = module.exports.ISO8601_FORMAT;
    }
    if (!date) {
        date =  module.exports.now();
    }

    var displayUTC = format.indexOf('O') > -1;

    var vDay = addZero(datePart(date, displayUTC, 'Date'));
    var vMonth = addZero(datePart(date, displayUTC, 'Month') + 1);
    var vYearLong = addZero(datePart(date, displayUTC, 'FullYear'));
    var vYearShort = addZero(vYearLong.substring(2, 4));
    var vYear = (format.indexOf('yyyy') > -1 ? vYearLong : vYearShort);
    var vHour = addZero(datePart(date, displayUTC, 'Hours'));
    var vMinute = addZero(datePart(date, displayUTC, 'Minutes'));
    var vSecond = addZero(datePart(date, displayUTC, 'Seconds'));
    var vMillisecond = padWithZeros(datePart(date, displayUTC, 'Milliseconds'), 3);
    var vTimeZone = offset(date.getTimezoneOffset());
    var formatted = format
        .replace(/dd/g, vDay)
        .replace(/MM/g, vMonth)
        .replace(/y{1,4}/g, vYear)
        .replace(/hh/g, vHour)
        .replace(/mm/g, vMinute)
        .replace(/ss/g, vSecond)
        .replace(/SSS/g, vMillisecond)
        .replace(/O/g, vTimeZone);
    return formatted;
}

function extractDateParts(pattern, str) {
  var matchers = [
    { pattern: /y{1,4}/, regexp: "\\d{1,4}", fn: function(date, value) { date.setFullYear(value); } },
    { pattern: /MM/, regexp: "\\d{1,2}", fn: function(date, value) { date.setMonth(value -1); } },
    { pattern: /dd/, regexp: "\\d{1,2}", fn: function(date, value) { date.setDate(value); } },
    { pattern: /hh/, regexp: "\\d{1,2}", fn: function(date, value) { date.setHours(value); } },
    { pattern: /mm/, regexp: "\\d\\d", fn: function(date, value) { date.setMinutes(value); } },
    { pattern: /ss/, regexp: "\\d\\d", fn: function(date, value) { date.setSeconds(value); } },
    { pattern: /SSS/, regexp: "\\d\\d\\d", fn: function(date, value) { date.setMilliseconds(value); } },
    { pattern: /O/, regexp: "[+-]\\d{3,4}|Z", fn: function(date, value) {
      if (value === 'Z') {
        value = 0;
      }
      var offset = Math.abs(value);
      var minutes = (offset % 100) + (Math.floor(offset / 100) * 60);
      date.setMinutes(date.getMinutes() + (value > 0 ? minutes : -minutes));
    } }
  ];

  var parsedPattern = matchers.reduce(function(p, m) {
    if (m.pattern.test(p.regexp)) {
      m.index = p.regexp.match(m.pattern).index;
      p.regexp = p.regexp.replace(m.pattern, "(" + m.regexp + ")");
    } else {
      m.index = -1;
    }
    return p;
  }, { regexp: pattern, index: [] });

  var dateFns = matchers.filter(function(m) {
    return m.index > -1;
  });
  dateFns.sort(function(a, b) { return a.index - b.index; });

  var matcher = new RegExp(parsedPattern.regexp);
  var matches = matcher.exec(str);
  if (matches) {
    var date = module.exports.now();
    dateFns.forEach(function(f, i) {
      f.fn(date, matches[i+1]);
    });
    return date;
  }

  throw new Error('String \'' + str + '\' could not be parsed as \'' + pattern + '\'');
}

function parse(pattern, str) {
  if (!pattern) {
    throw new Error('pattern must be supplied');
  }

  return extractDateParts(pattern, str);
}

/**
 * Used for testing - replace this function with a fixed date.
 */
function now() {
  return new Date();
}

module.exports = asString;
module.exports.asString = asString;
module.exports.parse = parse;
module.exports.now = now;
module.exports.ISO8601_FORMAT = 'yyyy-MM-ddThh:mm:ss.SSS';
module.exports.ISO8601_WITH_TZ_OFFSET_FORMAT = 'yyyy-MM-ddThh:mm:ss.SSSO';
module.exports.DATETIME_FORMAT = 'dd MM yyyy hh:mm:ss.SSS';
module.exports.ABSOLUTETIME_FORMAT = 'hh:mm:ss.SSS';


<|start_filename|>bin/game-server/node_modules/bops/to.js<|end_filename|>
module.exports = function(source, encoding) {
  return source.toString(encoding)
}


<|start_filename|>node_modules/blanket/src/loaders/blanket_cs.js<|end_filename|>
(function(_blanket){
    
/**
 * @license cs 0.4.3 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/jrburke/require-cs for details
 */

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
 
    // private property
    _keyStr : "<KEY>
 
    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
 
        input = Base64._utf8_encode(input);
 
        while (i < input.length) {
 
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
 
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
 
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
 
            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
        }
 
        return output;
    },
 
    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
 
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
        while (i < input.length) {
 
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
 
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
 
            output = output + String.fromCharCode(chr1);
 
            if (enc3 !== 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 !== 64) {
                output = output + String.fromCharCode(chr3);
            }
 
        }
 
        output = Base64._utf8_decode(output);
 
        return output;
 
    },
 
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
 
        for (var n = 0; n < string.length; n++) {
 
            var c = string.charCodeAt(n);
 
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
 
        }
 
        return utftext;
    },
 
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = 0, c2 = 0;
 
        while ( i < utftext.length ) {
 
            c = utftext.charCodeAt(i);
 
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
 
        }
 
        return string;
    }
 
};

define("cs", ['coffee-script'], function (CoffeeScript) {
    'use strict';
    var fs, getXhr,
        progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
        fetchText = function () {
            throw new Error('Environment unsupported.');
        },
        buildMap = {};

    if (typeof process !== "undefined" &&
               process.versions &&
               !!process.versions.node) {
        //Using special require.nodeRequire, something added by r.js.
        fs = require.nodeRequire('fs');
        fetchText = function (path, callback) {
            callback(fs.readFileSync(path, 'utf8'));
        };
    } else if ((typeof window !== "undefined" && window.navigator && window.document) || typeof importScripts !== "undefined") {
        // Browser action
        getXhr = function () {
            //Would love to dump the ActiveX crap in here. Need IE 6 to die first.
            var xhr, i, progId;
            if (typeof XMLHttpRequest !== "undefined") {
                return new XMLHttpRequest();
            } else {
                for (i = 0; i < 3; i += 1) {
                    progId = progIds[i];
                    try {
                        xhr = new ActiveXObject(progId);
                    } catch (e) {}

                    if (xhr) {
                        progIds = [progId];  // so faster next time
                        break;
                    }
                }
            }

            if (!xhr) {
                throw new Error("getXhr(): XMLHttpRequest not available");
            }

            return xhr;
        };

        fetchText = function (url, callback) {
            var xhr = getXhr();
            xhr.open('GET', url, true);
            xhr.onreadystatechange = function (evt) {
                //Do not explicitly handle errors, those should be
                //visible via console output in the browser.
                if (xhr.readyState === 4) {
                    callback(xhr.responseText);
                }
            };
            xhr.send(null);
        };
        // end browser.js adapters
    } else if (typeof Packages !== 'undefined') {
        //Why Java, why is this so awkward?
        fetchText = function (path, callback) {
            var stringBuffer, line,
                encoding = "utf-8",
                file = new java.io.File(path),
                lineSeparator = java.lang.System.getProperty("line.separator"),
                input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
                content = '';
            try {
                stringBuffer = new java.lang.StringBuffer();
                line = input.readLine();

                // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
                // http://www.unicode.org/faq/utf_bom.html

                // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
                if (line && line.length() && line.charAt(0) === 0xfeff) {
                    // Eat the BOM, since we've already found the encoding on this file,
                    // and we plan to concatenating this buffer with others; the BOM should
                    // only appear at the top of a file.
                    line = line.substring(1);
                }

                stringBuffer.append(line);

                while ((line = input.readLine()) !== null) {
                    stringBuffer.append(lineSeparator);
                    stringBuffer.append(line);
                }
                //Make sure we return a JavaScript string and not a Java string.
                content = String(stringBuffer.toString()); //String
            } finally {
                input.close();
            }
            callback(content);
        };
    }

    return {
        fetchText: fetchText,

        get: function () {
            return CoffeeScript;
        },

        write: function (pluginName, name, write) {
            if (buildMap.hasOwnProperty(name)) {
                var text = buildMap[name];
                write.asModule(pluginName + "!" + name, text);
            }
        },

        version: '0.4.3',

        load: function (name, parentRequire, load, config) {
            // preserve existing logic with new literate coffeescript extensions (*.litcoffee or *.coffee.md).
            // if name passes check, use it, as-is. otherwise, behave as before, appending .coffee to the
            // requirejs binding.
            var fullName = CoffeeScript.helpers.isCoffee(name) ? name : name + '.coffee';
            var path = parentRequire.toUrl(fullName);
            
            _blanket.requiringFile(path);
            var handleText = function(text) {
              //Hold on to the transformed text if a build.
              if (config.isBuild) {
                  buildMap[name] = text;
              }
              //IE with conditional comments on cannot handle the
              //sourceURL trick, so skip it if enabled.
              /*@if (@_jscript) @else @*/
              if (!config.isBuild) {
                  text += "\r\n//@ sourceURL=" + path;
              }
              /*@end@*/

              load.fromText(name, text);

              //Give result to load. Need to wait until the module
              //is fully parse, which will happen after this
              //execution.
              parentRequire([name], function (value) {
                  load(value);
              });
            };

            fetchText(path, function (text) {
                // preserve existing logic. integrate new 'literate' compile flag with any requirejs configs.
                var opts = config.CoffeeScript || {};
                opts.literate = CoffeeScript.helpers.isLiterate(fullName);
                opts.sourceMap = true;
                opts.header = true;
                opts.inline = true;
                opts.sourceFiles = [name + opts.literate ? '' : '.coffee'];
                opts.generatedFile = name + opts.literate ? '' : '.coffee';

                var compiled;
                //Do CoffeeScript transform.
                try {
                    compiled = CoffeeScript.compile(text, opts);
                } catch (err) {
                    err.message = "In " + path + ", " + err.message;
                    throw err;
                }
				text = compiled.js;

                _blanket.requiringFile(path,true);
                // If this file matches the blanket filter, instrument it.
                var match = _blanket.options("filter");
                if (_blanket.utils.matchPatternAttribute(
                        path.replace(".coffee.md","")
                            .replace(".litcoffee","")
                            .replace(".coffee",""),match)){
                    _blanket.instrument({
                        inputFile: text,
                        inputFileName: path+" (compiled)"
                    },function(instrumented){
                        handleText(instrumented);
                    });
                }
                else {
                  handleText(text);
                }


            });
        }
    };
});
})(blanket);


<|start_filename|>bin/game-server/node_modules/pomelo-admin/lib/modules/monitorLog.js<|end_filename|>
/*!
 * Pomelo -- consoleModule monitorLog
 * Copyright(c) 2012 fantasyni <<EMAIL>>
 * MIT Licensed
 */
var logger = require('pomelo-logger').getLogger('pomelo-admin', __filename);
var exec = require('child_process').exec;
var path = require('path');

var DEFAULT_INTERVAL = 5 * 60;		// in second

module.exports = function(opts) {
	return new Module(opts);
};

module.exports.moduleId = 'monitorLog';

/**
 * Initialize a new 'Module' with the given 'opts'
 *
 * @class Module
 * @constructor
 * @param {object} opts
 * @api public
 */
var Module = function(opts) {
	opts = opts || {};
	this.root = opts.path;
	this.interval = opts.interval || DEFAULT_INTERVAL;
};

 /**
 * collect monitor data from monitor
 *
 * @param {Object} agent monitorAgent object
 * @param {Object} msg client message
 * @param {Function} cb callback function
 * @api public
 */
Module.prototype.monitorHandler = function(agent, msg, cb) {
	if(!msg.logfile) {
		cb(new Error('logfile should not be empty'));
		return;
	}

	var serverId = agent.id;
	fetchLogs(this.root, msg, function (data) {
		cb(null, {serverId: serverId, body: data});
	});
};

/**
 * Handle client request
 *
 * @param {Object} agent masterAgent object
 * @param {Object} msg client message
 * @param {Function} cb callback function
 * @api public
 */
Module.prototype.clientHandler = function(agent, msg, cb) {
	agent.request(msg.serverId, module.exports.moduleId, msg, function(err, res) {
		if(err) {
			logger.error('fail to run log for ' + err.stack);
			return;
		}
		cb(null, res);
	});
};

//get the latest logs
var fetchLogs = function(root, msg, callback) {
	var number = msg.number;
	var logfile = msg.logfile;
	var serverId = msg.serverId;
	var filePath = path.join(root, getLogFileName(logfile, serverId));

	var endLogs = [];
	exec('tail -n ' + number + ' ' + filePath, function(error, output) {
		var endOut = [];
		output = output.replace(/^\s+|\s+$/g, "").split(/\s+/);

		for(var i=5; i<output.length; i+=6) {
			endOut.push(output[i]);
		}

		var endLength=endOut.length;
		for(var j=0; j<endLength; j++) {
			var map = {};
			var json;
			try{
				json = JSON.parse(endOut[j]);
			} catch(e) {
				logger.error('the log cannot parsed to json, '+e);
				continue;
			}
			map.time = json.time;
			map.route = json.route || json.service;
			map.serverId = serverId;
			map.timeUsed = json.timeUsed;
			map.params = endOut[j];
			endLogs.push(map);
		}

		callback({logfile:logfile,dataArray:endLogs});
	});
};

var getLogFileName = function(logfile, serverId) {
	return logfile + '-' + serverId + '.log';
};

<|start_filename|>bin/game-server/node_modules/pomelo-admin/lib/master/masterAgent.js<|end_filename|>
var logger = require('pomelo-logger').getLogger('pomelo-admin', 'MasterAgent');
var MqttServer = require('../protocol/mqtt/mqttServer');
var EventEmitter = require('events').EventEmitter;
var MasterSocket = require('./masterSocket');
var protocol = require('../util/protocol');
var utils = require('../util/utils');
var Util = require('util');

var ST_INITED = 1;
var ST_STARTED = 2;
var ST_CLOSED = 3;

/**
 * MasterAgent Constructor
 *
 * @class MasterAgent
 * @constructor
 * @param {Object} opts construct parameter
 *                 opts.consoleService {Object} consoleService
 *                 opts.id             {String} server id
 *                 opts.type           {String} server type, 'master', 'connector', etc.
 *                 opts.socket         {Object} socket-io object
 *                 opts.reqId          {Number} reqId add by 1
 *                 opts.callbacks      {Object} callbacks
 *                 opts.state          {Number} MasterAgent state
 * @api public
 */
var MasterAgent = function(consoleService, opts) {
  EventEmitter.call(this);
  this.reqId = 1;
  this.idMap = {};
  this.msgMap = {};
  this.typeMap = {};
  this.clients = {};
  this.sockets = {};
  this.slaveMap = {};
  this.server = null;
  this.callbacks = {};
  this.state = ST_INITED;
  this.whitelist = opts.whitelist;
  this.consoleService = consoleService;
};

Util.inherits(MasterAgent, EventEmitter);

/**
 * master listen to a port and handle register and request
 *
 * @param {String} port
 * @api public
 */
MasterAgent.prototype.listen = function(port, cb) {
  if (this.state > ST_INITED) {
    logger.error('master agent has started or closed.');
    return;
  }

  this.state = ST_STARTED;
  this.server = new MqttServer();
  this.server.listen(port);
  // this.server = sio.listen(port);
  // this.server.set('log level', 0);

  cb = cb || function() {}

  var self = this;
  this.server.on('error', function(err) {
    self.emit('error', err);
    cb(err);
  });

  this.server.once('listening', function() {
    setImmediate(function() {
      cb();
    });
  });

  this.server.on('connection', function(socket) {
    // var id, type, info, registered, username;
    var masterSocket = new MasterSocket();
    masterSocket['agent'] = self;
    masterSocket['socket'] = socket;

    self.sockets[socket.id] = socket;

    socket.on('register', function(msg) {
      // register a new connection
      masterSocket.onRegister(msg);
    }); // end of on 'register'

    // message from monitor
    socket.on('monitor', function(msg) {
      masterSocket.onMonitor(msg);
    }); // end of on 'monitor'

    // message from client
    socket.on('client', function(msg) {
      masterSocket.onClient(msg);
    }); // end of on 'client'

    socket.on('reconnect', function(msg) {
      masterSocket.onReconnect(msg);
    });

    socket.on('disconnect', function() {
      masterSocket.onDisconnect();
    });

    socket.on('close', function() {
      masterSocket.onDisconnect();
    });

    socket.on('error', function(err) {
      masterSocket.onError(err);
    });
  }); // end of on 'connection'
}; // end of listen

/**
 * close master agent
 *
 * @api public
 */
MasterAgent.prototype.close = function() {
  if (this.state > ST_STARTED) {
    return;
  }
  this.state = ST_CLOSED;
  this.server.close();
};

/**
 * set module
 *
 * @param {String} moduleId module id/name
 * @param {Object} value module object
 * @api public
 */
MasterAgent.prototype.set = function(moduleId, value) {
  this.consoleService.set(moduleId, value);
};

/**
 * get module
 *
 * @param {String} moduleId module id/name
 * @api public
 */
MasterAgent.prototype.get = function(moduleId) {
  return this.consoleService.get(moduleId);
};

/**
 * getClientById
 *
 * @param {String} clientId
 * @api public
 */
MasterAgent.prototype.getClientById = function(clientId) {
  return this.clients[clientId];
};

/**
 * request monitor{master node} data from monitor
 *
 * @param {String} serverId
 * @param {String} moduleId module id/name
 * @param {Object} msg
 * @param {Function} callback function
 * @api public
 */
MasterAgent.prototype.request = function(serverId, moduleId, msg, cb) {
  if (this.state > ST_STARTED) {
    return false;
  }

  cb = cb || function() {}

  var curId = this.reqId++;
  this.callbacks[curId] = cb;

  if (!this.msgMap[serverId]) {
    this.msgMap[serverId] = {};
  }

  this.msgMap[serverId][curId] = {
    moduleId: moduleId,
    msg: msg
  }

  var record = this.idMap[serverId];
  if (!record) {
    cb(new Error('unknown server id:' + serverId));
    return false;
  }

  sendToMonitor(record.socket, curId, moduleId, msg);

  return true;
};

/**
 * request server data from monitor by serverInfo{host:port}
 *
 * @param {String} serverId
 * @param {Object} serverInfo
 * @param {String} moduleId module id/name
 * @param {Object} msg
 * @param {Function} callback function
 * @api public
 */
MasterAgent.prototype.requestServer = function(serverId, serverInfo, moduleId, msg, cb) {
  if (this.state > ST_STARTED) {
    return false;
  }

  var record = this.idMap[serverId];
  if (!record) {
    utils.invokeCallback(cb, new Error('unknown server id:' + serverId));
    return false;
  }

  var curId = this.reqId++;
  this.callbacks[curId] = cb;

  if (utils.compareServer(record, serverInfo)) {
    sendToMonitor(record.socket, curId, moduleId, msg);
  } else {
    var slaves = this.slaveMap[serverId];
    for (var i = 0, l = slaves.length; i < l; i++) {
      if (utils.compareServer(slaves[i], serverInfo)) {
        sendToMonitor(slaves[i].socket, curId, moduleId, msg);
        break;
      }
    }
  }

  return true;
};

/**
 * notify a monitor{master node} by id without callback
 *
 * @param {String} serverId
 * @param {String} moduleId module id/name
 * @param {Object} msg
 * @api public
 */
MasterAgent.prototype.notifyById = function(serverId, moduleId, msg) {
  if (this.state > ST_STARTED) {
    return false;
  }

  var record = this.idMap[serverId];
  if (!record) {
    logger.error('fail to notifyById for unknown server id:' + serverId);
    return false;
  }

  sendToMonitor(record.socket, null, moduleId, msg);

  return true;
};

/**
 * notify a monitor by server{host:port} without callback
 *
 * @param {String} serverId
 * @param {Object} serverInfo{host:port}
 * @param {String} moduleId module id/name
 * @param {Object} msg
 * @api public
 */
MasterAgent.prototype.notifyByServer = function(serverId, serverInfo, moduleId, msg) {
  if (this.state > ST_STARTED) {
    return false;
  }

  var record = this.idMap[serverId];
  if (!record) {
    logger.error('fail to notifyByServer for unknown server id:' + serverId);
    return false;
  }

  if (utils.compareServer(record, serverInfo)) {
    sendToMonitor(record.socket, null, moduleId, msg);
  } else {
    var slaves = this.slaveMap[serverId];
    for (var i = 0, l = slaves.length; i < l; i++) {
      if (utils.compareServer(slaves[i], serverInfo)) {
        sendToMonitor(slaves[i].socket, null, moduleId, msg);
        break;
      }
    }
  }
  return true;
};

/**
 * notify slaves by id without callback
 *
 * @param {String} serverId
 * @param {String} moduleId module id/name
 * @param {Object} msg
 * @api public
 */
MasterAgent.prototype.notifySlavesById = function(serverId, moduleId, msg) {
  if (this.state > ST_STARTED) {
    return false;
  }

  var slaves = this.slaveMap[serverId];
  if (!slaves || slaves.length === 0) {
    logger.error('fail to notifySlavesById for unknown server id:' + serverId);
    return false;
  }

  broadcastMonitors(slaves, moduleId, msg);
  return true;
};

/**
 * notify monitors by type without callback
 *
 * @param {String} type serverType
 * @param {String} moduleId module id/name
 * @param {Object} msg
 * @api public
 */
MasterAgent.prototype.notifyByType = function(type, moduleId, msg) {
  if (this.state > ST_STARTED) {
    return false;
  }

  var list = this.typeMap[type];
  if (!list || list.length === 0) {
    logger.error('fail to notifyByType for unknown server type:' + type);
    return false;
  }
  broadcastMonitors(list, moduleId, msg);
  return true;
};

/**
 * notify all the monitors without callback
 *
 * @param {String} moduleId module id/name
 * @param {Object} msg
 * @api public
 */
MasterAgent.prototype.notifyAll = function(moduleId, msg) {
  if (this.state > ST_STARTED) {
    return false;
  }
  broadcastMonitors(this.idMap, moduleId, msg);
  return true;
};

/**
 * notify a client by id without callback
 *
 * @param {String} clientId
 * @param {String} moduleId module id/name
 * @param {Object} msg
 * @api public
 */
MasterAgent.prototype.notifyClient = function(clientId, moduleId, msg) {
  if (this.state > ST_STARTED) {
    return false;
  }

  var record = this.clients[clientId];
  if (!record) {
    logger.error('fail to notifyClient for unknown client id:' + clientId);
    return false;
  }
  sendToClient(record.socket, null, moduleId, msg);
};

MasterAgent.prototype.notifyCommand = function(command, moduleId, msg) {
  if (this.state > ST_STARTED) {
    return false;
  }
  broadcastCommand(this.idMap, command, moduleId, msg);
  return true;
};

/**
 * add monitor,client to connection -- idMap
 *
 * @param {Object} agent agent object
 * @param {String} id
 * @param {String} type serverType
 * @param {Object} socket socket-io object
 * @api private
 */
var addConnection = function(agent, id, type, pid, info, socket) {
  var record = {
    id: id,
    type: type,
    pid: pid,
    info: info,
    socket: socket
  };
  if (type === 'client') {
    agent.clients[id] = record;
  } else {
    if (!agent.idMap[id]) {
      agent.idMap[id] = record;
      var list = agent.typeMap[type] = agent.typeMap[type] || [];
      list.push(record);
    } else {
      var slaves = agent.slaveMap[id] = agent.slaveMap[id] || [];
      slaves.push(record);
    }
  }
  return record;
};

/**
 * remove monitor,client connection -- idMap
 *
 * @param {Object} agent agent object
 * @param {String} id
 * @param {String} type serverType
 * @api private
 */
var removeConnection = function(agent, id, type, info) {
  if (type === 'client') {
    delete agent.clients[id];
  } else {
    // remove master node in idMap and typeMap
    var record = agent.idMap[id];
    if (!record) {
      return;
    }
    var _info = record['info']; // info {host, port}
    if (utils.compareServer(_info, info)) {
      delete agent.idMap[id];
      var list = agent.typeMap[type];
      if (list) {
        for (var i = 0, l = list.length; i < l; i++) {
          if (list[i].id === id) {
            list.splice(i, 1);
            break;
          }
        }
        if (list.length === 0) {
          delete agent.typeMap[type];
        }
      }
    } else {
      // remove slave node in slaveMap
      var slaves = agent.slaveMap[id];
      if (slaves) {
        for (var i = 0, l = slaves.length; i < l; i++) {
          if (utils.compareServer(slaves[i]['info'], info)) {
            slaves.splice(i, 1);
            break;
          }
        }
        if (slaves.length === 0) {
          delete agent.slaveMap[id];
        }
      }
    }
  }
};

/**
 * send msg to monitor
 *
 * @param {Object} socket socket-io object
 * @param {Number} reqId request id
 * @param {String} moduleId module id/name
 * @param {Object} msg message
 * @api private
 */
var sendToMonitor = function(socket, reqId, moduleId, msg) {
  doSend(socket, 'monitor', protocol.composeRequest(reqId, moduleId, msg));
};

/**
 * send msg to client
 *
 * @param {Object} socket socket-io object
 * @param {Number} reqId request id
 * @param {String} moduleId module id/name
 * @param {Object} msg message
 * @api private
 */
var sendToClient = function(socket, reqId, moduleId, msg) {
  doSend(socket, 'client', protocol.composeRequest(reqId, moduleId, msg));
};

var doSend = function(socket, topic, msg) {
  socket.send(topic, msg);
}

/**
 * broadcast msg to monitor
 *
 * @param {Object} record registered modules
 * @param {String} moduleId module id/name
 * @param {Object} msg message
 * @api private
 */
var broadcastMonitors = function(records, moduleId, msg) {
  msg = protocol.composeRequest(null, moduleId, msg);

  if (records instanceof Array) {
    for (var i = 0, l = records.length; i < l; i++) {
      var socket = records[i].socket;
      doSend(socket, 'monitor', msg);
    }
  } else {
    for (var id in records) {
      var socket = records[id].socket;
      doSend(socket, 'monitor', msg);
    }
  }
};

var broadcastCommand = function(records, command, moduleId, msg) {
  msg = protocol.composeCommand(null, command, moduleId, msg);

  if (records instanceof Array) {
    for (var i = 0, l = records.length; i < l; i++) {
      var socket = records[i].socket;
      doSend(socket, 'monitor', msg);
    }
  } else {
    for (var id in records) {
      var socket = records[id].socket;
      doSend(socket, 'monitor', msg);
    }
  }
};

MasterAgent.prototype.doAuthUser = function(msg, socket, cb) {
  if (!msg.id) {
    // client should has a client id
    return cb(new Error('client should has a client id'));
  }

  var self = this;
  var username = msg.username;
  if (!username) {
    // client should auth with username
    doSend(socket, 'register', {
      code: protocol.PRO_FAIL,
      msg: 'client should auth with username'
    });
    return cb(new Error('client should auth with username'));
  }

  var authUser = self.consoleService.authUser;
  var env = self.consoleService.env;
  authUser(msg, env, function(user) {
    if (!user) {
      // client should auth with username
      doSend(socket, 'register', {
        code: protocol.PRO_FAIL,
        msg: 'client auth failed with username or password error'
      });
      return cb(new Error('client auth failed with username or password error'));
    }

    if (self.clients[msg.id]) {
      doSend(socket, 'register', {
        code: protocol.PRO_FAIL,
        msg: 'id has been registered. id:' + msg.id
      });
      return cb(new Error('id has been registered. id:' + msg.id));
    }

    logger.info('client user : ' + username + ' login to master');
    addConnection(self, msg.id, msg.type, null, user, socket);
    doSend(socket, 'register', {
      code: protocol.PRO_OK,
      msg: 'ok'
    });

    cb();
  });
};

MasterAgent.prototype.doAuthServer = function(msg, socket, cb) {
  var self = this;
  var authServer = self.consoleService.authServer;
  var env = self.consoleService.env;
  authServer(msg, env, function(status) {
    if (status !== 'ok') {
      doSend(socket, 'register', {
        code: protocol.PRO_FAIL,
        msg: 'server auth failed'
      });
      cb(new Error('server auth failed'));
      return;
    }

    var record = addConnection(self, msg.id, msg.serverType, msg.pid, msg.info, socket);

    doSend(socket, 'register', {
      code: protocol.PRO_OK,
      msg: 'ok'
    });
    msg.info = msg.info || {}
    msg.info.pid = msg.pid;
    self.emit('register', msg.info);
    cb(null);
  });
};

MasterAgent.prototype.doSend = doSend;

MasterAgent.prototype.sendToMonitor = sendToMonitor;

MasterAgent.prototype.addConnection = addConnection;

MasterAgent.prototype.removeConnection = removeConnection;

module.exports = MasterAgent;

<|start_filename|>bin/game-server/node_modules/pomelo-admin/sample/module.js<|end_filename|>
var logger = require('pomelo-logger').getLogger('pomelo-admin', 'test_module');

var DEFAULT_INTERVAL = 5; // in second
var DEFAULT_DELAY = 1; // in second

module.exports = function(opts) {
	return new Module(opts);
};

module.exports.moduleId = 'test_module';

var Module = function(opts) {
	opts = opts || {};
	this.type = opts.type || 'pull';
	this.interval = opts.interval || DEFAULT_INTERVAL;
	this.delay = opts.delay || DEFAULT_DELAY;
};

Module.prototype.monitorHandler = function(agent, msg, cb) {
	console.log('monitorHandler %j', msg);
	// agent.notify(module.exports.moduleId, {
	// 	serverId: agent.id,
	// 	body: {
	// 		hello: 'ok'
	// 	}
	// });
	cb(null, 'ok');
};

Module.prototype.masterHandler = function(agent, msg, cb) {
	if (!msg) {
		// agent.notifyAll(module.exports.moduleId);
		var sendMsg = {
			id: Date.now()
		}
		agent.request('test-server-1', module.exports.moduleId, sendMsg, function(err, r) {
			if (err) {
				console.error(err);
			}

			if (r) {
				console.log(r);
			}
		})
		return;
	}
	console.log('masterHandler %j', msg);
};

Module.prototype.clientHandler = function(agent, msg, cb) {
	console.log('clientHandler %j', msg);
};

<|start_filename|>bin/game-server/node_modules/pomelo-admin/node_modules/pomelo-scheduler/test/scheduleTest.js<|end_filename|>
var schedule = require('../lib/schedule');
var cronTrigger = require('../lib/cronTrigger');
var jobMap = [];

var simpleJob = function(data){
    var t = data.id+data.period;
    console.log("run for simple job :" + data.id + " period: " + data.period + " at time " + (new Date()));
}

var cronJob = function(data){
   console.log("run for cronJob :" + data.id  + " at time " + (new Date()));
}

function scheduleSimpleJobTest(count){
  var id = 0;
  for(var i = 0; i < count; i ++){
    var time = Math.ceil(Math.random() * 10 * 1000);
    var period = Math.ceil(Math.random()*60 * 1000 + 100)
    var id = schedule.scheduleJob({start:Date.now()+time,period:period}, simpleJob, {id:id++, period:period});
    jobMap.push(id);
  }
}

function scheduleCronJobTest(count){
  var id = 0;

//  var trigger = cronTrigger.decodeTrigger('* * 2-20 * * *');
  for(var i = 0; i < count; i++){
  var second = Math.floor(Math.random()*10);
    var id = schedule.scheduleJob('0/2,2-10,13-20,40-45,55-56 * * * * *', cronJob, {id:id++});
    jobMap.push(id);
  }
}

function cancleJob(data){
  var jobMap = data.jobMap;
  if(jobMap.length>0){
    var id = jobMap.pop();
    console.log("Cancel job : "  + id + " Last jobs count : " + jobMap.length);
    data.schedule.cancelJob(id);
}else
    console.log("All job has been cancled");
}

function scheduleCancleJobTest(){
  var id = schedule.scheduleJob({start:Date.now(),period:100, count:jobMap.length}, cancleJob, {jobMap:jobMap,schedule:schedule});
}

function test(){
  scheduleSimpleJobTest(5);

  scheduleCronJobTest(5);

//  scheduleCancleJobTest();
}

test();
//schedule.scheduleJob({period:30, count:4}, simpleJob, {name:'simpleJob'});

<|start_filename|>bin/game-server/node_modules/pomelo-protobuf/test/test.js<|end_filename|>
var protobuf = require('../lib/protobuf');
var util = require('../lib/util');

var protos = require('protos.json');

protobuf.init({
	encoderProtos: protos,
	decoderProtos: protos
});

describe('encodeTest', function() {
	for (var route in tc) {
		var msg = tc[route];
		var buffer = protobuf.encode(route, msg);

		console.log(msg);
		console.log(buffer.length);
		console.log(buffer)

		var decodeMsg = protobuf.decode(route, buffer);

		console.log(decodeMsg);

		util.equal(msg, decodeMsg).should.equal(true);
	}
});

<|start_filename|>bin/game-server/node_modules/mqtt/test/old/tester.js<|end_filename|>
var EventEmitter = require('events').EventEmitter,
  util = require('util'),
  assert = require('assert');

/*
 * Generates a mock stream object used for testing
 */
var Tester = function () {
  this.open = true;
  EventEmitter.call(this);
};

util.inherits(Tester, EventEmitter);

Tester.prototype.write = function (data) {
  assert.ok(this.open, "Not allowed to write, stream is closed");
  this.emit('data', data);
};

Tester.prototype.end = function () {
  this.open = false;
};

/*
 * used to fake events like close and error in tests
 */
Tester.prototype.do_emit = function (evt, data) {
  this.emit(evt, data);
};

module.exports = function () {
  return new Tester();
};



<|start_filename|>bin/game-server/node_modules/bops/typedarray/subarray.js<|end_filename|>
module.exports = subarray

function subarray(buf, from, to) {
  return buf.subarray(from || 0, to || buf.length)
}


<|start_filename|>bin/game-server/node_modules/mqtt/index.js<|end_filename|>
module.exports = require('./lib/mqtt');


<|start_filename|>bin/game-server/node_modules/bearcat-buffer/lib/inBuffer.js<|end_filename|>
var Utils = require('./util/utils');
var Codec = require('./util/codec');

var InBuffer = function(buffer) {
	this.buf = buffer;
	this.offset = 0;
	this.size = buffer.length;
}

InBuffer.prototype.read = function() {
	return this.readByte();
}

InBuffer.prototype.readBoolean = function() {
	var r = this.read();
	if (r < 0) {
		throw new Error('EOFException');
	}

	return (r != 0);
}

InBuffer.prototype.readByte = function() {
	this.check(1);
	return this.buf.readUInt8(this.offset++, true);
}

InBuffer.prototype.readBuffer = function() {
	var len = this.readUInt();
	this.check(len);
	var r = this.buf.slice(this.offset, this.offset + len);
	this.offset += len;
	return r;
}

InBuffer.prototype.readChar = function() {
	return this.readByte();
}

InBuffer.prototype.readVInt = function() {
	return Codec.decodeUInt32(this.getBytes());
}

InBuffer.prototype.readUInt = function() {
	return this.readVInt();
}

InBuffer.prototype.readSInt = function() {
	return Codec.decodeSInt32(this.getBytes());
}

InBuffer.prototype.readDouble = function() {
	this.check(8);
	var r = this.buf.readDoubleLE(this.offset, true);
	this.offset += 8;
	return r;
}

InBuffer.prototype.readFloat = function() {
	this.check(4);
	var r = this.buf.readFloatLE(this.offset, true);
	this.offset += 4;
	return r;
}

InBuffer.prototype.readInt = function() {
	this.check(4);
	var r = this.buf.readInt32LE(this.offset, true);
	this.offset += 4;
	return r;
}

InBuffer.prototype.readShort = function() {
	this.check(2);
	var r = this.buf.readInt16LE(this.offset, true);
	this.offset += 2;
	return r;
}

InBuffer.prototype.readUShort = function() {
	this.check(2);
	var r = this.buf.readUInt16LE(this.offset, true);
	this.offset += 2;
	return r;
}

InBuffer.prototype.readString = function() {
	var len = this.readUInt();
	this.check(len);
	var r = this.buf.toString('utf8', this.offset, this.offset + len);
	this.offset += len;
	return r;
}

InBuffer.prototype.getBytes = function() {
	var bytes = [];
	var offset = this.offset;

	var buffer = this.buf;
	var b;
	do {
		var b = buffer.readUInt8(offset, true);
		bytes.push(b);
		offset++;
	} while (b >= 128);

	this.offset = offset;

	return bytes;
}

InBuffer.prototype.readObject = function() {
	var type = this.readByte();
	var instance = null;
	var typeMap = Utils.typeMap;

	if (typeMap['null'] == type) {

	} else if (typeMap['buffer'] == type) {
		instance = this.readBuffer();
	} else if (typeMap['array'] == type) {
		instance = [];
		var len = this.readVInt();
		for (var i = 0; i < len; i++) {
			instance.push(this.readObject());
		}
	} else if (typeMap['string'] == type) {
		instance = this.readString();
	} else if (typeMap['object'] == type) {
		var objStr = this.readString();
		instance = JSON.parse(objStr);
	} else if (typeMap['bean'] == type) {
		var id = this.readString();
		var bearcat = Utils.getBearcat();
		var bean = bearcat.getBean(id);
		if (!bean) {
			throw new Error('readBean bean not found ' + id);
			return;
		}
		bean.readFields(this);
		instance = bean;
	} else if (typeMap['boolean'] == type) {
		instance = this.readBoolean();
	} else if (typeMap['float'] == type) {
		instance = this.readFloat();
	} else if (typeMap['uint'] == type) {
		instance = this.readUInt();
	} else if (typeMap['sint'] == type) {
		instance = this.readSInt();
	} else {
		throw new Error('readObject invalid read type ' + type);
	}

	return instance;
}

InBuffer.prototype.check = function(len) {
	if (this.offset + len > this.size) {
		throw new Error('IndexOutOfBoundsException');
	}
}

module.exports = InBuffer;

<|start_filename|>bin/game-server/node_modules/pomelo/template/game-server/config/adminServer.json<|end_filename|>
[{
    "type": "connector",
    "token": "<KEY>"
}
]

<|start_filename|>bin/game-server/node_modules/pomelo-scheduler/node_modules/log4js/.bob/instrumented/test/logger-test.js<|end_filename|>
"use strict";
var vows = require('vows')
, assert = require('assert')
, levels = require('../lib/levels')
, Logger = require('../lib/logger').Logger;

vows.describe('../lib/logger').addBatch({
  'constructor with no parameters': {
    topic: new Logger(),
    'should use default category': function(logger) {
      assert.equal(logger.category, Logger.DEFAULT_CATEGORY);
    },
    'should use TRACE log level': function(logger) {
      assert.equal(logger.level, levels.TRACE);
    }
  },

  'constructor with category': {
    topic: new Logger('cheese'),
    'should use category': function(logger) {
      assert.equal(logger.category, 'cheese');
    },
    'should use TRACE log level': function(logger) {
      assert.equal(logger.level, levels.TRACE);
    }
  },

  'constructor with category and level': {
    topic: new Logger('cheese', 'debug'),
    'should use category': function(logger) {
      assert.equal(logger.category, 'cheese');
    },
    'should use level': function(logger) {
      assert.equal(logger.level, levels.DEBUG);
    }
  },

  'isLevelEnabled': {
    topic: new Logger('cheese', 'info'),
    'should provide a level enabled function for all levels': function(logger) {
      assert.isFunction(logger.isTraceEnabled);
      assert.isFunction(logger.isDebugEnabled);
      assert.isFunction(logger.isInfoEnabled);
      assert.isFunction(logger.isWarnEnabled);
      assert.isFunction(logger.isErrorEnabled);
      assert.isFunction(logger.isFatalEnabled);
    },
    'should return the right values': function(logger) {
      assert.isFalse(logger.isTraceEnabled());
      assert.isFalse(logger.isDebugEnabled());
      assert.isTrue(logger.isInfoEnabled());
      assert.isTrue(logger.isWarnEnabled());
      assert.isTrue(logger.isErrorEnabled());
      assert.isTrue(logger.isFatalEnabled());
    }
  }
}).exportTo(module);


<|start_filename|>bin/game-server/node_modules/bearcat-buffer/index.js<|end_filename|>
module.exports.inBuffer = require('./lib/inBuffer');
module.exports.outBuffer = require('./lib/outBuffer');


<|start_filename|>bin/game-server/node_modules/mqtt/test/old/qos.test.js<|end_filename|>
/*global describe, it, before, after */

var assert = require('assert'),
  should = require('should');

var servers = require('./helpers/server');

var mqtt = require('../lib/mqtt'),
  HOST = 'localhost',
  PORT = (process.env.PORT || 1883) + 2;




describe.skip("Client-Server QOS Test", function () {
  before(function (done) {
    var self = this;
    this.server = servers.init_server(PORT);
    mqtt.createClient(PORT, HOST, function (err, client) {
      should.not.exist(err);
      self.client = client;
      done();
    });
  });

  describe("Client", function () {
    it("Client should connect", function (done) {
      this.client.connect({keepalive: 1000});
      this.client.on('connack', function (packet) {
        done();
      });
    });

    it("qos 0", function (done) {
      this.client.publish({
        topic: 'test0',
        payload: 'test',
        qos: 0
      });
      done();
    });


    it("qos 1", function (done) {
      this.client.once('puback', function (packet) {
        should.exist(packet);
        packet.should.have.property('messageId');
        done();
      });
      this.client.publish({
        topic: 'test1',
        payload: 'test',
        qos: 1
      });
    });

    it("qos 2", function (done) {
      this.client.once('pubrec', function (packet) {
        should.exist(packet);
        packet.should.have.property('messageId');
        done();
      });
      this.client.publish({
        topic: 'test2',
        payload: 'test',
        qos: 2
      });
    });
  });//describe client
});


<|start_filename|>bin/game-server/node_modules/bops/typedarray/from.js<|end_filename|>
module.exports = from

var base64 = require('base64-js')

var decoders = {
    hex: from_hex
  , utf8: from_utf
  , base64: from_base64
}

function from(source, encoding) {
  if(Array.isArray(source)) {
    return new Uint8Array(source)
  }

  return decoders[encoding || 'utf8'](source)
}

function from_hex(str) {
  var size = str.length / 2
    , buf = new Uint8Array(size)
    , character = ''

  for(var i = 0, len = str.length; i < len; ++i) {
    character += str.charAt(i)

    if(i > 0 && (i % 2) === 1) {
      buf[i>>>1] = parseInt(character, 16)
      character = '' 
    }
  }

  return buf 
}

function from_utf(str) {
  var arr = []
    , code

  for(var i = 0, len = str.length; i < len; ++i) {
    code = fixed_cca(str, i)

    if(code === false) {
      continue
    }

    if(code < 0x80) {
      arr[arr.length] = code

      continue
    }

    codepoint_to_bytes(arr, code)
  }

  return new Uint8Array(arr)
}

function codepoint_to_bytes(arr, code) {
  // find MSB, use that to determine byte count
  var copy_code = code
    , bit_count = 0
    , byte_count
    , prefix
    , _byte
    , pos

  do {
    ++bit_count
  } while(copy_code >>>= 1)

  byte_count = Math.ceil((bit_count - 1) / 5) | 0
  prefix = [0, 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc][byte_count]
  pos = [0, 0, 3, 4, 5, 6, 7][byte_count]

  _byte |= prefix

  bit_count = (7 - pos) + 6 * (byte_count - 1)

  while(bit_count) {
    _byte |= +!!(code & (1 << bit_count)) << (7 - pos)
    ++pos

    if(pos % 8 === 0) {
      arr[arr.length] = _byte
      _byte = 0x80
      pos = 2
    }

    --bit_count
  }

  if(pos) {
    _byte |= +!!(code & 1) << (7 - pos)
    arr[arr.length] = _byte
  }
}

function pad(str) {
  while(str.length < 8) {
    str = '0' + str
  }

  return str
}

function fixed_cca(str, idx) {
  idx = idx || 0

  var code = str.charCodeAt(idx)
    , lo
    , hi

  if(0xD800 <= code && code <= 0xDBFF) {
    lo = str.charCodeAt(idx + 1)
    hi = code

    if(isNaN(lo)) {
      throw new Error('High surrogate not followed by low surrogate')
    }

    return ((hi - 0xD800) * 0x400) + (lo - 0xDC00) + 0x10000
  }

  if(0xDC00 <= code && code <= 0xDFFF) {
    return false
  }

  return code
}

function from_base64(str) {
  return new Uint8Array(base64.toByteArray(str)) 
}


<|start_filename|>bin/game-server/node_modules/pomelo-protobuf/lib/codec.js<|end_filename|>
var Encoder = module.exports;

/**
 * [encode an uInt32, return a array of bytes]
 * @param  {[integer]} num
 * @return {[array]}
 */
Encoder.encodeUInt32 = function(num){
	var n = parseInt(num);
	if(isNaN(n) || n < 0){
		console.log(n);
		return null;
	}

	var result = [];
	do{
		var tmp = n % 128;
		var next = Math.floor(n/128);

		if(next !== 0){
			tmp = tmp + 128;
		}
		result.push(tmp);
		n = next;
	} while(n !== 0);

	return result;
};

/**
 * [encode a sInt32, return a byte array]
 * @param  {[sInt32]} num  The sInt32 need to encode
 * @return {[array]} A byte array represent the integer
 */
Encoder.encodeSInt32 = function(num){
	var n = parseInt(num);
	if(isNaN(n)){
		return null;
	}
	n = n<0?(Math.abs(n)*2-1):n*2;

	return Encoder.encodeUInt32(n);
};

Encoder.decodeUInt32 = function(bytes){
	var n = 0;

	for(var i = 0; i < bytes.length; i++){
		var m = parseInt(bytes[i]);
		n = n + ((m & 0x7f) * Math.pow(2,(7*i)));
		if(m < 128){
			return n;
		}
	}

	return n;
};


Encoder.decodeSInt32 = function(bytes){
	var n = this.decodeUInt32(bytes);
	var flag = ((n%2) === 1)?-1:1;

	n = ((n%2 + n)/2)*flag;

	return n;
};


<|start_filename|>bin/game-server/node_modules/pomelo/lib/util/countDownLatch.js<|end_filename|>
var exp = module.exports;

/**
 * Count down to zero or timeout and invoke cb finally.
 */
var CountDownLatch = function(count, opts, cb) {
  this.count = count;
  this.cb = cb;
  var self = this;
  if (opts.timeout) {
    this.timerId = setTimeout(function() {
      self.cb(true);
    }, opts.timeout);
  }
};

/**
 * Call when a task finish to count down.
 *
 * @api public
 */
CountDownLatch.prototype.done = function() {
  if(this.count <= 0) {
    throw new Error('illegal state.');
  }

  this.count--;
  if (this.count === 0) {
    if (this.timerId) {
      clearTimeout(this.timerId);
    }
    this.cb();
  }
};

/**
 * Create a count down latch
 *
 * @param {Integer} count
 * @param {Object} opts, opts.timeout indicates timeout, optional param
 * @param {Function} cb, cb(isTimeout)
 *
 * @api public
 */
exp.createCountDownLatch = function(count, opts, cb) {
  if(!count || count <= 0) {
    throw new Error('count should be positive.');
  }

  if (!cb && typeof opts === 'function') {
    cb = opts;
    opts = {};
  }

  if(typeof cb !== 'function') {
    throw new Error('cb should be a function.');
  }

  return new CountDownLatch(count, opts, cb);
};


<|start_filename|>bin/game-server/node_modules/bops/typedarray/to.js<|end_filename|>
module.exports = to

var base64 = require('base64-js')
  , toutf8 = require('to-utf8')

var encoders = {
    hex: to_hex
  , utf8: to_utf
  , base64: to_base64
}

function to(buf, encoding) {
  return encoders[encoding || 'utf8'](buf)
}

function to_hex(buf) {
  var str = ''
    , byt

  for(var i = 0, len = buf.length; i < len; ++i) {
    byt = buf[i]
    str += ((byt & 0xF0) >>> 4).toString(16)
    str += (byt & 0x0F).toString(16)
  }

  return str
}

function to_utf(buf) {
  return toutf8(buf)
}

function to_base64(buf) {
  return base64.fromByteArray(buf)
}



<|start_filename|>bin/game-server/node_modules/bops/test/from.js<|end_filename|>
var test = require('tape')
  , binary = require('../index')

test('from array works', function(assert) {
  var arr = [1, 2, 3]
    , buf = binary.from(arr)

  assert.equal(buf.length, arr.length)
  for(var i = 0, len = arr.length; i < len; ++i) {
    assert.equal(binary.readUInt8(buf, i), arr[i])
  }
  assert.end()
})

test('from utf8 works as expected', function(assert) {
  var buf = binary.from('\ud835\udc00 ƒello 淾淾淾 hello world 淾淾 yep ƒuu 淾 \ud83d\ude04', 'utf8')
    , expect

  expect = [0xf0, 0x9d, 0x90, 0x80, 0x20, 198,146,101,108,108,111,32,230,183,190,230,183,190,230,183,190,32,104,101,108,108,111,32,119,111,114,108,100,32,230,183,190,230,183,190,32,121,101,112,32,198,146,117,117,32,230,183,190,32,0xF0,0x9F,0x98,0x84]

  assert.equal(buf.length, expect.length)
  for(var i = 0, len = buf.length; i < len; ++i) {
    assert.equal(binary.readUInt8(buf, i), expect[i])
  }

  assert.end()
})

test('from utf8 works on odd unicode codepoints', function(assert) {
  var string = '好'

  var expect = [0xe5, 0xa5, 0xbd]
    , buf = binary.from(string)

  for(var i = 0, len = buf.length; i < len; ++i) {
    assert.equal(binary.readUInt8(buf, i), expect[i])
  }

  assert.end()
})

test('from hex works as expected', function(assert) {
  var buf = binary.from('68656c6c6f20776f726c64c692000a0809', 'hex')
    , expect

  expect = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 198, 146, 0, 10, 8, 9]

  assert.equal(buf.length, expect.length)
  for(var i = 0, len = buf.length; i < len; ++i) {
    assert.equal(binary.readUInt8(buf, i), expect[i])
  }

  assert.end()
})

test('from base64 works as expected', function(assert) {
  var buf = binary.from('aGVsbG8gd29ybGTGkgAKCAk=', 'base64')
    , expect

  expect = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 198, 146, 0, 10, 8, 9]

  assert.equal(buf.length, expect.length)
  for(var i = 0, len = buf.length; i < len; ++i) {
    assert.equal(binary.readUInt8(buf, i), expect[i])
  }

  assert.end()
})


<|start_filename|>bin/game-server/node_modules/mqtt/lib/parsing_utils_browser.js<|end_filename|>
var bops = require('bops');

module.exports.parseEncodedPayload = function(parser, buf, encoding, packet) {
  buf = bops.subarray(buf, parser._pos, parser._len);

  if (encoding !== 'binary') {
    buf = bops.to(buf, encoding);
  }

  packet.payload = buf;
};

module.exports.toString = function(parser, buf, length, encoding) {

  if (encoding !== 'binary') {
    buf = bops.to(buf, encoding);
  }

  return bops.to(bops.subarray(buf, parser._pos, parser._pos + length), 'utf8');
};


<|start_filename|>bin/game-server/node_modules/bops/typedarray/create.js<|end_filename|>
module.exports = function(size) {
  return new Uint8Array(size)
}


<|start_filename|>bin/game-server/node_modules/mqtt/test/secure_client.js<|end_filename|>
  
/**
 * Testing dependencies
 */
var mqtt = require('..')
  , abstractClientTests = require("./abstract_client");

/**
 * Modules to be tested
 */
var createClient = require('../lib/mqtt').createSecureClient;

/**
 * Testing options
 */
var port = 9899;

var KEY = __dirname + '/helpers/tls-key.pem';
var CERT = __dirname + '/helpers/tls-cert.pem';

var WRONG_CERT = __dirname + '/helpers/wrong-cert.pem';

/**
 * Test server
 */
var server = mqtt.createSecureServer(KEY, CERT, function (client) {
  client.on('connect', function(packet) {
    if (packet.clientId === 'invalid') {
      client.connack({returnCode: 2});
    } else {
      server.emit('connect', client);
      client.connack({returnCode: 0});
    }
  });

  client.on('publish', function (packet) {
    switch (packet.qos) {
      case 0:
        break;
      case 1:
        client.puback(packet);
        break;
      case 2:
        client.pubrec(packet);
        break;
    }
  });

  client.on('pubrel', function(packet) {
    client.pubcomp(packet);
  });

  client.on('pubrec', function(packet) {
    client.pubrel(packet);
  });

  client.on('pubcomp', function(packet) {
    // Nothing to be done
  });

  client.on('subscribe', function(packet) {
    client.suback({
      messageId: packet.messageId,
      granted: packet.subscriptions.map(function (e) {
        return e.qos;
      })
    });
  });

  client.on('unsubscribe', function(packet) {
    client.unsuback(packet);
  });

  client.on('pingreq', function(packet) {
    client.pingresp();
  });
}).listen(port);

describe('MqttSecureClient', function () {
  abstractClientTests(server, createClient, port);

  if (!process.version.match(/^v0.8/)) {
    describe('with secure parameters', function() {

      it('should validate successfully the CA', function (done) {
        var client = createClient(port, {
          ca: [CERT],
          rejectUnauthorized: true
        });

        client.on('error', done)

        server.once('connect', function(client) {
          done();
        });
      });

      it('should validate unsuccessfully the CA', function (done) {
        var client = createClient(port, {
          ca: [WRONG_CERT],
          rejectUnauthorized: true
        });

        server.once('connect', function(client) {
          done(new Error('it should not happen'));
        });

        client.once('error', function() {
          done()
        })
      });

      it('should emit close on TLS error', function (done) {
        var client = createClient(port, {
          ca: [WRONG_CERT],
          rejectUnauthorized: true
        });

        client.on('error', function() {})

        // TODO node v0.8.x emits multiple close events
        client.once('close', function() {
          done()
        })
      });
    })
  }
});


<|start_filename|>bin/game-server/node_modules/base64-js/lib/b64.js<|end_filename|>
(function (exports) {
	'use strict';

	var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

	function b64ToByteArray(b64) {
		var i, j, l, tmp, placeHolders, arr;
	
		if (b64.length % 4 > 0) {
			throw 'Invalid string. Length must be a multiple of 4';
		}

		// the number of equal signs (place holders)
		// if there are two placeholders, than the two characters before it
		// represent one byte
		// if there is only one, then the three characters before it represent 2 bytes
		// this is just a cheap hack to not do indexOf twice
		placeHolders = b64.indexOf('=');
		placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0;

		// base64 is 4/3 + up to two characters of the original data
		arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders);

		// if there are placeholders, only get up to the last complete 4 chars
		l = placeHolders > 0 ? b64.length - 4 : b64.length;

		for (i = 0, j = 0; i < l; i += 4, j += 3) {
			tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]);
			arr.push((tmp & 0xFF0000) >> 16);
			arr.push((tmp & 0xFF00) >> 8);
			arr.push(tmp & 0xFF);
		}

		if (placeHolders === 2) {
			tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4);
			arr.push(tmp & 0xFF);
		} else if (placeHolders === 1) {
			tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2);
			arr.push((tmp >> 8) & 0xFF);
			arr.push(tmp & 0xFF);
		}

		return arr;
	}

	function uint8ToBase64(uint8) {
		var i,
			extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
			output = "",
			temp, length;

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

		// go through the array every three bytes, we'll deal with trailing stuff later
		for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
			temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
			output += tripletToBase64(temp);
		}

		// pad the end with zeros, but make sure to not forget the extra bytes
		switch (extraBytes) {
			case 1:
				temp = uint8[uint8.length - 1];
				output += lookup[temp >> 2];
				output += lookup[(temp << 4) & 0x3F];
				output += '==';
				break;
			case 2:
				temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);
				output += lookup[temp >> 10];
				output += lookup[(temp >> 4) & 0x3F];
				output += lookup[(temp << 2) & 0x3F];
				output += '=';
				break;
		}

		return output;
	}

	module.exports.toByteArray = b64ToByteArray;
	module.exports.fromByteArray = uint8ToBase64;
}());


<|start_filename|>bin/game-server/node_modules/bops/join.js<|end_filename|>
var Buffer = require('buffer').Buffer

module.exports = function(targets, hint) {
  return hint !== undefined ?
    Buffer.concat(targets, hint) :
    Buffer.concat(targets)
}


<|start_filename|>bin/game-server/node_modules/mqtt/examples/client/secure-client.js<|end_filename|>

var mqtt = require('../..');
var KEY = __dirname + '/../../test/helpers/tls-key.pem';
var CERT = __dirname + '/../../test/helpers/tls-cert.pem';

var PORT = 8443;

var options = {
  keyPath: KEY,
  certPath: CERT,
  rejectUnauthorized : false
};

var client = mqtt.createSecureClient(PORT, options);

client.subscribe('messages');
client.publish('messages', 'Current time is: ' + new Date());
client.on('message', function(topic, message) {
  console.log(message);
});


<|start_filename|>bin/game-server/node_modules/bops/test/to.js<|end_filename|>
var test = require('tape')
  , binary = require('../index')

test('to utf8 works as expected', function(assert) {
  var buf = binary.from([198,146,101,108,108,111,32,230,183,190,230,183,190,230,183,190,32,104,101,108,108,111,32,119,111,114,108,100,32,230,183,190,230,183,190,32,121,101,112,32,198,146,117,117,32,230,183,190])
    , expect = 'ƒello 淾淾淾 hello world 淾淾 yep ƒuu 淾'

  assert.equal(expect, binary.to(buf, 'utf8'))
  assert.end()
})

test('from hex works as expected', function(assert) {
  var buf = binary.from([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 198, 146, 0, 10, 8, 9])
    , expect = '68656c6c6f20776f726c64c692000a0809'

  assert.equal(binary.to(buf, 'hex'), expect)
  assert.end()
})

test('from base64 works as expected', function(assert) {
  var buf = binary.from([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 198, 146, 0, 10, 8, 9])
    , expect = 'aGVsbG8gd29ybGTGkgAKCAk='

  assert.equal(binary.to(buf, 'base64'), expect)
  assert.end()
})


<|start_filename|>bin/game-server/node_modules/bops/typedarray/join.js<|end_filename|>
module.exports = join

function join(targets, hint) {
  if(!targets.length) {
    return new Uint8Array(0)
  }

  var len = hint !== undefined ? hint : get_length(targets)
    , out = new Uint8Array(len)
    , cur = targets[0]
    , curlen = cur.length
    , curidx = 0
    , curoff = 0
    , i = 0

  while(i < len) {
    if(curoff === curlen) {
      curoff = 0
      ++curidx
      cur = targets[curidx]
      curlen = cur && cur.length
      continue
    }
    out[i++] = cur[curoff++] 
  }

  return out
}

function get_length(targets) {
  var size = 0
  for(var i = 0, len = targets.length; i < len; ++i) {
    size += targets[i].byteLength
  }
  return size
}


<|start_filename|>bin/game-server/node_modules/mqtt/test/util.js<|end_filename|>
/**
 * Requires
 */

var util = require('util')
  , Stream = require('stream').Transform;

if (!Stream) {
  Stream = require("readable-stream").Transform;
}

/**
 * Export TestStream
 */

var TestStream = module.exports.TestStream = 
function TestStream() {
  if (!this instanceof TestStream) return new TestStream();

  Stream.call(this);
};
util.inherits(TestStream, Stream);

TestStream.prototype._transform = function(buffer, encoding, callback) {
  if (!Buffer.isBuffer(buffer)) {
    buffer = new Buffer(buffer, encoding);
  }
  setTimeout(function () {
    callback(null, buffer);
  }, 10);
};


<|start_filename|>bin/game-server/node_modules/mqtt-connection/test/connection.parse.js<|end_filename|>
/**
 * Testing requires
 */
var should = require('should')
  , stream = require('./util').testStream;

// This is so we can use eql to compare Packet objects with plain objects:
should.config.checkProtoEql = false;

/**
 * Units under test
 */
var Connection = require('../connection');

module.exports = function() {

  describe('connect', function() {
    it('should fire a connect event (minimal)', function(done) {
      var expected =  {
        cmd: "connect",
        retain: false,
        qos: 0,
        dup: false,
        length: 18,
        protocolId: "MQIsdp",
        protocolVersion: 3,
        clean: false,
        keepalive: 30,
        clientId: "test",
        topic: null,
        payload: null
      };

      var fixture = [
        16, 18, // Header
        0, 6, // Protocol id length
        77, 81, 73, 115, 100, 112, // Protocol id
        3, // Protocol version
        0, // Connect flags
        0, 30, // Keepalive
        0, 4, //Client id length
        116, 101, 115, 116 // Client id
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('connect', function(packet) {
        packet.should.eql(expected);
        done();
      });

    });

    it('should fire a connect event (maximal)', function(done) {
      var expected = {
        cmd: "connect",
        retain: false,
        qos: 0,
        dup: false,
        length: 54,
        protocolId: "MQIsdp",
        protocolVersion: 3,
        will: {
          retain: true,
          qos: 2,
          topic: "topic",
          payload: new Buffer("payload")
        },
        clean: true,
        keepalive: 30,
        clientId: "test",
        username: "username",
        password: new Buffer("password"),
        topic: null,
        payload: null
      };
      var fixture = [
        16, 54, // Header
        0, 6, // Protocol id length
        77, 81, 73, 115, 100, 112, // Protocol id
        3, // Protocol version
        246, // Connect flags
        0, 30, // Keepalive
        0, 4, // Client id length
        116, 101, 115, 116, // Client id
        0, 5, // will topic length
        116, 111, 112, 105, 99, // will topic
        0, 7, // will payload length
        112, 97, 121, 108, 111, 97, 100, // will payload
        0, 8, // username length
        117, 115, 101, 114, 110, 97, 109, 101, // username
        0, 8, // password length
        112, 97, 115, 115, 119, 111, 114, 100 //password
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('connect', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });

    describe('parse errors', function() {
      it('should say protocol not parseable', function(done) {
        var fixture = [
          16, 4,
          0, 6,
          77, 81
        ];

        this.stream.write(new Buffer(fixture));
        this.conn.once('error', function(err) {
          err.message.should.match(/cannot parse protocol id/i);
          done();
        });
      });
    });
  });

  describe('connack', function() {
    it('should fire a connack event (rc = 0)', function(done) {
      var expected = {
        cmd: 'connack',
        retain: false,
        qos: 0,
        dup: false,
        length: 2,
        sessionPresent: false,
        returnCode: 0,
        topic: null,
        payload: null
      }

      var fixture = [32, 2, 0, 0];

      this.stream.write(new Buffer(fixture));

      this.conn.once('connack', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });

    it('should fire a connack event (rc = 5)', function(done) {
      var expected = {
        cmd: 'connack',
        retain: false,
        qos: 0,
        dup: false,
        length: 2,
        sessionPresent: false,
        returnCode: 5,
        topic: null,
        payload: null
      }

      var fixture = [32, 2, 0, 5];

      this.stream.write(new Buffer(fixture));

      this.conn.once('connack', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('publish', function() {
    it('should fire a publish event (minimal)', function(done) {
      var expected = {
        cmd: "publish",
        retain: false,
        qos: 0,
        dup: false,
        length: 10,
        topic: "test",
        payload: new Buffer("test")
      };

      var fixture = [
        48, 10, // Header
        0, 4, // Topic length
        116, 101, 115, 116, // Topic (test)
        116, 101, 115, 116 // Payload (test)
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('publish', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });

    it('should fire a publish event with 2KB payload', function(done) {
      var expected = {
        cmd: "publish",
        retain: false,
        qos: 0,
        dup: false,
        length: 2054,
        topic: "test",
        payload: new Buffer(2048)
      };

      var fixture = new Buffer([
        48, 134, 16, // Header
        0, 4, // Topic length
        116, 101, 115, 116, // Topic (test)
      ]);

      fixture = Buffer.concat([fixture, expected.payload]);

      var s = stream()
      var c = new Connection(s);

      s.write(fixture);

      c.once('publish', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });

    it('should fire a publish event with 2MB payload', function(done) {
      var expected = {
        cmd: "publish",
        retain: false,
        qos: 0,
        dup: false,
        length: 6 + 2 * 1024 * 1024,
        topic: "test",
        payload: new Buffer(2 * 1024 * 1024)
      };

      var fixture = new Buffer([
        48, 134, 128, 128, 1, // Header
        0, 4, // Topic length
        116, 101, 115, 116, // Topic (test)
      ]);

      fixture = Buffer.concat([fixture, expected.payload]);

      var s = stream()
      var c = new Connection(s);

      s.write(fixture);

      c.once('publish', function(packet) {
        // comparing the whole 2MB buffer is very slow so only check the length
        packet.length.should.eql(expected.length);
        done();
      });
    });

    it('should fire a publish event (maximal)', function (done) {
      var expected = {
        cmd:"publish",
        retain: true,
        qos: 2,
        length: 12,
        dup: true,
        topic: "test",
        messageId: 10,
        payload: new Buffer("test")
      };

      var fixture = [
        61, 12, // Header
        0, 4, // Topic length
        116, 101, 115, 116, // Topic
        0, 10, // Message id
        116, 101, 115, 116 // Payload
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('publish', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });

    it('should fire an empty publish', function(done) {
      var expected = {
        cmd: "publish",
        retain: false,
        qos: 0,
        dup: false,
        length: 6,
        topic: "test",
        payload: new Buffer(0)
      };

      var fixture = [
        48, 6, // Header
        0, 4, // Topic length
        116, 101, 115, 116 // Topic
        // Empty payload
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('publish', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });

    it('should parse a splitted publish', function(done) {
      var expected = {
        cmd: "publish",
        retain: false,
        qos: 0,
        dup: false,
        length: 10,
        topic: "test",
        payload: new Buffer("test")
      };

      var fixture1 = [
        48, 10, // Header
        0, 4, // Topic length
        116, 101, 115, 116 // Topic (test)
      ];

      var fixture2 = [
        116, 101, 115, 116 // Payload (test)
      ];

      this.stream.write(new Buffer(fixture1));
      this.stream.write(new Buffer(fixture2));

      this.conn.once('publish', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('puback', function() {
    it('should fire a puback event', function(done) {
      var expected = {
        cmd: 'puback',
        retain: false,
        qos: 0,
        dup: false,
        length: 2,
        messageId: 2,
        topic: null,
        payload: null
      };

      var fixture = [
        64, 2, // Header
        0, 2 // Message id
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('puback', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('pubrec', function() {
    it('should fire a pubrec event', function(done) {
      var expected = {
        cmd: 'pubrec',
        retain: false,
        qos: 0,
        dup: false,
        length: 2,
        messageId: 3,
        topic: null,
        payload: null
      };

      var fixture = [
        80, 2, // Header
        0, 3 // Message id
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('pubrec', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('pubrel', function() {
    it('should fire a pubrel event', function(done) {
      var expected = {
        cmd: 'pubrel',
        retain: false,
        qos: 0,
        dup: false,
        length: 2,
        messageId: 4,
        topic: null,
        payload: null
      };

      var fixture = [
        96, 2, // Header
        0, 4 // Message id
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('pubrel', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('pubcomp', function() {
    it('should fire a pubcomp event', function(done) {
      var expected = {
        cmd: 'pubcomp',
        retain: false,
        qos: 0,
        dup: false,
        length: 2,
        messageId: 5,
        topic: null,
        payload: null
      };

      var fixture = [
        112, 2, // Header
        0, 5 // Message id
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('pubcomp', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('subscribe', function() {
    it('should fire a subscribe event (1 topic)', function (done) {
      var expected = {
        cmd: 'subscribe',
        retain: false,
        qos: 1,
        dup: false,
        length: 9,
        subscriptions: [
          {
            topic: "test",
            qos: 0
          }
        ],
        messageId: 6,
        topic: null,
        payload: null
      };

      var fixture = [
        130, 9, // Header (publish, qos=1, length=9)
        0, 6, // message id (6)
        0, 4, // topic length,
        116, 101, 115, 116, // Topic (test)
        0 // qos (0)
      ];
      this.stream.write(new Buffer(fixture));

      this.conn.once('subscribe', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });

    it('should fire a subscribe event (3 topic)', function (done) {
      var expected = {
        cmd: 'subscribe',
        retain: false,
        qos: 1,
        dup: false,
        length: 23,
        subscriptions: [
          {
            topic: "test",
            qos: 0
          },{
            topic: "uest",
            qos: 1
          },{
            topic: "tfst",
            qos: 2
          }
        ],
        messageId: 6,
        topic: null,
        payload: null
      };

      var fixture = [
        130, 23, // Header (publish, qos=1, length=9)
        0, 6, // message id (6)
        0, 4, // topic length,
        116, 101, 115, 116, // Topic (test)
        0, // qos (0)
        0, 4, // topic length
        117, 101, 115, 116, // Topic (uest)
        1, // qos (1)
        0, 4, // topic length
        116, 102, 115, 116, // Topic (tfst)
        2 // qos (2)
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('subscribe', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('suback', function() {
    it('should fire a suback event', function(done) {
      var expected = {
        cmd: 'suback',
        retain: false,
        qos: 0,
        dup: false,
        length: 6,
        granted: [0, 1, 2, 128],
        messageId: 6,
        topic: null,
        payload: null
      };

      var fixture = [
        144, 6, // Header
        0, 6, // Message id
        0, 1, 2, 128 // Granted qos (0, 1, 2) and a rejected being 0x80
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('suback', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('unsubscribe', function() {
    it('should fire an unsubscribe event', function(done) {
      var expected = {
        cmd: 'unsubscribe',
        retain: false,
        qos: 1,
        dup: false,
        length: 14,
        unsubscriptions: [
          'tfst',
          'test'
        ],
        messageId: 7,
        topic: null,
        payload: null
      }

      var fixture = [
        162, 14,
        0, 7, // message id (7)
        0, 4, // topic length
        116, 102, 115, 116, // Topic (tfst)
        0, 4, // topic length,
        116, 101, 115, 116, // Topic (test)
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('unsubscribe', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('unsuback', function() {
    it('should fire a unsuback event', function(done) {
      var expected = {
        cmd: 'unsuback',
        retain: false,
        qos: 0,
        dup: false,
        length: 2,
        messageId: 8,
        topic: null,
        payload: null
      };

      var fixture = [
        176, 2, // Header
        0, 8 // Message id
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('unsuback', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('pingreq', function() {
    it('should fire a pingreq event', function(done) {
      var expected = {
        cmd: 'pingreq',
        retain: false,
        qos: 0,
        dup: false,
        length: 0,
        topic: null,
        payload: null
      };

      var fixture = [
        192, 0 // Header
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('pingreq', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('pingresp', function() {
    it('should fire a pingresp event', function(done) {
      var expected = {
        cmd: 'pingresp',
        retain: false,
        qos: 0,
        dup: false,
        length: 0,
        topic: null,
        payload: null
      };

      var fixture = [
        208, 0 // Header
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('pingresp', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('disconnect', function() {
    it('should fire a disconnect event', function(done) {
      var expected = {
        cmd: 'disconnect',
        retain: false,
        qos: 0,
        dup: false,
        length: 0,
        topic: null,
        payload: null
      };

      var fixture = [
        224, 0 // Header
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('disconnect', function(packet) {
        packet.should.eql(expected);
        done();
      });
    });
  });

  describe('reserverd (15)', function() {
    it('should emit an error', function(done) {
      var fixture = [
        240, 0 // Header
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('error', function(err) {
        done();
      });
    });
  });

  describe('reserverd (0)', function() {
    it('should emit an error', function(done) {
      var fixture = [
        0, 0 // Header
      ];

      this.stream.write(new Buffer(fixture));

      this.conn.once('error', function(err) {
        done();
      });
    });
  });
};


<|start_filename|>bin/game-server/node_modules/pomelo/lib/components/session.js<|end_filename|>
var SessionService = require('../common/service/sessionService');

module.exports = function(app, opts) {
  var cmp = new Component(app, opts);
  app.set('sessionService', cmp, true);
  return cmp;
};

/**
 * Session component. Manage sessions.
 *
 * @param {Object} app  current application context
 * @param {Object} opts attach parameters
 */
var Component = function(app, opts) {
  opts = opts || {};
  this.app = app;
  this.service = new SessionService(opts);

  var getFun = function(m) {
    return (function() {
          return function() {
            return self.service[m].apply(self.service, arguments);
          };
    })();
  };
  // proxy the service methods except the lifecycle interfaces of component
  var method, self = this;
  for(var m in this.service) {
    if(m !== 'start' && m !== 'stop') {
      method = this.service[m];
      if(typeof method === 'function') {
        this[m] = getFun(m);
      }
    }
  }
};

Component.prototype.name = '__session__';


<|start_filename|>bin/game-server/node_modules/mqtt/test/mqtt.js<|end_filename|>
/**
 * Testing includes
 */

var should = require('should')
  , net = require('net')
  , sinon = require('sinon');

/**
 * Unit under test
 */

var mqtt = require('../lib/mqtt');

describe('mqtt', function() {

  describe('#connect', function () {
    it('should return an MqttClient when connect is called with mqtt:/ url', function () {
      var c = mqtt.connect('mqtt://localhost:1883');

      c.should.be.instanceOf(mqtt.MqttClient);
    });

    it('should return an MqttClient with username option set', function () {
      var c = mqtt.connect('mqtt://user:pass@localhost:1883');

      c.should.be.instanceOf(mqtt.MqttClient);
      c.options.should.have.property('username', 'user');
      c.options.should.have.property('password', '<PASSWORD>');
    });

    it('should return an MqttClient with username and password options set', function () {
      var c = mqtt.connect('mqtt://user@localhost:1883');

      c.should.be.instanceOf(mqtt.MqttClient);
      c.options.should.have.property('username', 'user');
    });

    it('should return an MqttClient with the clientid option set', function () {
      var c = mqtt.connect('mqtt://user@localhost:1883?clientId=123');

      c.should.be.instanceOf(mqtt.MqttClient);
      c.options.should.have.property('clientId', '123');
    });

    it('should return an MqttClient when connect is called with tcp:/ url', function () {
      var c = mqtt.connect('tcp://localhost');

      c.should.be.instanceOf(mqtt.MqttClient);
    });

    it('should return an MqttClient with correct host when called with a host and port', function () {
      sinon.spy(mqtt, "createClient");
      var c = mqtt.connect('tcp://user:pass@localhost:1883');
      mqtt.createClient.calledWith('1883', 'localhost').should.be.ok;
    });

    it('should throw an error when connect is called without a brokerUrl', function () {
      (function(){
        mqtt.connect()
      }).should.throwError(/^Missing brokerUrl/);
    });

    var sslOpts = {
      keyPath: __dirname + '/helpers/private-key.pem',
      certPath: __dirname + '/helpers/public-cert.pem',
      ca: [__dirname + '/helpers/public-cert.pem']
    };

    it('should return an MqttClient when connect is called with mqtts:/ url', function () {
      var c = mqtt.connect('mqtts://localhost', sslOpts);

      c.on('error', function() {});

      c.should.be.instanceOf(mqtt.MqttClient);
    });

    it('should return an MqttClient when connect is called with ssl:/ url', function () {
      var c = mqtt.connect('ssl://localhost', sslOpts);

      c.on('error', function() {});

      c.should.be.instanceOf(mqtt.MqttClient);
    });

    it('should throw an error when an unknown protocol is supplied', function () {
      (function(){
        mqtt.connect('http://localhost')
      }).should.throwError(/^Unknown protocol/);
    });
  });

  describe('#createClient', function() {
    it('should return an MqttClient', function() {
      var c = mqtt.createClient();

      c.should.be.instanceOf(mqtt.MqttClient);
    });
  });

  describe('#createSecureClient', function() {
    it('should return an MqttClient', function() {
      var c = mqtt.createSecureClient();

      c.on('error', function() {});

      c.should.be.instanceOf(mqtt.MqttClient);
    });

    it('should support passing the key and cert', function() {
      var c = mqtt.createSecureClient({
        keyPath: __dirname + '/helpers/private-key.pem',
        certPath: __dirname + '/helpers/public-cert.pem'
      });

      c.on('error', function() {});

      c.should.be.instanceOf(mqtt.MqttClient);
    });

    it('should throw on incorrect args');
  });

  describe('#createSecureClientWithListCA', function() {
    it('should return an MqttClient', function() {
      var c = mqtt.createSecureClient();

      c.on('error', function() {});

      c.should.be.instanceOf(mqtt.MqttClient);
    });

    it('should support passing the key, cert and CA list', function() {
      var c = mqtt.createSecureClient({
        keyPath: __dirname + '/helpers/private-key.pem',
        certPath: __dirname + '/helpers/public-cert.pem',
        ca: [__dirname + '/helpers/public-cert.pem']
      });

      c.on('error', function() {});

      c.should.be.instanceOf(mqtt.MqttClient);
    });

    it('should throw on incorrect args');
  });

  describe('#createServer', function() {
    it('should return an MqttServer', function() {
      var s = mqtt.createServer();

      s.should.be.instanceOf(mqtt.MqttServer);
    });
  });

  describe('#createSecureServer', function() {
    it('should return an MqttSecureServer', function() {
      var s = mqtt.createSecureServer(
        __dirname + '/helpers/private-key.pem', 
        __dirname + '/helpers/public-cert.pem'
      );
      s.should.be.instanceOf(mqtt.MqttSecureServer);
    });
  });

  describe('#createConnection', function() {
    before(function () {
      // Setup dummy server
      
      // If there's an error it's probably EADDRINUSE
      // Just use whatever's there already (likely mosquitto)
      this.server = new net.Server();
      this.server.listen(1883);
      this.server.on('error', function(){});
    });
    it('should return an MqttConnection', function() {
      var c = mqtt.createConnection();

      c.should.be.instanceOf(mqtt.MqttConnection);
    });

    it('should fire callback on net connect', function(done) {
      mqtt.createConnection(done);
    });
    it('should bind stream close to connection', function(done) {
      var c = mqtt.createConnection();
      c.once('connected', function() {
        c.once('close', function() { done() });
        c.stream.end();
      });
    });
    it('should bind stream error to conn', function(done) {
      var c = mqtt.createConnection();
      c.once('error', function() { done() });
      c.stream.emit('error', new Error('Bad idea!'));
    });
  });
});


<|start_filename|>bin/game-server/node_modules/pomelo-loader/test/mock-remote/area/addThreeRemote.js<|end_filename|>
/**
 * Mock remote service
 */
module.exports = {
	doService: function(value, cb) {
		cb(null, value + 3);
	}
};

<|start_filename|>bin/game-server/node_modules/pomelo-scheduler/node_modules/log4js/.bob/instrumented/test/global-log-level-test.js<|end_filename|>
"use strict";
var vows = require('vows')
, assert = require('assert');

vows.describe('log4js global loglevel').addBatch({
  'global loglevel' : {
    topic: function() {
      var log4js = require('../lib/log4js');
      return log4js;
    },
    
    'set global loglevel on creation': function(log4js) {
      var log1 = log4js.getLogger('log1');
      var level = 'OFF';
      if (log1.level.toString() == level) {
        level = 'TRACE';
      }
      assert.notEqual(log1.level.toString(), level);
      
      log4js.setGlobalLogLevel(level);
      assert.equal(log1.level.toString(), level);

      var log2 = log4js.getLogger('log2');
      assert.equal(log2.level.toString(), level);
    },
    
    'global change loglevel': function(log4js) {
      var log1 = log4js.getLogger('log1');
      var log2 = log4js.getLogger('log2');
      var level = 'OFF';
      if (log1.level.toString() == level) {
        level = 'TRACE';
      }
      assert.notEqual(log1.level.toString(), level);
      
      log4js.setGlobalLogLevel(level);
      assert.equal(log1.level.toString(), level);
      assert.equal(log2.level.toString(), level);
    },

    'override loglevel': function(log4js) {
      var log1 = log4js.getLogger('log1');
      var log2 = log4js.getLogger('log2');
      var level = 'OFF';
      if (log1.level.toString() == level) {
        level = 'TRACE';
      }
      assert.notEqual(log1.level.toString(), level);
      
      var oldLevel = log1.level.toString();
      assert.equal(log2.level.toString(), oldLevel);
      
      log2.setLevel(level);
      assert.equal(log1.level.toString(), oldLevel);
      assert.equal(log2.level.toString(), level);
      assert.notEqual(oldLevel, level);
      
      log2.removeLevel();
      assert.equal(log1.level.toString(), oldLevel);
      assert.equal(log2.level.toString(), oldLevel);
    },
    
    'preload loglevel': function(log4js) {
      var log1 = log4js.getLogger('log1');
      var level = 'OFF';
      if (log1.level.toString() == level) {
        level = 'TRACE';
      }
      assert.notEqual(log1.level.toString(), level);
      
      var oldLevel = log1.level.toString();
      log4js.getLogger('log2').setLevel(level);
      
      assert.equal(log1.level.toString(), oldLevel);
      
      // get again same logger but as different variable
      var log2 = log4js.getLogger('log2');
      assert.equal(log2.level.toString(), level);
      assert.notEqual(oldLevel, level);
      
      log2.removeLevel();
      assert.equal(log1.level.toString(), oldLevel);
      assert.equal(log2.level.toString(), oldLevel);
    }
  }
}).export(module);


<|start_filename|>bin/game-server/node_modules/node-bignumber/lib/rsa/rng.js<|end_filename|>
/*
 * Random number generator - requires a PRNG backend, e.g. prng4.js
 * 
 * Copyright (c) 2003-2005  <NAME>
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
 *
 * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
 * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * In addition, the following condition applies:
 *
 * All redistributions must retain an intact copy of this copyright notice
 * and disclaimer.
 */

 var crypto = require('crypto');

function rng_get_bytes(ba) {
  var i;
  var random = crypto.randomBytes(ba.length);
  for(i = 0; i < ba.length; ++i) ba[i] = random[i];
}

function SecureRandom() {}

function Arcfour() {
  this.i = 0;
  this.j = 0;
  this.S = new Array();
}

// Initialize arcfour context from key, an array of ints, each from [0..255]
function ARC4init(key) {
  var i, j, t;
  for(i = 0; i < 256; ++i)
    this.S[i] = i;
  j = 0;
  for(i = 0; i < 256; ++i) {
    j = (j + this.S[i] + key[i % key.length]) & 255;
    t = this.S[i];
    this.S[i] = this.S[j];
    this.S[j] = t;
  }
  this.i = 0;
  this.j = 0;
}

function ARC4next() {
  var t;
  this.i = (this.i + 1) & 255;
  this.j = (this.j + this.S[this.i]) & 255;
  t = this.S[this.i];
  this.S[this.i] = this.S[this.j];
  this.S[this.j] = t;
  return this.S[(t + this.S[this.i]) & 255];
}

// Plug in your RNG constructor here
function prng_newstate() {
  return new Arcfour();
}

// Pool size must be a multiple of 4 and greater than 32.
// An array of bytes the size of the pool will be passed to init()
var rng_psize = 256;

SecureRandom.prototype.nextBytes = rng_get_bytes;
Arcfour.prototype.init = ARC4init;
Arcfour.prototype.next = ARC4next;

module.exports = SecureRandom;


<|start_filename|>node_modules/mocha/lib/reporters/list.js<|end_filename|>
'use strict';
/**
 * @module List
 */
/**
 * Module dependencies.
 */

var Base = require('./base');
var inherits = require('../utils').inherits;
var constants = require('../runner').constants;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
var EVENT_RUN_END = constants.EVENT_RUN_END;
var EVENT_TEST_BEGIN = constants.EVENT_TEST_BEGIN;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
var color = Base.color;
var cursor = Base.cursor;

/**
 * Expose `List`.
 */

exports = module.exports = List;

/**
 * Constructs a new `List` reporter instance.
 *
 * @public
 * @class
 * @memberof Mocha.reporters
 * @extends Mocha.reporters.Base
 * @param {Runner} runner - Instance triggers reporter actions.
 * @param {Object} [options] - runner options
 */
function List(runner, options) {
  Base.call(this, runner, options);

  var self = this;
  var n = 0;

  runner.on(EVENT_RUN_BEGIN, function() {
    console.log();
  });

  runner.on(EVENT_TEST_BEGIN, function(test) {
    process.stdout.write(color('pass', '    ' + test.fullTitle() + ': '));
  });

  runner.on(EVENT_TEST_PENDING, function(test) {
    var fmt = color('checkmark', '  -') + color('pending', ' %s');
    console.log(fmt, test.fullTitle());
  });

  runner.on(EVENT_TEST_PASS, function(test) {
    var fmt =
      color('checkmark', '  ' + Base.symbols.ok) +
      color('pass', ' %s: ') +
      color(test.speed, '%dms');
    cursor.CR();
    console.log(fmt, test.fullTitle(), test.duration);
  });

  runner.on(EVENT_TEST_FAIL, function(test) {
    cursor.CR();
    console.log(color('fail', '  %d) %s'), ++n, test.fullTitle());
  });

  runner.once(EVENT_RUN_END, self.epilogue.bind(self));
}

/**
 * Inherit from `Base.prototype`.
 */
inherits(List, Base);

List.description = 'like "spec" reporter but flat';


<|start_filename|>bin/game-server/node_modules/pomelo-monitor/index.js<|end_filename|>
module.exports.psmonitor=require('./lib/processMonitor');
module.exports.sysmonitor=require('./lib/systemMonitor');


<|start_filename|>bin/game-server/node_modules/bops/is.js<|end_filename|>
var Buffer = require('buffer').Buffer

module.exports = function(buffer) {
  return Buffer.isBuffer(buffer);
}


<|start_filename|>bin/game-server/node_modules/bops/test/copy.js<|end_filename|>
var test = require('tape')
  , binary = require('../index')

test('copy works as expected', function(assert) {
  var tmp1 = binary.create(16)
    , tmp2 = binary.create(16)

  for(var i = 0, len = 16; i < len; ++i) {
    binary.writeUInt8(tmp1, Math.random() * 0xFF & 0xFF, i)
    binary.writeUInt8(tmp2, Math.random() * 0xFF & 0xFF, i) 
  }

  binary.copy(tmp1, tmp2)
  for(var i = 0, len = 16; i < len; ++i) {
    assert.equal(binary.readUInt8(tmp2, i), binary.readUInt8(tmp1, i))
  }

  // overlapping copy
  binary.copy(tmp1, tmp1, 2, 0, 6)

  for(var i = 2, len = 8; i < len; ++i) {
    assert.equal(binary.readUInt8(tmp1, i), binary.readUInt8(tmp2, i - 2)) 
  }
  assert.end()
})


<|start_filename|>bin/game-server/node_modules/node-bignumber/original/rsasign-1.2.js<|end_filename|>
/*! rsasign-1.2.js (c) 2012 <NAME> | kjur.github.com/jsrsasign/license
 */
//
// rsa-sign.js - adding signing functions to RSAKey class.
//
//
// version: 1.2.1 (08 May 2012)
//
// Copyright (c) 2010-2012 <NAME> (<EMAIL>)
//
// This software is licensed under the terms of the MIT License.
// http://kjur.github.com/jsrsasign/license/
//
// The above copyright and license notice shall be 
// included in all copies or substantial portions of the Software.

//
// Depends on:
//   function sha1.hex(s) of sha1.js
//   jsbn.js
//   jsbn2.js
//   rsa.js
//   rsa2.js
//

// keysize / pmstrlen
//  512 /  128
// 1024 /  256
// 2048 /  512
// 4096 / 1024

/**
 * @property {Dictionary} _RSASIGN_DIHEAD
 * @description Array of head part of hexadecimal DigestInfo value for hash algorithms.
 * You can add any DigestInfo hash algorith for signing.
 * See PKCS#1 v2.1 spec (p38).
 */
var _RSASIGN_DIHEAD = [];
_RSASIGN_DIHEAD['sha1'] =      "3021300906052b0e03021a05000414";
_RSASIGN_DIHEAD['sha256'] =    "3031300d060960864801650304020105000420";
_RSASIGN_DIHEAD['sha384'] =    "3041300d060960864801650304020205000430";
_RSASIGN_DIHEAD['sha512'] =    "3051300d060960864801650304020305000440";
_RSASIGN_DIHEAD['md2'] =       "3020300c06082a864886f70d020205000410";
_RSASIGN_DIHEAD['md5'] =       "3020300c06082a864886f70d020505000410";
_RSASIGN_DIHEAD['ripemd160'] = "3021300906052b2403020105000414";

/**
 * @property {Dictionary} _RSASIGN_HASHHEXFUNC
 * @description Array of functions which calculate hash and returns it as hexadecimal.
 * You can add any hash algorithm implementations.
 */
var _RSASIGN_HASHHEXFUNC = [];
_RSASIGN_HASHHEXFUNC['sha1'] =      function(s){return hex_sha1(s);};  // http://pajhome.org.uk/crypt/md5/md5.html
_RSASIGN_HASHHEXFUNC['sha256'] =    function(s){return hex_sha256(s);} // http://pajhome.org.uk/crypt/md5/md5.html
_RSASIGN_HASHHEXFUNC['sha512'] =    function(s){return hex_sha512(s);} // http://pajhome.org.uk/crypt/md5/md5.html
_RSASIGN_HASHHEXFUNC['md5'] =       function(s){return hex_md5(s);};   // http://pajhome.org.uk/crypt/md5/md5.html
_RSASIGN_HASHHEXFUNC['ripemd160'] = function(s){return hex_rmd160(s);};   // http://pajhome.org.uk/crypt/md5/md5.html

//_RSASIGN_HASHHEXFUNC['sha1'] =   function(s){return sha1.hex(s);}   // http://user1.matsumoto.ne.jp/~goma/js/hash.html
//_RSASIGN_HASHHEXFUNC['sha256'] = function(s){return sha256.hex;}    // http://user1.matsumoto.ne.jp/~goma/js/hash.html

var _RE_HEXDECONLY = new RegExp("");
_RE_HEXDECONLY.compile("[^0-9a-f]", "gi");

// ========================================================================
// Signature Generation
// ========================================================================

function _rsasign_getHexPaddedDigestInfoForString(s, keySize, hashAlg) {
  var pmStrLen = keySize / 4;
  var hashFunc = _RSASIGN_HASHHEXFUNC[hashAlg];
  var sHashHex = hashFunc(s);

  var sHead = "0001";
  var sTail = "00" + _RSASIGN_DIHEAD[hashAlg] + sHashHex;
  var sMid = "";
  var fLen = pmStrLen - sHead.length - sTail.length;
  for (var i = 0; i < fLen; i += 2) {
    sMid += "ff";
  }
  sPaddedMessageHex = sHead + sMid + sTail;
  return sPaddedMessageHex;
}

function _zeroPaddingOfSignature(hex, bitLength) {
  var s = "";
  var nZero = bitLength / 4 - hex.length;
  for (var i = 0; i < nZero; i++) {
    s = s + "0";
  }
  return s + hex;
}

/**
 * sign for a message string with RSA private key.<br/>
 * @name signString
 * @memberOf RSAKey#
 * @function
 * @param {String} s message string to be signed.
 * @param {String} hashAlg hash algorithm name for signing.<br/>
 * @return returns hexadecimal string of signature value.
 */
function _rsasign_signString(s, hashAlg) {
  //alert("this.n.bitLength() = " + this.n.bitLength());
  var hPM = _rsasign_getHexPaddedDigestInfoForString(s, this.n.bitLength(), hashAlg);
  var biPaddedMessage = parseBigInt(hPM, 16);
  var biSign = this.doPrivate(biPaddedMessage);
  var hexSign = biSign.toString(16);
  return _zeroPaddingOfSignature(hexSign, this.n.bitLength());
}

function _rsasign_signStringWithSHA1(s) {
  return _rsasign_signString(s, 'sha1');
}

function _rsasign_signStringWithSHA256(s) {
  return _rsasign_signString(s, 'sha256');
}

// ========================================================================
// Signature Verification
// ========================================================================

function _rsasign_getDecryptSignatureBI(biSig, hN, hE) {
  var rsa = new RSAKey();
  rsa.setPublic(hN, hE);
  var biDecryptedSig = rsa.doPublic(biSig);
  return biDecryptedSig;
}

function _rsasign_getHexDigestInfoFromSig(biSig, hN, hE) {
  var biDecryptedSig = _rsasign_getDecryptSignatureBI(biSig, hN, hE);
  var hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, '');
  return hDigestInfo;
}

function _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo) {
  for (var algName in _RSASIGN_DIHEAD) {
    var head = _RSASIGN_DIHEAD[algName];
    var len = head.length;
    if (hDigestInfo.substring(0, len) == head) {
      var a = [algName, hDigestInfo.substring(len)];
      return a;
    }
  }
  return [];
}

function _rsasign_verifySignatureWithArgs(sMsg, biSig, hN, hE) {
  var hDigestInfo = _rsasign_getHexDigestInfoFromSig(biSig, hN, hE);
  var digestInfoAry = _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo);
  if (digestInfoAry.length == 0) return false;
  var algName = digestInfoAry[0];
  var diHashValue = digestInfoAry[1];
  var ff = _RSASIGN_HASHHEXFUNC[algName];
  var msgHashValue = ff(sMsg);
  return (diHashValue == msgHashValue);
}

function _rsasign_verifyHexSignatureForMessage(hSig, sMsg) {
  var biSig = parseBigInt(hSig, 16);
  var result = _rsasign_verifySignatureWithArgs(sMsg, biSig,
						this.n.toString(16),
						this.e.toString(16));
  return result;
}

/**
 * verifies a sigature for a message string with RSA public key.<br/>
 * @name verifyString
 * @memberOf RSAKey#
 * @function
 * @param {String} sMsg message string to be verified.
 * @param {String} hSig hexadecimal string of siganture.<br/>
 *                 non-hexadecimal charactors including new lines will be ignored.
 * @return returns 1 if valid, otherwise 0
 */
function _rsasign_verifyString(sMsg, hSig) {
  hSig = hSig.replace(_RE_HEXDECONLY, '');
  if (hSig.length != this.n.bitLength() / 4) return 0;
  hSig = hSig.replace(/[ \n]+/g, "");
  var biSig = parseBigInt(hSig, 16);
  var biDecryptedSig = this.doPublic(biSig);
  var hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, '');
  var digestInfoAry = _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo);
  
  if (digestInfoAry.length == 0) return false;
  var algName = digestInfoAry[0];
  var diHashValue = digestInfoAry[1];
  var ff = _RSASIGN_HASHHEXFUNC[algName];
  var msgHashValue = ff(sMsg);
  return (diHashValue == msgHashValue);
}

RSAKey.prototype.signString = _rsasign_signString;
RSAKey.prototype.signStringWithSHA1 = _rsasign_signStringWithSHA1;
RSAKey.prototype.signStringWithSHA256 = _rsasign_signStringWithSHA256;
RSAKey.prototype.sign = _rsasign_signString;
RSAKey.prototype.signWithSHA1 = _rsasign_signStringWithSHA1;
RSAKey.prototype.signWithSHA256 = _rsasign_signStringWithSHA256;

RSAKey.prototype.verifyString = _rsasign_verifyString;
RSAKey.prototype.verifyHexSignatureForMessage = _rsasign_verifyHexSignatureForMessage;
RSAKey.prototype.verify = _rsasign_verifyString;
RSAKey.prototype.verifyHexSignatureForByteArrayMessage = _rsasign_verifyHexSignatureForMessage;

/**
 * @name RSAKey
 * @class
 * @description <NAME> RSA Key class and extension
 */


<|start_filename|>bin/game-server/node_modules/pomelo/test/filters/handler/timeout.js<|end_filename|>
var should = require('should');
var timeoutFilter = require('../../../lib/filters/handler/timeout');
var FilterService = require('../../../lib/common/service/filterService');
var util = require('util');
var mockSession = {
  key : "123"
};

var WAIT_TIME = 100;
describe("#serialFilter",function(){
  it("should do before filter ok",function(done){
    var service = new FilterService();
    var filter = timeoutFilter();
    service.before(filter);

    service.beforeFilter(null,mockSession,function(){
      should.exist(mockSession);

      should.exist(mockSession.__timeout__);
      done();
    });
  });

  it("should do after filter by doing before filter ok",function(done){
    var service = new FilterService();
    var filter = timeoutFilter();
    var _session ;
    service.before(filter);

    service.beforeFilter(null,mockSession,function(){
      should.exist(mockSession);
      should.exist(mockSession.__timeout__);
      _session = mockSession;
    });

    service.after(filter);

    service.afterFilter(null,null,mockSession,null,function(){
      should.exist(mockSession);
      should.strictEqual(mockSession,_session);
    });

    setTimeout(done,WAIT_TIME);
    done();
  });
});

<|start_filename|>bin/game-server/node_modules/bops/typedarray/is.js<|end_filename|>

module.exports = function(buffer) {
  return buffer instanceof Uint8Array;
}


<|start_filename|>node_modules/blanket/src/node-loaders/cjsx.js<|end_filename|>
var simpleNodeLoader = require('./simple-node-loader');

module.exports = function(blanket) {
    var compiler = require("coffee-react"),
        oldLoaderCS = require.extensions['.cjsx'];

    var compile = function(content) {
        return compiler.compile(content);
    };

    require.extensions['.cjsx'] = simpleNodeLoader(blanket, oldLoaderCS, compile, /\.cjsx/);
};


<|start_filename|>bin/game-server/node_modules/bops/typedarray/copy.js<|end_filename|>
module.exports = copy

var slice = [].slice

function copy(source, target, target_start, source_start, source_end) {
  target_start = arguments.length < 3 ? 0 : target_start
  source_start = arguments.length < 4 ? 0 : source_start
  source_end = arguments.length < 5 ? source.length : source_end

  if(source_end === source_start) {
    return
  }

  if(target.length === 0 || source.length === 0) {
    return
  }

  if(source_end > source.length) {
    source_end = source.length
  }

  if(target.length - target_start < source_end - source_start) {
    source_end = target.length - target_start + source_start
  }

  if(source.buffer !== target.buffer) {
    return fast_copy(source, target, target_start, source_start, source_end)
  }
  return slow_copy(source, target, target_start, source_start, source_end)
}

function fast_copy(source, target, target_start, source_start, source_end) {
  var len = (source_end - source_start) + target_start

  for(var i = target_start, j = source_start;
      i < len;
      ++i,
      ++j) {
    target[i] = source[j]
  }
}

function slow_copy(from, to, j, i, jend) {
  // the buffers could overlap.
  var iend = jend + i
    , tmp = new Uint8Array(slice.call(from, i, iend))
    , x = 0

  for(; i < iend; ++i, ++x) {
    to[j++] = tmp[x]
  }
}


<|start_filename|>node_modules/blanket/src/reporters/simple_json_reporter.js<|end_filename|>
//simple_json_reporter
(function (){

    var body = document.body;

    var appendHtml = function (el, str) {
        var div = document.createElement('div');
        div.innerText = str;
        el.appendChild(div);
    };

    blanket.customReporter= function(coverageData){
        appendHtml(body, JSON.stringify(coverageData,null,"\t"));
    };
})();

<|start_filename|>bin/game-server/node_modules/pomelo-monitor/utils/util.js<|end_filename|>
/**
 * convert Date as  yyyy-mm-dd hh:mm:ss
 */
function formatTime(date) {
	var n = date.getFullYear(); 
	var y = date.getMonth() + 1;
	var r = date.getDate(); 
	var mytime = date.toLocaleTimeString(); 
	var mytimes = n+ "-" + y + "-" + r + " " + mytime;
  return mytimes;
}
module.exports.formatTime = formatTime;


<|start_filename|>bin/game-server/node_modules/mqtt-connection/test/util.js<|end_filename|>

var through       = require('through2')
  , setImmediate  = global.setImmediate

setImmediate = setImmediate || function(func) {
  setTimeout(func, 0)
}

module.exports.testStream = function() {
  return through(function(buf, enc, cb) {
    var that = this;
    setImmediate(function() {
      that.push(buf)
      cb();
    });
  });
};


<|start_filename|>node_modules/blanket/src/qunit/noautorun.js<|end_filename|>
if (typeof QUnit !== 'undefined'){ QUnit.config.autostart = false; }

<|start_filename|>bin/game-server/node_modules/pomelo/lib/index.js<|end_filename|>
module.exports = require('./pomelo');

<|start_filename|>bin/game-server/node_modules/pomelo-scheduler/node_modules/async/Makefile<|end_filename|>
PACKAGE = asyncjs
NODEJS = $(if $(shell test -f /usr/bin/nodejs && echo "true"),nodejs,node)

BUILDDIR = dist

all: build

build: $(wildcard  lib/*.js)
	mkdir -p $(BUILDDIR)
	uglifyjs lib/async.js > $(BUILDDIR)/async.min.js

test:
	nodeunit test

clean:
	rm -rf $(BUILDDIR)

lint:
	nodelint --config nodelint.cfg lib/async.js

.PHONY: test build all


<|start_filename|>bin/game-server/node_modules/pomelo-admin/lib/modules/watchServer.js<|end_filename|>
/*!
 * Pomelo -- consoleModule watchServer
 * Copyright(c) 2013 fantasyni <<EMAIL>>
 * MIT Licensed
 */
var logger = require('pomelo-logger').getLogger('pomelo-admin', __filename);
var countDownLatch = require('../util/countDownLatch');
var monitor = require('pomelo-monitor');
var utils = require('../util/utils');
var util = require('util');
var fs = require('fs');
var vm = require('vm');

module.exports = function(opts) {
	return new Module(opts);
};

module.exports.moduleId = 'watchServer';

var Module = function(opts) {
	opts = opts || {};
	this.app = opts.app;
};

Module.prototype.monitorHandler = function(agent, msg, cb) {
	var comd = msg['comd'];
	var context = msg['context'];
	var param = msg['param'];
	var app = this.app;

	var handle = 'monitor';

	switch (comd) {
		case 'servers':
			showServers(handle, agent, comd, context, cb);
			break;
		case 'connections':
			showConnections(handle, agent, app, comd, context, cb);
			break;
		case 'logins':
			showLogins(handle, agent, app, comd, context, cb);
			break;
		case 'modules':
			showModules(handle, agent, comd, context, cb);
			break;
		case 'status':
			showStatus(handle, agent, comd, context, cb);
			break;
		case 'config':
			showConfig(handle, agent, app, comd, context, param, cb);
			break;
		case 'proxy':
			showProxy(handle, agent, app, comd, context, param, cb);
			break;
		case 'handler':
			showHandler(handle, agent, app, comd, context, param, cb);
			break;
		case 'components':
			showComponents(handle, agent, app, comd, context, param, cb);
			break;
		case 'settings':
			showSettings(handle, agent, app, comd, context, param, cb);
			break;
		case 'cpu':
			dumpCPU(handle, agent, comd, context, param, cb);
			break;
		case 'memory':
			dumpMemory(handle, agent, comd, context, param, cb);
			break;
		case 'get':
			getApp(handle, agent, app, comd, context, param, cb);
			break;
		case 'set':
			setApp(handle, agent, app, comd, context, param, cb);
			break;
		case 'enable':
			enableApp(handle, agent, app, comd, context, param, cb);
			break;
		case 'disable':
			disableApp(handle, agent, app, comd, context, param, cb);
			break;
		case 'run':
			runScript(handle, agent, app, comd, context, param, cb);
			break;
		default:
			showError(handle, agent, comd, context, cb);
	}
};

Module.prototype.clientHandler = function(agent, msg, cb) {
	var comd = msg['comd'];
	var context = msg['context'];
	var param = msg['param'];
	var app = this.app; // master app

	if (!comd || !context) {
		cb('lack of comd or context param');
		return;
	}

	var handle = 'client';
	switch (comd) {
		case 'servers':
			showServers(handle, agent, comd, context, cb);
			break;
		case 'connections':
			showConnections(handle, agent, app, comd, context, cb);
			break;
		case 'logins':
			showLogins(handle, agent, app, comd, context, cb);
			break;
		case 'modules':
			showModules(handle, agent, comd, context, cb);
			break;
		case 'status':
			showStatus(handle, agent, comd, context, cb);
			break;
		case 'config':
			showConfig(handle, agent, app, comd, context, param, cb);
			break;
		case 'proxy':
			showProxy(handle, agent, app, comd, context, param, cb);
			break;
		case 'handler':
			showHandler(handle, agent, app, comd, context, param, cb);
			break;
		case 'components':
			showComponents(handle, agent, app, comd, context, param, cb);
			break;
		case 'settings':
			showSettings(handle, agent, app, comd, context, param, cb);
			break;
		case 'cpu':
			dumpCPU(handle, agent, comd, context, param, cb);
			break;
		case 'memory':
			dumpMemory(handle, agent, comd, context, param, cb);
			break;
		case 'get':
			getApp(handle, agent, app, comd, context, param, cb);
			break;
		case 'set':
			setApp(handle, agent, app, comd, context, param, cb);
			break;
		case 'enable':
			enableApp(handle, agent, app, comd, context, param, cb);
			break;
		case 'disable':
			disableApp(handle, agent, app, comd, context, param, cb);
			break;
		case 'run':
			runScript(handle, agent, app, comd, context, param, cb);
			break;
		default:
			showError(handle, agent, comd, context, cb);
	}
};

function showServers(handle, agent, comd, context, cb) {
	if (handle === 'client') {
		var sid, record;
		var serverInfo = {};
		var count = utils.size(agent.idMap);
		var latch = countDownLatch.createCountDownLatch(count, function() {
			cb(null, {
				msg: serverInfo
			});
		});

		for (sid in agent.idMap) {
			record = agent.idMap[sid];
			agent.request(record.id, module.exports.moduleId, {
				comd: comd,
				context: context
			}, function(msg) {
				serverInfo[msg.serverId] = msg.body;
				latch.done();
			});
		}
	} else if (handle === 'monitor') {
		var serverId = agent.id;
		var serverType = agent.type;
		var info = agent.info;
		var pid = process.pid;
		var heapUsed = (process.memoryUsage().heapUsed / (1000 * 1000)).toFixed(2);
		var uptime = (process.uptime() / 60).toFixed(2);
		cb({
			serverId: serverId,
			body: {
				serverId: serverId,
				serverType: serverType,
				host: info['host'],
				port: info['port'],
				pid: pid,
				heapUsed: heapUsed,
				uptime: uptime
			}
		});
	}

}

function showConnections(handle, agent, app, comd, context, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			var sid, record;
			var serverInfo = {};
			var count = 0;
			for (var key in agent.idMap) {
				if (agent.idMap[key].info.frontend === 'true') {
					count++;
				}
			}
			var latch = countDownLatch.createCountDownLatch(count, function() {
				cb(null, {
					msg: serverInfo
				});
			});

			for (sid in agent.idMap) {
				record = agent.idMap[sid];
				if (record.info.frontend === 'true') {
					agent.request(record.id, module.exports.moduleId, {
						comd: comd,
						context: context
					}, function(msg) {
						serverInfo[msg.serverId] = msg.body;
						latch.done();
					});
				}
			}
		} else {
			var record = agent.idMap[context];
			if (!record) {
				cb("the server " + context + " not exist");
			}
			if (record.info.frontend === 'true') {
				agent.request(record.id, module.exports.moduleId, {
					comd: comd,
					context: context
				}, function(msg) {
					var serverInfo = {};
					serverInfo[msg.serverId] = msg.body;
					cb(null, {
						msg: serverInfo
					});
				});
			} else {
				cb('\nthis command should be applied to frontend server\n');
			}
		}
	} else if (handle === 'monitor') {
		var connection = app.components.__connection__;
		if (!connection) {
			cb({
				serverId: agent.id,
				body: 'error'
			});
			return;
		}

		cb({
			serverId: agent.id,
			body: connection.getStatisticsInfo()
		});
	}
}


function showLogins(handle, agent, app, comd, context, cb) {
	showConnections(handle, agent, app, comd, context, cb);
}

function showModules(handle, agent, comd, context, cb) {
	var modules = agent.consoleService.modules;
	var result = [];
	for (var module in modules) {
		result.push(module);
	}
	cb(null, {
		msg: result
	});
}

function showStatus(handle, agent, comd, context, cb) {
	if (handle === 'client') {
		agent.request(context, module.exports.moduleId, {
			comd: comd,
			context: context
		}, function(err, msg) {
			cb(null, {
				msg: msg
			});
		});
	} else if (handle === 'monitor') {
		var serverId = agent.id;
		var pid = process.pid;
		var params = {
			serverId: serverId,
			pid: pid
		};
		monitor.psmonitor.getPsInfo(params, function(err, data) {
			cb(null, {
				serverId: agent.id,
				body: data
			})
		});
	}
}

function showConfig(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (param === 'master') {
			cb(null, {
				masterConfig: app.get('masterConfig') || 'no config to master in app.js',
				masterInfo: app.get('master')
			});
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		var key = param + 'Config';
		cb(null, clone(param, app.get(key)));
	}
}

function showProxy(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		proxyCb(app, context, cb);
	}
}

function showHandler(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		handlerCb(app, context, cb);
	}
}

function showComponents(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		var _components = app.components;
		var res = {};
		for (var key in _components) {
			var name = getComponentName(key);
			res[name] = clone(name, app.get(name + 'Config'))
		}
		cb(null, res);
	}
}

function showSettings(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		var _settings = app.settings;
		var res = {};
		for (var key in _settings) {
			if (key.match(/^__\w+__$/) || key.match(/\w+Config$/)) {
				continue;
			}
			if (!checkJSON(_settings[key])) {
				res[key] = 'Object';
				continue;
			}
			res[key] = _settings[key];
		}
		cb(null, res);
	}
}

function dumpCPU(handle, agent, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(err, msg);
		});
	} else if (handle === 'monitor') {
		var times = param['times'];
		var filepath = param['filepath'];
		var force = param['force'];
		cb(null, 'cpu dump is unused in 1.0 of pomelo');
		/**
		if (!/\.cpuprofile$/.test(filepath)) {
			filepath = filepath + '.cpuprofile';
		}
		if (!times || !/^[0-9]*[1-9][0-9]*$/.test(times)) {
			cb('no times or times invalid error');
			return;
		}
		checkFilePath(filepath, force, function(err) {
			if (err) {
				cb(err);
				return;
			}
			//ndump.cpu(filepath, times);
			cb(null, filepath + ' cpu dump ok');
		});
		*/

	}
}

function dumpMemory(handle, agent, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(err, msg);
		});
	} else if (handle === 'monitor') {
		var filepath = param['filepath'];
		var force = param['force'];
		if (!/\.heapsnapshot$/.test(filepath)) {
			filepath = filepath + '.heapsnapshot';
		}
		checkFilePath(filepath, force, function(err) {
			if (err) {
				cb(err);
				return;
			}
			var heapdump = null;
			try {
				heapdump = require('heapdump');
				heapdump.writeSnapshot(filepath);
				cb(null, filepath + ' memory dump ok')
			} catch (e) {
				cb('pomelo-admin require heapdump');
			}
		});
	}
}

function getApp(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		var res = app.get(param);
		if (!checkJSON(res)) {
			res = 'object';
		}
		cb(null, res || null);
	}
}

function setApp(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		var key = param['key'];
		var value = param['value'];
		app.set(key, value);
		cb(null, 'set ' + key + ':' + value + ' ok');
	}
}

function enableApp(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		app.enable(param);
		cb(null, 'enable ' + param + ' ok');
	}
}

function disableApp(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		app.disable(param);
		cb(null, 'disable ' + param + ' ok');
	}
}

function runScript(handle, agent, app, comd, context, param, cb) {
	if (handle === 'client') {
		if (context === 'all') {
			cb('context error');
			return;
		}

		agent.request(context, module.exports.moduleId, {
			comd: comd,
			param: param,
			context: context
		}, function(err, msg) {
			cb(null, msg);
		});
	} else if (handle === 'monitor') {
		var ctx = {
			app: app,
			result: null
		};
		try {
			vm.runInNewContext('result = ' + param, ctx, 'myApp.vm');
			cb(null, util.inspect(ctx.result));
		} catch (e) {
			cb(null, e.stack);
		}
	}
}

function showError(handle, agent, comd, context, cb) {

}

function clone(param, obj) {
	var result = {};
	var flag = 1;
	for (var key in obj) {
		if (typeof obj[key] === 'function' || typeof obj[key] === 'object') {
			continue;
		}
		flag = 0;
		result[key] = obj[key];
	}
	if (flag) {
		// return 'no ' + param + 'Config info';
	}
	return result;
}

function checkFilePath(filepath, force, cb) {
	if (!force && fs.existsSync(filepath)) {
		cb('filepath file exist');
		return;
	}
	fs.writeFile(filepath, 'test', function(err) {
		if (err) {
			cb('filepath invalid error');
			return;
		}
		fs.unlinkSync(filepath);
		cb(null);
	})
}

function proxyCb(app, context, cb) {
	var msg = {};
	var __proxy__ = app.components.__proxy__;
	if (__proxy__ && __proxy__.client && __proxy__.client.proxies.user) {
		var proxies = __proxy__.client.proxies.user;
		var server = app.getServerById(context);
		if (!server) {
			cb('no server with this id ' + context);
		} else {
			var type = server['serverType'];
			var tmp = proxies[type];
			msg[type] = {};
			for (var _proxy in tmp) {
				var r = tmp[_proxy];
				msg[type][_proxy] = {};
				for (var _rpc in r) {
					if (typeof r[_rpc] === 'function') {
						msg[type][_proxy][_rpc] = 'function';
					}
				}
			}
			cb(null, msg);
		}
	} else {
		cb('no proxy loaded');
	}
}

function handlerCb(app, context, cb) {
	var msg = {};
	var __server__ = app.components.__server__;
	if (__server__ && __server__.server && __server__.server.handlerService.handlers) {
		var handles = __server__.server.handlerService.handlers;
		var server = app.getServerById(context);
		if (!server) {
			cb('no server with this id ' + context);
		} else {
			var type = server['serverType'];
			var tmp = handles;
			msg[type] = {};
			for (var _p in tmp) {
				var r = tmp[_p];
				msg[type][_p] = {};
				for (var _r in r) {
					if (typeof r[_r] === 'function') {
						msg[type][_p][_r] = 'function';
					}
				}
			}
			cb(null, msg);
		}
	} else {
		cb('no handler loaded');
	}
}

function getComponentName(c) {
	var t = c.match(/^__(\w+)__$/);
	if (t) {
		t = t[1];
	}
	return t;
}

function checkJSON(obj) {
	if (!obj) {
		return true;
	}
	try {
		JSON.stringify(obj);
	} catch (e) {
		return false;
	}
	return true;
}

<|start_filename|>bin/game-server/node_modules/pomelo-rpc/lib/util/coder.js<|end_filename|>
var logger = require('pomelo-logger').getLogger('pomelo-rpc', 'Coder');
// var OutBuffer = require('./buffer/outputBuffer');
// var InBuffer = require('./buffer/inputBuffer');
var bBuffer = require('bearcat-buffer');
var OutBuffer = bBuffer.outBuffer;
var InBuffer = bBuffer.inBuffer;

var Coder = {};

Coder.encodeClient = function(id, msg, servicesMap) {
	// logger.debug('[encodeClient] id %s msg %j', id, msg);
	var outBuf = new OutBuffer();
	outBuf.writeUInt(id);
	var namespace = msg['namespace'];
	var serverType = msg['serverType'];
	var service = msg['service'];
	var method = msg['method'];
	var args = msg['args'] || [];
	outBuf.writeShort(servicesMap[0][namespace]);
	outBuf.writeShort(servicesMap[1][service]);
	outBuf.writeShort(servicesMap[2][method]);
	// outBuf.writeString(namespace);
	// outBuf.writeString(service);
	// outBuf.writeString(method);

	outBuf.writeObject(args);

	return outBuf.getBuffer();
}

Coder.encodeServer = function(id, args) {
	// logger.debug('[encodeServer] id %s args %j', id, args);
	var outBuf = new OutBuffer();
	outBuf.writeUInt(id);
	outBuf.writeObject(args);
	return outBuf.getBuffer();	
}

Coder.decodeServer = function(buf, servicesMap) {
	var inBuf = new InBuffer(buf);
	var id = inBuf.readUInt();
	var namespace = servicesMap[3][inBuf.readShort()];
	var service = servicesMap[4][inBuf.readShort()];
	var method = servicesMap[5][inBuf.readShort()];
	// var namespace = inBuf.readString();
	// var service = inBuf.readString();
	// var method = inBuf.readString();

	var args = inBuf.readObject();
	// logger.debug('[decodeServer] namespace %s service %s method %s args %j', namespace, service, method, args)

	return {
		id: id,
		msg: {
			namespace: namespace,
			// serverType: serverType,
			service: service,
			method: method,
			args: args
		}
	}
}

Coder.decodeClient = function(buf) {
	var inBuf = new InBuffer(buf);
	var id = inBuf.readUInt();
	var resp = inBuf.readObject();
	// logger.debug('[decodeClient] id %s resp %j', id, resp);
	return {
		id: id,
		resp: resp
	}
}

module.exports = Coder;

<|start_filename|>bin/game-server/node_modules/pomelo/template/npm-install.bat<|end_filename|>
::npm-install.bat
@echo off
::install web server dependencies && game server dependencies
cd web-server && npm install -d && cd .. && cd game-server && npm install -d

<|start_filename|>bin/game-server/node_modules/pomelo/lib/connectors/udpsocket.js<|end_filename|>
var util = require('util');
var handler = require('./common/handler');
var protocol = require('pomelo-protocol');
var Package = protocol.Package;
var EventEmitter = require('events').EventEmitter;
var logger = require('pomelo-logger').getLogger('pomelo', __filename);

var ST_INITED = 0;
var ST_WAIT_ACK = 1;
var ST_WORKING = 2;
var ST_CLOSED = 3;

var Socket = function(id, socket, peer) {
	EventEmitter.call(this);
	
  this.id = id;
	this.socket = socket;
  this.peer = peer;
	this.host = peer.address;
	this.port = peer.port;
	this.remoteAddress = {
    ip: this.host,
    port: this.port
  };

  var self = this;
  this.on('package', function(pkg) {
    if(!!pkg) {
      pkg = Package.decode(pkg);
      handler(self, pkg);
    }
  });

  this.state = ST_INITED;
};

util.inherits(Socket, EventEmitter);

module.exports = Socket;

/**
 * Send byte data package to client.
 *
 * @param  {Buffer} msg byte data
 */
Socket.prototype.send = function(msg) {
  if(this.state !== ST_WORKING) {
    return;
  }
  if(msg instanceof String) {
    msg = new Buffer(msg);
  } else if(!(msg instanceof Buffer)) {
    msg = new Buffer(JSON.stringify(msg));
  }
  this.sendRaw(Package.encode(Package.TYPE_DATA, msg));
};

Socket.prototype.sendRaw = function(msg) {
	this.socket.send(msg, 0, msg.length, this.port, this.host, function(err, bytes) {
    if(!!err)	{
      logger.error('send msg to remote with err: %j', err.stack);
      return;
    }
  });
};

Socket.prototype.sendForce = function(msg) {
  if(this.state === ST_CLOSED) {
    return;
  }
  this.sendRaw(msg);
};

Socket.prototype.handshakeResponse = function(resp) {
  if(this.state !== ST_INITED) {
    return;
  }
  this.sendRaw(resp);
  this.state = ST_WAIT_ACK;
};

Socket.prototype.sendBatch = function(msgs) {
  if(this.state !== ST_WORKING) {
    return;
  }
  var rs = [];
  for(var i=0; i<msgs.length; i++) {
    var src = Package.encode(Package.TYPE_DATA, msgs[i]);
    rs.push(src);
  }
  this.sendRaw(Buffer.concat(rs));
};

Socket.prototype.disconnect = function() {
  if(this.state === ST_CLOSED) {
    return;
  }
  this.state = ST_CLOSED;
  this.emit('disconnect', 'the connection is disconnected.');
};

<|start_filename|>bin/game-server/node_modules/bops/copy.js<|end_filename|>
module.exports = copy

function copy(source, target, target_start, source_start, source_end) {
  return source.copy(target, target_start, source_start, source_end)
}


<|start_filename|>bin/game-server/node_modules/mqtt/test/old/smoke.test.js<|end_filename|>
/*global describe, it */
/* 
 * Just a simple syntax test
 * if you can not require then there is something major wrong
 */
var make_tester = require('./tester');

describe("Require all modules", function () {
  it("connection", function () {
    var O = require('../lib/connection'),
      o = new O(make_tester());
  });

  it("generate", function () {
    var c = require('../lib/generate');
  });

  it("mqtt", function () {
    var c = require('../lib/mqtt');
  });

  it("parse", function () {
    var c = require('../lib/parse');
  });

  it("protocol", function () {
    var c = require('../lib/protocol');
  });

  it("index", function () {
    var o = require('../index.js');
  });
});


<|start_filename|>bin/game-server/node_modules/pomelo-protobuf/test/writeProtos.js<|end_filename|>
var protobuf = require('../lib/protobuf');
var fs = require('fs');

var protoFile = "./rootMsg.json";
var protoTarget = "./rootProtos.json";
var msgFile = "./rootMsgTC";
var msgTarget = "./rootMsg.json";

var protos = protobuf.parse(require(protoFile));

console.log(protos);
fs.writeFile(protoTarget, JSON.stringify(protos, null ,2));

fs.writeFile(msgTarget, JSON.stringify(require(msgFile), null ,2));



<|start_filename|>bin/game-server/node_modules/stream-pkg/index.js<|end_filename|>
module.exports = process.env.STREAM_PKG_COV ?
  require('./lib-cov/composer') :
  require('./lib/composer');

<|start_filename|>bin/game-server/node_modules/pomelo/lib/connectors/hybrid/switcher.js<|end_filename|>
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var WSProcessor = require('./wsprocessor');
var TCPProcessor = require('./tcpprocessor');
var logger = require('pomelo-logger').getLogger('pomelo', __filename);

var HTTP_METHODS = [
  'GET', 'POST', 'DELETE', 'PUT', 'HEAD'
];

var ST_STARTED = 1;
var ST_CLOSED = 2;

var DEFAULT_TIMEOUT = 90;

/**
 * Switcher for tcp and websocket protocol
 *
 * @param {Object} server tcp server instance from node.js net module
 */
var Switcher = function(server, opts) {
  EventEmitter.call(this);
  this.server = server;
  this.wsprocessor = new WSProcessor();
  this.tcpprocessor = new TCPProcessor(opts.closeMethod);
  this.id = 1;
  this.timeout = (opts.timeout || DEFAULT_TIMEOUT) * 1000;
  this.setNoDelay = opts.setNoDelay;

  if (!opts.ssl) {
    this.server.on('connection', this.newSocket.bind(this));
  } else {
    this.server.on('secureConnection', this.newSocket.bind(this));
    this.server.on('clientError', function(e, tlsSo) {
      logger.warn('an ssl error occured before handshake established: ', e);
      tlsSo.destroy();
    });
  }

  this.wsprocessor.on('connection', this.emit.bind(this, 'connection'));
  this.tcpprocessor.on('connection', this.emit.bind(this, 'connection'));

  this.state = ST_STARTED;
};
util.inherits(Switcher, EventEmitter);

module.exports = Switcher;

Switcher.prototype.newSocket = function(socket) {
  if(this.state !== ST_STARTED) {
    return;
  }

  socket.setTimeout(this.timeout, function() {
     logger.warn('connection is timeout without communication, the remote ip is %s && port is %s',
       socket.remoteAddress, socket.remotePort);
     socket.destroy();
  });

  var self = this;

  socket.once('data', function(data) {
    // FIXME: handle incomplete HTTP method
    if(isHttp(data)) {
      processHttp(self, self.wsprocessor, socket, data);
    } else {
      if(!!self.setNoDelay) {
        socket.setNoDelay(true);
      }
      processTcp(self, self.tcpprocessor, socket, data);
    }
  });
};

Switcher.prototype.close = function() {
  if(this.state !== ST_STARTED) {
    return;
  }

  this.state = ST_CLOSED;
  this.wsprocessor.close();
  this.tcpprocessor.close();
};

var isHttp = function(data) {
  var head = data.toString('utf8', 0, 4);

  for(var i=0, l=HTTP_METHODS.length; i<l; i++) {
    if(head.indexOf(HTTP_METHODS[i]) === 0) {
      return true;
    }
  }

  return false;
};

var processHttp = function(switcher, processor, socket, data) {
  processor.add(socket, data);
};

var processTcp = function(switcher, processor, socket, data) {
  processor.add(socket, data);
};


<|start_filename|>bin/game-server/node_modules/mqtt/test/client.fault_tolerance.js<|end_filename|>
var should = require('should')
  , mqtt   = require('../lib/mqtt');

describe('Fault tolerance', function () {

  describe('reconnecting', function () {
    it('should attempt to reconnect once server is down', function (done) {
      this.timeout(15000);

      var fork   = require('child_process').fork;
      var server = fork(__dirname + '/helpers/server_process.js');

      var client = mqtt.createClient('3000', 'localhost', { keepalive: 1 });

      client.once('connect', function () {
        server.kill('SIGINT'); // mocks server shutdown

        client.once('close', function () {
          should.exist(client.reconnectTimer);
          done();
        });
      });
    });
  });

});
