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