@bakit/gateway 3.0.2 → 3.0.3

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.
package/dist/index.js DELETED
@@ -1,633 +0,0 @@
1
- import EventEmitter from 'events';
2
- import { createInflate, constants } from 'zlib';
3
- import { TextDecoder } from 'util';
4
- import { randomInt, randomUUID } from 'crypto';
5
- import WebSocket from 'ws';
6
- import { GatewayOpcodes, GatewayDispatchEvents, GatewayCloseCodes } from 'discord-api-types/v10';
7
- import { fork } from 'child_process';
8
- import { dirname, resolve } from 'path';
9
- import { fileURLToPath } from 'url';
10
- import { isCommonJS } from '@bakit/utils';
11
- import { Collection } from '@discordjs/collection';
12
- import PQueue from 'p-queue';
13
- import { REST } from '@bakit/rest';
14
-
15
- // src/lib/Shard.ts
16
- var MIN_HEARTBEAT_INTERVAL = 1e3, MAX_HEARTBEAT_INTERVAL = 6e4, SAFE_HEARTBEAT_INTERVAL = 45e3, ShardState = /* @__PURE__ */ ((ShardState2) => (ShardState2[ShardState2.Idle = 0] = "Idle", ShardState2[ShardState2.Connecting = 1] = "Connecting", ShardState2[ShardState2.Ready = 2] = "Ready", ShardState2[ShardState2.Resuming = 3] = "Resuming", ShardState2[ShardState2.Disconnecting = 4] = "Disconnecting", ShardState2[ShardState2.Disconnected = 5] = "Disconnected", ShardState2))(ShardState || {}), ShardStrategy = /* @__PURE__ */ ((ShardStrategy2) => (ShardStrategy2[ShardStrategy2.Resume = 0] = "Resume", ShardStrategy2[ShardStrategy2.Reconnect = 1] = "Reconnect", ShardStrategy2[ShardStrategy2.Shutdown = 2] = "Shutdown", ShardStrategy2))(ShardStrategy || {}), Shard = class extends EventEmitter {
17
- constructor(id, options) {
18
- super();
19
- this.id = id;
20
- this.options = options;
21
- }
22
- #state = 0 /* Idle */;
23
- #ws;
24
- #inflater;
25
- #textDecoder = new TextDecoder();
26
- #decompressBuffer = [];
27
- #sessionId;
28
- #lastSequence;
29
- #resumeGatewayURL;
30
- #lastHeartbeatSent = -1;
31
- #lastHeartbeatAck = -1;
32
- #missedHeartbeats = 0;
33
- #heartbeatInterval;
34
- #heartbeatTimeout;
35
- #reconnectTimeout;
36
- #strategy;
37
- get state() {
38
- return this.#state;
39
- }
40
- get latency() {
41
- return this.#lastHeartbeatSent === -1 || this.#lastHeartbeatAck === -1 ? -1 : this.#lastHeartbeatAck - this.#lastHeartbeatSent;
42
- }
43
- get resumable() {
44
- let hasSessionId = this.#sessionId !== void 0, hasSequence = this.#lastSequence !== void 0;
45
- return this.#strategy === 0 /* Resume */ && hasSequence && hasSessionId;
46
- }
47
- async connect() {
48
- if (this.#state !== 0 /* Idle */ && this.#state !== 5 /* Disconnected */)
49
- throw new Error("Shard already connecting or connected");
50
- return new Promise((resolve2, reject) => {
51
- let cleanup = () => {
52
- this.off("error", onError), this.off("ready", onReady);
53
- }, onReady = () => {
54
- cleanup(), resolve2();
55
- }, onError = (err) => {
56
- cleanup(), reject(err);
57
- };
58
- this.once("ready", onReady), this.once("error", onError), this.#init();
59
- });
60
- }
61
- disconnect(code) {
62
- return new Promise((resolve2) => {
63
- if (this.#state = 4 /* Disconnecting */, this.#strategy = 2 /* Shutdown */, !this.#ws) {
64
- resolve2();
65
- return;
66
- }
67
- this.#ws.once("close", () => {
68
- resolve2();
69
- }), this.#ws.close(code);
70
- });
71
- }
72
- resume() {
73
- this.resumable && (this.#state = 3 /* Resuming */, this.send({
74
- op: GatewayOpcodes.Resume,
75
- d: {
76
- token: this.options.token,
77
- session_id: this.#sessionId,
78
- seq: this.#lastSequence
79
- }
80
- }));
81
- }
82
- identify() {
83
- this.send({
84
- op: GatewayOpcodes.Identify,
85
- d: {
86
- token: this.options.token,
87
- intents: Number(this.options.intents),
88
- properties: {
89
- os: process.platform,
90
- browser: "bakit",
91
- device: "bakit"
92
- },
93
- shard: [this.id, this.options.total]
94
- }
95
- });
96
- }
97
- send(payload) {
98
- this.#ws?.readyState === WebSocket.OPEN && this.#ws.send(JSON.stringify(payload));
99
- }
100
- sendHeartbeat() {
101
- if (this.#lastHeartbeatSent !== -1 && this.#lastHeartbeatAck < this.#lastHeartbeatSent ? this.#missedHeartbeats++ : this.#missedHeartbeats = 0, this.#missedHeartbeats >= 2) {
102
- this.emit("debug", "Missed 2 heartbeats, reconnecting"), this.#ws?.terminate();
103
- return;
104
- }
105
- this.send({
106
- op: GatewayOpcodes.Heartbeat,
107
- d: this.#lastSequence ?? null
108
- }), this.#lastHeartbeatSent = Date.now();
109
- }
110
- #init() {
111
- this.#state = 1 /* Connecting */, this.#strategy ??= 1 /* Reconnect */;
112
- let url = new URL(
113
- this.#strategy === 0 /* Resume */ && this.#resumeGatewayURL ? this.#resumeGatewayURL : this.options.gateway.baseURL
114
- );
115
- url.searchParams.set("v", String(this.options.gateway.version)), url.searchParams.set("encoding", "json"), url.searchParams.set("compress", "zlib-stream"), this.#ws = new WebSocket(url, { perMessageDeflate: false }), this.#inflater = createInflate({ flush: constants.Z_SYNC_FLUSH }), this.#inflater.on("data", (chunk) => this.#onInflate(chunk)), this.#inflater.on("error", (err) => {
116
- this.emit("error", err), this.#ws?.terminate();
117
- }), this.#ws.on("message", (data) => this.#onMessage(data)), this.#ws.on("close", (code) => this.#onClose(code)), this.#ws.on("error", (err) => this.emit("error", err));
118
- }
119
- #onMessage(data) {
120
- if (!this.#inflater) {
121
- try {
122
- let text = data.toString(), payload = JSON.parse(text);
123
- this.#handlePayload(payload);
124
- } catch (error) {
125
- this.emit("error", error);
126
- }
127
- return;
128
- }
129
- let buffer;
130
- Buffer.isBuffer(data) ? buffer = data : Array.isArray(data) ? buffer = Buffer.concat(data) : data instanceof ArrayBuffer ? buffer = Buffer.from(data) : buffer = Buffer.from(String(data));
131
- let hasSyncFlush = buffer.length >= 4 && buffer[buffer.length - 4] === 0 && buffer[buffer.length - 3] === 0 && buffer[buffer.length - 2] === 255 && buffer[buffer.length - 1] === 255;
132
- this.#inflater.write(buffer, (writeError) => {
133
- if (writeError) {
134
- this.emit("error", writeError);
135
- return;
136
- }
137
- hasSyncFlush && this.#inflater?.flush(constants.Z_SYNC_FLUSH);
138
- });
139
- }
140
- #onInflate(chunk) {
141
- this.#decompressBuffer.push(chunk);
142
- let fullBuffer = Buffer.concat(this.#decompressBuffer);
143
- try {
144
- let text = this.#textDecoder.decode(fullBuffer), payload = JSON.parse(text);
145
- this.#handlePayload(payload), this.#decompressBuffer = [];
146
- } catch (error) {
147
- if (error instanceof SyntaxError) {
148
- let text = this.#textDecoder.decode(fullBuffer);
149
- if (text.includes("{") && !isValidJSON(text))
150
- return;
151
- this.emit("error", error), this.#decompressBuffer = [];
152
- }
153
- }
154
- }
155
- #handlePayload(payload) {
156
- switch (this.emit("raw", payload), payload.op) {
157
- case GatewayOpcodes.Dispatch: {
158
- this.#handleDispatch(payload);
159
- break;
160
- }
161
- case GatewayOpcodes.Hello: {
162
- this.#startHeartbeat(payload.d.heartbeat_interval), this.resumable ? this.resume() : this.emit("needIdentify");
163
- break;
164
- }
165
- case GatewayOpcodes.Heartbeat: {
166
- this.sendHeartbeat();
167
- break;
168
- }
169
- case GatewayOpcodes.HeartbeatAck: {
170
- this.#lastHeartbeatAck = Date.now();
171
- break;
172
- }
173
- case GatewayOpcodes.InvalidSession: {
174
- payload.d ? this.#strategy = 0 /* Resume */ : (this.#strategy = 1 /* Reconnect */, this.#sessionId = void 0, this.#lastSequence = void 0, this.#resumeGatewayURL = void 0), this.emit("debug", `Invalid session (resumable=${this.resumable})`), this.#ws?.terminate();
175
- break;
176
- }
177
- case GatewayOpcodes.Reconnect: {
178
- this.#strategy = 0 /* Resume */, this.emit("debug", "Reconnecting to gateway"), this.#ws?.terminate();
179
- break;
180
- }
181
- }
182
- }
183
- #handleDispatch(payload) {
184
- switch (this.#lastSequence = payload.s, this.emit("dispatch", payload), payload.t) {
185
- case GatewayDispatchEvents.Ready: {
186
- let { d: data } = payload;
187
- this.#state = 2 /* Ready */, this.#sessionId = data.session_id, this.#resumeGatewayURL = data.resume_gateway_url, this.emit("ready", data);
188
- break;
189
- }
190
- case GatewayDispatchEvents.Resumed: {
191
- this.#state = 2 /* Ready */, this.#strategy = void 0, this.emit("resume");
192
- break;
193
- }
194
- }
195
- }
196
- #onClose(code) {
197
- if (this.#cleanup(), this.#state = 5 /* Disconnected */, this.emit("disconnect", code), this.#strategy === 2 /* Shutdown */) {
198
- switch (code) {
199
- case GatewayCloseCodes.AuthenticationFailed:
200
- this.emit("error", new Error("Invalid token provided"));
201
- break;
202
- case GatewayCloseCodes.InvalidIntents:
203
- this.emit("error", new Error("Invalid intents provided"));
204
- break;
205
- case GatewayCloseCodes.DisallowedIntents:
206
- this.emit("error", new Error("Disallowed intents provided"));
207
- break;
208
- }
209
- return;
210
- } else this.#strategy || (this.#strategy = this.#getStrategy(code));
211
- (this.#strategy === 1 /* Reconnect */ || this.#strategy === 0 /* Resume */) && this.#scheduleReconnect();
212
- }
213
- #getStrategy(code) {
214
- switch (code) {
215
- case GatewayCloseCodes.AuthenticationFailed:
216
- case GatewayCloseCodes.InvalidIntents:
217
- case GatewayCloseCodes.DisallowedIntents:
218
- return 2 /* Shutdown */;
219
- case GatewayCloseCodes.InvalidSeq:
220
- case GatewayCloseCodes.SessionTimedOut:
221
- return 1 /* Reconnect */;
222
- default:
223
- return 0 /* Resume */;
224
- }
225
- }
226
- #scheduleReconnect(delay = 1e3) {
227
- this.#reconnectTimeout || (this.#reconnectTimeout = setTimeout(() => {
228
- this.#reconnectTimeout = void 0, this.#state = 0 /* Idle */, this.#init();
229
- }, delay));
230
- }
231
- #startHeartbeat(interval) {
232
- this.#heartbeatInterval && (clearInterval(this.#heartbeatInterval), this.#heartbeatInterval = void 0), (interval < MIN_HEARTBEAT_INTERVAL || interval > MAX_HEARTBEAT_INTERVAL) && (interval = SAFE_HEARTBEAT_INTERVAL);
233
- let jitter = randomInt(0, 10) / 100, firstDelay = Math.floor(interval * jitter);
234
- this.emit("debug", `Starting heartbeat (interval=${interval}ms, jitter=${firstDelay}ms)`), this.#heartbeatTimeout = setTimeout(() => {
235
- this.sendHeartbeat(), this.#heartbeatInterval = setInterval(() => this.sendHeartbeat(), interval);
236
- }, firstDelay);
237
- }
238
- #cleanup() {
239
- clearTimeout(this.#reconnectTimeout), clearInterval(this.#heartbeatInterval), clearTimeout(this.#heartbeatTimeout), this.#inflater?.destroy(), this.#inflater = void 0, this.#ws?.removeAllListeners(), this.#ws = void 0, this.#decompressBuffer = [], this.#missedHeartbeats = 0;
240
- }
241
- };
242
- function isValidJSON(str) {
243
- try {
244
- return JSON.parse(str), !0;
245
- } catch {
246
- return false;
247
- }
248
- }
249
- var EVAL_TIMEOUT = 3e4, __filename$1 = fileURLToPath(import.meta.url), __dirname$1 = dirname(__filename$1);
250
- function isDispatchPayload(payload) {
251
- return payload.op === "dispatch";
252
- }
253
- function isIdentifyPayload(payload) {
254
- return payload.op === "identify";
255
- }
256
- function isSendPayload(payload) {
257
- return payload.op === "send";
258
- }
259
- function isEvalRequestPayload(payload) {
260
- return payload.op === "eval";
261
- }
262
- function isEvalResponsePayload(payload) {
263
- return payload.op === "evalResponse";
264
- }
265
- var ClusterProcess = class _ClusterProcess extends EventEmitter {
266
- constructor(manager, id, options = {}) {
267
- super();
268
- this.manager = manager;
269
- this.id = id;
270
- this.setMaxListeners(0);
271
- let entry = resolve(__dirname$1, isCommonJS() ? "cluster.cjs" : "cluster.js");
272
- this.process = fork(entry, {
273
- env: options.env,
274
- execArgv: options.execArgv,
275
- stdio: ["inherit", "inherit", "inherit", "ipc"]
276
- }), this.#bindProcessEvents();
277
- }
278
- process;
279
- #pendingEvals = /* @__PURE__ */ new Map();
280
- #shards = /* @__PURE__ */ new Set();
281
- get shards() {
282
- return new Set(this.#shards);
283
- }
284
- get killed() {
285
- return this.process.killed || !this.process.connected;
286
- }
287
- kill(signal = "SIGTERM") {
288
- if (!this.killed) {
289
- for (let [nonce, pending] of this.#pendingEvals)
290
- clearTimeout(pending.timeout), pending.reject(new Error(`Process killed before eval completed (nonce: ${nonce})`));
291
- this.#pendingEvals.clear(), this.process.kill(signal);
292
- }
293
- }
294
- async eval(fn, ctx) {
295
- let nonce = randomUUID();
296
- return new Promise((resolve2, reject) => {
297
- let timeoutId = setTimeout(() => {
298
- this.#pendingEvals.delete(nonce), reject(new Error(`Eval timed out after ${EVAL_TIMEOUT}ms`));
299
- }, EVAL_TIMEOUT);
300
- this.#pendingEvals.set(nonce, {
301
- resolve: resolve2,
302
- reject,
303
- timeout: timeoutId
304
- });
305
- let context;
306
- try {
307
- context = JSON.stringify(ctx ?? null);
308
- } catch {
309
- reject(new Error("Eval context is not serializable"));
310
- return;
311
- }
312
- let script = `(${fn.toString()})(cluster, ${context})`;
313
- this.sendIPC({
314
- op: "eval",
315
- d: { nonce, script }
316
- });
317
- });
318
- }
319
- send(idOrPayload, payload) {
320
- let hasShardId = typeof idOrPayload == "number" && payload !== void 0, shardId = hasShardId ? idOrPayload : void 0, data = hasShardId ? payload : idOrPayload;
321
- this.sendIPC({
322
- op: "send",
323
- d: { shardId, data }
324
- });
325
- }
326
- sendIPC(message) {
327
- if (!(!this.process.connected || this.process.killed))
328
- try {
329
- this.process.send(message, void 0, void 0, (err) => {
330
- err && this.emit("error", err);
331
- });
332
- } catch (err) {
333
- this.emit("error", err);
334
- }
335
- }
336
- identifyShard(id) {
337
- this.sendIPC({
338
- op: "identify",
339
- d: id
340
- });
341
- }
342
- #bindProcessEvents() {
343
- this.process.on("message", (message) => this.#handleIPC(message)), this.process.on("error", (err) => this.emit("error", err)), this.process.on("disconnect", () => this.emit("debug", "Process disconnected")), this.process.on("exit", (code) => {
344
- for (let [nonce, pending] of this.#pendingEvals)
345
- clearTimeout(pending.timeout), pending.reject(new Error(`Process exited (code: ${code}) before eval completed (nonce: ${nonce})`));
346
- this.#pendingEvals.clear();
347
- });
348
- }
349
- #handleIPC(message) {
350
- if (this.#isValidPayload(message)) {
351
- if (isDispatchPayload(message)) {
352
- this.#handleDispatchPayload(message);
353
- return;
354
- }
355
- if (isEvalResponsePayload(message)) {
356
- this.#handleEvalResponse(message);
357
- return;
358
- }
359
- }
360
- }
361
- #handleDispatchPayload(payload) {
362
- payload.t === "shardAdd" && this.#shards.add(payload.d[0]), this.emit(payload.t, ...payload.d);
363
- }
364
- #handleEvalResponse(payload) {
365
- let pending = this.#pendingEvals.get(payload.d.nonce);
366
- if (!pending) {
367
- this.emit("debug", `Received eval response for unknown nonce: ${payload.d.nonce}`);
368
- return;
369
- }
370
- if (pending.timeout && clearTimeout(pending.timeout), this.#pendingEvals.delete(payload.d.nonce), payload.d.success)
371
- pending.resolve({
372
- success: true,
373
- data: payload.d.result,
374
- cluster: this
375
- });
376
- else {
377
- let error = new Error(payload.d.error ?? "Unknown eval error");
378
- pending.resolve({
379
- success: false,
380
- error,
381
- cluster: this
382
- });
383
- }
384
- }
385
- #isValidPayload(message) {
386
- if (typeof message != "object" || message === null)
387
- return false;
388
- let payload = message;
389
- return payload.op === "dispatch" || payload.op === "identify" || payload.op === "send" || payload.op === "eval" || payload.op === "evalResponse";
390
- }
391
- static bindProcess(cluster) {
392
- let superEmit = cluster.emit.bind(cluster), safeSend = (message) => {
393
- process.connected && process.send?.(message, void 0, void 0, (err) => {
394
- err && cluster.emit("error", err);
395
- });
396
- };
397
- cluster.emit = function(eventName, ...args) {
398
- let result = superEmit(eventName, ...args);
399
- return safeSend({
400
- op: "dispatch",
401
- t: eventName,
402
- d: args
403
- }), result;
404
- };
405
- let messageHandler = async (message) => {
406
- if (isIdentifyPayload(message)) {
407
- cluster.shards.get(message.d)?.identify();
408
- return;
409
- }
410
- if (isSendPayload(message)) {
411
- message.d.shardId !== void 0 ? cluster.send(message.d.shardId, message.d.data) : cluster.send(message.d.data);
412
- return;
413
- }
414
- if (isEvalRequestPayload(message)) {
415
- await _ClusterProcess.#handleEvalRequest(cluster, message, safeSend);
416
- return;
417
- }
418
- };
419
- process.on("message", messageHandler);
420
- }
421
- static async #handleEvalRequest(cluster, payload, safeSend) {
422
- let { nonce, script } = payload.d, executeEval = async () => await new Function("cluster", `return ${script}`)(cluster), timeoutId;
423
- try {
424
- let evalPromise = executeEval(), timeoutPromise = new Promise((_, reject) => {
425
- timeoutId = setTimeout(() => {
426
- reject(new Error(`Eval execution timed out after ${EVAL_TIMEOUT}ms`));
427
- }, EVAL_TIMEOUT);
428
- }), result = await Promise.race([evalPromise, timeoutPromise]);
429
- timeoutId && clearTimeout(timeoutId), safeSend({
430
- op: "evalResponse",
431
- d: {
432
- nonce,
433
- success: !0,
434
- result
435
- }
436
- });
437
- } catch (err) {
438
- timeoutId && clearTimeout(timeoutId), safeSend({
439
- op: "evalResponse",
440
- d: {
441
- nonce,
442
- success: false,
443
- result: void 0,
444
- error: err instanceof Error ? err.message : String(err)
445
- }
446
- });
447
- }
448
- }
449
- };
450
- var Cluster = class extends EventEmitter {
451
- constructor(id, options) {
452
- super();
453
- this.id = id;
454
- this.options = options;
455
- }
456
- shards = new Collection();
457
- #readyCount = 0;
458
- #starting = false;
459
- get size() {
460
- return this.shards.size;
461
- }
462
- get ready() {
463
- return this.#readyCount === this.options.shards.length;
464
- }
465
- async spawn() {
466
- if (!this.#starting) {
467
- this.#starting = true, this.emit("debug", `Spawning ${this.options.shards.length} shards...`);
468
- for (let i of this.options.shards)
469
- await this.#spawnShard(i);
470
- this.emit("debug", "All shards spawned");
471
- }
472
- }
473
- async shutdown(code = 1e3) {
474
- this.emit("debug", "Shutting down cluster...");
475
- let tasks = [];
476
- for (let shard of this.shards.values())
477
- tasks.push(shard.disconnect(code));
478
- await Promise.allSettled(tasks), this.emit("debug", "Cluster shutdown complete");
479
- }
480
- broadcast(fn) {
481
- for (let shard of this.shards.values())
482
- fn(shard);
483
- }
484
- send(idOrPayload, payload) {
485
- let hasId = typeof idOrPayload == "number" && payload !== void 0, shardId = hasId ? idOrPayload : void 0, data = hasId ? payload : idOrPayload;
486
- shardId !== void 0 ? this.shards.get(shardId)?.send(data) : this.broadcast((shard) => shard.send(data));
487
- }
488
- async #spawnShard(id) {
489
- let shard = new Shard(id, {
490
- token: this.options.token,
491
- intents: this.options.intents,
492
- total: this.options.total,
493
- gateway: this.options.gateway
494
- });
495
- this.#bindShardEvents(shard), this.shards.set(id, shard), this.emit("shardAdd", id), await shard.connect();
496
- }
497
- #bindShardEvents(shard) {
498
- let id = shard.id;
499
- shard.on("ready", () => {
500
- this.#readyCount++, this.emit("debug", `Shard ${id} ready`), this.emit("shardReady", id), this.ready && this.emit("ready");
501
- }), shard.on("resume", () => {
502
- this.emit("debug", `Shard ${id} resumed`), this.emit("shardResume", id);
503
- }), shard.on("disconnect", (code) => {
504
- this.emit("debug", `Shard ${id} disconnected (${code})`), this.emit("shardDisconnect", id, code);
505
- }), shard.on("error", (err) => {
506
- this.emit("debug", `Shard ${id} error: ${err.message}`), this.emit("shardError", id, err);
507
- }), shard.on("raw", (payload) => {
508
- this.emit("raw", id, payload);
509
- }), shard.on("dispatch", (payload) => {
510
- this.emit("dispatch", id, payload);
511
- }), shard.on("needIdentify", () => {
512
- this.emit("needIdentify", id);
513
- }), shard.on("debug", (msg) => {
514
- this.emit("debug", `[Shard ${id}] ${msg}`);
515
- });
516
- }
517
- };
518
- var ShardingManager = class extends EventEmitter {
519
- clusters = new Collection();
520
- options;
521
- rest;
522
- #gatewayInfo;
523
- #totalShards = 0;
524
- #readyCount = 0;
525
- #identifyQueue;
526
- constructor(options, rest) {
527
- super(), this.setMaxListeners(0), this.options = {
528
- shardsPerCluster: 5,
529
- totalShards: options.totalShards ?? "auto",
530
- ...options
531
- }, rest || (rest = new REST({ token: this.options.token })), this.rest = rest;
532
- }
533
- get totalClusters() {
534
- let { shardsPerCluster } = this.options;
535
- return shardsPerCluster <= 0 ? 0 : Math.ceil(this.totalShards / shardsPerCluster);
536
- }
537
- get totalShards() {
538
- return this.#totalShards;
539
- }
540
- get ready() {
541
- return this.totalClusters > 0 && this.#readyCount === this.totalClusters;
542
- }
543
- async spawn() {
544
- this.#gatewayInfo = await this.rest.get("/gateway/bot");
545
- let { session_start_limit: limit } = this.#gatewayInfo;
546
- this.#totalShards = typeof this.options.totalShards == "number" ? this.options.totalShards : this.#gatewayInfo.shards, this.#identifyQueue = new PQueue({
547
- concurrency: limit.max_concurrency,
548
- intervalCap: limit.max_concurrency,
549
- interval: 5e3
550
- });
551
- let { totalShards, totalClusters } = this;
552
- this.emit("debug", `Spawning ${totalClusters} clusters (${totalShards} total shards)...`);
553
- for (let i = 0; i < totalClusters; i++)
554
- this.#spawnCluster(i);
555
- this.emit("debug", "All clusters spawned");
556
- }
557
- async kill(signal = "SIGTERM") {
558
- this.emit("debug", "Shutting down all clusters...");
559
- let tasks = [];
560
- for (let cluster of this.clusters.values())
561
- tasks.push(
562
- new Promise((resolve2) => {
563
- cluster.process.once("exit", () => resolve2()), cluster.kill(signal);
564
- })
565
- );
566
- await Promise.all(tasks), this.emit("debug", "All clusters shut down");
567
- }
568
- broadcast(payload) {
569
- for (let cluster of this.clusters.values())
570
- cluster.send(payload);
571
- }
572
- async broadcastEval(fn) {
573
- let promises = this.clusters.map((cluster) => cluster.eval(fn));
574
- return Promise.all(promises);
575
- }
576
- send(shardId, payload) {
577
- let cluster = this.clusters.find((cluster2) => cluster2.shards.has(shardId));
578
- if (!cluster)
579
- throw new Error(`Shard ${shardId} not found`);
580
- cluster.send(payload);
581
- }
582
- requestIdentify(cluster, shardId) {
583
- this.#identifyQueue?.add(() => cluster.identifyShard(shardId));
584
- }
585
- #getShardIdsForCluster(clusterId) {
586
- let start = clusterId * this.options.shardsPerCluster, end = Math.min(start + this.options.shardsPerCluster, this.totalShards);
587
- return Array.from({ length: end - start }, (_, i) => start + i);
588
- }
589
- #spawnCluster(id) {
590
- let shardIds = this.#getShardIdsForCluster(id), firstShardId = shardIds[0], lastShardId = shardIds[shardIds.length - 1];
591
- this.emit("debug", `Spawning cluster ${id} (shards ${firstShardId}-${lastShardId})`);
592
- let env = {
593
- ...process.env,
594
- BAKIT_CLUSTER_ID: String(id),
595
- BAKIT_CLUSTER_SHARD_TOTAL: String(this.totalShards),
596
- BAKIT_CLUSTER_SHARD_LIST: JSON.stringify(shardIds),
597
- BAKIT_DISCORD_TOKEN: this.options.token,
598
- BAKIT_DISCORD_INTENTS: String(this.options.intents),
599
- BAKIT_DISCORD_GATEWAY_URL: this.#gatewayInfo?.url,
600
- BAKIT_DISCORD_GATEWAY_VERSION: "10"
601
- }, cluster = new ClusterProcess(this, id, { env });
602
- this.#bindClusterEvents(cluster, id), this.clusters.set(id, cluster), this.emit("clusterCreate", cluster);
603
- }
604
- #bindClusterEvents(cluster, id) {
605
- cluster.on("ready", () => {
606
- this.#readyCount++, this.emit("clusterReady", cluster), this.ready && this.emit("ready");
607
- }), cluster.process.on("exit", (code) => {
608
- this.emit("clusterExit", cluster, code), this.clusters.delete(id), this.#readyCount = Math.max(0, this.#readyCount - 1);
609
- }), cluster.on("error", (err) => {
610
- this.emit("clusterError", cluster, err);
611
- }), cluster.on("debug", (msg) => {
612
- this.emit("debug", `[Cluster ${id}] ${msg}`);
613
- }), cluster.on("dispatch", (shardId, payload) => {
614
- this.emit("dispatch", cluster, shardId, payload);
615
- }), cluster.on("raw", (shardId, payload) => {
616
- this.emit("raw", cluster, shardId, payload);
617
- }), cluster.on("shardAdd", (shardId) => {
618
- this.emit("shardAdd", cluster, shardId);
619
- }), cluster.on("shardReady", (shardId) => {
620
- this.emit("shardReady", cluster, shardId);
621
- }), cluster.on("shardDisconnect", (shardId, code) => {
622
- this.emit("shardDisconnect", cluster, shardId, code);
623
- }), cluster.on("shardResume", (shardId) => {
624
- this.emit("shardResume", cluster, shardId);
625
- }), cluster.on("shardError", (shardId, error) => {
626
- this.emit("shardError", cluster, shardId, error);
627
- }), cluster.on("needIdentify", (shardId) => {
628
- this.requestIdentify(cluster, shardId);
629
- });
630
- }
631
- };
632
-
633
- export { Cluster, ClusterProcess, Shard, ShardState, ShardStrategy, ShardingManager };