|
| 1 | +/** |
| 2 | + * Copyright (c) 2015-present, Facebook, Inc. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. An additional grant |
| 7 | + * of patent rights can be found in the PATENTS file in the same directory. |
| 8 | + * |
| 9 | + * @format |
| 10 | + * @flow |
| 11 | + */ |
| 12 | + |
| 13 | +'use strict'; |
| 14 | + |
| 15 | +import type {Server as HTTPServer} from 'http'; |
| 16 | +import type {Server as HTTPSServer} from 'https'; |
| 17 | + |
| 18 | +type WebsocketServiceInterface<T> = { |
| 19 | + +onClientConnect: ( |
| 20 | + url: string, |
| 21 | + sendFn: (data: string) => mixed, |
| 22 | + ) => Promise<T>, |
| 23 | + +onClientDisconnect?: (client: T) => mixed, |
| 24 | + +onClientError?: (client: T, e: Error) => mixed, |
| 25 | + +onClientMessage?: (client: T, message: string) => mixed, |
| 26 | +}; |
| 27 | + |
| 28 | +type HMROptions<TClient> = { |
| 29 | + httpServer: HTTPServer | HTTPSServer, |
| 30 | + websocketServer: WebsocketServiceInterface<TClient>, |
| 31 | + path: string, |
| 32 | +}; |
| 33 | + |
| 34 | +/** |
| 35 | + * Attaches a WebSocket based connection to the Packager to expose |
| 36 | + * Hot Module Replacement updates to the simulator. |
| 37 | + */ |
| 38 | +function attachWebsocketServer<TClient: Object>({ |
| 39 | + httpServer, |
| 40 | + websocketServer, |
| 41 | + path, |
| 42 | +}: HMROptions<TClient>) { |
| 43 | + const WebSocketServer = require('ws').Server; |
| 44 | + const wss = new WebSocketServer({ |
| 45 | + server: httpServer, |
| 46 | + path: path, |
| 47 | + }); |
| 48 | + |
| 49 | + wss.on('connection', async ws => { |
| 50 | + const url = ws.upgradeReq.url; |
| 51 | + |
| 52 | + const sendFn = ws.send.bind(ws); |
| 53 | + |
| 54 | + const client = await websocketServer.onClientConnect(url, sendFn); |
| 55 | + |
| 56 | + ws.on('error', e => { |
| 57 | + websocketServer.onClientError && websocketServer.onClientError(client, e); |
| 58 | + }); |
| 59 | + |
| 60 | + ws.on('close', () => { |
| 61 | + websocketServer.onClientDisconnect && |
| 62 | + websocketServer.onClientDisconnect(client); |
| 63 | + }); |
| 64 | + |
| 65 | + ws.on('message', message => { |
| 66 | + websocketServer.onClientMessage && |
| 67 | + websocketServer.onClientMessage(client, message); |
| 68 | + }); |
| 69 | + }); |
| 70 | +} |
| 71 | + |
| 72 | +module.exports = attachWebsocketServer; |
0 commit comments