Launch the server for serving the client JS plus static files
@param {BrowserSync} bs
@returns {{staticServer: (http.Server), proxyServer: (http.Server)}}
542016
function createServer(bs) {
    var proxy = bs.options.get("proxy");
    var server = bs.options.get("server");

    if (!proxy && !server) {
        return require("./snippet-server")(bs);
    }

    if (proxy) {
        return require("./proxy-server")(bs);
    }

    if (server) {
        return require("./static-server")(bs);
    }
}
78221
async function start() {
  try {
    await server.register({ plugin: hapijsStatusMonitor });
    await server.start();
  }
  catch (err) {
    console.log(err);
    process.exit(1);
  }

  console.log('Server running at:', server.info.uri);
}
374284
function tasksComplete(bs) {
    return function(err) {
        if (err) {
            bs.logger.setOnce("useLevelPrefixes", true).error(err.message);
        }

        /**
         * Set active flag
         */
        bs.active = true;

        /**
         * @deprecated
         */
        bs.events.emit("init", bs);

        /**
         * This is no-longer needed as the Callback now only resolves
         * when everything (including slow things, like the tunnel) is ready.
         * It's here purely for backwards compatibility.
         * @deprecated
         */
        bs.events.emit("service:running", {
            options: bs.options,
            baseDir: bs.options.getIn(["server", "baseDir"]),
            type: bs.options.get("mode"),
            port: bs.options.get("port"),
            url: bs.options.getIn(["urls", "local"]),
            urls: bs.options.get("urls").toJS(),
            tunnel: bs.options.getIn(["urls", "tunnel"])
        });

        /**
         * Call any option-provided callbacks
         */
        bs.callback("ready", null, bs);

        /**
         * Finally, call the user-provided callback given as last arg
         */
        bs.cb(null, bs);
    };
}
527156
function (appServer) {
      appServer.use(function (req, res, next) {
        if (process.env.ENVIRONMENT === 'development') {
          // Lets not console log for status polling or webpack hot module reloading
          if (
            !req.url.includes('/status') &&
            !req.url.includes('/__webpack_hmr')
          ) {
            console.log('Using middleware for ' + req.url)
          }
        }
        next()
      })

      // Add webpack hot middleware to use for error overlay
      // Quiet is set to true because well let WebpackDevServer handle console logging
      appServer.use(webpackHotMiddleware(compiler))

      // If there is a server.js file load it and pass appServer to it
      if (pathToServer) {
        require(pathToServer)(appServer)
      }
    }
1334273
function Server(options) {
  var that = this;
  that.options = options || {};
  that.stack = [];
  bind.call(that);
}
998656
function serveRoutes(server) {
    self.server = server;
    server.app.use(serve);
    server.app.get('/admin/statics', function(req, res) { res.send(Object.keys(self.file$)); });
    watchAll();
    return self; // chainable
  }
226064
function Server(opts){
  // Shorthand, no "new" required.
  if (!(this instanceof Server))
    return new Server(...arguments);

  if (typeof opts !== 'object')
    opts = {};

  this.clients = opts.dummies || [];

  this.server = opts.server || new SocketServer(socket => {
    let client = new Client(socket);
    this.clients.push(client);
    this.emit('connection', client);

    client._socket.once('data', handshake.bind(client));
    client.on('handshake-done', () => {
      client._socket.on('data', message.bind(client));
    });
  });
}
939737
function startServer(serverPromise) {
    var self = this,
        startTime = Date.now(),
        browsersStarting,
        serverTimeout,
        serverProcess = fork(__dirname + '/KarmaWorker.js', { silent: true });

    // Limit the time it can take for a server to start to config.waitForServerTime seconds
    serverTimeout = setTimeout(function() {
        self._setStatus(KarmaServerStatus.DEFUNCT);
        serverPromise.reject(
            'Could not connect to a Karma server on port ' + self._config.port + ' within ' +
            self._config.waitForServerTime + ' seconds'
        );
    }, self._config.waitForServerTime * 1000);

    serverProcess.send({ command: 'start', config: self._config });

    serverProcess.stdout.on('data', function(data) {
        var message = data.toString('utf-8'),
            messageParts = message.split(/\s/g);

        logger.debug(message);

        //this is a hack: because Karma exposes no method of determining when the server is started up we'll dissect the log messages
        if(message.indexOf('Starting browser') > -1) {
            browsersStarting = browsersStarting ? browsersStarting.concat([messageParts[4]]) : [messageParts[4]];
        }
        if(message.indexOf('Connected on socket') > -1) {
            browsersStarting.pop();
            if(browsersStarting && browsersStarting.length === 0) {
                clearTimeout(serverTimeout);
                self._setStatus(KarmaServerStatus.READY);

                logger.info(
                    'Karma server started after %dms and is listening on port %d',
                    (Date.now() - startTime), self._config.port
                );

                serverPromise.resolve(self);
            }
        }
    });

    return serverProcess;
}
806113
function run() {
    generator.load(function(err) {
      if (err) return log(err);

      if (opts.outputOnly) {
        generator.outputPages(function(err, result) {
          if (err) { log(err); }
          log('output %s generated pages', u.flatten(result).length);
        });

        var statics = require('./server/serve-statics')(opts, function(){
          statics.outputAll();
        });
        require('./server/serve-scripts')(opts).outputAll(generator);
        generator.unload();
        return;
      }

      if (opts.logPages) {
        generator.logPages();
        generator.unload();
        return;
      }

      require('./server/watch-sources')(generator);
      generator.listen(true);

      if (!opts['no-server']) { expressApp(); }
    });
  }
