Creates an IPC messenger
@constructor
@param {string} namespace - prefix for unix socket file descriptors
@param {object} options - messenger configuration
762880
function Messenger(namespace, options) {
  if (!(this instanceof Messenger)) {
    return new Messenger(namespace, options);
  }

  if (!namespace) {
    throw new Error('Cannot create Messenger without a namespace');
  }

  events.EventEmitter.call(this);

  this.namespace = namespace;
  this.options = merge(Object.create(Messenger.DEFAULTS), options || {});
  this.socketPath = this._getFileDescriptorPath(this.options.uid);

  this._init();
}
474987
function Cipher(config) {

  /* config:
      namespace
      nid - node id, integer representing a node within the same namespace (e.g. web1, web2...)
      logger - winston instance
      log - function containing a custom call to the logger
      poolSize
      redis
        host
        port
        options
  */

	// Make sure we have a valid config object
	this._config = config = (config || {});
	  
	// A pool of clients for outgoing requests
	this._outgoingClientPool = []

	// All clients listening to pub-sub channels
	this._subscribeClientPool = [];

	// All clients waiting via the BLPOP/BRPOP commands, namespaced by route name
	this._queueClientPools = {};

	// Auth to use if new clients are added
	this._auth = config.auth || {};

	// Connection config
	this._connection = config.connection || {}

	// Namespace to prefix on all message routes
	if(!config.namespace) {throw Error("No namespace provided!");}
	else {this._namespace = config.namespace}

	// Random id for node addressing
	//this._nid = Math.floor(Math.random()*9999999999);
	//this._nid = config.nid ? config.nid : Math.floor(Math.random()*9999999999); // allowing nid to be configured
	this._nid = config.nid ? config.nid : 0; // allowing nid to be configured with a default of 0

	// Logging
  // allow the winston instance to be passed to cipher
	if(!config.logger) {  
    this._logger = new (Winston.Logger) ({ });
    this._logger.add(Winston.transports.Console);
	} else {
    this._logger = config.logger;
  }
  // allow the log function to be passed to cipher
	if(!config.log) { 
    this._log = function (message, attr) {
      this._logger.log(attr.level, message, attr);
    }
  } else {
    this._log = config.log;
  }

	// Ensure there is a pool size (not that it means anything right now...)
	config.poolSize = (config.poolSize || 1);

	// Provision clients in the outgoing client pools
	var poolSize = config.poolSize;
	do {
		this.addToPool(this._outgoingClientPool);
	} while(--poolSize);
	
	// Provision clients for the pub/sub subscription
	poolSize = config.poolSize;
	do {
		var subClient = this.addToPool(this._subscribeClientPool);

		subClient.PSUBSCRIBE(this._namespace.concat(".*"))
		subClient.on("pmessage", this.recvSubMsg.bind(this));
	} while(--poolSize);

	// Add the two base queue listeners - REALLY NEED TO CLEAN THIS UP
	this.addQueueListeners([this._namespace, "*"].join("."));
	this.addQueueListeners([this._namespace, this._nid].join("."));

	// Transmit route handlers
	this._transmitHandlers = {};

	// Broadcast route handlers
	this._broadcastHandlers = {};

	// Log the address
	//console.log("Cipher is running at %s.%d", this._namespace, this._nid);
  this.log_info("Cipher is running at " + this._namespace + "." + this._nid, {});
}
943404
function Server (options) {
  options = utils.clone(options || {});

  var ns = this._ns = utils.createNamespace(options);
  var id = this.id = options.id || utils.uniqueId('server');
  var debug = this._debug = utils.debug('server:' + id);
  var me = this;

  var server = this._server = new net.Server();
  server.on('error', function (err) {
    me._debug('emit error: %s', err);
    me.emit('error', err);
  });
  server.on('close', function () {
    me._debug('emit close');
    me.emit('close');
  });
  server.on('listening', function () {
    me._debug('emit listening');
    me.emit('listening');
  });
  server.on('connection', function (s) {
    me._debug('emit connection [%s] %s:%s', s.remoteFamily, s.remoteAddress, s.remotePort);
    me.emit('connection', s);
    me._handleNewConnection(s);
  });

  this._clients = {};
  this._clientCounter = 0;
  this._keyStatus = new KeyStatus(options);

  debug('created');
}
1327572
function(options, zookeeperOptions) {
    EventEmitter.call(this);

    this.modules = {};
    this.middlewares = [];

    this.options = options || {};
    this.zookeeperOptions = zookeeperOptions || {};

    this.zookeeper = undefined;
    if(this.zookeeperOptions && Object.keys(this.zookeeperOptions).length) {
        this.zookeeper = new Zookeeper(
            this.zookeeperOptions.connectString,
            this.zookeeperOptions,
            this.zookeeperOptions.root,
            this.zookeeperOptions.prefix);
    }

    this.server = helper.createServer(options, this._onClientConnected.bind(this));
}
1088945
function Router(options) {
  var self = this;

  options = options || {};

  this.__namespace__ = options.namespace || 'tabex_default_';
  this.__node_id__ = Math.floor(Math.random() * 1e10) + 1;
  this.__last_message_cnt__ = 0;
  this.__handlers__ = [];
  this.__router_channels__ = {};

  // Constants for convenience
  this.__router_id_prefix__ = this.__namespace__ + 'router_';
  this.__router_channels_prefix__ = this.__namespace__ + 'subscribed_';
  this.__lock_prefix__ = this.__namespace__ + 'lock_';

  // IE broadcasts storage events also to the same window, we should filter that messages
  this.__storage_events_filter__ = [];

  for (var i = 0; i < 100; i++) {
    this.__storage_events_filter__.push('');
  }

  this.__ls__ = new LocalStorage();

  // Id of master tab
  this.__master_id__ = null;

  // Handle `localStorage` update
  $$.addEvent(window, 'storage', function (e) {
    if (e.key === null) {
      // If event is caused by `localStorage.clear()` `key` will be null. Skip this
      // event and reestablish normal behaviour by `.__check_master__()` call.
      self.__check_master__();
      return;
    }

    // IE needs kludge because event fire before data was saved
    if ('onstoragecommit' in document) {
      setTimeout(function () {
        self.__on_changed__(e);
      }, 1);

      return;
    }

    self.__on_changed__(e);
  });

  // Handle page unload (listen `onbeforeunload` and `onunload` to ensure that data is stored successfully)
  // http://stackoverflow.com/questions/3775566/javascript-question-onbeforeunload-or-onunload
  //
  this.__destroyed__ = false;
  $$.addEvent(window, 'beforeunload', function () {
    self.__destroy__();
  });
  $$.addEvent(window, 'unload', function () {
    self.__destroy__();
  });

  // Update current tab info and check master alive
  this.__check_master__();

  // Instell timers & remember those to cleanup in __destroy__()
  this.__timer_cm__ = Timer.setInterval(function () {
    self.__check_master__();
  }, UPDATE_INTERVAL);

  // Remove outdated lock records
  this.__timer_lc__ = Timer.setInterval(function () {
    self.__locks_cleanup__();
  }, 1000);
}
947101
function ( options ) {
			this.protocol = options.protocol || 'http';
			this.port = options.port;
			this.server = options.server;
			this.path = options.path;
			this.proxy = options.proxy;
			this.jar = request.jar(); // create new cookie jar for each instance

			this.debug = options.debug;

			// set up logging
			const winston = require( 'winston' ),
				// file logging
				path = require( 'path' ),
				fs = require( 'fs' ),
				logDir = path.dirname( process.argv[ 1 ] ) + '/log/',
				logFile = logDir + path.basename( process.argv[ 1 ], '.js' ) + '.log',
				// how many tasks (i.e. requests) to run in parallel
				concurrency = options.concurrency || 3;

			this.logger = new ( winston.Logger )();

			// console logging
			if ( this.debug ) {
				this.logger.add( winston.transports.Console, {
					level: 'debug'
				} );
			}

			this.logger.cli();

			if ( fs.existsSync( logDir ) ) {
				this.logger.add( winston.transports.File, {
					colorize: true,
					filename: logFile,
					json: false,
					level: this.debug ? 'debug' : 'info'
				} );
			}

			// requests queue
			// @see https://github.com/caolan/async#queue
			this.queue = async.queue( function ( task, callback ) {
			// process the task (and call the provided callback once it's completed)
				task( callback );
			}, concurrency );

			// HTTP client
			this.formatUrl = require( 'url' ).format;

			this.userAgent = options.userAgent || ( `nodemw/${VERSION} (node.js ${process.version}; ${process.platform} ${process.arch})` );
			this.version = VERSION;

			// debug info
			this.info( process.argv.join( ' ' ) );
			this.info( this.userAgent );

			let port = this.port ? `:${this.port}` : '';

			this.info( `Using <${this.protocol}://${this.server}${port}${this.path}/api.php> as API entry point` );
			this.info( '----' );
		}
