SockJSServer.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. /* eslint-disable
  3. class-methods-use-this,
  4. func-names
  5. */
  6. const sockjs = require('sockjs');
  7. const BaseServer = require('./BaseServer');
  8. // Workaround for sockjs@~0.3.19
  9. // sockjs will remove Origin header, however Origin header is required for checking host.
  10. // See https://github.com/webpack/webpack-dev-server/issues/1604 for more information
  11. {
  12. // eslint-disable-next-line global-require
  13. const SockjsSession = require('sockjs/lib/transport').Session;
  14. const decorateConnection = SockjsSession.prototype.decorateConnection;
  15. SockjsSession.prototype.decorateConnection = function(req) {
  16. decorateConnection.call(this, req);
  17. const connection = this.connection;
  18. if (
  19. connection.headers &&
  20. !('origin' in connection.headers) &&
  21. 'origin' in req.headers
  22. ) {
  23. connection.headers.origin = req.headers.origin;
  24. }
  25. };
  26. }
  27. module.exports = class SockJSServer extends BaseServer {
  28. // options has: error (function), debug (function), server (http/s server), path (string)
  29. constructor(server) {
  30. super(server);
  31. this.socket = sockjs.createServer({
  32. // Use provided up-to-date sockjs-client
  33. sockjs_url: '/__webpack_dev_server__/sockjs.bundle.js',
  34. // Limit useless logs
  35. log: (severity, line) => {
  36. if (severity === 'error') {
  37. this.server.log.error(line);
  38. } else {
  39. this.server.log.debug(line);
  40. }
  41. },
  42. });
  43. this.socket.installHandlers(this.server.listeningApp, {
  44. prefix: this.server.sockPath,
  45. });
  46. }
  47. send(connection, message) {
  48. connection.write(message);
  49. }
  50. close(connection) {
  51. connection.close();
  52. }
  53. // f should return the resulting connection
  54. onConnection(f) {
  55. this.socket.on('connection', f);
  56. }
  57. };