cloudstorm 0.3.2 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,6 @@ const events_1 = require("events");
6
6
  const BetterWs_1 = __importDefault(require("../structures/BetterWs"));
7
7
  const Constants_1 = require("../Constants");
8
8
  const Intents_1 = __importDefault(require("../Intents"));
9
- const ws_1 = __importDefault(require("ws"));
10
9
  let reconnecting = false;
11
10
  /**
12
11
  * Class used for acting based on received events.
@@ -21,12 +20,11 @@ class DiscordConnector extends events_1.EventEmitter {
21
20
  */
22
21
  constructor(id, client) {
23
22
  super();
24
- this.betterWs = null;
25
23
  this.heartbeatTimeout = null;
26
24
  this.heartbeatInterval = 0;
27
25
  this._trace = null;
28
26
  this.seq = 0;
29
- this.status = "init";
27
+ this.status = "disconnected";
30
28
  this.sessionId = null;
31
29
  this.lastACKAt = 0;
32
30
  this.lastHeartbeatSend = 0;
@@ -35,37 +33,28 @@ class DiscordConnector extends events_1.EventEmitter {
35
33
  this.client = client;
36
34
  this.options = client.options;
37
35
  this.reconnect = this.options.reconnect || true;
38
- }
39
- /**
40
- * Connect to Discord.
41
- */
42
- connect() {
43
- if (!this.betterWs) {
44
- this.betterWs = new BetterWs_1.default(this.options.endpoint, this.options.ws);
45
- }
46
- else {
47
- this.betterWs.removeAllListeners();
48
- this.betterWs.recreateWs(this.options.endpoint, this.options.ws);
49
- }
36
+ this.betterWs = new BetterWs_1.default(this.options.endpoint, this.options.ws);
50
37
  this.betterWs.on("ws_open", () => {
51
38
  this.status = "connecting";
39
+ this.emit("stateChange", "connecting");
52
40
  reconnecting = false;
53
41
  });
54
42
  this.betterWs.on("ws_message", msg => this.messageAction(msg));
55
43
  this.betterWs.on("ws_close", (code, reason) => this.handleWsClose(code, reason));
56
- this.betterWs.on("debug", event => {
57
- this.client.emit("debug", event);
58
- });
59
- this.betterWs.on("debug_send", data => {
60
- this.client.emit("rawSend", data);
61
- });
44
+ this.betterWs.on("debug", event => this.client.emit("debug", event));
45
+ this.betterWs.on("debug_send", data => this.client.emit("rawSend", data));
46
+ }
47
+ /**
48
+ * Connect to Discord.
49
+ */
50
+ connect() {
51
+ return this.betterWs.connect();
62
52
  }
63
53
  /**
64
54
  * Close the websocket connection and disconnect.
65
55
  */
66
56
  async disconnect() {
67
- var _a;
68
- return (_a = this.betterWs) === null || _a === void 0 ? void 0 : _a.close(1000, "Disconnected by User");
57
+ return this.betterWs.close();
69
58
  }
70
59
  /**
71
60
  * Called with a parsed Websocket message to execute further actions.
@@ -96,9 +85,8 @@ class DiscordConnector extends events_1.EventEmitter {
96
85
  this.disconnect();
97
86
  break;
98
87
  case Constants_1.GATEWAY_OP_CODES.INVALID_SESSION:
99
- if (message.d && this.sessionId) {
88
+ if (message.d && this.sessionId)
100
89
  this.resume();
101
- }
102
90
  else {
103
91
  this.seq = 0;
104
92
  this.sessionId = "";
@@ -116,9 +104,8 @@ class DiscordConnector extends events_1.EventEmitter {
116
104
  else
117
105
  this.disconnect();
118
106
  }
119
- else {
107
+ else
120
108
  this.heartbeat();
121
- }
122
109
  }, this.heartbeatInterval);
123
110
  this._trace = message.d._trace;
124
111
  this.identify();
@@ -137,24 +124,15 @@ class DiscordConnector extends events_1.EventEmitter {
137
124
  * @param resume Whether or not the client intends to send an OP 6 RESUME later.
138
125
  */
139
126
  async _reconnect(resume = false) {
140
- var _a, _b, _c;
141
127
  if (resume)
142
128
  reconnecting = true;
143
- if (((_a = this.betterWs) === null || _a === void 0 ? void 0 : _a.ws.readyState) === ws_1.default.CONNECTING) {
144
- this.emit("error", `Client was attempting to ${resume ? "resume" : "reconnect"} while the WebSocket was still in the connecting state. This should never happen.${this.options.reconnect ? " Restarting the connect loop." : ""}`);
145
- this.reset();
146
- if (this.options.reconnect)
147
- this.connect();
148
- }
149
- // This is for instances where the gateway asks the client to reconnect. The ws would be closed by the time the code reaches here.
150
- if (((_b = this.betterWs) === null || _b === void 0 ? void 0 : _b.ws.readyState) === ws_1.default.OPEN)
151
- await ((_c = this.betterWs) === null || _c === void 0 ? void 0 : _c.close(resume ? 4000 : 1012, "reconnecting"));
152
- if (resume) {
129
+ if (this.betterWs.status === 2)
130
+ void this.client.emit("error", `Client was attempting to ${resume ? "resume" : "reconnect"} while the WebSocket was still in the connecting state. This should never happen.`);
131
+ await this.betterWs.close();
132
+ if (resume)
153
133
  this.clearHeartBeat();
154
- }
155
- else {
134
+ else
156
135
  this.reset();
157
- }
158
136
  this.connect();
159
137
  }
160
138
  /**
@@ -181,10 +159,12 @@ class DiscordConnector extends events_1.EventEmitter {
181
159
  * @param force Whether CloudStorm should send an OP 2 IDENTIFY even if there's a session that could be resumed.
182
160
  */
183
161
  async identify(force) {
184
- var _a;
185
- if (this.sessionId && !force) {
162
+ if (this.betterWs.status !== 1)
163
+ void this.client.emit("debug", "Client was attempting to identify when the ws was not open");
164
+ if (this.sessionId && !force)
186
165
  return this.resume();
187
- }
166
+ this.status = "identifying";
167
+ this.emit("stateChange", "identifying");
188
168
  const data = {
189
169
  op: Constants_1.GATEWAY_OP_CODES.IDENTIFY,
190
170
  d: {
@@ -201,14 +181,17 @@ class DiscordConnector extends events_1.EventEmitter {
201
181
  };
202
182
  if (this.options.initialPresence)
203
183
  Object.assign(data.d, { presence: this._checkPresenceData(this.options.initialPresence) });
204
- return (_a = this.betterWs) === null || _a === void 0 ? void 0 : _a.sendMessage(data);
184
+ return this.betterWs.sendMessage(data);
205
185
  }
206
186
  /**
207
187
  * Send an OP 6 RESUME to the gateway.
208
188
  */
209
189
  async resume() {
210
- var _a;
211
- return (_a = this.betterWs) === null || _a === void 0 ? void 0 : _a.sendMessage({
190
+ if (this.betterWs.status !== 1)
191
+ void this.client.emit("debug", "Client was attempting to resume when the ws was not open");
192
+ this.status = "resuming";
193
+ this.emit("stateChange", "resuming");
194
+ return this.betterWs.sendMessage({
212
195
  op: Constants_1.GATEWAY_OP_CODES.RESUME,
213
196
  d: { seq: this.seq, token: this.options.token, session_id: this.sessionId }
214
197
  });
@@ -217,10 +200,9 @@ class DiscordConnector extends events_1.EventEmitter {
217
200
  * Send an OP 1 HEARTBEAT to the gateway.
218
201
  */
219
202
  heartbeat() {
220
- var _a, _b;
221
- if (((_a = this.betterWs) === null || _a === void 0 ? void 0 : _a.ws.readyState) !== ws_1.default.OPEN)
222
- return;
223
- (_b = this.betterWs) === null || _b === void 0 ? void 0 : _b.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.HEARTBEAT, d: this.seq });
203
+ if (this.betterWs.status !== 1)
204
+ void this.client.emit("debug", "Client was attempting to heartbeat when the ws was not open");
205
+ this.betterWs.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.HEARTBEAT, d: this.seq });
224
206
  this.lastHeartbeatSend = Date.now();
225
207
  }
226
208
  /**
@@ -231,10 +213,10 @@ class DiscordConnector extends events_1.EventEmitter {
231
213
  switch (message.t) {
232
214
  case "READY":
233
215
  case "RESUMED":
234
- if (message.t === "READY") {
216
+ if (message.t === "READY")
235
217
  this.sessionId = message.d.session_id;
236
- }
237
218
  this.status = "ready";
219
+ this.emit("stateChange", "ready");
238
220
  this._trace = message.d._trace;
239
221
  this.emit("ready", message.t === "RESUMED");
240
222
  this.emit("event", message);
@@ -249,94 +231,86 @@ class DiscordConnector extends events_1.EventEmitter {
249
231
  * @param reason Close reason if any.
250
232
  */
251
233
  handleWsClose(code, reason) {
252
- var _a;
253
234
  let gracefulClose = false;
254
235
  this.status = "disconnected";
236
+ this.emit("stateChange", "disconnected");
255
237
  // Disallowed Intents.
256
- if (code === 4014) {
257
- this.emit("error", "Disallowed Intents, check your client options and application page.");
258
- }
238
+ if (code === 4014)
239
+ this.client.emit("error", "Disallowed Intents, check your client options and application page.");
259
240
  // Invalid Intents.
260
- if (code === 4013) {
261
- this.emit("error", "Invalid Intents data, check your client options.");
262
- }
241
+ if (code === 4013)
242
+ this.client.emit("error", "Invalid Intents data, check your client options.");
263
243
  // Invalid API version.
264
- if (code === 4012) {
265
- this.emit("error", "Invalid API version.");
266
- }
244
+ if (code === 4012)
245
+ this.client.emit("error", "Invalid API version.");
267
246
  // Sharding required.
268
- if (code === 4011) {
269
- this.emit("error", "Shard would be on over 2500 guilds. Add more shards.");
270
- }
247
+ if (code === 4011)
248
+ this.client.emit("error", "Shard would be on over 2500 guilds. Add more shards.");
271
249
  // Invalid shard.
272
- if (code === 4010) {
273
- this.emit("error", "Invalid sharding data, check your client options.");
274
- }
250
+ if (code === 4010)
251
+ this.client.emit("error", "Invalid sharding data, check your client options.");
275
252
  // Session timed out.
276
253
  // force identify if the session is marked as invalid.
277
254
  if (code === 4009) {
278
- this.emit("error", "Session timed out.");
255
+ this.client.emit("error", "Session timed out.");
279
256
  this.clearHeartBeat();
280
257
  this.connect();
281
258
  }
282
259
  // Rate limited.
283
260
  if (code === 4008) {
284
- this.emit("error", "You are being rate limited. Wait before sending more packets.");
261
+ this.client.emit("error", "You are being rate limited. Wait before sending more packets.");
285
262
  this.clearHeartBeat();
286
263
  this.connect();
287
264
  }
288
265
  // Invalid sequence.
289
266
  if (code === 4007) {
290
- this.emit("error", "Invalid sequence. Reconnecting and starting a new session.");
267
+ this.client.emit("error", "Invalid sequence. Reconnecting and starting a new session.");
291
268
  this.reset();
292
269
  this.connect();
293
270
  }
294
271
  // Already authenticated.
295
272
  if (code === 4005) {
296
- this.emit("error", "You sent more than one OP 2 IDENTIFY payload while the websocket was open.");
273
+ this.client.emit("error", "You sent more than one OP 2 IDENTIFY payload while the websocket was open.");
297
274
  this.clearHeartBeat();
298
275
  this.connect();
299
276
  }
300
277
  // Authentication failed.
301
- if (code === 4004) {
302
- this.emit("error", "Tried to connect with an invalid token");
303
- }
278
+ if (code === 4004)
279
+ this.client.emit("error", "Tried to connect with an invalid token");
304
280
  // Not authenticated.
305
281
  if (code === 4003) {
306
- this.emit("error", "You tried to send a packet before sending an OP 2 IDENTIFY or OP 6 RESUME.");
282
+ this.client.emit("error", "You tried to send a packet before sending an OP 2 IDENTIFY or OP 6 RESUME.");
307
283
  this.clearHeartBeat();
308
284
  this.connect();
309
285
  }
310
286
  // Decode error.
311
287
  if (code === 4002) {
312
- this.emit("error", "You sent an invalid payload");
288
+ this.client.emit("error", "You sent an invalid payload");
313
289
  this.clearHeartBeat();
314
290
  this.connect();
315
291
  }
316
292
  // Invalid opcode.
317
293
  if (code === 4001) {
318
- this.emit("error", "You sent an invalid opcode or invalid payload for an opcode");
294
+ this.client.emit("error", "You sent an invalid opcode or invalid payload for an opcode");
319
295
  this.clearHeartBeat();
320
296
  this.connect();
321
297
  }
322
298
  // Generic error / safe self closing code.
323
299
  if (code === 4000) {
324
- if (reconnecting) {
300
+ if (reconnecting)
325
301
  gracefulClose = true;
326
- }
327
302
  else {
328
- this.emit("error", "Error code 4000 received. Attempting to resume");
303
+ this.client.emit("error", "Error code 4000 received. Attempting to resume");
329
304
  this.clearHeartBeat();
330
305
  this.connect();
331
306
  }
332
307
  }
333
308
  // Don't try to reconnect when true
334
- if (code === 1000 && reason === "Disconnected by User") {
309
+ if (code === 1000 && reason === "Disconnected by User")
335
310
  gracefulClose = true;
336
- }
337
311
  if (gracefulClose) {
338
312
  this.clearHeartBeat();
339
- (_a = this.betterWs) === null || _a === void 0 ? void 0 : _a.removeAllListeners();
313
+ this.betterWs.removeAllListeners();
340
314
  }
341
315
  this.emit("disconnect", code, reason, gracefulClose);
342
316
  }
@@ -344,28 +318,24 @@ class DiscordConnector extends events_1.EventEmitter {
344
318
  * Send an OP 3 PRESENCE_UPDATE to the gateway.
345
319
  * @param data Presence data to send.
346
320
  */
347
- async presenceUpdate(data = {}) {
348
- var _a;
349
- return (_a = this.betterWs) === null || _a === void 0 ? void 0 : _a.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.PRESENCE_UPDATE, d: this._checkPresenceData(data) });
321
+ async presenceUpdate(data) {
322
+ return this.betterWs.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.PRESENCE_UPDATE, d: this._checkPresenceData(data) });
350
323
  }
351
324
  /**
352
325
  * Send an OP 4 VOICE_STATE_UPDATE to the gateway.
353
326
  * @param data Voice state update data to send.
354
327
  */
355
328
  async voiceStateUpdate(data) {
356
- var _a;
357
- if (!data) {
329
+ if (!data)
358
330
  return Promise.resolve();
359
- }
360
- return (_a = this.betterWs) === null || _a === void 0 ? void 0 : _a.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.VOICE_STATE_UPDATE, d: this._checkVoiceStateUpdateData(data) });
331
+ return this.betterWs.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.VOICE_STATE_UPDATE, d: this._checkVoiceStateUpdateData(data) });
361
332
  }
