forked from cerebral/overmind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevtoolBackend.js
More file actions
106 lines (96 loc) · 2.65 KB
/
DevtoolBackend.js
File metadata and controls
106 lines (96 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const WebSocket = require('ws')
class DevtoolBackend {
constructor(options) {
this.options = options
this.onError = this.onError.bind(this)
this.onClientConnection = this.onClientConnection.bind(this)
this.onDevtoolConnection = this.onDevtoolConnection.bind(this)
this.onClientMessage = this.onClientMessage.bind(this)
this.onDevtoolMessage = this.onDevtoolMessage.bind(this)
this.devtoolServer = new WebSocket.Server(
{
port: options.port,
},
() => {}
)
this.devtoolServer.on('connection', this.onDevtoolConnection)
}
onDevtoolConnection(ws) {
this.devtoolSocket = ws
this.devtoolSocket.on('message', this.onDevtoolMessage)
}
async onDevtoolMessage(message) {
const parsedMessage = JSON.parse(message)
switch (parsedMessage.type) {
case 'storage:get':
this.evaluateDevtoolMessage(parsedMessage, () =>
this.options.storage.get(parsedMessage.data.key)
)
break
case 'storage:set':
this.evaluateDevtoolMessage(parsedMessage, () =>
this.options.storage.set(parsedMessage.key, parsedMessage.data)
)
break
case 'storage:clear':
this.evaluateDevtoolMessage(parsedMessage, () =>
this.options.storage.clear()
)
break
case 'relaunch':
this.options.onRelaunch()
break
case 'connect':
this.createClientServer(parsedMessage.data)
break
default:
this.clientSocket.send(JSON.stringify(parsedMessage.data))
}
}
onError() {
this.devtoolServer.emit('port:exists')
}
onClientConnection(ws) {
this.clientSocket = ws
this.clientSocket.on('message', this.onClientMessage)
}
onClientMessage(message) {
this.devtoolSocket.send(`
{
"type": "message",
"data": ${message}
}
`)
}
async evaluateDevtoolMessage(message, cb) {
const result = await cb()
if ('evaluate' in message) {
this.devtoolSocket.send(
JSON.stringify({
type: 'evaluated',
data: {
id: message.evaluate,
data: result,
},
})
)
}
}
createClientServer(port) {
if (this.clientPort === Number(port)) {
return
}
if (this.clientServer) {
this.clientServer.close()
}
this.clientPort = Number(port)
this.clientServer = new WebSocket.Server(
{ port: this.clientPort },
() => {}
)
this.clientServer.on('connection', this.onClientConnection)
this.clientServer.on('error', this.onError)
}
}
DevtoolBackend.create = (options) => new DevtoolBackend(options)
module.exports = DevtoolBackend