microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/common/extensionMessaging.ts
68lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. |
| 3 | |
| 4 | import * as Q from "q"; |
| 5 | import * as net from "net"; |
| 6 | |
| 7 | /** |
| 8 | * Pipe path used for communicating with the server. |
| 9 | */ |
| 10 | let WIN_ServerPipePath = "\\\\?\\pipe\\vscodereactnative"; |
| 11 | let UNIX_ServerPipePath = "/tmp/vscodereactnative.sock"; |
| 12 | |
| 13 | export let ErrorMarker = "vscodereactnative-error-marker"; |
| 14 | |
| 15 | export let getPipePath = (): string => { |
| 16 | return (process.platform === "win32" ? WIN_ServerPipePath : UNIX_ServerPipePath); |
| 17 | }; |
| 18 | |
| 19 | /** |
| 20 | * Defines the messages sent to the extension. |
| 21 | * Add new messages to this enum. |
| 22 | */ |
| 23 | export enum ExtensionMessage { |
| 24 | START_PACKAGER, |
| 25 | STOP_PACKAGER, |
| 26 | PREWARM_BUNDLE_CACHE |
| 27 | } |
| 28 | |
| 29 | export interface MessageWithArguments { |
| 30 | message: ExtensionMessage; |
| 31 | args: any[]; |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Sends messages to the extension. |
| 36 | */ |
| 37 | export class ExtensionMessageSender { |
| 38 | |
| 39 | public sendMessage(message: ExtensionMessage, args?: any[]): Q.Promise<any> { |
| 40 | let deferred = Q.defer<any>(); |
| 41 | let messageWithArguments: MessageWithArguments = { message: message, args: args }; |
| 42 | let body = ""; |
| 43 | |
| 44 | let socket = net.connect(getPipePath(), function() { |
| 45 | let messageJson = JSON.stringify(messageWithArguments); |
| 46 | socket.write(messageJson); |
| 47 | }); |
| 48 | |
| 49 | socket.on("data", function(data: any) { |
| 50 | body += data; |
| 51 | }); |
| 52 | |
| 53 | socket.on("end", function() { |
| 54 | try { |
| 55 | if (body === ErrorMarker) { |
| 56 | deferred.reject(new Error("An error ocurred while handling message: " + ExtensionMessage[message])); |
| 57 | } else { |
| 58 | let responseBody: any = body ? JSON.parse(body) : null; |
| 59 | deferred.resolve(responseBody); |
| 60 | } |
| 61 | } catch (e) { |
| 62 | deferred.reject(e); |
| 63 | } |
| 64 | }); |
| 65 | |
| 66 | return deferred.promise; |
| 67 | } |
| 68 | } |