@bakit/gateway 2.0.0-alpha.36

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Louis Johnson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,156 @@
1
+ import { EventBus, ReadonlyCollection } from '@bakit/utils';
2
+ import { GatewayReadyDispatchData, GatewayReceivePayload, GatewayDispatchPayload, GatewaySendPayload } from 'discord-api-types/gateway';
3
+ import { ValueOf } from 'type-fest';
4
+ import { GatewayReadyDispatchData as GatewayReadyDispatchData$1, GatewayReceivePayload as GatewayReceivePayload$1, GatewayDispatchPayload as GatewayDispatchPayload$1, GatewaySendPayload as GatewaySendPayload$1 } from 'discord-api-types/v10';
5
+ import { RESTOptions, REST } from '@bakit/rest';
6
+
7
+ interface ShardOptions {
8
+ id: number;
9
+ total: number;
10
+ token: string;
11
+ intents: number | bigint;
12
+ gateway?: ShardGatewayOptions;
13
+ }
14
+ interface ShardGatewayOptions {
15
+ baseURL: string;
16
+ version: number;
17
+ }
18
+ interface ShardEvents {
19
+ ready: [payload: GatewayReadyDispatchData];
20
+ disconnect: [code: number];
21
+ resume: [];
22
+ error: [error: Error];
23
+ debug: [message: string];
24
+ raw: [payload: GatewayReceivePayload];
25
+ dispatch: [payload: GatewayDispatchPayload];
26
+ requestIdentify: [];
27
+ }
28
+ /**
29
+ * High-level lifecycle state of the shard connection.
30
+ */
31
+ declare const ShardState: {
32
+ /** Not connected. */
33
+ Idle: number;
34
+ /** Initialzing connection. */
35
+ Connecting: number;
36
+ /** Connected to gateway and identified. */
37
+ Ready: number;
38
+ /** Resuming the session. */
39
+ Resuming: number;
40
+ /** Disconnected the connection. */
41
+ Disconnected: number;
42
+ };
43
+ type ShardState = ValueOf<typeof ShardState>;
44
+ /**
45
+ * Strategy describes *what to do next after a disconnect*.
46
+ * This is intentionally separate from ShardState.
47
+ */
48
+ declare const ShardStrategy: {
49
+ /** No decision yet (default on close). */
50
+ Unknown: number;
51
+ /** Reconnect with IDENTIFY (new session). */
52
+ Reconnect: number;
53
+ /** Reconnect and try RESUME. */
54
+ Resume: number;
55
+ /** Do not reconnect. */
56
+ Shutdown: number;
57
+ };
58
+ type ShardStrategy = ValueOf<typeof ShardStrategy>;
59
+ interface Shard extends EventBus<ShardEvents> {
60
+ readonly id: number;
61
+ readonly state: ShardState;
62
+ readonly latency: number;
63
+ connect(): Promise<void>;
64
+ disconnect(code?: number): Promise<void>;
65
+ send(payload: GatewaySendPayload): void;
66
+ identify(): void;
67
+ }
68
+ /**
69
+ * Creates a shard object which can be used to connect to the Discord gateway.
70
+ *
71
+ * @param {ShardOptions} options - The options to create the shard with.
72
+ * @returns {Shard} - The created shard object.
73
+ */
74
+ declare function createShard(options: ShardOptions): Shard;
75
+
76
+ interface GatewayWorkerOptions {
77
+ id: number;
78
+ total: number;
79
+ token: string;
80
+ intents: number | bigint;
81
+ shards: number[];
82
+ gatewayURL: string;
83
+ }
84
+ interface GatewayWorker extends EventBus<GatewayWorkerEvents> {
85
+ readonly id: number;
86
+ readonly shards: ReadonlyCollection<number, Shard>;
87
+ readonly shardIds: number[];
88
+ readonly latency: number;
89
+ readonly state: GatewayWorkerState;
90
+ start(): Promise<void>;
91
+ stop(code?: number): Promise<void>;
92
+ /**
93
+ * Broadcast the given payload to all shards connections.
94
+ * @param {GatewaySendPayload} payload - The payload to send.
95
+ */
96
+ broadcast(payload: GatewaySendPayload$1): void;
97
+ }
98
+ interface GatewayWorkerEvents {
99
+ ready: [];
100
+ stop: [];
101
+ resume: [];
102
+ degrade: [readyCount: number, total: number];
103
+ shardReady: [shardId: number, payload: GatewayReadyDispatchData$1];
104
+ shardDisconnect: [shardId: number, code: number];
105
+ shardRaw: [shardId: number, payload: GatewayReceivePayload$1];
106
+ shardDispatch: [shardId: number, payload: GatewayDispatchPayload$1];
107
+ shardRequestIdentify: [shardId: number];
108
+ debug: [message: string];
109
+ error: [error: Error];
110
+ }
111
+ declare const GatewayWorkerState: {
112
+ readonly Idle: 0;
113
+ readonly Starting: 1;
114
+ readonly Ready: 2;
115
+ readonly Degraded: 3;
116
+ readonly Stopped: 4;
117
+ };
118
+ type GatewayWorkerState = ValueOf<typeof GatewayWorkerState>;
119
+ declare function createWorker(options: GatewayWorkerOptions): GatewayWorker;
120
+ declare function bindWorkerToProcess(worker: GatewayWorker): void;
121
+ declare function getWorkerOptions(): GatewayWorkerOptions;
122
+
123
+ declare const DEFAULT_WORKER_PATH: string;
124
+ interface GatewayManagerOptions {
125
+ token: string;
126
+ intents: number | bigint;
127
+ workerPath?: string;
128
+ gatewayURL?: string;
129
+ totalShards?: number | "auto";
130
+ shardsPerWorker?: number;
131
+ rest?: RESTOptions;
132
+ }
133
+ declare const DEFAULT_GATEWAY_MANAGER_OPTIONS: {
134
+ readonly gatewayURL: "wss://gateway.discord.gg";
135
+ readonly totalShards: "auto";
136
+ readonly shardsPerWorker: 5;
137
+ };
138
+ interface GatewayManagerEvents {
139
+ error: [error: Error];
140
+ shardReady: [workerId: number, shardId: number, payload: GatewayReadyDispatchData$1];
141
+ shardDisconnect: [workerId: number, shardId: number, code?: number];
142
+ shardRaw: [workerId: number, shardId: number, payload: GatewayReceivePayload$1];
143
+ shardDispatch: [workerId: number, shardId: number, payload: GatewayDispatchPayload$1];
144
+ workerReady: [workerId: number];
145
+ workerStop: [workerId: number];
146
+ }
147
+ interface GatewayManager extends EventBus<GatewayManagerEvents> {
148
+ readonly rest: REST;
149
+ spawn(): Promise<void>;
150
+ broadcast(payload: GatewaySendPayload$1): void;
151
+ sendToWorker(id: number, payload: GatewaySendPayload$1): void;
152
+ sendToShard(id: number, payload: GatewaySendPayload$1): void;
153
+ }
154
+ declare function createGatewayManager(options: GatewayManagerOptions): GatewayManager;
155
+
156
+ export { DEFAULT_GATEWAY_MANAGER_OPTIONS, DEFAULT_WORKER_PATH, type GatewayManager, type GatewayManagerEvents, type GatewayManagerOptions, type GatewayWorker, type GatewayWorkerEvents, type GatewayWorkerOptions, GatewayWorkerState, type Shard, type ShardEvents, type ShardGatewayOptions, type ShardOptions, ShardState, ShardStrategy, bindWorkerToProcess, createGatewayManager, createShard, createWorker, getWorkerOptions };
package/dist/index.js ADDED
@@ -0,0 +1,460 @@
1
+ import { WebSocket } from 'ws';
2
+ import { createInflate, constants } from 'zlib';
3
+ import { attachEventBus, Collection, createQueue } from '@bakit/utils';
4
+ import { GatewayOpcodes, GatewayCloseCodes, GatewayDispatchEvents } from 'discord-api-types/gateway';
5
+ import { fileURLToPath } from 'url';
6
+ import { fork } from 'child_process';
7
+ import { createREST } from '@bakit/rest';
8
+
9
+ // src/lib/shard.ts
10
+ var ZLIB_FLUSH = Buffer.from([0, 0, 255, 255]), DEFAULT_SHARD_OPTIONS = {
11
+ gateway: {
12
+ baseURL: "wss://gateway.discord.gg",
13
+ version: 10
14
+ }
15
+ }, ShardState = {
16
+ /** Not connected. */
17
+ Idle: 0,
18
+ /** Initialzing connection. */
19
+ Connecting: 1,
20
+ /** Connected to gateway and identified. */
21
+ Ready: 2,
22
+ /** Resuming the session. */
23
+ Resuming: 3,
24
+ /** Disconnected the connection. */
25
+ Disconnected: 4
26
+ }, ShardStrategy = {
27
+ /** No decision yet (default on close). */
28
+ Unknown: 1,
29
+ /** Reconnect with IDENTIFY (new session). */
30
+ Reconnect: 2,
31
+ /** Reconnect and try RESUME. */
32
+ Resume: 3,
33
+ /** Do not reconnect. */
34
+ Shutdown: 4
35
+ };
36
+ function createShard(options) {
37
+ let resolvedOptions = { ...DEFAULT_SHARD_OPTIONS, ...options }, state = ShardState.Idle, strategy = ShardStrategy.Unknown, ws, resumeGatewayURL, inflater, zlibBuffer, sessionId, lastSequence, lastHeartbeatSent = -1, lastHeartbeatAcknowledged = -1, missedHeartbeats = 0, reconnectTimeout, heartbeatTimeout, heartbeatInterval, self = attachEventBus({
38
+ send,
39
+ connect,
40
+ disconnect,
41
+ identify,
42
+ get id() {
43
+ return options.id;
44
+ },
45
+ get state() {
46
+ return state;
47
+ },
48
+ get latency() {
49
+ return lastHeartbeatSent === -1 || lastHeartbeatAcknowledged === -1 ? -1 : lastHeartbeatAcknowledged - lastHeartbeatSent;
50
+ }
51
+ });
52
+ function init() {
53
+ if (state !== ShardState.Idle && state !== ShardState.Disconnected) {
54
+ self.emit("error", new Error("Shard is already connected or connecting."));
55
+ return;
56
+ }
57
+ if (strategy === ShardStrategy.Shutdown)
58
+ return;
59
+ state = ShardState.Connecting;
60
+ let { gateway } = resolvedOptions, baseURL = isResumable() && resumeGatewayURL ? resumeGatewayURL : gateway.baseURL, url = new URL(baseURL);
61
+ url.searchParams.set("v", gateway.version.toString()), url.searchParams.set("encoding", "json"), url.searchParams.set("compress", "zlib-stream"), ws = new WebSocket(url.toString(), {
62
+ perMessageDeflate: false
63
+ }), zlibBuffer = Buffer.alloc(0), inflater = createInflate({
64
+ flush: constants.Z_SYNC_FLUSH
65
+ }), inflater.on("data", (chunk) => {
66
+ try {
67
+ let payload = JSON.parse(chunk.toString("utf8"));
68
+ handlePayload(payload);
69
+ } catch (err) {
70
+ self.emit("error", err);
71
+ }
72
+ }), inflater.on("error", (err) => {
73
+ self.emit("error", err), ws?.terminate();
74
+ }), ws.on("message", onMessage), ws.on("close", onClose), ws.on("error", (err) => self.emit("error", err));
75
+ }
76
+ function cleanup() {
77
+ heartbeatInterval && (clearInterval(heartbeatInterval), heartbeatInterval = void 0), heartbeatTimeout && (clearTimeout(heartbeatTimeout), heartbeatTimeout = void 0), reconnectTimeout && (clearTimeout(reconnectTimeout), reconnectTimeout = void 0), inflater && (inflater.destroy(), inflater = void 0), zlibBuffer && (zlibBuffer = void 0), ws && (ws.readyState !== WebSocket.CLOSED && ws.terminate(), ws.removeAllListeners(), ws = void 0), missedHeartbeats = 0, lastHeartbeatSent = -1, lastHeartbeatAcknowledged = -1;
78
+ }
79
+ function connect() {
80
+ return new Promise((resolve) => {
81
+ state !== ShardState.Idle && state !== ShardState.Disconnected || (strategy = ShardStrategy.Unknown, self.once("ready", () => resolve()), init());
82
+ });
83
+ }
84
+ function disconnect(code = 1e3) {
85
+ return new Promise((resolve) => {
86
+ if (strategy = ShardStrategy.Shutdown, !ws) {
87
+ resolve();
88
+ return;
89
+ }
90
+ ws.once("close", () => {
91
+ resolve();
92
+ }), ws.close(code);
93
+ });
94
+ }
95
+ function onMessage(data) {
96
+ if (!(!(data instanceof Buffer) || !zlibBuffer)) {
97
+ if (data.length > 8 * 1024 * 1024) {
98
+ ws?.terminate();
99
+ return;
100
+ }
101
+ zlibBuffer = Buffer.concat([zlibBuffer, data]), zlibBuffer.subarray(zlibBuffer.length - 4).equals(ZLIB_FLUSH) && (inflater?.write(zlibBuffer), zlibBuffer = Buffer.alloc(0));
102
+ }
103
+ }
104
+ function onClose(code) {
105
+ if (cleanup(), state = ShardState.Disconnected, self.emit("disconnect", code), strategy === ShardStrategy.Shutdown) {
106
+ switch (code) {
107
+ case GatewayCloseCodes.AuthenticationFailed:
108
+ self.emit("error", new Error("Invalid token provided"));
109
+ break;
110
+ case GatewayCloseCodes.InvalidIntents:
111
+ self.emit("error", new Error("Invalid intents provided"));
112
+ break;
113
+ case GatewayCloseCodes.DisallowedIntents:
114
+ self.emit("error", new Error("Disallowed intents provided"));
115
+ break;
116
+ }
117
+ return;
118
+ }
119
+ strategy === ShardStrategy.Unknown && (strategy = getReconnectStrategy(code)), (strategy === ShardStrategy.Reconnect || strategy === ShardStrategy.Resume) && scheduleReconnect();
120
+ }
121
+ function handlePayload(payload) {
122
+ switch (self.emit("raw", payload), payload.op) {
123
+ case GatewayOpcodes.Dispatch: {
124
+ handleDispatch(payload);
125
+ break;
126
+ }
127
+ case GatewayOpcodes.Hello: {
128
+ startHeartbeat(payload.d.heartbeat_interval), isResumable() ? resume() : self.emit("requestIdentify");
129
+ break;
130
+ }
131
+ case GatewayOpcodes.Heartbeat: {
132
+ sendHeartbeat();
133
+ break;
134
+ }
135
+ case GatewayOpcodes.HeartbeatAck: {
136
+ lastHeartbeatAcknowledged = Date.now();
137
+ break;
138
+ }
139
+ case GatewayOpcodes.InvalidSession: {
140
+ payload.d ? strategy = ShardStrategy.Resume : (strategy = ShardStrategy.Reconnect, sessionId = void 0, lastSequence = void 0, resumeGatewayURL = void 0), self.emit("debug", `Invalid session (resumable=${isResumable()})`), ws?.terminate();
141
+ break;
142
+ }
143
+ case GatewayOpcodes.Reconnect: {
144
+ strategy = ShardStrategy.Resume, self.emit("debug", "Reconnecting to gateway"), ws?.terminate();
145
+ break;
146
+ }
147
+ }
148
+ }
149
+ function handleDispatch(payload) {
150
+ switch (lastSequence = payload.s, self.emit("dispatch", payload), payload.t) {
151
+ case GatewayDispatchEvents.Ready: {
152
+ let { d: data } = payload;
153
+ state = ShardState.Ready, sessionId = data.session_id, resumeGatewayURL = data.resume_gateway_url, self.emit("ready", data);
154
+ break;
155
+ }
156
+ case GatewayDispatchEvents.Resumed: {
157
+ state = ShardState.Ready, strategy = ShardStrategy.Unknown, self.emit("resume");
158
+ break;
159
+ }
160
+ }
161
+ }
162
+ function isResumable() {
163
+ let hasSessionId = sessionId !== void 0, hasSequence = lastSequence !== void 0;
164
+ return strategy === ShardStrategy.Resume && hasSequence && hasSessionId;
165
+ }
166
+ function getReconnectStrategy(code) {
167
+ switch (code) {
168
+ case GatewayCloseCodes.AuthenticationFailed:
169
+ case GatewayCloseCodes.InvalidIntents:
170
+ case GatewayCloseCodes.DisallowedIntents:
171
+ return ShardStrategy.Shutdown;
172
+ case GatewayCloseCodes.InvalidSeq:
173
+ case GatewayCloseCodes.SessionTimedOut:
174
+ return ShardStrategy.Reconnect;
175
+ default:
176
+ return ShardStrategy.Resume;
177
+ }
178
+ }
179
+ function identify() {
180
+ send({
181
+ op: GatewayOpcodes.Identify,
182
+ d: {
183
+ token: resolvedOptions.token,
184
+ intents: Number(resolvedOptions.intents),
185
+ properties: {
186
+ os: process.platform,
187
+ browser: "bakit",
188
+ device: "bakit"
189
+ },
190
+ shard: [resolvedOptions.id, resolvedOptions.total]
191
+ }
192
+ });
193
+ }
194
+ function resume() {
195
+ state = ShardState.Resuming, send({
196
+ op: GatewayOpcodes.Resume,
197
+ d: {
198
+ token: resolvedOptions.token,
199
+ session_id: sessionId,
200
+ seq: lastSequence
201
+ }
202
+ });
203
+ }
204
+ function sendHeartbeat() {
205
+ if (lastHeartbeatSent !== -1 && lastHeartbeatAcknowledged < lastHeartbeatSent ? missedHeartbeats++ : missedHeartbeats = 0, missedHeartbeats >= 2) {
206
+ self.emit("debug", "Missed 2 heartbeats, reconnecting"), ws?.terminate();
207
+ return;
208
+ }
209
+ send({
210
+ op: GatewayOpcodes.Heartbeat,
211
+ d: lastSequence ?? null
212
+ }), lastHeartbeatSent = Date.now();
213
+ }
214
+ function startHeartbeat(interval) {
215
+ heartbeatInterval && (clearInterval(heartbeatInterval), heartbeatInterval = void 0);
216
+ let jitter = Math.random(), firstDelay = Math.floor(interval * jitter);
217
+ self.emit("debug", `Starting heartbeat (interval=${interval}ms, jitter=${firstDelay}ms)`), heartbeatTimeout = setTimeout(() => {
218
+ sendHeartbeat(), heartbeatInterval = setInterval(sendHeartbeat, interval);
219
+ }, firstDelay);
220
+ }
221
+ function scheduleReconnect(delay = 1e3) {
222
+ reconnectTimeout || (reconnectTimeout = setTimeout(() => {
223
+ reconnectTimeout = void 0, state = ShardState.Idle, init();
224
+ }, delay));
225
+ }
226
+ function send(payload) {
227
+ ws?.readyState === WebSocket.OPEN && ws.send(JSON.stringify(payload));
228
+ }
229
+ return self;
230
+ }
231
+ var GatewayWorkerState = {
232
+ Idle: 0,
233
+ Starting: 1,
234
+ Ready: 2,
235
+ Degraded: 3,
236
+ Stopped: 4
237
+ };
238
+ function createWorker(options) {
239
+ let shards = new Collection(), state = GatewayWorkerState.Idle, readyShards = /* @__PURE__ */ new Set(), self = attachEventBus({
240
+ get id() {
241
+ return options.id;
242
+ },
243
+ get shards() {
244
+ return shards;
245
+ },
246
+ get shardIds() {
247
+ return [...options.shards];
248
+ },
249
+ get latency() {
250
+ let count = 0, sumLatency = shards.reduce((acc, shard) => shard.latency === -1 ? acc : (count++, acc + shard.latency), 0);
251
+ return count === 0 ? -1 : sumLatency / count;
252
+ },
253
+ get state() {
254
+ return state;
255
+ },
256
+ start,
257
+ stop,
258
+ broadcast
259
+ });
260
+ async function start() {
261
+ if (!(state !== GatewayWorkerState.Idle && state !== GatewayWorkerState.Stopped)) {
262
+ state = GatewayWorkerState.Starting;
263
+ for (let id of options.shards) {
264
+ let shard = createShard({
265
+ id,
266
+ token: options.token,
267
+ intents: options.intents,
268
+ total: options.total,
269
+ gateway: {
270
+ baseURL: options.gatewayURL,
271
+ version: 10
272
+ }
273
+ });
274
+ shards.set(id, shard), shard.on("ready", (data) => {
275
+ if (readyShards.add(id), self.emit("shardReady", id, data), state !== GatewayWorkerState.Ready && readyShards.size === options.shards.length) {
276
+ let wasDegraded = state === GatewayWorkerState.Degraded;
277
+ state = GatewayWorkerState.Ready, self.emit(wasDegraded ? "resume" : "ready");
278
+ }
279
+ }), shard.on("disconnect", (code) => {
280
+ readyShards.delete(id), self.emit("shardDisconnect", id, code), state !== GatewayWorkerState.Starting && state !== GatewayWorkerState.Degraded && readyShards.size < options.shards.length && (state = GatewayWorkerState.Degraded, self.emit("degrade", readyShards.size, options.shards.length));
281
+ }), shard.on("raw", (payload) => self.emit("shardRaw", id, payload)), shard.on("dispatch", (payload) => self.emit("shardDispatch", id, payload)), shard.on("error", (err) => self.emit("error", err)), shard.on("debug", (msg) => self.emit("debug", `[Shard ${id}] ${msg}`)), shard.on("requestIdentify", () => self.emit("shardRequestIdentify", id)), shard.connect();
282
+ }
283
+ }
284
+ }
285
+ async function stop(code = 1e3) {
286
+ await Promise.all(shards.map((shard) => shard.disconnect(code))), state = GatewayWorkerState.Stopped, shards.clear(), readyShards.clear(), self.emit("stop");
287
+ }
288
+ function broadcast(payload) {
289
+ for (let shard of shards.values())
290
+ shard.state === ShardState.Ready && shard.send(payload);
291
+ }
292
+ return self;
293
+ }
294
+ function bindWorkerToProcess(worker) {
295
+ worker.on("shardRaw", (shardId, payload) => send("shardRaw", { shardId, payload })), worker.on("shardDispatch", (shardId, payload) => send("shardDispatch", { shardId, payload })), worker.on("shardReady", (shardId, payload) => send("shardReady", { shardId, payload })), worker.on("shardDisconnect", (shardId, code) => send("shardDisconnect", { shardId, code })), worker.on("shardRequestIdentify", (shardId) => send("shardRequestIdentify", { shardId })), worker.on("ready", () => send("ready", {})), worker.on("stop", () => send("stop", {})), worker.on("error", (error) => {
296
+ send("workerError", {
297
+ error: { message: error.message, stack: error.stack }
298
+ });
299
+ });
300
+ function send(type, payload) {
301
+ process.send?.({ type, ...payload });
302
+ }
303
+ process.on("SIGINT", () => {
304
+ }), process.on("SIGTERM", async () => {
305
+ await worker.stop(1e3), process.exit(0);
306
+ }), process.on("message", (message) => {
307
+ switch (message.type) {
308
+ case "identifyShard": {
309
+ worker.shards.get(message.shardId)?.identify();
310
+ break;
311
+ }
312
+ case "broadcast": {
313
+ worker.broadcast(message.payload);
314
+ break;
315
+ }
316
+ case "sendToShard": {
317
+ worker.shards.get(message.shardId)?.send(message.payload);
318
+ break;
319
+ }
320
+ }
321
+ });
322
+ }
323
+ function getWorkerOptions() {
324
+ let { WORKER_DATA } = process.env;
325
+ if (!WORKER_DATA)
326
+ throw new Error("WORKER_DATA is not set");
327
+ return JSON.parse(WORKER_DATA);
328
+ }
329
+ var DEFAULT_WORKER_PATH = fileURLToPath(new URL("./services/worker.js", import.meta.url)), DEFAULT_GATEWAY_MANAGER_OPTIONS = {
330
+ gatewayURL: "wss://gateway.discord.gg",
331
+ totalShards: "auto",
332
+ shardsPerWorker: 5
333
+ };
334
+ function createGatewayManager(options) {
335
+ let opts = {
336
+ ...DEFAULT_GATEWAY_MANAGER_OPTIONS,
337
+ ...options
338
+ }, identifyQueue, workers = new Collection(), rest = createREST(opts.rest ?? { token: options.token }), self = attachEventBus({
339
+ get rest() {
340
+ return rest;
341
+ },
342
+ spawn,
343
+ broadcast,
344
+ sendToWorker,
345
+ sendToShard
346
+ });
347
+ async function spawn() {
348
+ let gatewayBotInfo = await rest.get("/gateway/bot"), { session_start_limit: limit } = gatewayBotInfo, totalShards = opts.totalShards === "auto" ? gatewayBotInfo.shards : opts.totalShards, totalWorkers = Math.ceil(totalShards / opts.shardsPerWorker);
349
+ if (limit.remaining < totalShards) {
350
+ let error = new Error(
351
+ [
352
+ "Not enough remaining gateway sessions to spawn shards.",
353
+ `Required: ${totalShards}`,
354
+ `Remaining: ${limit.remaining}`,
355
+ `Resets in: ${Math.ceil(limit.reset_after / 1e3)}s`
356
+ ].join(" ")
357
+ );
358
+ self.emit("error", error);
359
+ return;
360
+ }
361
+ identifyQueue && (identifyQueue.pause(), identifyQueue = void 0), identifyQueue = createQueue({
362
+ concurrency: limit.max_concurrency,
363
+ intervalCap: limit.max_concurrency,
364
+ interval: 5e3
365
+ });
366
+ for (let i = 0; i < totalWorkers; i++) {
367
+ let start = i * opts.shardsPerWorker, shards = Array.from({ length: Math.min(opts.shardsPerWorker, totalShards - start) }, (_, j) => start + j), workerOptions = {
368
+ id: i,
369
+ total: totalShards,
370
+ token: options.token,
371
+ intents: options.intents,
372
+ shards,
373
+ gatewayURL: opts.gatewayURL ?? "wss://gateway.discord.gg"
374
+ };
375
+ workers.set(i, spawnWorker(workerOptions));
376
+ }
377
+ }
378
+ async function shutdown(signal) {
379
+ console.log(`Received ${signal}, shutting down...`), await Promise.all(
380
+ [...workers.values()].map((child) => new Promise((resolve) => {
381
+ child.once("exit", () => resolve()), child.kill("SIGTERM");
382
+ }))
383
+ ), process.exit(0);
384
+ }
385
+ process.once("SIGINT", shutdown), process.once("SIGTERM", shutdown);
386
+ function spawnWorker(payload) {
387
+ let child = fork(opts.workerPath ?? DEFAULT_WORKER_PATH, [], {
388
+ env: {
389
+ WORKER_DATA: JSON.stringify(payload)
390
+ },
391
+ stdio: "inherit"
392
+ });
393
+ return child.on("message", (msg) => {
394
+ switch (msg.type) {
395
+ case "shardRaw": {
396
+ self.emit("shardRaw", payload.id, msg.shardId, msg.payload);
397
+ break;
398
+ }
399
+ case "shardDispatch": {
400
+ self.emit("shardDispatch", payload.id, msg.shardId, msg.payload);
401
+ break;
402
+ }
403
+ case "shardReady": {
404
+ self.emit("shardReady", payload.id, msg.shardId, msg.payload);
405
+ break;
406
+ }
407
+ case "shardDisconnect": {
408
+ self.emit("shardDisconnect", payload.id, msg.shardId, msg.code);
409
+ break;
410
+ }
411
+ case "shardRequestIdentify": {
412
+ identifyQueue?.add(async () => {
413
+ child.connected && child.send({
414
+ type: "identifyShard",
415
+ shardId: msg.shardId
416
+ });
417
+ });
418
+ break;
419
+ }
420
+ case "ready": {
421
+ self.emit("workerReady", payload.id);
422
+ break;
423
+ }
424
+ case "stop": {
425
+ self.emit("workerStop", payload.id);
426
+ break;
427
+ }
428
+ case "workerError": {
429
+ self.emit("error", new Error(`[worker ${payload.id}] ${msg.error.message}`));
430
+ break;
431
+ }
432
+ }
433
+ }), child;
434
+ }
435
+ function broadcast(payload) {
436
+ for (let child of workers.values())
437
+ child.connected && child.send({
438
+ type: "broadcast",
439
+ payload
440
+ });
441
+ }
442
+ function sendToShard(shardId, payload) {
443
+ let workerId = Math.floor(shardId / opts.shardsPerWorker), child = workers.get(workerId);
444
+ return child?.connected ? (child.send({
445
+ type: "sendToShard",
446
+ shardId,
447
+ payload
448
+ }), true) : false;
449
+ }
450
+ function sendToWorker(workerId, payload) {
451
+ let child = workers.get(workerId);
452
+ return child?.connected ? (child.send({
453
+ type: "broadcast",
454
+ payload
455
+ }), true) : false;
456
+ }
457
+ return self;
458
+ }
459
+
460
+ export { DEFAULT_GATEWAY_MANAGER_OPTIONS, DEFAULT_WORKER_PATH, GatewayWorkerState, ShardState, ShardStrategy, bindWorkerToProcess, createGatewayManager, createShard, createWorker, getWorkerOptions };
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,6 @@
1
+ import { createWorker, getWorkerOptions, bindWorkerToProcess } from '@bakit/gateway';
2
+
3
+ // src/services/worker.ts
4
+ var worker = createWorker(getWorkerOptions());
5
+ bindWorkerToProcess(worker);
6
+ await worker.start();
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@bakit/gateway",
3
+ "version": "2.0.0-alpha.36",
4
+ "description": "Gateway manager for bakit framework",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./dist/index.js",
9
+ "types": "./dist/index.d.ts"
10
+ }
11
+ },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "homepage": "https://github.com/louiszn/bakit#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/louiszn/bakit.git"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/louiszn/bakit/issues"
22
+ },
23
+ "keywords": [
24
+ "discord-bot",
25
+ "bakit",
26
+ "framework"
27
+ ],
28
+ "author": "louiszn",
29
+ "license": "MIT",
30
+ "dependencies": {
31
+ "discord-api-types": "^0.38.37",
32
+ "type-fest": "^4.41.0",
33
+ "ws": "^8.18.3",
34
+ "@bakit/utils": "2.0.0-alpha.36",
35
+ "@bakit/rest": "2.0.0-alpha.36",
36
+ "@bakit/service": "2.0.0-alpha.36"
37
+ },
38
+ "devDependencies": {
39
+ "@types/ws": "^8.18.1"
40
+ },
41
+ "scripts": {
42
+ "build": "tsup",
43
+ "type-check": "tsc --noEmit",
44
+ "test": "vitest run --pass-with-no-tests"
45
+ }
46
+ }