Bug 1467571 [wpt PR 11385] - Make manifest's parsers quicker, a=testonly
[gecko.git] / devtools / shared / transport / websocket-transport.js
blob66e49912c203f669770a15ae4aea0291624b2c3f
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 "use strict";
7 const EventEmitter = require("devtools/shared/event-emitter");
9 function WebSocketDebuggerTransport(socket) {
10   EventEmitter.decorate(this);
12   this.active = false;
13   this.hooks = null;
14   this.socket = socket;
17 WebSocketDebuggerTransport.prototype = {
18   ready() {
19     if (this.active) {
20       return;
21     }
23     this.socket.addEventListener("message", this);
24     this.socket.addEventListener("close", this);
26     this.active = true;
27   },
29   send(object) {
30     this.emit("send", object);
31     if (this.socket) {
32       this.socket.send(JSON.stringify(object));
33     }
34   },
36   startBulkSend() {
37     throw new Error("Bulk send is not supported by WebSocket transport");
38   },
40   close() {
41     this.emit("close");
42     this.active = false;
44     this.socket.removeEventListener("message", this);
45     this.socket.removeEventListener("close", this);
46     this.socket.close();
47     this.socket = null;
49     if (this.hooks) {
50       this.hooks.onClosed();
51       this.hooks = null;
52     }
53   },
55   handleEvent(event) {
56     switch (event.type) {
57       case "message":
58         this.onMessage(event);
59         break;
60       case "close":
61         this.close();
62         break;
63     }
64   },
66   onMessage({ data }) {
67     if (typeof data !== "string") {
68       throw new Error("Binary messages are not supported by WebSocket transport");
69     }
71     const object = JSON.parse(data);
72     this.emit("packet", object);
73     if (this.hooks) {
74       this.hooks.onPacket(object);
75     }
76   },
79 module.exports = WebSocketDebuggerTransport;