Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose Sockjs server/client #1662

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion client-src/default/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ const onSocketMsg = {
log.error('[WDS] Disconnected!');
sendMsg('Close');
},
custom(data) {
sendMsg('custom', data);
},
};

let hostname = urlParts.hostname;
Expand Down Expand Up @@ -218,7 +221,13 @@ const socketUrl = url.format({
: querystring.parse(urlParts.path).sockPath || urlParts.path,
});

socket(socketUrl, onSocketMsg);
const send = socket(socketUrl, onSocketMsg);

self.addEventListener('message', (message) => {
if (message.data.type === 'sendWebpackDevServer') {
send(message.data.data);
}
});

let isUnloading = false;
self.addEventListener('beforeunload', () => {
Expand Down
20 changes: 20 additions & 0 deletions client-src/default/listen.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

/* global __resourceQuery WorkerGlobalScope self */

function listen(callback, eventName = 'custom') {
const type = `webpack${eventName}`;

function handle(message) {
if (message.data == null || message.data.type !== type) return;
callback(message.data);
}

self.addEventListener('message', handle);

return function unsubscribe() {
self.removeEventListener('message', handle);
};
}

module.exports = listen;
21 changes: 21 additions & 0 deletions client-src/default/send.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

/* global WorkerGlobalScope self */

function sendWebpackDevServer(data) {
if (
typeof self !== 'undefined' &&
(typeof WorkerGlobalScope === 'undefined' ||
!(self instanceof WorkerGlobalScope))
) {
self.postMessage(
{
type: 'sendWebpackDevServer',
data: JSON.stringify(data),
},
'*'
);
}
}

module.exports = sendWebpackDevServer;
16 changes: 14 additions & 2 deletions client-src/default/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,21 @@ const SockJS = require('sockjs-client/dist/sockjs');

let retries = 0;
let sock = null;
let messageQueue = [];

const socket = function initSocket(url, handlers) {
function send(message) {
if (sock.readyState === SockJS.OPEN) return sock.send(message);
messageQueue.push(message);
}

const socket = function initSocket(url, handlers, messages) {
sock = new SockJS(url);

sock.onopen = function onopen() {
messageQueue.forEach(function dequeue(message) {
sock.send(message);
});
messageQueue = [];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Breaking change for multi compiler compilation

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Never remove messages, because you can have two/three/four clients, and some clients can have delay

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do you mean? If you lose connection and reconnect you probably don't want to resend all messages again?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added the message queue for messages that are sent before the connection is fully established or else you will get an error from sockjs.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@EloB open two or three browsers and tests how it works, we already do same before and remove this, because it is break situation when you have more then one client (some client can disconnect and connect again)

Copy link
Author

@EloB EloB Feb 14, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That initSocket looks really weird in the first place because it's not pure and does side effects on sock in a recursive fashion.

Copy link
Author

@EloB EloB Feb 14, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@evilebottnawi Maybe we could rewrite that initSocket to be pure instead?

retries = 0;
};

Expand All @@ -29,7 +39,7 @@ const socket = function initSocket(url, handlers) {
retries += 1;

setTimeout(() => {
socket(url, handlers);
socket(url, handlers, messages);
}, retryInMs);
}
};
Expand All @@ -41,6 +51,8 @@ const socket = function initSocket(url, handlers) {
handlers[msg.type](msg.data);
}
};

return send;
};

module.exports = socket;
15 changes: 15 additions & 0 deletions examples/cli/advanced-sockjs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Advanced SockJS use

You can now extend the functionality of the SockJS with your custom needs.

To run this example, run this command in your console or terminal:

```console
npm run webpack-dev-server -- --advanced-sockjs
```

## What Should Happen

When you visit http://localhost:8080/ then it will automatically send any javascript errors to the webpack-dev-server.

If you have opened http://localhost:8080/devtools and do keystrokes while you have http://localhost:8080/ running you will see your keystrokes on that page.
29 changes: 29 additions & 0 deletions examples/cli/advanced-sockjs/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict';

const target = document.querySelector('#target');

target.innerHTML = `
Open <a href="/devtools" target="_blank">devtools</a> in a new window
<div id="keypressed"></div>
`;

if (process.env.NODE_ENV === 'development') {
// Simple example to send uncaught error to webpack-dev-server for logging
const send = require('../../../client/send'); // eslint-disable-line global-require
window.addEventListener('error', (error) =>
send({
type: 'log',
data: error.message,
})
);

// Simple example of outputting of keystrokes from devtools on screen
const listen = require('../../../client/listen'); // eslint-disable-line global-require
listen((message) => {
if (message.data.type === 'keypress') {
document.querySelector('#keypressed').innerHTML += message.data.data;
}
});
}

throw new Error('Hello world');
14 changes: 14 additions & 0 deletions examples/cli/advanced-sockjs/devTools.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

const send = require('../../../client/send');

const target = document.querySelector('#target');

target.innerHTML = `Click anywhere on this page and then do some keystrokes`;

document.addEventListener('keypress', (event) =>
send({
type: 'keypress',
data: String.fromCharCode(event.which),
})
);
37 changes: 37 additions & 0 deletions examples/cli/advanced-sockjs/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const { setup } = require('../../util');

const appConfig = setup({
name: 'Your app',
entry: './app.js',
});
Object.assign(appConfig.output, {
publicPath: '/',
});

const devToolsConfig = setup({
name: 'Your custom devTools',
entry: './devTools.js',
devServer: {
before: function before(app, server) {
server.subscribeClientData(({ message }) => {
switch (message.type) {
case 'log':
return console.log(message.data);
case 'keypress':
return server.sockWrite(server.sockets, 'custom', message);
default:
}
});
},
},
});
Object.assign(devToolsConfig.output, {
path: `${devToolsConfig.output.path}/devtools`,
publicPath: '/devtools',
});

module.exports = function createConfigs(env, argv) {
return [].concat(argv.mode === 'production' ? [] : devToolsConfig, appConfig);
};
6 changes: 3 additions & 3 deletions examples/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ module.exports = {

if (result.devServer.before) {
const proxy = result.devServer.before;
result.devServer.before = function replace(app) {
before(app);
proxy(app);
result.devServer.before = function replace(app, server) {
before(app, server);
proxy(app, server);
};
} else {
result.devServer.before = before;
Expand Down
19 changes: 19 additions & 0 deletions lib/Server.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ const STATS = {
errorDetails: false,
};

const CLIENT_EVENT = 'webpack-dev-server-data';

class Server {
constructor(compiler, options = {}, _log) {
this.log = _log || createLogger(options);
Expand Down Expand Up @@ -685,6 +687,16 @@ class Server {
next();
}

subscribeClientData(handle) {
const { app } = this;

app.on(CLIENT_EVENT, handle);

return function unsubscribeClientData() {
app.off(CLIENT_EVENT, handle);
};
}

checkHost(headers) {
return this.checkHeaders(headers, 'host');
}
Expand Down Expand Up @@ -812,6 +824,13 @@ class Server {

this.sockets.push(connection);

connection.on('data', (data) =>
this.app.emit(CLIENT_EVENT, {
socket: connection,
message: JSON.parse(data),
})
);

connection.on('close', () => {
const idx = this.sockets.indexOf(connection);

Expand Down