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