From 5e4f286f4891bb6052dac7784b49d05aa0839a7b Mon Sep 17 00:00:00 2001 From: Rafael Oleza Date: Fri, 8 Sep 2017 06:15:14 -0700 Subject: [PATCH] Use the new Delta HMR implementation from the internal React Native CLI Reviewed By: jeanlauliac Differential Revision: D5765025 fbshipit-source-id: fbf516c26382773c623bd3e0c2ba8b668bfd8b31 --- .../server/util/attachWebsocketServer.js | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 local-cli/server/util/attachWebsocketServer.js diff --git a/local-cli/server/util/attachWebsocketServer.js b/local-cli/server/util/attachWebsocketServer.js new file mode 100644 index 00000000000..ae9efed0fb9 --- /dev/null +++ b/local-cli/server/util/attachWebsocketServer.js @@ -0,0 +1,72 @@ +/** + * 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. + * + * @format + * @flow + */ + +'use strict'; + +import type {Server as HTTPServer} from 'http'; +import type {Server as HTTPSServer} from 'https'; + +type WebsocketServiceInterface = { + +onClientConnect: ( + url: string, + sendFn: (data: string) => mixed, + ) => Promise, + +onClientDisconnect?: (client: T) => mixed, + +onClientError?: (client: T, e: Error) => mixed, + +onClientMessage?: (client: T, message: string) => mixed, +}; + +type HMROptions = { + httpServer: HTTPServer | HTTPSServer, + websocketServer: WebsocketServiceInterface, + path: string, +}; + +/** + * Attaches a WebSocket based connection to the Packager to expose + * Hot Module Replacement updates to the simulator. + */ +function attachWebsocketServer({ + httpServer, + websocketServer, + path, +}: HMROptions) { + const WebSocketServer = require('ws').Server; + const wss = new WebSocketServer({ + server: httpServer, + path: path, + }); + + wss.on('connection', async ws => { + const url = ws.upgradeReq.url; + + const sendFn = ws.send.bind(ws); + + const client = await websocketServer.onClientConnect(url, sendFn); + + ws.on('error', e => { + websocketServer.onClientError && websocketServer.onClientError(client, e); + }); + + ws.on('close', () => { + websocketServer.onClientDisconnect && + websocketServer.onClientDisconnect(client); + }); + + ws.on('message', message => { + websocketServer.onClientMessage && + websocketServer.onClientMessage(client, message); + }); + }); +} + +module.exports = attachWebsocketServer;