bakit 3.0.0 → 3.1.0

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.mjs ADDED
@@ -0,0 +1,908 @@
1
+ import { Cluster, Shard, ShardState, ShardStrategy, ShardingManager, ShardingManager as ShardingManager$1 } from "@bakit/gateway";
2
+ import { DEFAULT_REST_OPTIONS, DiscordHTTPError, REST, REST as REST$1, RESTAdapter, RESTMethod, createREST, createRESTAdapter } from "@bakit/rest";
3
+ import { Service, ServiceDriver, ServiceProcess, ServiceState, TransportClient, TransportServer, createService, createTransportClient, createTransportServer } from "@bakit/service";
4
+ import { capitalize, getSnowflakeDate, instanceToObject, isCommonJS, isESM, isPlainObject, isPromiseLike, promisify, sleep } from "@bakit/utils";
5
+ import EventEmitter from "node:events";
6
+ import * as DiscordAPIV10 from "discord-api-types/v10";
7
+ import { ChannelType, GatewayDispatchEvents, GatewayIntentBits, GatewayIntentBits as Intent, Routes } from "discord-api-types/v10";
8
+ import { Collection } from "@discordjs/collection";
9
+ import { applyMixins, createMixin } from "tiny-mixin";
10
+
11
+ //#region src/lib/structures/BaseStructure.ts
12
+ var BaseStructure = class {
13
+ constructor(client) {
14
+ Object.defineProperty(this, "client", {
15
+ value: client,
16
+ enumerable: false,
17
+ writable: false
18
+ });
19
+ }
20
+ toJSON() {
21
+ return {};
22
+ }
23
+ };
24
+
25
+ //#endregion
26
+ //#region src/lib/structures/User.ts
27
+ var User = class extends BaseStructure {
28
+ constructor(client, data) {
29
+ super(client);
30
+ this.data = data;
31
+ }
32
+ get id() {
33
+ return this.data.id;
34
+ }
35
+ get username() {
36
+ return this.data.username;
37
+ }
38
+ get discriminator() {
39
+ return this.data.discriminator;
40
+ }
41
+ get globalName() {
42
+ return this.data.global_name;
43
+ }
44
+ get tag() {
45
+ return this.discriminator !== "0" && this.discriminator !== "0000" ? `${this.username}#${this.discriminator}` : this.username;
46
+ }
47
+ get displayName() {
48
+ return this.globalName ?? this.tag;
49
+ }
50
+ get avatar() {
51
+ return this.data.avatar ?? void 0;
52
+ }
53
+ get bot() {
54
+ return !!this.data.bot;
55
+ }
56
+ get system() {
57
+ return !!this.data.system;
58
+ }
59
+ get mfaEnabled() {
60
+ return this.data.mfa_enabled;
61
+ }
62
+ get locale() {
63
+ return this.data.locale;
64
+ }
65
+ get verified() {
66
+ return this.data.verified;
67
+ }
68
+ get email() {
69
+ return this.data.email;
70
+ }
71
+ get flags() {
72
+ return this.data.flags;
73
+ }
74
+ get premiumType() {
75
+ return this.data.premium_type;
76
+ }
77
+ get publicFlags() {
78
+ return this.data.public_flags;
79
+ }
80
+ get banner() {
81
+ return this.data.banner;
82
+ }
83
+ get accentColor() {
84
+ return this.data.accent_color ?? void 0;
85
+ }
86
+ get createdAt() {
87
+ return getSnowflakeDate(this.id);
88
+ }
89
+ get createdTimestamp() {
90
+ return this.createdAt.getTime();
91
+ }
92
+ get hexAccentColor() {
93
+ return this.accentColor !== void 0 ? `#${this.accentColor.toString(16).padStart(6, "0")}` : void 0;
94
+ }
95
+ get defaultAvatarURL() {
96
+ return `https://cdn.discordapp.com/embed/avatars/${this.discriminator !== "0" && this.discriminator !== "0000" ? BigInt(this.discriminator) % 5n : (BigInt(this.id) >> 22n) % 6n}.png`;
97
+ }
98
+ getAvatarURL(options) {
99
+ if (!this.avatar) return;
100
+ const isAnimated = this.avatar.startsWith("a_");
101
+ const ext = options?.extension ?? (isAnimated ? "gif" : "png");
102
+ const size = options?.size ? `?size=${options.size}` : "";
103
+ return `https://cdn.discordapp.com/avatars/${this.id}/${this.avatar}.${ext}${size}`;
104
+ }
105
+ getDisplayAvatarURL(options) {
106
+ return this.getAvatarURL(options) ?? this.defaultAvatarURL;
107
+ }
108
+ equals(other) {
109
+ if (typeof other === "string") return other === this.id;
110
+ return other.id === this.id && other.username === this.username && other.discriminator === this.discriminator && other.bot === this.bot && other.createdTimestamp === this.createdTimestamp;
111
+ }
112
+ async createDM(force = false) {
113
+ return this.client.helper.createDM(this.id, force);
114
+ }
115
+ async send(options) {
116
+ return await (await this.createDM()).send(options);
117
+ }
118
+ _patch(data) {
119
+ this.data = {
120
+ ...this.data,
121
+ ...data
122
+ };
123
+ }
124
+ toJSON() {
125
+ return this.data;
126
+ }
127
+ toString() {
128
+ return `<@${this.id}>`;
129
+ }
130
+ };
131
+
132
+ //#endregion
133
+ //#region src/lib/structures/channel/BaseChannel.ts
134
+ var BaseChannel = class extends BaseStructure {
135
+ constructor(client, data) {
136
+ super(client);
137
+ this.data = data;
138
+ }
139
+ get id() {
140
+ return this.data.id;
141
+ }
142
+ get type() {
143
+ return this.data.type;
144
+ }
145
+ toString() {
146
+ return `<#${this.id}>`;
147
+ }
148
+ toJSON() {
149
+ return this.data;
150
+ }
151
+ isTextBased() {
152
+ return "send" in this;
153
+ }
154
+ isVoiceBased() {
155
+ return "join" in this;
156
+ }
157
+ isDM() {
158
+ return this.type === ChannelType.DM;
159
+ }
160
+ inGuild() {
161
+ return "guild_id" in this.data;
162
+ }
163
+ fetch() {
164
+ return this.client.helper.fetchChannel(this.id, true);
165
+ }
166
+ _patch(data) {
167
+ this.data = {
168
+ ...this.data,
169
+ ...data
170
+ };
171
+ }
172
+ };
173
+
174
+ //#endregion
175
+ //#region src/lib/mixins/ChannelMixin.ts
176
+ const TextBasedChannelMixin = createMixin((base) => {
177
+ class TextBasedChannel extends base {
178
+ send(options) {
179
+ return this.client.helper.createMessage(this.id, options);
180
+ }
181
+ }
182
+ return TextBasedChannel;
183
+ });
184
+ const VoiceBasedChannelMixin = createMixin((base) => {
185
+ class VoiceBasedChannel extends base {}
186
+ return VoiceBasedChannel;
187
+ });
188
+ const GuildChannelMixin = createMixin((base) => {
189
+ class GuildChannel extends base {
190
+ get guildId() {
191
+ if (!this.data.guild_id) throw new Error("This channel is not a guild channel");
192
+ return this.data.guild_id;
193
+ }
194
+ get guild() {
195
+ return this.client.cache.guilds.get(this.guildId);
196
+ }
197
+ }
198
+ return GuildChannel;
199
+ });
200
+
201
+ //#endregion
202
+ //#region src/lib/structures/channel/DMChannel.ts
203
+ var DMChannel = class extends applyMixins(BaseChannel, [TextBasedChannelMixin]) {
204
+ #cachedRecipients;
205
+ constructor(client, data) {
206
+ super(client, data);
207
+ }
208
+ get recipients() {
209
+ if (!this.#cachedRecipients) {
210
+ this.#cachedRecipients = new Collection();
211
+ for (const recipient of this.data.recipients ?? []) {
212
+ let user;
213
+ if (this.client.cache.isModuleEnabled("users")) user = this.client.cache.resolveLocal(this.client.cache.users.local, recipient.id, () => new User(this.client, recipient), (user) => user._patch(recipient));
214
+ else user = new User(this.client, recipient);
215
+ this.#cachedRecipients.set(recipient.id, user);
216
+ }
217
+ }
218
+ return this.#cachedRecipients;
219
+ }
220
+ get recipientId() {
221
+ const id = (this.data.recipients ?? []).find((user) => user.id !== this.client.user.id)?.id;
222
+ if (!id) throw new Error("No recipients found");
223
+ return id;
224
+ }
225
+ get recipient() {
226
+ const user = this.recipients.get(this.recipientId);
227
+ if (!user) throw new Error("Recipient not found");
228
+ return user;
229
+ }
230
+ async fetch() {
231
+ const data = await this.client.rest.post(Routes.userChannels(), { body: { recipient_id: this.recipientId } });
232
+ this._patch(data);
233
+ await this.#initRecipientsCache();
234
+ return this;
235
+ }
236
+ send(options) {
237
+ return super.send(options);
238
+ }
239
+ async fetchRecipients(force = false) {
240
+ if (!force && this.data.recipients?.length) {
241
+ await this.#initRecipientsCache();
242
+ return this.#cachedRecipients;
243
+ }
244
+ await this.fetch();
245
+ return this.#cachedRecipients;
246
+ }
247
+ async #initRecipientsCache() {
248
+ this.#cachedRecipients = new Collection();
249
+ for (const recipient of this.data.recipients ?? []) {
250
+ let user;
251
+ if (this.client.cache.isModuleEnabled("users")) user = await this.client.cache.resolve(this.client.cache.users, recipient.id, () => new User(this.client, recipient), (user) => user._patch(recipient));
252
+ else user = new User(this.client, recipient);
253
+ this.#cachedRecipients.set(recipient.id, user);
254
+ }
255
+ }
256
+ _patch(data) {
257
+ super._patch(data);
258
+ this.#cachedRecipients = void 0;
259
+ }
260
+ };
261
+
262
+ //#endregion
263
+ //#region src/lib/structures/Message.ts
264
+ var Message = class extends BaseStructure {
265
+ #cachedAuthor;
266
+ constructor(client, data) {
267
+ super(client);
268
+ this.data = data;
269
+ this.#ensureChannelCache();
270
+ }
271
+ get partial() {
272
+ return typeof this.data.content !== "string" || typeof this.data.author !== "object";
273
+ }
274
+ get content() {
275
+ return this.data.content;
276
+ }
277
+ get id() {
278
+ return this.data.id;
279
+ }
280
+ get channelId() {
281
+ return this.data.channel_id;
282
+ }
283
+ get channel() {
284
+ return this.#ensureChannelCache();
285
+ }
286
+ get guildId() {
287
+ return "guild_id" in this.data ? this.data.guild_id : void 0;
288
+ }
289
+ get guild() {
290
+ return this.guildId ? this.client.cache.guilds.get(this.guildId) : void 0;
291
+ }
292
+ /**
293
+ * The author of this message.
294
+ *
295
+ * **Note:** This property returns the cached `User` synchronously.
296
+ * It may be stale if the users cache has short lifetime or uses an asynchronous remote store.
297
+ * To ensure the author is up-to-date, use the `fetchAuthor()` method instead.
298
+ */
299
+ get author() {
300
+ let author = this.#cachedAuthor;
301
+ if (!author && this.client.cache.isModuleEnabled("users")) author = this.client.cache.resolveLocal(this.client.cache.users.local, this.data.author.id, () => new User(this.client, this.data.author), (user) => user._patch(this.data.author));
302
+ if (!author) author = new User(this.client, this.data.author);
303
+ this.#cachedAuthor = author;
304
+ return this.#cachedAuthor;
305
+ }
306
+ get createdAt() {
307
+ return new Date(this.data.timestamp);
308
+ }
309
+ get editedAt() {
310
+ return this.data.edited_timestamp ? new Date(this.data.edited_timestamp) : void 0;
311
+ }
312
+ get createdTimestamp() {
313
+ return this.createdAt.getTime();
314
+ }
315
+ get editedTimestamp() {
316
+ return this.editedAt?.getTime();
317
+ }
318
+ get url() {
319
+ return `https://discord.com/channels/${this.guildId ?? "@me"}/${this.channelId}/${this.id}`;
320
+ }
321
+ inGuild() {
322
+ return this.guild !== void 0;
323
+ }
324
+ async fetch() {
325
+ const message = await this.client.helper.fetchMessage(this.channelId, this.id);
326
+ this.data = message.data;
327
+ this.#cachedAuthor = await this.client.cache.resolve(this.client.cache.users, message.data.author.id, () => new User(this.client, message.data.author));
328
+ return this;
329
+ }
330
+ /**
331
+ * Fetches the author of this message from cache or Discord API.
332
+ *
333
+ * **Note:** It is recommended to use this method instead of the `author` property
334
+ * if the users cache has short lifetime or is backed by an asynchronous remote cache.
335
+ *
336
+ * @param force - Whether to bypass the cache and force a request to the API.
337
+ * @returns A promise that resolves to the `User` who authored this message.
338
+ */
339
+ async fetchAuthor(force = false) {
340
+ if (!force && this.client.cache.isModuleEnabled("users")) return this.client.cache.resolve(this.client.cache.users, this.data.author.id, () => new User(this.client, this.data.author), (user) => user._patch(this.data.author));
341
+ return this.client.helper.fetchUser(this.data.author.id, force);
342
+ }
343
+ async reply(options) {
344
+ return this.client.helper.replyMessage(this.channelId, this.id, options);
345
+ }
346
+ async sendToChannel(options) {
347
+ return this.client.helper.createMessage(this.channelId, options);
348
+ }
349
+ async edit(options) {
350
+ return this.client.helper.editMessage(this.channelId, this.id, options);
351
+ }
352
+ async _patch(data) {
353
+ this.data = {
354
+ ...this.data,
355
+ ...data
356
+ };
357
+ if (data.author && this.client.cache.isModuleEnabled("users")) if (this.client.cache.isModuleEnabled("users")) this.#cachedAuthor = await this.client.cache.resolve(this.client.cache.users, data.author.id, () => new User(this.client, data.author));
358
+ else this.#cachedAuthor?._patch(data.author);
359
+ }
360
+ #ensureChannelCache() {
361
+ const { client } = this;
362
+ let channel = client.cache.channels.get(this.channelId);
363
+ if (!channel) if (this.inGuild()) channel = this.guild.channels.get(this.channelId);
364
+ else {
365
+ channel = new DMChannel(client, {
366
+ id: this.channelId,
367
+ type: ChannelType.DM,
368
+ name: null,
369
+ recipients: [this.data.author, this.client.user.data]
370
+ });
371
+ console.log(channel);
372
+ }
373
+ if (!channel) throw new Error(`Channel not found: ${this.channelId}`);
374
+ client.cache.channels.set(this.channelId, channel);
375
+ return channel;
376
+ }
377
+ toJSON() {
378
+ return this.data;
379
+ }
380
+ toString() {
381
+ return this.data.content;
382
+ }
383
+ };
384
+
385
+ //#endregion
386
+ //#region src/lib/structures/channel/GuildTextChannel.ts
387
+ var GuildTextChannel = class extends applyMixins(BaseChannel, [GuildChannelMixin, TextBasedChannelMixin]) {};
388
+
389
+ //#endregion
390
+ //#region src/lib/structures/channel/GuildVoiceChannel.ts
391
+ var GuildVoiceChannel = class extends applyMixins(BaseChannel, [
392
+ GuildChannelMixin,
393
+ TextBasedChannelMixin,
394
+ VoiceBasedChannelMixin
395
+ ]) {};
396
+
397
+ //#endregion
398
+ //#region src/lib/utils/channel.ts
399
+ function createChannel(client, data) {
400
+ switch (data.type) {
401
+ case ChannelType.GuildText: return new GuildTextChannel(client, data);
402
+ case ChannelType.GuildVoice: return new GuildVoiceChannel(client, data);
403
+ case ChannelType.DM: return new DMChannel(client, data);
404
+ default: return null;
405
+ }
406
+ }
407
+
408
+ //#endregion
409
+ //#region src/lib/structures/Guild.ts
410
+ var Guild = class extends BaseStructure {
411
+ channels = new Collection();
412
+ constructor(client, data) {
413
+ super(client);
414
+ this.data = data;
415
+ this.#initChannels();
416
+ }
417
+ get id() {
418
+ return this.data.id;
419
+ }
420
+ get name() {
421
+ return this.data.name;
422
+ }
423
+ get icon() {
424
+ return this.data.icon;
425
+ }
426
+ get banner() {
427
+ return this.data.banner;
428
+ }
429
+ get owner() {
430
+ return this.data.owner_id;
431
+ }
432
+ get mfaLevel() {
433
+ return this.data.mfa_level;
434
+ }
435
+ get verificationLevel() {
436
+ return this.data.verification_level;
437
+ }
438
+ _patch(data) {
439
+ this.data = {
440
+ ...this.data,
441
+ ...data
442
+ };
443
+ this.#initChannels();
444
+ }
445
+ #initChannels() {
446
+ if (!("channels" in this.data)) return;
447
+ for (const id of this.channels.keys()) this.client.cache.channels.delete(id);
448
+ this.channels.clear();
449
+ for (const channelData of this.data.channels) {
450
+ const channel = createChannel(this.client, channelData);
451
+ if (channel) {
452
+ this.channels.set(channel.id, channel);
453
+ this.client.cache.channels.set(channel.id, channel);
454
+ }
455
+ }
456
+ }
457
+ };
458
+
459
+ //#endregion
460
+ //#region src/lib/client/ClientHelper.ts
461
+ var ClientHelper = class ClientHelper {
462
+ constructor(client) {
463
+ Object.defineProperty(this, "client", {
464
+ value: client,
465
+ enumerable: false,
466
+ writable: false
467
+ });
468
+ }
469
+ async fetchUser(userId, force = false) {
470
+ let user;
471
+ if (this.client.cache.isModuleEnabled("users")) user = await this.client.cache.users.get(userId);
472
+ if (!user || force) {
473
+ const data = await this.client.rest.get(Routes.user(userId));
474
+ if (this.client.cache.isModuleEnabled("users")) user = await this.client.cache.resolve(this.client.cache.users, userId, () => new User(this.client, data), (u) => u._patch(data));
475
+ else user = new User(this.client, data);
476
+ }
477
+ return user;
478
+ }
479
+ async createDM(userId, force = false) {
480
+ if (!force) {
481
+ const channel = this.client.cache.channels.find((c) => c.isDM() && c.recipientId === userId);
482
+ if (channel && channel.isDM()) return channel;
483
+ }
484
+ const data = await this.client.rest.post(Routes.userChannels(), { body: { recipient_id: userId } });
485
+ const channel = new DMChannel(this.client, data);
486
+ await channel.fetchRecipients();
487
+ this.client.cache.channels.set(channel.id, channel);
488
+ return channel;
489
+ }
490
+ async fetchMessage(channelId, messageId, force = false) {
491
+ let message;
492
+ if (this.client.cache.isModuleEnabled("messages")) message = await this.client.cache.messages.get(messageId);
493
+ if (!message || force) {
494
+ const data = await this.client.rest.get(Routes.channelMessage(channelId, messageId));
495
+ if (this.client.cache.isModuleEnabled("messages")) message = await this.client.cache.resolve(this.client.cache.messages, messageId, () => new Message(this.client, data), (m) => m._patch(data));
496
+ else message = new Message(this.client, data);
497
+ }
498
+ return message;
499
+ }
500
+ async deleteMessage(channelId, messageId) {
501
+ await this.client.rest.delete(Routes.channelMessage(channelId, messageId));
502
+ if (this.client.cache.isModuleEnabled("messages")) await this.client.cache.messages.delete(messageId);
503
+ }
504
+ async createMessage(channelId, options) {
505
+ if (typeof options === "string") options = { content: options };
506
+ const data = this.client.rest.post(Routes.channelMessages(channelId), { body: ClientHelper.toAPICreateMessagePayload(options) });
507
+ const message = new Message(this.client, await data);
508
+ if (this.client.cache.isModuleEnabled("messages")) await this.client.cache.messages.set(message.id, message);
509
+ return message;
510
+ }
511
+ async editMessage(channelId, messageId, options) {
512
+ if (typeof options === "string") options = { content: options };
513
+ const data = await this.client.rest.patch(Routes.channelMessage(channelId, messageId), { body: ClientHelper.toAPICreateMessagePayload(options) });
514
+ let message;
515
+ if (this.client.cache.isModuleEnabled("messages")) message = await this.client.cache.resolve(this.client.cache.messages, messageId, () => new Message(this.client, data), (m) => m._patch(data));
516
+ else message = new Message(this.client, data);
517
+ return message;
518
+ }
519
+ async replyMessage(channelId, messageId, options) {
520
+ return this.createMessage(channelId, {
521
+ ...options,
522
+ messageReference: {
523
+ channel_id: channelId,
524
+ message_id: messageId
525
+ }
526
+ });
527
+ }
528
+ async fetchGuild(guildId, force = false) {
529
+ let guild = this.client.cache.guilds.get(guildId);
530
+ if (!guild || force) {
531
+ const data = await this.client.rest.get(Routes.guild(guildId));
532
+ guild = new Guild(this.client, data);
533
+ this.client.cache.guilds.set(guildId, guild);
534
+ }
535
+ return guild;
536
+ }
537
+ async fetchChannel(channelId, force = false) {
538
+ let channel = this.client.cache.channels.get(channelId);
539
+ if (!channel || force) {
540
+ const data = await this.client.rest.get(Routes.channel(channelId));
541
+ channel = createChannel(this.client, data) ?? void 0;
542
+ if (!channel) throw new Error(`Channel not found: ${channelId}`);
543
+ this.client.cache.channels.set(channelId, channel);
544
+ if (channel.inGuild()) channel.guild.channels.set(channelId, channel);
545
+ }
546
+ return channel;
547
+ }
548
+ static toAPICreateMessagePayload(options) {
549
+ return {
550
+ content: options.content,
551
+ tts: options.tts,
552
+ embeds: options.embeds,
553
+ allowed_mentions: options.allowedMentions,
554
+ message_reference: options.messageReference,
555
+ flags: options.flags
556
+ };
557
+ }
558
+ };
559
+
560
+ //#endregion
561
+ //#region src/lib/client/Partial.ts
562
+ let Partial = /* @__PURE__ */ function(Partial) {
563
+ Partial[Partial["Message"] = 0] = "Message";
564
+ Partial[Partial["User"] = 1] = "User";
565
+ return Partial;
566
+ }({});
567
+
568
+ //#endregion
569
+ //#region src/lib/utils/IntentsBitField.ts
570
+ var IntentsBitField = class IntentsBitField {
571
+ value;
572
+ constructor(input) {
573
+ this.value = IntentsBitField.resolve(input);
574
+ }
575
+ static resolve(input) {
576
+ if (Array.isArray(input)) return input.reduce((acc, intent) => acc | BigInt(intent), 0n);
577
+ return BigInt(input);
578
+ }
579
+ has(intent) {
580
+ return (this.value & BigInt(intent)) !== 0n;
581
+ }
582
+ toBigInt() {
583
+ return this.value;
584
+ }
585
+ toNumber() {
586
+ return Number(this.value);
587
+ }
588
+ toJSON() {
589
+ return this.value.toString();
590
+ }
591
+ toString() {
592
+ return this.value.toString();
593
+ }
594
+ };
595
+
596
+ //#endregion
597
+ //#region src/lib/utils/cache/adapters/BaseCacheAdapter.ts
598
+ var BaseCacheAdapter = class {};
599
+
600
+ //#endregion
601
+ //#region src/lib/utils/cache/adapters/LocalCacheAdapter.ts
602
+ var LocalCacheAdapter = class extends BaseCacheAdapter {
603
+ collection = new Collection();
604
+ #sweepTimer;
605
+ get(key) {
606
+ const entry = this.collection.get(key);
607
+ if (!entry) return;
608
+ if (entry.expiresAt && entry.expiresAt < Date.now()) {
609
+ this.collection.delete(key);
610
+ return;
611
+ }
612
+ this.#setupSweepTTL();
613
+ return entry.value;
614
+ }
615
+ set(key, value, ttl) {
616
+ const expiresAt = ttl ? Date.now() + ttl : void 0;
617
+ this.collection.set(key, {
618
+ value,
619
+ expiresAt
620
+ });
621
+ this.#setupSweepTTL();
622
+ }
623
+ delete(key) {
624
+ this.#setupSweepTTL();
625
+ this.collection.delete(key);
626
+ }
627
+ clear() {
628
+ this.collection.clear();
629
+ clearTimeout(this.#sweepTimer);
630
+ this.#sweepTimer = void 0;
631
+ }
632
+ has(key) {
633
+ this.#setupSweepTTL();
634
+ return this.get(key) !== void 0;
635
+ }
636
+ find(filter) {
637
+ for (const entry of this.collection.values()) if (filter(entry.value)) return entry.value;
638
+ }
639
+ sweep(filter) {
640
+ for (const [key, entry] of this.collection) if (filter(entry.value)) this.delete(key);
641
+ }
642
+ sweepTTL() {
643
+ for (const [key, entry] of this.collection) if (entry.expiresAt && entry.expiresAt < Date.now()) this.delete(key);
644
+ }
645
+ #setupSweepTTL() {
646
+ if (!this.collection.size) return;
647
+ if (this.#sweepTimer) return;
648
+ this.#sweepTimer = setTimeout(() => {
649
+ this.#sweepTimer = void 0;
650
+ this.sweepTTL();
651
+ this.#setupSweepTTL();
652
+ }, 1e3);
653
+ }
654
+ };
655
+
656
+ //#endregion
657
+ //#region src/lib/utils/cache/HybridCache.ts
658
+ var HybridCache = class {
659
+ local = new LocalCacheAdapter();
660
+ constructor(remote, defaultTTL) {
661
+ this.remote = remote;
662
+ this.defaultTTL = defaultTTL;
663
+ }
664
+ async get(key) {
665
+ const local = this.local.get(key);
666
+ if (local !== void 0) return local;
667
+ const remote = await this.remote?.get(key);
668
+ if (remote !== void 0) this.local.set(key, remote);
669
+ return remote;
670
+ }
671
+ async sweep(filter) {
672
+ this.local.sweep(filter);
673
+ await this.remote?.sweep(filter);
674
+ }
675
+ async set(key, value, ttl = this.defaultTTL) {
676
+ this.local.set(key, value, ttl);
677
+ await this.remote?.set(key, value, ttl);
678
+ }
679
+ async delete(key) {
680
+ this.local.delete(key);
681
+ await this.remote?.delete(key);
682
+ }
683
+ async clear() {
684
+ this.local.clear();
685
+ await this.remote?.clear();
686
+ }
687
+ async has(key) {
688
+ return await this.get(key) !== void 0;
689
+ }
690
+ };
691
+
692
+ //#endregion
693
+ //#region src/lib/client/ClientCacheManager.ts
694
+ var ClientCacheManager = class {
695
+ channels = new LocalCacheAdapter();
696
+ guilds = new LocalCacheAdapter();
697
+ #users;
698
+ #messages;
699
+ #sweepers = new Collection();
700
+ constructor(options) {
701
+ this.options = options;
702
+ }
703
+ get users() {
704
+ let options;
705
+ if (typeof this.options.users === "object") options = this.options.users;
706
+ else options = { enabled: !!this.options.users };
707
+ if (!options.enabled) throw new Error("User cache is disabled");
708
+ if (!this.#users) this.#users = new HybridCache(options.adapter, options.ttl);
709
+ if (options.sweeper) this.#sweepers.set("users", setInterval(() => this.#users.sweep(options.sweeper.filter), options.sweeper.interval));
710
+ return this.#users;
711
+ }
712
+ get messages() {
713
+ let options;
714
+ if (typeof this.options.messages === "object") options = this.options.messages;
715
+ else options = { enabled: !!this.options.messages };
716
+ if (!options.enabled) throw new Error("Message cache is disabled");
717
+ if (!this.#messages) this.#messages = new HybridCache(options.adapter, options.ttl);
718
+ if (options.sweeper) this.#sweepers.set("messages", setInterval(() => this.#messages.sweep(options.sweeper.filter), options.sweeper.interval));
719
+ return this.#messages;
720
+ }
721
+ isModuleEnabled(module) {
722
+ return typeof this.options[module] === "object" ? this.options[module].enabled : !!this.options[module];
723
+ }
724
+ async resolve(cache, id, factory, patch) {
725
+ let value = await cache.get(id);
726
+ if (!value) {
727
+ value = factory();
728
+ await cache.set(id, value);
729
+ }
730
+ if (patch) patch(value);
731
+ return value;
732
+ }
733
+ resolveLocal(cache, id, factory, patch) {
734
+ let value = cache.get(id);
735
+ if (!value) {
736
+ value = factory();
737
+ cache.set(id, value);
738
+ }
739
+ if (patch) patch(value);
740
+ return value;
741
+ }
742
+ };
743
+
744
+ //#endregion
745
+ //#region src/lib/client/dispatches/registry.ts
746
+ const handlers = {};
747
+ function registerHandler(event, handler) {
748
+ if (handlers[event]) throw new Error(`Handler for ${event} already registered`);
749
+ handlers[event] = handler;
750
+ }
751
+
752
+ //#endregion
753
+ //#region src/lib/client/dispatches/handlers/message.ts
754
+ async function onCreateAndUpdate$1(client, payload) {
755
+ let message;
756
+ if (client.cache.isModuleEnabled("messages")) message = await client.cache.resolve(client.cache.messages, payload.d.id, () => new Message(client, payload.d), (m) => m._patch(payload.d));
757
+ else message = new Message(client, payload.d);
758
+ if (message.partial && !client.options.partials.has(Partial.Message)) return;
759
+ client.emit(payload.t === GatewayDispatchEvents.MessageUpdate ? "messageUpdate" : "messageCreate", message);
760
+ }
761
+ registerHandler(GatewayDispatchEvents.MessageCreate, onCreateAndUpdate$1);
762
+ registerHandler(GatewayDispatchEvents.MessageUpdate, onCreateAndUpdate$1);
763
+ registerHandler(GatewayDispatchEvents.MessageDelete, async (client, payload) => {
764
+ let message;
765
+ if (client.cache.isModuleEnabled("messages")) message = await client.cache.messages.get(payload.d.id);
766
+ if (!message) message = new Message(client, payload.d);
767
+ client.emit("messageDelete", message);
768
+ });
769
+
770
+ //#endregion
771
+ //#region src/lib/client/dispatches/handlers/guild.ts
772
+ async function onCreateAndUpdate(client, payload) {
773
+ const guild = await client.cache.resolve(client.cache.guilds, payload.d.id, () => new Guild(client, payload.d), (g) => g._patch(payload.d));
774
+ if (payload.t === GatewayDispatchEvents.GuildCreate) client.emit(payload.d.unavailable ? "guildCreate" : "guildAvailable", guild);
775
+ else client.emit("guildUpdate", guild);
776
+ }
777
+ registerHandler(GatewayDispatchEvents.GuildCreate, onCreateAndUpdate);
778
+ registerHandler(GatewayDispatchEvents.GuildUpdate, onCreateAndUpdate);
779
+ registerHandler(GatewayDispatchEvents.GuildDelete, async (client, payload) => {
780
+ const guild = client.cache.guilds.get(payload.d.id);
781
+ if (!guild) return;
782
+ for (const channel of guild.channels.values()) client.cache.channels.delete(channel.id);
783
+ client.cache.guilds.delete(payload.d.id);
784
+ client.emit("guildDelete", guild);
785
+ });
786
+
787
+ //#endregion
788
+ //#region src/lib/client/dispatches/handlers/channel.ts
789
+ async function onCreateOrUpdate(client, payload) {
790
+ const channel = await client.cache.resolve(client.cache.channels, payload.d.id, () => createChannel(client, payload.d), (c) => c?._patch(payload.d));
791
+ if (!channel) return;
792
+ if (channel.inGuild() && !channel.guild.channels.has(channel.id)) channel.guild.channels.set(channel.id, channel);
793
+ client.emit(payload.t === GatewayDispatchEvents.ChannelCreate ? "channelCreate" : "channelUpdate", channel);
794
+ }
795
+ registerHandler(GatewayDispatchEvents.ChannelCreate, onCreateOrUpdate);
796
+ registerHandler(GatewayDispatchEvents.ChannelUpdate, onCreateOrUpdate);
797
+ registerHandler(GatewayDispatchEvents.ChannelDelete, (client, payload) => {
798
+ const channel = client.cache.channels.get(payload.d.id);
799
+ const guild = client.cache.guilds.get(payload.d.guild_id);
800
+ if (guild) guild.channels.delete(payload.d.id);
801
+ if (!channel) return;
802
+ client.cache.channels.delete(payload.d.id);
803
+ client.emit("channelDelete", channel);
804
+ });
805
+
806
+ //#endregion
807
+ //#region src/lib/client/dispatches/handlers/user.ts
808
+ registerHandler(GatewayDispatchEvents.UserUpdate, async (client, payload) => {
809
+ if (payload.d.id === client.user?.id) client.user._patch(payload.d);
810
+ let user;
811
+ if (client.cache.isModuleEnabled("users")) user = await client.cache.resolve(client.cache.users, payload.d.id, () => new User(client, payload.d), (user) => user._patch(payload.d));
812
+ else user = new User(client, payload.d);
813
+ client.emit("userUpdate", user);
814
+ });
815
+
816
+ //#endregion
817
+ //#region src/lib/client/Client.ts
818
+ var Client = class extends EventEmitter {
819
+ options;
820
+ shards;
821
+ rest;
822
+ helper;
823
+ cache;
824
+ #user;
825
+ #ready = false;
826
+ constructor(options, rest) {
827
+ super();
828
+ const intents = options.intents instanceof IntentsBitField ? options.intents : new IntentsBitField(options.intents);
829
+ const sharding = {
830
+ shardsPerCluster: options.sharding?.shardsPerCluster ?? 1,
831
+ totalShards: options.sharding?.totalShards ?? 1
832
+ };
833
+ this.options = {
834
+ token: options.token,
835
+ intents,
836
+ sharding,
837
+ partials: new Set(options.partials ?? []),
838
+ cache: options.cache ?? {}
839
+ };
840
+ this.rest = rest ?? new REST$1({ token: options.token });
841
+ this.shards = new ShardingManager$1({
842
+ ...this.options.sharding,
843
+ token: this.options.token,
844
+ intents: this.options.intents.toBigInt()
845
+ }, rest);
846
+ this.cache = new ClientCacheManager(this.options.cache);
847
+ this.helper = new ClientHelper(this);
848
+ this.#setupShardsListeners();
849
+ }
850
+ get user() {
851
+ return this.#user;
852
+ }
853
+ async login() {
854
+ if (this.#user || this.shards.ready || this.shards.clusters.size > 0) throw new Error("Cannot login twice");
855
+ await this.shards.spawn();
856
+ return new Promise((resolve, reject) => {
857
+ const cleanup = () => {
858
+ this.removeListener("ready", onReady);
859
+ this.removeListener("error", onError);
860
+ };
861
+ const onReady = () => {
862
+ cleanup();
863
+ resolve();
864
+ };
865
+ const onError = (error) => {
866
+ cleanup();
867
+ reject(error);
868
+ };
869
+ this.once("ready", onReady);
870
+ this.once("error", onError);
871
+ });
872
+ }
873
+ #setupShardsListeners() {
874
+ this.shards.on("dispatch", (_, shardId, payload) => this.#handleDispatch(shardId, payload));
875
+ this.shards.on("raw", (_, shardId, payload) => this.emit("raw", shardId, payload));
876
+ this.shards.once("ready", () => this.#tryEmitReady());
877
+ }
878
+ async #handleDispatch(shardId, payload) {
879
+ this.emit("dispatch", shardId, payload);
880
+ switch (payload.t) {
881
+ case GatewayDispatchEvents.Ready:
882
+ this.#user ??= new User(this, payload.d.user);
883
+ this.#tryEmitReady();
884
+ break;
885
+ default: {
886
+ const handler = handlers[payload.t];
887
+ if (handler) await handler(this, payload);
888
+ break;
889
+ }
890
+ }
891
+ }
892
+ /**
893
+ * We use this method to emit ready event only once since we have 2 ways to emit it.
894
+ * @private
895
+ */
896
+ #tryEmitReady() {
897
+ if (this.#ready || !this.#user || !this.shards.ready) return;
898
+ this.#ready = true;
899
+ this.emit("ready", this.#user);
900
+ }
901
+ };
902
+ function createClient(options) {
903
+ return new Client(options);
904
+ }
905
+
906
+ //#endregion
907
+ export { BaseCacheAdapter, BaseChannel, Client, ClientHelper, Cluster, DEFAULT_REST_OPTIONS, DiscordAPIV10, DiscordHTTPError, Guild, GuildTextChannel, GuildVoiceChannel, HybridCache, Intent, IntentsBitField, LocalCacheAdapter, Message, Partial, REST, RESTAdapter, RESTMethod, Service, ServiceDriver, ServiceProcess, ServiceState, Shard, ShardState, ShardStrategy, ShardingManager, TransportClient, TransportServer, User, capitalize, createClient, createREST, createRESTAdapter, createService, createTransportClient, createTransportServer, instanceToObject, isCommonJS, isESM, isPlainObject, isPromiseLike, promisify, sleep };
908
+ //# sourceMappingURL=index.mjs.map