## GhostServer
@constructor
@param {Object} rootApp - parent express instance
765452
function GhostServer(rootApp) {
    this.rootApp = rootApp;
    this.httpServer = null;
    this.connections = {};
    this.connectionId = 0;

    // Expose config module for use externally.
    this.config = config;
}
996170
function (args, config, logger, helper) {
      console.log(chalk.blue('Running server on http://localhost:' + port + '.....PID:' + process.pid))

      var express = require('express')
      var expressApp = express()

      // require server path and pass express expressApp to it
      require(pathToServer)(expressApp)

      expressApp.listen(port)
    }
771706
function DiscoveryServerSSDP(app) {
  app.properties[SERVER.Capabilities][THISMIDDLEWARE.CAPABILITY] = {};
  app.properties[SERVER.Capabilities][THISMIDDLEWARE.CAPABILITY][SERVER.Version] = packageVersion;

  //Also register as standard IOPA DISCOVERY SERVER MIDDLEWARE
  app.properties[SERVER.Capabilities][IOPA.CAPABILITIES.DiscoveryServer] = {};
  app.properties[SERVER.Capabilities][IOPA.CAPABILITIES.DiscoveryServer][SERVER.Version] = app.properties[SERVER.Capabilities][IOPA.CAPABILITIES.App][SERVER.Version];

  this._devices = {};
  this._factory = new iopa.Factory();
  this._SSDPserver = null;
  this._HTTPserver = null;
 
  this._SSDPclient = null;

  app.device = app.device || {};
  app.device.register = this.register.bind(this, app.device.register || function (device) { return Promise.resolve(device); });
  app.device.unregister = this.register.bind(this, app.device.unregister || function (id) { return Promise.resolve(id); });
  
  this.ssdpApp = new iopa.App();
  this.ssdpApp.use(IopaUDP);
  this.ssdpApp.use(IopaSSDP);
  this.ssdpApp.use(IopaMessageLogger);

  this.ssdpApp.use(this.invoke.bind(this));
  
  this.httpApp = new iopa.App();
  this.httpApp.use(IopaTCP);
  this.httpApp.use(IopaMessageLogger);
  this.httpApp.use(IopaHTTP);
  this.httpApp.use(this.invoke.bind(this));
}
1289691
function RouterState(root, snapshot) {
        _super.call(this, root);
        this.snapshot = snapshot;
        setRouterStateSnapshot(this, root);
    }
612851
function (services, callback) {
          var http = require('http');
          var app = require('express')();
          var server = http.createServer(app);

          // get remote services
          //var fakedb1 = services[0];
          //var fakedb2 = services[1];

          // all express-related stuff goes here, e.g.
          app.use(function (req, res) { res.end('Handled by PID = ' + process.pid); });

          // all socket.io stuff goes here
          //var io = require('socket.io')(server);

          // don't do server.listen(...)!
          // just pass the server instance to the final async's callback
          callback(null, server);
        }