1028991
function(options, callback)
{
    // Setup IPC connection
    this.ipc = new WorkerIPC();

    // Setup the IPC logger transport
    var workerConf = {
        logger: {
            transports: [
                new (IPCLogger)({
                    worker    : this,
                    colorize  : true,
                    timestamp : function() {

                        var part = moment().format().yellow.bold;

                        if (cluster.isMaster) {
                            part += ' [Master]'.red.bold;
                        } else {
                            part += ' [Worker]'.white.bold;
                        }

                        return part;
                    },
                    level  : 'debug',
                    silent : false
                })
            ]
        },
        requestLogger: {
            transports: [
                new (IPCLogger)({
                    type     : 'request',
                    worker   : this,
                    colorize : false,
                    level    : 'info',
                    silent   : false
                })
            ]
        }
    };

    // Extend the given worker configuration
    arguments[0] = extend(true, workerConf, arguments[2] || {});

    // Call the super constructor
    Worker.super_.call(this, options);
}
892894
function createZooKeeperClient(options) {
	options = options || {};

	if (!options.hosts) {
		throw new Error('Missing configuration server.discoveryService.options.hosts for ZooKeeper');
	}

	// client options, with better defaults than node-zookeeper-client provides

	var clientOpts = options.options || {};

	clientOpts.sessionTimeout = clientOpts.hasOwnProperty('sessionTimeout') ? clientOpts.sessionTimeout : 30000;
	clientOpts.spinDelay = clientOpts.hasOwnProperty('spinDelay') ? clientOpts.spinDelay : 1000;
	clientOpts.retries = clientOpts.hasOwnProperty('retries') ? clientOpts.retries : 3;

	// connect to the database

	var client = zooKeeper.createClient(options.hosts, clientOpts);

	client.on('connected', function () {
		logger.verbose('ZooKeeper connection established');
	});

	client.on('connectedReadOnly', function () {
		logger.error('ZooKeeper connection established to a read-only server');
	});

	client.on('disconnected', function () {
		logger.verbose('ZooKeeper connection dropped');
	});

	client.on('expired', function () {
		logger.verbose('ZooKeeper client session expired');
	});

	client.on('authenticationFailed', function () {
		logger.error('ZooKeeper authentication failed');
	});

	return client;
}
802437
function Client(options) {
  var self = this;

  // Filers
  this.__filters_in__ = [];
  this.__filters_out__ = [];

  // Subscriptions
  this.__subscriptions__ = [];

  // Current node id
  this.__node_id__ = Math.floor(Math.random() * 1e10) + 1;

  // Message incremental counter
  this.__last_message_cnt__ = 0;

  // List of ignoring messages
  this.__ignore_list__ = {};

  // Router
  this.__router__ = options.router;

  this.__router__.onmessage(function (channel, message) {
    self.__onmessage__(channel, message);
  });

  // Lock handlers
  this.__lock_handlers__ = {};

  // If client make lock request - store handler and remove it from message
  this.filterOut(function (channel, message, callback) {
    if (channel === '!sys.lock.request') {
      var fn = message.data.fn;
      var lockId = message.data.id;

      delete message.data.fn;

      // Wrap handler to pass unlock function into it
      self.__lock_handlers__[message.id] = function () {
        fn(function unlock() {
          self.emit('!sys.lock.release', { id: lockId });
        });
      };
    }

    callback(channel, message);
  });

  // If lock acquired - execute handler
  this.filterIn(function (channel, message, callback) {
    if (channel === '!sys.lock.acquired' && self.__lock_handlers__[message.data.request_id]) {
      self.__lock_handlers__[message.data.request_id]();
      delete self.__lock_handlers__[message.data.request_id];
    }

    callback(channel, message);
  });
}
860272
function _initializeCommunication(options) {
                var mapping;
                var onmessage;

                // Grab the event channel and initialize a new mapper
                this.eventChannel = options.eventChannel || new Channels({
                    events: options.events,
                    commands: options.commands,
                    reqres: options.reqres
                });
                this.mapper = new PostMessageMapper(this.eventChannel);

                // Bind the mapping method to the mapper
                mapping = this.mapper.toEvent.bind(this.mapper);
                // Create the message handler which uses the mapping method
                onmessage = _createMessageHandler(mapping).bind(this);

                // Initialize a message channel with the message handler
                this.messageChannel = new PostMessageChannel(options, onmessage);
            }