617229
function(bs, done) {
        /**
         * An extra port is not needed in snippet/server mode
         */
        if (bs.options.get("mode") !== "proxy") {
            return done();
        }

        /**
         * Web socket support is disabled by default
         */
        if (!bs.options.getIn(["proxy", "ws"])) {
            return done();
        }

        /**
         * Use 1 higher than server port by default...
         */
        var socketPort = bs.options.get("port") + 1;

        /**
         * Or use the user-defined socket.port option instead
         */
        if (bs.options.hasIn(["socket", "port"])) {
            socketPort = bs.options.getIn(["socket", "port"]);
        }

        utils.getPort(bs.options.get("listen", "localhost"), socketPort, null, function(err, port) {
            if (err) {
                return utils.fail(true, err, bs.cb);
            }
            done(null, {
                optionsIn: [
                    {
                        path: ["socket", "port"],
                        value: port
                    }
                ]
            });
        });
    }
1349144
function createServer() {
  function app(req, res, next) {
    app.handle(req, res, next);
  }
  app.method = '*';
  merge(app, proto);
  merge(app, EventEmitter.prototype);
  app.stack = [];
  app.params = [];
  app._cachedEvents = [] ;
  app.routedMethods = {} ;
  app.locals = Object.create(null);
  for (var i = 0; i < arguments.length; ++i) {
    app.use(arguments[i]);
  }

  //create methods app.invite, app.register, etc..
  methods.forEach((method) => {
    app[method.toLowerCase()] = app.use.bind(app, method.toLowerCase()) ;
  }) ;

  //special handling for cdr events
  app.on = function(event, listener) {
    if (0 === event.indexOf('cdr:')) {
      if (app.client) {
        app.client.on(event, function() {
          var args = Array.prototype.slice.call(arguments) ;
          EventEmitter.prototype.emit.apply(app, [event].concat(args)) ;
        }) ;
      }
      else {
        this._cachedEvents.push(event) ;
      }
    }
    //delegate all others to standard EventEmitter prototype
    return EventEmitter.prototype.addListener.call(app, event, listener) ;
  } ;

  return app;
}
943905
function initWebServer(settings) {

    const server = {
        app:       null,
        server:    null,
        io:        null,
        settings:  settings
    };

    settings.port = parseInt(settings.port, 10) || 0;

    if (settings.port) {
        if (settings.secure) {
            if (!settings.certificates) return null;
        }
        if (settings.auth) {
            const session =          require('express-session');
            const AdapterStore =     require(utils.controllerDir + '/lib/session.js')(session, settings.ttl);
            // Authentication checked by server itself
            store = new AdapterStore({adapter: adapter});
            settings.secret           = secret;
            settings.store            = store;
            settings.ttl              = settings.ttl || 3600;
            settings.forceWebSockets  = settings.forceWebSockets || false;
        }

        adapter.getPort(settings.port, port => {
            if (parseInt(port, 10) !== settings.port && !adapter.config.findNextPort) {
                adapter.log.error('port ' + settings.port + ' already in use');
                process.exit(1);
            }
            settings.port = port;

            server.server = LE.createServer((req, res) => {
                res.writeHead(501);
                res.end('Not Implemented');
            }, settings, adapter.config.certificates, adapter.config.leConfig, adapter.log);

            server.server.listen(settings.port, (settings.bind && settings.bind !== '0.0.0.0') ? settings.bind : undefined);

            settings.crossDomain     = true;
            settings.ttl             = settings.ttl || 3600;
            settings.forceWebSockets = settings.forceWebSockets || false;

            server.io = new IOSocket(server.server, settings, adapter);
        });
    } else {
        adapter.log.error('port missing');
        process.exit(1);
    }

    return server;
}
1050866
function emitServer({
  port,
  prompts,
  promptsForRender,
  whenPrompts,
  withoutWhenPrompts,
  templatePath = DEFAULT_TPL_PATH,
  tplData = {
    title: '😊 Dulcet Inquirer'
  }
}) {
  const string = fs.readFileSync(templatePath).toString()
  const compiled = template(string, { interpolate: /<%=([\s\S]+?)%>/g })

  const emitter = new EventEmitter()
  const promptValues = prompts.reduce(function(set, val) {
    set[val.name] = val
    return set
  }, {})

  const store = withoutWhenPrompts.reduce(function(set, { name, default: _default }) {
    set[name] = _default
    return set
  }, {})

  function getErrorMsg(prompt, value) {
    if (prompt && typeof prompt.validate === 'function') {
      const msg = prompt.validate(value, store)
      if (typeof msg === 'string') {
        return msg
      }
    }
  }
  function getErrors() {
    const errors = {}
    prompts.forEach(function(prompt) {
      const msg = getErrorMsg(prompt, store[prompt.name])
      if (msg) {
        errors[prompt.name] = msg
      }
    })
    return Object.keys(errors).length ? errors : null
  }

  const server = app.listen(port, function() {
    emitter.emit('server-started')
  })
  app._server = server

  app.get('/', function(req, res) {
    res.type('html')
    res.send(
      compiled(
        Object.assign({}, tplData, {
          prompts: promptsForRender
        })
      )
    )
  })

  app.get('/when', function(req, res) {
    const passedList = []
    const failedList = []
    whenPrompts.forEach(function(item) {
      if (item.when(store)) {
        if (!store.hasOwnProperty(item.name)) {
          store[item.name] = item.default
        }
        passedList.push(item)
      } else {
        if (item.name in store) {
          delete store[item.name]
        }
        failedList.push(item)
      }
    })

    pass(res, 'when-passed', {
      passed: passedList.map(item => item.name),
      failed: failedList.map(item => item.name)
    })
  })

  app.get('/set', function(req, res) {
    const { name, value } = JSON.parse(req.query._)
    const prompt = prompts.find(x => x.name === name)
    if (prompt && typeof prompt.validate === 'function') {
      const msg = getErrorMsg(promptValues[name], value)
      if (msg) {
        store[name] = value
        pass(res, 'errors', { [name]: msg })
      } else {
        store[name] = value
        pass(res, 'validate-passed', name)
      }
      return
    }
    // console.log('set:before', store)
    store[name] = value
    // console.log('set:after', store)
    pass(res, 'passed', name)
  })

  // app.get('/transformer', function() {
  //   compiled(prompts)
  // })

  app.post('/submit', function(req, res) {
    // const { values } = req.query
    const errors = getErrors()
    if (errors) {
      pass(res, 'errors', errors)
    } else {
      pass(res, 'close', 'Submit succeed!')

      emitter.emit('done', store)
    }
    // store = values
  })
  return emitter
}
949886
function startServer(alerts, params, port, resources) {
    const compiledAlerts = compileMarkdown(alerts);
    const app = http.createServer((req, res) =>
        res.end(resources[req.url] || resources['/index.html']));
    const io = listen(app);
    io.on('connection', socket => {
        emitInfo(`new session for ${socket.handshake.address}`);
        socket.emit('update', compiledAlerts);
        socket.on('disconnect', () => {
            emitInfo(`disconnected session ${socket.handshake.address}`);
        });
    });

    return new Promise(resolve => app.listen(port, emitRungEmoji & resolve))
        .then(~watchChanges(io, params));
}
566286
function Server(srv, opts){
  if (!(this instanceof Server)) return new Server(srv, opts);
  if ('object' == typeof srv && srv instanceof Object && !srv.listen) {
    opts = srv;
    srv = null;
  }
  opts = opts || {};
  this.nsps = {};
  this.parentNsps = new Map();
  this.path(opts.path || '/socket.io');
  this.serveClient(false !== opts.serveClient);
  this.parser = opts.parser || parser;
  this.encoder = new this.parser.Encoder();
  this.adapter(opts.adapter || Adapter);
  this.origins(opts.origins || '*:*');
  this.sockets = this.of('/');
  if (srv) this.attach(srv, opts);
}
206947
def serve(path, livereload, port, verbose):
    
    setup_logging(verbose)
    run_app(*serve_static(static_path=path, livereload=livereload, port=port))
1337643
function startAppServer(fn) {
  if (!checkingAppServerPort) {
    server = fork(appServer.file, [], appServer.options);
    server.on('exit', code => {
      checkingAppServerPort = false;
      server.removeAllListeners();
      server = null;
      fn(Error('failed to start server'));
    });

    checkingAppServerPort = true;
    waitForPortOpen(appServer.port, fn);
  }
}