362
333
  /**
363
334
  * Send an OP 8 REQUEST_GUILD_MEMBERS to the gateway.
364
335
  * @param data Data to send.
365
336
  */
366
337
  async requestGuildMembers(data) {
367
- var _a;
368
- return (_a = this.betterWs) === null || _a === void 0 ? void 0 : _a.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.REQUEST_GUILD_MEMBERS, d: this._checkRequestGuildMembersData(data) });
338
+ return this.betterWs.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.REQUEST_GUILD_MEMBERS, d: this._checkRequestGuildMembersData(data) });
369
339
  }
370
340
  /**
371
341
  * Checks presence data and fills in missing elements.
@@ -374,7 +344,7 @@ class DiscordConnector extends events_1.EventEmitter {
374
344
  */
375
345
  _checkPresenceData(data) {
376
346
  data.status = data.status || "online";
377
- data.activities = data.activities && Array.isArray(data.activities) ? data.activities : null;
347
+ data.activities = data.activities && Array.isArray(data.activities) ? data.activities : [];
378
348
  if (data.activities) {
379
349
  for (const activity of data.activities) {
380
350
  const index = data.activities.indexOf(activity);
@@ -385,7 +355,7 @@ class DiscordConnector extends events_1.EventEmitter {
385
355
  }
386
356
  }
387
357
  data.afk = data.afk || false;
388
- data.since = data.since || false;
358
+ data.since = data.since || Date.now();
389
359
  return data;
390
360
  }
391
361
  /**
@@ -1,10 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  import { EventEmitter } from "events";
3
- import zlib from "zlib-sync";
4
- import WebSocket from "ws";
5
3
  import RatelimitBucket from "./RatelimitBucket";
6
4
  interface BWSEvents {
7
- error: [Error | string];
8
5
  ws_open: [];
9
6
  ws_close: [number, string];
10
7
  ws_message: [import("../Types").IGatewayMessage];
@@ -30,58 +27,24 @@ interface BetterWs {
30
27
  * Helper Class for simplifying the websocket connection to Discord.
31
28
  */
32
29
  declare class BetterWs extends EventEmitter {
33
- ws: WebSocket;
30
+ encoding: "etf" | "json";
31
+ compress: boolean;
32
+ address: string;
33
+ options: import("../Types").IClientWSOptions;
34
34
  wsBucket: RatelimitBucket;
35
35
  presenceBucket: RatelimitBucket;
36
- zlibInflate: zlib.Inflate | null;
37
- options: import("../Types").IClientWSOptions;
38
- compress: boolean;
39
- static readonly default: typeof BetterWs;
40
- /**
41
- * Create a new BetterWs instance.
42
- */
43
- constructor(address: string, options?: import("../Types").IClientWSOptions);
44
- /**
45
- * Get the raw websocket connection currently used.
46
- */
47
- get rawWs(): WebSocket;
48
- /**
49
- * Add eventlisteners to a passed websocket connection.
50
- * @param ws Websocket.
51
- */
52
- private bindWs;
53
- /**
54
- * Create a new websocket connection if the old one was closed/destroyed.
55
- * @param address Address to connect to.
56
- * @param options Options used by the websocket connection.
57
- */
58
- recreateWs(address: string, options?: import("../Types").IClientWSOptions): void;
59
- /**
60
- * Called upon opening of the websocket connection.
61
- */
62
- private onOpen;
63
- /**
64
- * Called once a websocket message is received,
65
- * uncompresses the message using zlib and parses it via Erlpack or JSON.parse.
66
- * @param message Message received by websocket.
67
- */
68
- private onMessage;
69
- /**
70
- * Called when the websocket connection closes for some reason.
71
- * @param code Websocket close code.
72
- * @param reason Reason of the close if any.
73
- */
74
- private onClose;
75
- /**
76
- * Send a message to the Discord gateway.
77
- * @param data Data to send.
78
- */
79
- sendMessage(data: any): Promise<void>;
80
- /**
81
- * Close the current websocket connection.
82
- * @param code Websocket close code to use.
83
- * @param reason Reason of the disconnect.
84
- */
85
- close(code?: number, reason?: string): Promise<void>;
36
+ private _socket;
37
+ private _internal;
38
+ private _connecting;
39
+ constructor(address: string, options: import("../Types").IClientWSOptions);
40
+ get status(): 2 | 3 | 4 | 1;
41
+ connect(): Promise<void>;
42
+ close(): Promise<void>;
43
+ sendMessage(data: import("../Types").IWSMessage): Promise<void>;
44
+ private _write;
45
+ private _onError;
46
+ private _onClose;
47
+ private _onReadable;
48
+ private _processFrame;
86
49
  }
87
50
  export = BetterWs;