1202862
function createProtocol(attrs, opts) {
  opts = opts || {};

  var name = attrs.protocol;
  if (!name) {
    throw new Error('missing protocol name');
  }
  if (attrs.namespace !== undefined) {
    opts.namespace = attrs.namespace;
  } else {
    var match = /^(.*)\.[^.]+$/.exec(name);
    if (match) {
      opts.namespace = match[1];
    }
  }
  name = types.qualify(name, opts.namespace);

  if (attrs.types) {
    attrs.types.forEach(function (obj) { types.createType(obj, opts); });
  }

  var messages = {};
  if (attrs.messages) {
    Object.keys(attrs.messages).forEach(function (key) {
      messages[key] = new Message(key, attrs.messages[key], opts);
    });
  }
  return new Protocol(name, messages, opts.registry || {});
}
572150
function Sender(prefix) {
        if (!prefix) {

            // Transports can't work without a prefix/namespace
            throw new Error(enplug.classes.Transport.prototype.TAG + 'Senders must specify a method prefix.');
        }

        /**
         * {@link Transport} namespace.
         * @type {string}
         */
        this.prefix = prefix;

        /**
         * Disables validation of method params. Used for testing.
         * @type {boolean}
         */
        this.novalidate = false;

        /**
         * Sends and receives messages to/from the parent window.
         * @type {Transport}
         */
        this.transport = new enplug.classes.Transport(window, prefix);
    }