346697
function serve(app, couch) {
  var url = require('url');
  var port = 3000,
      staticDir = 'attachments',
      tmpDir = '/tmp/couchapp-compile-' + process.pid,
      logDbRewrites = false;
  var arg;
  while(arg = process.argv.shift()){
    if(arg == '-p'){
      port = parseInt(process.argv.shift());
    }
    if(arg == '-d'){
      staticDir = process.argv.shift();
    }
    if(arg == '-l'){
      logDbRewrites = true;
    }
  }
  var dbUrlObj = url.parse(couch);

  var proxyPaths = {}
  var dbPrefix = '../../';
  for (var i in app.doc.rewrites){
    var rw = app.doc.rewrites[i];
    // Rewrites starting with '../../' are proxied to the database
    if (rw.to.indexOf(dbPrefix) == 0){
      var proxyPath = rw.from;
      if(proxyPath[proxyPath.length -1] == '*') {
        proxyPath = proxyPath.substring(0,proxyPath.length-1)
      }
      var dbPath = rw.to.substring(dbPrefix.length);
      if(dbPath[dbPath.length - 1] == '*'){
        dbPath = dbPath.substring(0,dbPath.length-1)
      }
      if(dbPath.indexOf('*') >=0 ){
        if(logDbRewrites){
          console.log("Don't know how to proxy '" + rw.from + "' to CouchDB at " + rw.from );
        }
      } else {
        proxyPaths[proxyPath] =
          dbUrlObj.protocol + '//' + dbUrlObj.host +
          path.normalize(dbUrlObj.pathname + dbPath);
          if(logDbRewrites){
            console.log("Proxying rewrite '" + proxyPath + "' to CouchDB at " + proxyPaths[proxyPath] );
          }
      }
    }
  }

  var connect = require('connect');
  var httpProxy = require('http-proxy'),
      connect   = require('connect'),
      logger = require('morgan'),
      serveStatic = require('serve-static'),
      errorHandler = require('errorhandler'),
      connectCompiler;
  try{
      connectCompiler = require('connect-compiler');
  } catch(e) {}


  var proxy = httpProxy.createProxyServer({
    target: {
      host: dbUrlObj.host,
      hostname: dbUrlObj.hostname,
      port: dbUrlObj.port,
      https: dbUrlObj.protocol == 'https:',
    }
  });
  var app = connect()
    .use(logger('dev'))
    .use(serveStatic(staticDir));
  if(connectCompiler){
    console.log('Will compile assets with connect-assets.');
    var ignore = [];
    var quote = function(str) {
      return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    }
    for(var prefix in proxyPaths){
      ignore.push(quote(prefix));
    }
    if(ignore.length){
      //console.log("Asset compile ignore paths:", '^(' +  ignore.join('|') + ')');
      ignore  = new RegExp('^(' +  ignore.join('|') + ')');
    } else {
      ignore = null;
    }
    app.use(connectCompiler({
      enabled: ['coffee'] ,
      src: staticDir,
      dest: tmpDir,
      ignore :  ignore,
    }))
    .use(serveStatic(tmpDir));
  }
  app.use(function(req, res, next) {
      for(var prefix in proxyPaths){
        var dbPath = proxyPaths[prefix];
        if (req.url.indexOf(prefix) === 0) {
          var dbURL = req.url.replace(prefix,dbPath);
          if(logDbRewrites){
            console.log("*** ", req.url , ' -> ', dbURL);
          }
          req.url = dbURL;
          req.headers['host'] = dbUrlObj.host;
          proxy.proxyRequest(req, res);
          return;
        }
      }
      var body = '404 Not found.\nNo static file or db route matched.';
      res.statusCode = 404;
      res.setHeader('Content-Length', body.length);
      res.end(body);
     })
    .use(errorHandler())
    .listen(port);
  console.log("Serving couchapp at: http://0.0.0.0:" + port +"/");

  //Cleanup the temp directory on exit
  var cleanup = function(){
    var rmDir = function(dirPath) {
      try { var files = fs.readdirSync(dirPath); }
      catch(e) { return; }
      if (files.length > 0)
        for (var i = 0; i < files.length; i++) {
          var filePath = dirPath + '/' + files[i];
          if (fs.statSync(filePath).isFile())
            fs.unlinkSync(filePath);
          else
            rmDir(filePath);
        }
      fs.rmdirSync(dirPath);
    };
    rmDir(tmpDir);
  };
  process.on('exit',cleanup);
  process.on('SIGINT',function(){
    cleanup()
    process.exit();
  });
}
1060792
function(parentModule, kbox, id, app, callback) {

  if (typeof callback === 'undefined' && typeof app === 'function') {
    callback = app;
    app = undefined;
  }

  // Try to load module from node_modules and other directories.
  var parts = id.split('@');
  var pkg = parts[0];
  //var ver = parts[1];

  // Try to load module.
  return requireFromNodeModulesAndOtherDirs(parentModule, kbox, pkg, app)
  // Return.
  .nodeify(callback);

}
10834
function startServer() {
  var server = require('http').createServer(app);
  var socket = socketio(server, {
    serveClient: true,
    path: '/socket.io-client'
  });
  // Setup SocketIO
  socketConfig(socket);
  return server;
}
158629
function initServer (args) {
    // get server args
    var server = requireValidOptionalObject(args.server)
    // create module methods
    moduleMethods.forEach(methodName => {
        var method = server[methodName]
        // skip if no method in args
        if (!defined(method)) {
            return
        }
        // require function
        this.assert(typeof method === 'function', 110, `${methodName} method must be function`)
        // create module method
        this.module.method(methodName, method)
    })
}
689337
function (rootComp) {
      var self = this;
      var stop = false;
      var renderQueue = [];

      var transitionState = function () {
        var stateChanged, metaChanged;

        if (renderQueue.length === 1) {
          var singleFrame = renderQueue[0];

          stateChanged = singleFrame.stateChanged;
          metaChanged = singleFrame.metaChanged;

          if (stateChanged) self._previousState = singleFrame.previousState;
          if (metaChanged) self._previousMetaState = singleFrame.previousMetaState;
        } else {
          var elderStateChangedFrame = Util.find(renderQueue, function (q) { return q.stateChanged; });
          var elderMetaChangedFrame = Util.find(renderQueue, function (q) { return q.metaChanged; });

          stateChanged = !!elderStateChangedFrame;
          metaChanged = !!elderMetaChangedFrame;

          if (stateChanged) self._previousState = elderStateChangedFrame.previousState;
          if (metaChanged) self._previousMetaState = elderMetaChangedFrame.previousMetaState;
        }

        self._stateChanged = stateChanged;
        self._metaChanged = metaChanged;

        renderQueue = [];
      };

      var forceUpdate = function (comp, f) {
        if (comp.isMounted()) {
          comp.forceUpdate(f);
        }
      };

      var logError = function (message, cause) {
        if (self._options.logger) {
          try {
            self._options.logger.error(message, cause);
          }
          catch (e) {
            defaultLogger.error(message, cause);
          }
        }
      };

      var catchingRenderErrors = function (f) {
        try {
          f();
        } catch (e) {
          if (self._options.stopOnRenderError) {
            stop = true;
          }

          logError('Morearty: render error. ' + (stop ? 'Will exit on next render attempt.' : 'Continuing.'), e);
        }
      };

      var render = function () {
        transitionState();

        self._renderQueued = false;

        catchingRenderErrors(function () {
          if (self._fullUpdateQueued) {
            self._fullUpdateInProgress = true;

            forceUpdate(rootComp, function () {
              self._fullUpdateQueued = false;
              self._fullUpdateInProgress = false;
            });
          } else {
            forceUpdate(rootComp);

            self._componentQueue.forEach(function (c) {
              forceUpdate(c);
              savePreviousState(c);
            });
            self._componentQueue = [];
          }
        });
      };

      if (!self._options.renderOnce) {
        var renderRoutine = getRenderRoutine(self);

        var listenerId = self._stateBinding.addListener(function (changes) {
          if (stop) {
            self._stateBinding.removeListener(listenerId);
          } else {
            var stateChanged = changes.isValueChanged(), metaChanged = changes.isMetaChanged();

            if (stateChanged || metaChanged) {
              renderQueue.push({
                stateChanged: stateChanged,
                metaChanged: metaChanged,
                previousState: (stateChanged || null) && changes.getPreviousBackingValue(),
                previousMetaState: (metaChanged || null) && changes.getPreviousBackingMeta()
              });

              if (!self._renderQueued) {
                self._renderQueued = true;
                renderRoutine(render);
              }
            }
          }
        });
      }

      catchingRenderErrors(rootComp.forceUpdate.bind(rootComp));
    }
