Bug 1826760 - Make dom/media/platforms/wmf buildable outside of a unified build envir...
[gecko.git] / remote / server / WebSocketTransport.sys.mjs
blobe2a7183fdb7cf5786e2c18bcbced034e5a68a086
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 // This is an XPCOM service-ified copy of ../devtools/shared/transport/websocket-transport.js.
7 const lazy = {};
9 ChromeUtils.defineESModuleGetters(lazy, {
10   EventEmitter: "resource://gre/modules/EventEmitter.sys.mjs",
11 });
13 export function WebSocketTransport(socket) {
14   lazy.EventEmitter.decorate(this);
16   this.active = false;
17   this.hooks = null;
18   this.socket = socket;
21 WebSocketTransport.prototype = {
22   ready() {
23     if (this.active) {
24       return;
25     }
27     this.socket.addEventListener("message", this);
28     this.socket.addEventListener("close", this);
30     this.active = true;
31   },
33   send(object) {
34     this.emit("send", object);
35     if (this.socket) {
36       this.socket.send(JSON.stringify(object));
37     }
38   },
40   startBulkSend() {
41     throw new Error("Bulk send is not supported by WebSocket transport");
42   },
44   close() {
45     if (!this.socket) {
46       return;
47     }
48     this.emit("close");
49     this.active = false;
51     this.socket.removeEventListener("message", this);
52     this.socket.removeEventListener("close", this);
53     this.socket.close();
54     this.socket = null;
56     if (this.hooks) {
57       this.hooks.onClosed();
58       this.hooks = null;
59     }
60   },
62   handleEvent(event) {
63     switch (event.type) {
64       case "message":
65         this.onMessage(event);
66         break;
67       case "close":
68         this.close();
69         break;
70     }
71   },
73   onMessage({ data }) {
74     if (typeof data !== "string") {
75       throw new Error(
76         "Binary messages are not supported by WebSocket transport"
77       );
78     }
80     const object = JSON.parse(data);
81     this.emit("packet", object);
82     if (this.hooks) {
83       this.hooks.onPacket(object);
84     }
85   },