react-native/local-cli/server/util/webSocketProxy.js
Alex Kotliarskyi 64d56f34b7 Improve Chrome debugger
Summary:
`debugger.html` contained a ton of hacky code that was needed to ensure we have a clean JS runtime every time a client RN app connects. That was needed because we used the page's global environment as runtime. Some time ago WebWorker support was added and now we run RN code inside an isolated WebWorker instance, and we can safely get rid of all these hacks.

This has a bunch of nice side-effects: debug reload works faster, `console.log`s are preserved, `debuggerWorker.js` selection doesn't change.

Made sure the debugging (breakpoints, etc.) still works as before.

Small demo
![](http://g.recordit.co/FPdVHLHPUW.gif)
Closes https://github.com/facebook/react-native/pull/5715

Reviewed By: svcscm

Differential Revision: D2906602

Pulled By: frantic

fb-gh-sync-id: 1a6ab9a5655d7c32ddd23619564e59c377b53a35
2016-02-05 15:17:33 -08:00

78 lines
2.0 KiB
JavaScript

/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
function attachToServer(server, path) {
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({
server: server,
path: path
});
var debuggerSocket, clientSocket;
function send(dest, message) {
if (!dest) {
return;
}
try {
dest.send(message);
} catch(e) {
console.warn(e);
// Sometimes this call throws 'not opened'
}
}
wss.on('connection', function(ws) {
const {url} = ws.upgradeReq;
if (url.indexOf('role=debugger') > -1) {
if (debuggerSocket) {
ws.close(1011, 'Another debugger is already connected');
return;
}
debuggerSocket = ws;
debuggerSocket.onerror =
debuggerSocket.onclose = () => {
debuggerSocket = null;
if (clientSocket) {
clientSocket.close(1011, 'Debugger was disconnected');
}
};
debuggerSocket.onmessage = ({data}) => send(clientSocket, data);
} else if (url.indexOf('role=client') > -1) {
if (clientSocket) {
clientSocket.onerror = clientSocket.onclose = clientSocket.onmessage = null;
clientSocket.close(1011, 'Another client connected');
}
clientSocket = ws;
clientSocket.onerror =
clientSocket.onclose = () => {
clientSocket = null;
send(debuggerSocket, JSON.stringify({method: '$disconnected'}));
};
clientSocket.onmessage = ({data}) => send(debuggerSocket, data);
} else {
ws.close(1011, 'Missing role param');
}
});
return {
server: wss,
isChromeConnected: function() {
return !!debuggerSocket;
}
};
}
module.exports = {
attachToServer: attachToServer
};