1319873
function GhostRouter(options) {
    const router = express.Router(options);

    function innerRouter(req, res, next) {
        return innerRouter.handle(req, res, next);
    }

    Object.setPrototypeOf(innerRouter, router);

    Object.defineProperty(innerRouter, 'name', {
        value: options.parent.name,
        writable: false
    });

    innerRouter.parent = options.parent;
    return innerRouter;
}
253623
function (options, callback) {
    if (this.stopAppServerFunc) {
      this.stopAppServerFunc(options, callback);
    } else if (this.appServer) {
      this.appServer.stop(callback);
    } else {
      callback();
    }
  }
1211609
function initWebServer(settings) {

    let server = {
        app:       null,
        server:    null,
        io:        null,
        settings:  settings
    };
    adapter.subscribeForeignObjects('system.config');

    settings.ttl = parseInt(settings.ttl, 10) || 3600;
    if (!settings.whiteListEnabled && settings.whiteListSettings) delete settings.whiteListSettings;

    settings.defaultUser = settings.defaultUser || 'system.user.admin';
    if (!settings.defaultUser.match(/^system\.user\./)) settings.defaultUser = 'system.user.' + settings.defaultUser;

    if (settings.port) {
        if (settings.secure) {
            if (!settings.certificates) {
                return null;
            }
        }
        server.app = express();

        server.app.disable('x-powered-by');
        // enable use of i-frames together with HTTPS
        server.app.get('/*', (req, res, next) => {
            res.header('X-Frame-Options' , 'SAMEORIGIN');
            next(); // http://expressjs.com/guide.html#passing-route control
        });

        if (settings.auth) {

            initAuth(server, settings);

            let autoLogonOrRedirectToLogin = (req, res, next, redirect) => {
                if (!settings.whiteListSettings) {
                    if (/\.css(\?.*)?$/.test(req.originalUrl)) {
                        return res.status(200).send('');
                    } else
					if (/\.js(\?.*)?$/.test(req.originalUrl)) {
						// return always valid js file for js, because if cache is active it leads to errors
                        const parts = req.originalUrl.split('/');
                        parts.shift();
                        const ref = parts.join('/');
						// if request for web/lib, ignore it, because no redirect information
						if (parts[0] === 'lib') return res.status(200).send('');
						return res.status(200).send('document.location="/login/index.html?href=" + encodeURI(location.href.replace(location.origin, ""));');
					} else {
						return res.redirect(redirect);
					}
				}
                let remoteIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
                let whiteListIp = server.io.getWhiteListIpForAddress(remoteIp, settings.whiteListSettings);
				adapter.log.silly('whiteListIp ' + whiteListIp);
                if (!whiteListIp || settings.whiteListSettings[whiteListIp].user === 'auth') {
                    if (/\.css(\?.*)?$/.test(req.originalUrl)) {
                        return res.status(200).send('');
                    } else if (/\.js(\?.*)?$/.test(req.originalUrl)) {
						// return always valid js file for js, because if cache is active it leads to errors
						let parts = req.originalUrl.split('/');
                        parts.shift();
                        const ref = parts.join('/');
						if (parts[0] === 'lib') return res.status(200).send('');
                        return res.status(200).send('document.location="/login/index.html?href=" + encodeURI(location.href.replace(location.origin, ""));');
					} else {
						return res.redirect(redirect);
					}
				}
                req.logIn(settings.whiteListSettings[whiteListIp].user, err => {
					return next(err);
                });
            };

            server.app.post('/login', (req, res, next) => {
                let redirect = '/';
                let parts;
                if (req.body.origin) {
                    parts = req.body.origin.split('=');
                    if (parts[1]) redirect = decodeURIComponent(parts[1]);
                }
                if (req.body && req.body.username && settings.addUserName && redirect.indexOf('?') === -1) {
                    parts = redirect.split('#');
                    parts[0] += '?' + req.body.username;
                    redirect = parts.join('#');
                }
                passport.authenticate('local', {
                    successRedirect: redirect,
                    failureRedirect: '/login/index.html' + req.body.origin + (req.body.origin ? '&error' : '?error'),
                    failureFlash: 'Invalid username or password.'
                })(req, res, next);
            });

            server.app.get('/logout', (req, res) => {
                req.logout();
                res.redirect('/login/index.html');
            });

            // route middleware to make sure a user is logged in
            server.app.use((req, res, next) => {
				// if cache.manifest got back not 200 it makes an error
                if (req.isAuthenticated() ||
                    /web\.\d+\/login-bg\.png(\?.*)?$/.test(req.originalUrl) ||
                    /cache\.manifest(\?.*)?$/.test(req.originalUrl) ||
                    /^\/login\//.test(req.originalUrl) ||
                    /\.ico(\?.*)?$/.test(req.originalUrl)
                ) {
                    return next();
                } else {
                    autoLogonOrRedirectToLogin(req, res, next, '/login/index.html?href=' + encodeURIComponent(req.originalUrl));
                }
            });
        } else {
            server.app.get('/login', (req, res) => {
                res.redirect('/');
            });
            server.app.get('/logout', (req, res) => {
                res.redirect('/');
            });

            if (settings.whiteListEnabled) {
                initAuth(server, settings);
                server.app.use((req, res, next) => {
                    let remoteIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
                    let whiteListIp = server.io.getWhiteListIpForAddress(remoteIp, settings.whiteListSettings);
                    adapter.log.silly('whiteListIp ' + whiteListIp);
                    if (whiteListIp) {
                       req.logIn(settings.whiteListSettings[whiteListIp].user, err => {
                            return next(err);
                        });
                    } else {
                        req.logIn(settings.defaultUser, err => {
                            return next(err);
                        });
                    }
                });
            }
        }

        // Init read from states
        server.app.get('/state/*', (req, res) => {
            try {
                const fileName = req.url.split('/', 3)[2].split('?', 2);
                adapter.getForeignObject(fileName[0], (err, obj) => {
                    let contentType = 'text/plain';
                    if (obj && obj.common.type === 'file')  {
                        contentType = mime.lookup(fileName[0]);
                    }
                    adapter.getBinaryState(fileName[0], {user: req.user ? 'system.user.' + req.user : settings.defaultUser}, (err, obj) => {
                        if (!err && obj !== null && obj !== undefined) {
                            if (obj && typeof obj === 'object' && obj.val !== undefined && obj.ack !== undefined) {
                                res.set('Content-Type', 'application/json');
                            } else {
                                res.set('Content-Type', contentType || 'text/plain');
                            }
                            res.status(200).send(obj);
                        } else {
                            res.status(404).send('404 Not found. File ' + fileName[0] + ' not found');
                        }
                    });
                });
            } catch (e) {
                res.status(500).send('500. Error' + e);
            }
        });

        server.app.get('*/_socket/info.js', (req, res) => {
            res.set('Content-Type', 'application/javascript');
            res.status(200).send(getInfoJs(settings));
        });

        // Enable CORS
        if (settings.socketio) {
            server.app.use((req, res, next) => {
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');

                // intercept OPTIONS method
                if ('OPTIONS' === req.method) {
                    res.status(200).send(200);
                } else {
                    next();
                }
            });
        }

        let appOptions = {};
        if (settings.cache) appOptions.maxAge = 30758400000;

        server.server = LE.createServer(server.app, settings, settings.certificates, settings.leConfig, adapter.log);
        server.server.__server = server;
    } else {
        adapter.log.error('port missing');
        adapter.terminate ? adapter.terminate(1): process.exit(1);
    }

    if (server.server) {
        settings.port = parseInt(settings.port, 10);
        adapter.getPort(settings.port, port => {
            port = parseInt(port, 10);
            if (port !== settings.port && !settings.findNextPort) {
                adapter.log.error('port ' + settings.port + ' already in use');
                adapter.terminate ? adapter.terminate(1): process.exit(1);
            }
            server.server.listen(port, (!settings.bind || settings.bind === '0.0.0.0') ? undefined : settings.bind || undefined);
            adapter.log.info('http' + (settings.secure ? 's' : '') + ' server listening on port ' + port);
        });
    }

    // activate extensions
    for (let e in extensions) {
        if (!extensions.hasOwnProperty(e)) continue;
        try {
            // for debug purposes try to load file in current directory "/lib/file.js" (elsewise node.js cannot debug it)
            let parts = extensions[e].path.split('/');
            parts.shift();
            let extAPI;
            if (fs.existsSync(__dirname + '/' + parts.join('/'))) {
                extAPI = require(__dirname + '/' + parts.join('/'));
            } else {
                extAPI = require(utils.appName + '.' + extensions[e].path);
            }

            extensions[e].obj = new extAPI(server.server, {secure: settings.secure, port: settings.port}, adapter, extensions[e].config, server.app);
            adapter.log.info('Connect extension "' + extensions[e].path + '"');
        } catch (err) {
            adapter.log.error('Cannot start extension "' + e + '": ' + err);
        }
    }

    // Activate integrated simple API
    if (settings.simpleapi) {
        let SimpleAPI = require(utils.appName + '.simple-api/lib/simpleapi.js');

        server.api = new SimpleAPI(server.server, {secure: settings.secure, port: settings.port}, adapter);
    }

    // Activate integrated socket
    if (ownSocket) {
        let IOSocket = require(utils.appName + '.socketio/lib/socket.js');
        let socketSettings = JSON.parse(JSON.stringify(settings));
        // Authentication checked by server itself
        socketSettings.auth             = settings.auth;
        socketSettings.secret           = secret;
        socketSettings.store            = store;
        socketSettings.ttl              = settings.ttl || 3600;
        socketSettings.forceWebSockets  = settings.forceWebSockets || false;
        server.io = new IOSocket(server.server, socketSettings, adapter);
    }

    if (server.app) {
        // deliver web files from objectDB
        server.app.use('/', (req, res) => {

            let url = decodeURI(req.url);
            // remove all ../
            // important: Linux does not normalize "\" but fs.readFile accepts it as '/'
            url = path.normalize(url.replace(/\\/g, '/')).replace(/\\/g, '/');
            // remove '////' at start and let only one
            if (url[0] === '/' && url[1] === '/') {
                let i = 2;
                while (url[i] === '/') i++;
                url = url.substring(i - 1);
            }
            if ((url[0] === '.' && url[1] === '.') || (url[0] === '/' && url[1] === '.' && url[2] === '.')) {
                res.status(404).send('Not found');
                return;
            }

            if (server.api && server.api.checkRequest(url)) {
                server.api.restApi(req, res);
                return;
            }

            if (url === '/' || url === '/index.html') {
                getListOfAllAdapters((err, data) => {
                    if (err) {
                        res.status(500).send('500. Error' + e);
                    } else {
                        res
                            .set('Content-Type', 'text/html')
                            .status(200)
                            .send(data);
                    }
                });
                return;
            }

            // add index.html
            url = url.replace(/\/($|\?|#)/, '/index.html$1');

            if (url.match(/^\/adapter\//)) {
                // add .admin to adapter name
                url = url.replace(/^\/adapter\/([a-zA-Z0-9-_]+)\//, '/$1.admin/');
            }

            if (url.match(/^\/lib\//)) {
                url = '/' + adapter.name + url;
            }
            if (url.match(/^\/admin\//)) {
                url = '/' + adapter.name + url;
            }
            url = url.split('/');
            // Skip first /
            url.shift();
            // Get ID
            let id = url.shift();
            let versionPrefix = url[0];
            url = url.join('/');
            let pos = url.indexOf('?');
            let noFileCache;
            if (pos !== -1) {
                url = url.substring(0, pos);
                // disable file cache if request like /vis/files/picture.png?noCache
                noFileCache = true;
            }

            // get adapter name
            if (webByVersion[id]) {
                if (!versionPrefix || !versionPrefix.match(/^\d+\.\d+.\d+$/)) {
                    // redirect to version
                    res.set('location', '/' + id + '/' + webByVersion[id] + '/' + url);
                    res.status(301).send();
                    return;
                }
            }

            if (settings.cache && cache[id + '/' + url] && !noFileCache) {
                res.contentType(cache[id + '/' + url].mimeType);
                res.status(200).send(cache[id + '/' + url].buffer);
            } else {
                if (id === 'login' && url === 'index.html') {
                    loginPage = loginPage || prepareLoginTemplate();
                    let buffer = loginPage;

                    if (buffer === null || buffer === undefined) {
                        res.contentType('text/html');
                        res.status(200).send('File ' + url + ' not found', 404);
                    } else {
                        // Store file in cache
                        if (settings.cache) {
                            cache[id + '/' + url] = {buffer: buffer.toString(), mimeType: 'text/html'};
                        }
                        res.contentType('text/html');
                        res.status(200).send(buffer.toString());
                    }
                } else {
                    // special solution for socket.io
                    if (socketIoFile !== false && url.match(/\/socket\.io\.js(\?.*)?$/)) {
                        if (socketIoFile) {
                            res.contentType('text/javascript');
                            res.status(200).send(socketIoFile);
                            return
                        } else {
                            try {
                                const dir = require.resolve('socket.io-client');
                                const fileDir = path.join(path.dirname(dir), '../dist/');
                                if (fs.existsSync(fileDir + 'socket.io.min.js')) {
                                    socketIoFile = fs.readFileSync(fileDir + 'socket.io.min.js');
                                } else {
                                    socketIoFile = fs.readFileSync(fileDir + 'socket.io.js');
                                }
                            } catch (e) {
                                socketIoFile = false;
                            }
                            if (socketIoFile) {
                                res.contentType('text/javascript');
                                res.status(200).send(socketIoFile);
                                return
                            }
                        }
                    }
                    
                    adapter.readFile(id, webByVersion[id] ? url.substring(versionPrefix.length + 1) : url , {user: req.user ? 'system.user.' + req.user : settings.defaultUser, noFileCache: noFileCache}, (err, buffer, mimeType) => {
                        if (buffer === null || buffer === undefined || err) {
                            res.contentType('text/html');
                            res.status(404).send('File ' + url + ' not found: ' + err);
                        } else {
                            mimeType = mimeType || mime.lookup(url) || 'text/javascript';

                            // Store file in cache
                            if (settings.cache) {
                                cache[id + '/' + url] = {
                                    buffer: buffer,
                                    mimeType: mimeType
                                };
                            }

                            res.contentType(mimeType);
                            res.status(200).send(buffer);
                        }
                    });
                }
            }
        });
    }

    if (server.server) {
        return server;
    } else {
        return null;
    }
}
179061
function HttpServer(options) {
  options = options || {};

  if (options.root) {
    this.root = options.root;
  }
  else {
    try {
      fs.lstatSync('./public');
      this.root = './public';
    }
    catch (err) {
      this.root = './';
    }
  }

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

  this.cache = options.cache === undefined ? 3600 : options.cache; // in seconds.
  this.showDir = options.showDir !== 'false';
  this.autoIndex = options.autoIndex !== 'false';
  this.gzip = options.gzip === true;
  this.contentType = options.contentType || 'application/octet-stream';

  if (options.ext) {
    this.ext = options.ext === true
      ? 'html'
      : options.ext;
  }

  var before = options.before ? options.before.slice() : [];

  before.push(function (req, res) {
    if (options.logFn) {
      options.logFn(req, res);
    }

    res.emit('next');
  });

  if (options.cors) {
    this.headers['Access-Control-Allow-Origin'] = '*';
    this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range';
    if (options.corsHeaders) {
      options.corsHeaders.split(/\s*,\s*/)
          .forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this);
    }
    before.push(corser.create(options.corsHeaders ? {
      requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/)
    } : null));
  }

  if (options.robots) {
    before.push(function (req, res) {
      if (req.url === '/robots.txt') {
        res.setHeader('Content-Type', 'text/plain');
        var robots = options.robots === true
          ? 'User-agent: *\nDisallow: /'
          : options.robots.replace(/\\n/, '\n');

        return res.end(robots);
      }

      res.emit('next');
    });
  }

  before.push(ecstatic({
    root: this.root,
    cache: this.cache,
    showDir: this.showDir,
    autoIndex: this.autoIndex,
    defaultExt: this.ext,
    gzip: this.gzip,
    contentType: this.contentType,
//    handleError: typeof options.proxy !== 'string'
    handleError: (!options.fallback || typeof options.proxy === 'string')
  }));

  if (typeof options.proxy === 'string') {
    var proxy = httpProxy.createProxyServer({});
    before.push(function (req, res) {
      proxy.web(req, res, {
        target: options.proxy,
        changeOrigin: true
      });
    });
  }

  if (options.fallback) {
    before.push(function (req, res) {
      if (res.statusCode === 404) {
        res.redirect(options.fallback.address, 301);
      }
    });
  }

  var serverOptions = {
    before: before,
    headers: this.headers,
    onError: function (err, req, res) {
      if (options.logFn) {
        options.logFn(req, res, err);
      }

      res.end();
    }
  };

  if (options.https) {
    serverOptions.https = options.https;
  }

  this.server = union.createServer(serverOptions);
}
1002009
function server(argv, config, args) {
  const roots = args.projectRoots.concat(args.root);
  args.projectRoots = roots.concat(
    findSymlinksPaths(NODE_MODULES, roots)
  );

  console.log(formatBanner(
    'Running packager on port ' + args.port + '.\n\n' +
    'Keep this packager running while developing on any JS projects. ' +
    'Feel free to close this tab and run your own packager instance if you ' +
    'prefer.\n\n' +
    'https://github.com/facebook/react-native', {
      marginLeft: 1,
      marginRight: 1,
      paddingBottom: 1,
    })
  );

  console.log(
    'Looking for JS files in\n  ',
    chalk.dim(args.projectRoots.join('\n   ')),
    '\n'
  );

  process.on('uncaughtException', error => {
    if (error.code === 'EADDRINUSE') {
      console.log(
        chalk.bgRed.bold(' ERROR '),
        chalk.red('Packager can\'t listen on port', chalk.bold(args.port))
      );
      console.log('Most likely another process is already using this port');
      console.log('Run the following command to find out which process:');
      console.log('\n  ', chalk.bold('lsof -n -i4TCP:' + args.port), '\n');
      console.log('You can either shut down the other process:');
      console.log('\n  ', chalk.bold('kill -9 <PID>'), '\n');
      console.log('or run packager on different port.');
    } else {
      console.log(chalk.bgRed.bold(' ERROR '), chalk.red(error.message));
      const errorAttributes = JSON.stringify(error);
      if (errorAttributes !== '{}') {
        console.error(chalk.red(errorAttributes));
      }
      console.error(chalk.red(error.stack));
    }
    console.log('\nSee', chalk.underline('http://facebook.github.io/react-native/docs/troubleshooting.html'));
    console.log('for common problems and solutions.');
    process.exit(11);
  });

  runServer(args, config, () => console.log('\nReact packager ready.\n'));
}
605973
function(callback) {
        if (res.parsedHeader.payload.mode === 'handshake') {
          res.session = {
            sid: reqSid,
            cert: senderCert,
            token: reqToken
          };
          callback(null);
        } else {
          var querySid;
          if (sessionStore instanceof Store || 'undefined' !== typeof window) {
            querySid = my.config.urlBase;
          } else {
            querySid = reqSid;
          }
          // load the session if exists
          sessionStore.load(querySid, function(err, session){
            if (err) {
              callback(err);
            } else if (session) {
              log.debug('%s loaded session', app.name);
              log.debug(session);
              res.session = session;
              callback(null);
            } else {
              callback('session expired');
            }
          });
        }
      }
457173
function (options, callback) {
    var log = this.log;

    log('starting app server');
    if (this.startAppServerFunc) {
      // manual starting of app server
      this.startAppServerFunc(options, callback);
    } else {
      // let smocks-magellan-nightwatch automatically handle the work
      var appServer = this.appServer = new Hapi.Server();
      appServer.connection({ port: this.appPort });
      appServer.route([{
        method: 'GET',
        path: '/{path*}',
        handler: function (req, reply) {
          log('request made: ' + req.path);
          var requestPath = req.path;
          var artifactPath = Path.join(options.distPath, requestPath);
          if (requestPath.match(/\/[^\.]*$/i)) {
            log('handling response as container html file');
            // it's the main index file.  In order to re-use the transpiled files, we need to
            // ensure that the container html file represents the correct mock port so
            // we will replace that out when returning the file contents
            replyWithIndexFile(options, reply);
          } else {
            log('handling response: ' + requestPath);

            fs.exists(artifactPath, function (exists) {
              if (exists) {
                var mimeType = mimeTypes.lookup(artifactPath);
                fs.readFile(artifactPath, function (err, buffer) {
                  if (err) {
                    log('error loading file: ' + artifactPath + ': ' + e.message);
                    reply(err);
                  } else {
                    log('responding with ' + artifactPath);
                    reply(buffer).type(mimeType);
                  }
                });
              } else {
                log(artifactPath + ' does not exist... 404');
                reply({message: artifactPath + ' does not exist'}).code(404);
              }
            });
          }
        }
      }]);
      appServer.start(callback);
    }
  }