-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.js
137 lines (110 loc) · 2.41 KB
/
engine.js
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
/**
* Abstraction of WebSocket connection.
*/
import EventEmitter from "eventemitter3"
/**
* @typedef {object} Payload
* @property {string} cmd
* @property {string} [channel]
* @property {string} [nick]
* @property {string} [text]
*/
/**
* @typedef {object} Msg
*
* @property {string} text
*
* @property {string} [cmd]
*
* @property {string} [type]
* @property {string} [nick]
* @property {string} [trip]
* @property {string} [from]
*
* @property {string[]?} [nicks]
* @property {User[]?} [users]
*
* @property {string?} [time]
* @property {string?} [color]
*
* @property {boolean} [admin]
* @property {boolean} [mod]
*/
/**
* @typedef {function(Msg):void} Callback
*/
const Commands = Object.freeze({
chat: "chat",
updateMessage: "updateMessage",
info: "info",
emote: "emote",
warn: "warn",
onlineSet: "onlineSet",
onlineAdd: "onlineAdd",
onlineRemove: "onlineRemove",
updateUser: "updateUser",
captcha: "captcha",
noCmd: Symbol("noCmd"),
})
const Events = Object.freeze({
message: Symbol("message"),
rawMessage: Symbol("rawMessage")
})
class Engine extends EventEmitter {
/** @type {string} */
ws_url
/** @type {boolean} */
joined
/** @type {string} */
channel
/**
* @param {string} ws_url
*/
constructor(ws_url) {
super()
this.ws_url = ws_url
this.joined = false
}
/**
* @param {Payload} data
*/
send(data) {
this.ws.send(JSON.stringify(data))
}
/**
* @returns {Promise<void>}
*/
async connect() {
return await new Promise((resolve, reject) => {
this.ws = new WebSocket(this.ws_url)
this.ws.onmessage = (e) => {
/** @type {Msg} */
const msg = JSON.parse(e.data)
this.emit(Events.rawMessage, e.data)
this.emit(Events.message, msg)
this.emit(msg.cmd ?? Commands.noCmd, msg)
}
this.ws.onopen = () => resolve()
})
}
/**
* @param {string} channel
* @param {string} nick
*/
async join(channel, nick) {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
throw new Error("Connection not established yet")
}
this.send({ cmd: "join", channel, nick })
await new Promise((resolve, reject) => {
this.once(Commands.onlineSet, () => resolve())
})
this.joined = true
this.channel = channel
}
close() {
this.ws.close()
this.joined = false
}
}
export { Engine, Commands, Events }