1013184
function $createClient(options) {
        /*
         * Ensure we have default options.
         */
        options = extend({}, {}, options);

        const { url, transport } = options;

        if (_clients[url]) {
            return _clients[url];
        }

        const client = mqtt.connect(url, transport);

        _clients[url] = client;

        return client;
    }
1146847
def _create_namespace(namespace, apiserver_url):
    '''  '''
    # Prepare URL
    url = "{0}/api/v1/namespaces".format(apiserver_url)
    # Prepare data
    data = {
        "kind": "Namespace",
        "apiVersion": "v1",
        "metadata": {
            "name": namespace,
        }
    }
    log.trace("namespace creation requests: %s", data)
    # Make request
    ret = _kpost(url, data)
    log.trace("result is: %s", ret)
    # Check requests status
    return ret
837563
function transformOptions(options) {
  // create namespace object if namespace is passed in as string
  if (typeof options.ns === 'string') options.ns = [options.ns];
  if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
  if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];

  // extend whitelist with cimode
  if (options.whitelist && options.whitelist.indexOf('cimode') < 0) options.whitelist.push('cimode');

  return options;
}
1360935
function createTypeScriptLanguageService(options) {
    // Discover referenced files
    const FILES = discoverAndReadFiles(options);
    // Add fake usage files
    options.inlineEntryPoints.forEach((inlineEntryPoint, index) => {
        FILES[`inlineEntryPoint.${index}.ts`] = inlineEntryPoint;
    });
    // Add additional typings
    options.typings.forEach((typing) => {
        const filePath = path.join(options.sourcesRoot, typing);
        FILES[typing] = fs.readFileSync(filePath).toString();
    });
    // Resolve libs
    const RESOLVED_LIBS = {};
    options.libs.forEach((filename) => {
        const filepath = path.join(TYPESCRIPT_LIB_FOLDER, filename);
        RESOLVED_LIBS[`defaultLib:${filename}`] = fs.readFileSync(filepath).toString();
    });
    const compilerOptions = ts.convertCompilerOptionsFromJson(options.compilerOptions, options.sourcesRoot).options;
    const host = new TypeScriptLanguageServiceHost(RESOLVED_LIBS, FILES, compilerOptions);
    return ts.createLanguageService(host);
}
849678
function (options) {

      var clientShell = this,
      context = {},
      // Default settings.
      defaultSettings = {
        namespace: 'shotgun',
        debug: false
      };

      // Override default settings with supplied options.
      var settings = clientShell.settings = extend(true, {}, defaultSettings, options);

      // Instruct socket.io to connect to the server.
      var socket = clientShell.socket = io.connect('/' + settings.namespace);

      // Proxy any listeners onto the socket itself.
      clientShell.on = function () {
        socket.on.apply(socket, arguments);
        return clientShell;
      };

      // Proxy any emit calls onto the socket itself.
      clientShell.emit = function () {
        socket.emit.apply(socket, arguments);
        return clientShell;
      };

      function getCookies() {
        var cookies = {};
        if (document.cookie.length > 0)
          document.cookie.split(';').forEach(function (cookie) {
            var components = cookie.split('='),
            name = components[0].trim(),
            value = components[1];
            if (name.indexOf(settings.namespace + '-') === 0) {
              name = name.replace(settings.namespace + '-', '');
              cookies[name] = decodeURIComponent(value);
            }
          });
          return cookies;
      }

      clientShell
      // Save context when it changes.
      .on('contextChanged', function (contextData) {
        context = contextData;
      })
      // Create a function for setting cookies in the browser.
      .on('setCookie', function (name, value, days) {
        var expiration = new Date();
        expiration.setDate(expiration.getDate() + days);
        value = encodeURIComponent(value) + ((days === null) ? "" : ";expires=" + expiration.toUTCString());
        document.cookie = settings.namespace + '-' + name + "=" + value;
      })
      .on('getCookie', function (name, callback) {
        // Create a cookies property on the context and fill it with all the cookies for this shell.
        var cookies = getCookies();
        callback(cookies[name]);
      })
      .on('getAllCookies', function (callback) {
        var cookies = getCookies();
        callback(cookies);
      });

      // Create an execute function that looks similar to the shotgun shell execute function for ease of use.
      clientShell.execute = function (cmdStr, contextOverride, options) {
        // If a context was passed in then override the stored context with it.
        if (contextOverride) context = contextOverride;
        socket.emit('execute', cmdStr, context, options);
        return clientShell;
      };

      return clientShell;
    }