@fluxerjs/core 1.2.4 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -18,21 +18,23 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
 
20
20
  // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- AttachmentBuilder: () => import_builders3.AttachmentBuilder,
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ AttachmentBuilder: () => import_builders4.AttachmentBuilder,
24
24
  Base: () => Base,
25
+ BaseInteraction: () => BaseInteraction,
25
26
  CDN_URL: () => CDN_URL,
26
27
  CategoryChannel: () => CategoryChannel,
27
28
  Channel: () => Channel,
28
29
  ChannelManager: () => ChannelManager,
30
+ ChatInputCommandInteraction: () => ChatInputCommandInteraction,
29
31
  Client: () => Client,
30
32
  ClientUser: () => ClientUser,
31
33
  DMChannel: () => DMChannel,
32
- EmbedBuilder: () => import_builders3.EmbedBuilder,
33
- ErrorCodes: () => ErrorCodes,
34
+ EmbedBuilder: () => import_builders4.EmbedBuilder,
35
+ ErrorCodes: () => import_util2.ErrorCodes,
34
36
  Events: () => Events,
35
- FluxerError: () => FluxerError,
37
+ FluxerError: () => import_util.FluxerError,
36
38
  GatewayOpcodes: () => import_types22.GatewayOpcodes,
37
39
  Guild: () => Guild,
38
40
  GuildBan: () => GuildBan,
@@ -48,18 +50,18 @@ __export(index_exports, {
48
50
  MessageAttachmentFlags: () => import_types22.MessageAttachmentFlags,
49
51
  MessageCollector: () => MessageCollector,
50
52
  MessageManager: () => MessageManager,
51
- MessagePayload: () => import_builders3.MessagePayload,
53
+ MessagePayload: () => import_builders4.MessagePayload,
52
54
  MessageReaction: () => MessageReaction,
53
- PermissionFlags: () => import_util10.PermissionFlags,
54
- PermissionsBitField: () => import_util10.PermissionsBitField,
55
+ PermissionFlags: () => import_util12.PermissionFlags,
56
+ PermissionsBitField: () => import_util12.PermissionsBitField,
55
57
  ReactionCollector: () => ReactionCollector,
56
58
  Role: () => Role,
57
59
  Routes: () => import_types22.Routes,
58
60
  STATIC_CDN_URL: () => STATIC_CDN_URL,
59
61
  TextChannel: () => TextChannel,
60
62
  User: () => User,
61
- UserFlagsBitField: () => import_util10.UserFlagsBitField,
62
- UserFlagsBits: () => import_util10.UserFlagsBits,
63
+ UserFlagsBitField: () => import_util12.UserFlagsBitField,
64
+ UserFlagsBits: () => import_util12.UserFlagsBits,
63
65
  UsersManager: () => UsersManager,
64
66
  VoiceChannel: () => VoiceChannel,
65
67
  Webhook: () => Webhook,
@@ -69,12 +71,14 @@ __export(index_exports, {
69
71
  cdnDisplayAvatarURL: () => cdnDisplayAvatarURL,
70
72
  cdnMemberAvatarURL: () => cdnMemberAvatarURL,
71
73
  cdnMemberBannerURL: () => cdnMemberBannerURL,
72
- parsePrefixCommand: () => import_util9.parsePrefixCommand,
73
- parseUserMention: () => import_util9.parseUserMention,
74
- resolvePermissionsToBitfield: () => import_util10.resolvePermissionsToBitfield,
75
- resolveTenorToImageUrl: () => import_util9.resolveTenorToImageUrl
74
+ createInteraction: () => createInteraction,
75
+ isChatInputCommandInteraction: () => isChatInputCommandInteraction,
76
+ parsePrefixCommand: () => import_util11.parsePrefixCommand,
77
+ parseUserMention: () => import_util11.parseUserMention,
78
+ resolvePermissionsToBitfield: () => import_util12.resolvePermissionsToBitfield,
79
+ resolveTenorToImageUrl: () => import_util11.resolveTenorToImageUrl
76
80
  });
77
- module.exports = __toCommonJS(index_exports);
81
+ module.exports = __toCommonJS(src_exports);
78
82
 
79
83
  // src/client/Client.ts
80
84
  var import_events3 = require("events");
@@ -85,33 +89,14 @@ var import_types21 = require("@fluxerjs/types");
85
89
  // src/client/ChannelManager.ts
86
90
  var import_collection4 = require("@fluxerjs/collection");
87
91
  var import_types6 = require("@fluxerjs/types");
88
- var import_util3 = require("@fluxerjs/util");
92
+ var import_util5 = require("@fluxerjs/util");
89
93
  var import_rest2 = require("@fluxerjs/rest");
90
94
 
91
95
  // src/errors/FluxerError.ts
92
- var FluxerError = class _FluxerError extends Error {
93
- code;
94
- constructor(message, options) {
95
- super(message, options?.cause ? { cause: options.cause } : void 0);
96
- this.name = "FluxerError";
97
- this.code = options?.code;
98
- Object.setPrototypeOf(this, _FluxerError.prototype);
99
- }
100
- };
96
+ var import_util = require("@fluxerjs/util");
101
97
 
102
98
  // src/errors/ErrorCodes.ts
103
- var ErrorCodes = {
104
- ClientNotReady: "CLIENT_NOT_READY",
105
- InvalidToken: "INVALID_TOKEN",
106
- AlreadyLoggedIn: "ALREADY_LOGGED_IN",
107
- ChannelNotFound: "CHANNEL_NOT_FOUND",
108
- MessageNotFound: "MESSAGE_NOT_FOUND",
109
- GuildNotFound: "GUILD_NOT_FOUND",
110
- MemberNotFound: "MEMBER_NOT_FOUND",
111
- RoleNotFound: "ROLE_NOT_FOUND",
112
- EmojiNotInGuild: "EMOJI_NOT_IN_GUILD",
113
- EmojiNotFound: "EMOJI_NOT_FOUND"
114
- };
99
+ var import_util2 = require("@fluxerjs/util");
115
100
 
116
101
  // src/util/messageUtils.ts
117
102
  var import_builders = require("@fluxerjs/builders");
@@ -123,20 +108,37 @@ async function resolveMessageFiles(files) {
123
108
  const filename = f.filename ?? f.name;
124
109
  if ("url" in f && f.url) {
125
110
  if (!URL.canParse(f.url)) {
126
- throw new Error(`Invalid file URL at index ${i}: ${f.url}`);
111
+ throw new import_util.FluxerError(`Invalid file URL at index ${i}: ${f.url}`, {
112
+ code: import_util2.ErrorCodes.InvalidFileUrl
113
+ });
114
+ }
115
+ let res;
116
+ try {
117
+ res = await fetch(f.url, {
118
+ signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS)
119
+ });
120
+ } catch (err) {
121
+ throw new import_util.FluxerError(`Failed to fetch file from ${f.url}`, {
122
+ code: import_util2.ErrorCodes.FileFetchFailed,
123
+ cause: err instanceof Error ? err : void 0
124
+ });
127
125
  }
128
- const res = await fetch(f.url, {
129
- signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS)
130
- });
131
126
  if (!res.ok) {
132
- throw new Error(`Failed to fetch file from ${f.url}: ${res.status} ${res.statusText}`);
127
+ throw new import_util.FluxerError(
128
+ `Failed to fetch file from ${f.url}: ${res.status} ${res.statusText}`,
129
+ {
130
+ code: import_util2.ErrorCodes.FileFetchFailed
131
+ }
132
+ );
133
133
  }
134
134
  const data = await res.arrayBuffer();
135
135
  result.push({ name: f.name, data, filename });
136
136
  } else if ("data" in f && f.data != null) {
137
137
  result.push({ name: f.name, data: f.data, filename });
138
138
  } else {
139
- throw new Error(`File at index ${i} must have either "data" or "url"`);
139
+ throw new import_util.FluxerError(`File at index ${i} must have either "data" or "url"`, {
140
+ code: import_util2.ErrorCodes.InvalidAttachment
141
+ });
140
142
  }
141
143
  }
142
144
  return result;
@@ -206,6 +208,7 @@ var Events = {
206
208
  GuildMemberAdd: "guildMemberAdd",
207
209
  GuildMemberUpdate: "guildMemberUpdate",
208
210
  GuildMemberRemove: "guildMemberRemove",
211
+ GuildMembersChunk: "guildMembersChunk",
209
212
  GuildRoleCreate: "guildRoleCreate",
210
213
  GuildRoleUpdate: "guildRoleUpdate",
211
214
  GuildRoleDelete: "guildRoleDelete",
@@ -605,12 +608,12 @@ var MessageManager = class {
605
608
  } catch (err) {
606
609
  if (err instanceof import_rest.RateLimitError) throw err;
607
610
  if (err instanceof import_rest.FluxerAPIError && err.statusCode === 404) {
608
- throw new FluxerError(`Message ${messageId} not found in channel ${this.channelId}`, {
609
- code: ErrorCodes.MessageNotFound,
611
+ throw new import_util.FluxerError(`Message ${messageId} not found in channel ${this.channelId}`, {
612
+ code: import_util2.ErrorCodes.MessageNotFound,
610
613
  cause: err
611
614
  });
612
615
  }
613
- throw err instanceof FluxerError ? err : new FluxerError(String(err), { cause: err });
616
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError(String(err), { cause: err });
614
617
  }
615
618
  }
616
619
  };
@@ -669,11 +672,12 @@ var MessageCollector = class extends import_events2.EventEmitter {
669
672
 
670
673
  // src/structures/Channel.ts
671
674
  var import_types5 = require("@fluxerjs/types");
672
- var import_util = require("@fluxerjs/util");
673
- var import_util2 = require("@fluxerjs/util");
675
+ var import_util3 = require("@fluxerjs/util");
676
+ var import_util4 = require("@fluxerjs/util");
674
677
 
675
678
  // src/structures/Webhook.ts
676
679
  var import_types3 = require("@fluxerjs/types");
680
+ var import_builders3 = require("@fluxerjs/builders");
677
681
 
678
682
  // src/util/Constants.ts
679
683
  var CDN_URL = "https://fluxerusercontent.com";
@@ -800,8 +804,9 @@ var Webhook = class _Webhook extends Base {
800
804
  */
801
805
  async send(options, wait) {
802
806
  if (!this.token) {
803
- throw new Error(
804
- "Webhook token is required to send. The token is only returned when creating a webhook; fetched webhooks cannot send."
807
+ throw new import_util.FluxerError(
808
+ "Webhook token is required to send. The token is only returned when creating a webhook; fetched webhooks cannot send.",
809
+ { code: import_util2.ErrorCodes.WebhookTokenRequired }
805
810
  );
806
811
  }
807
812
  const opts = typeof options === "string" ? { content: options } : options;
@@ -818,6 +823,59 @@ var Webhook = class _Webhook extends Base {
818
823
  }
819
824
  return void 0;
820
825
  }
826
+ /**
827
+ * Edit a message previously sent by this webhook.
828
+ * Requires the webhook token.
829
+ */
830
+ async editMessage(messageId, options) {
831
+ if (!this.token) {
832
+ throw new import_util.FluxerError(
833
+ "Webhook token is required to edit messages. The token is only returned when creating a webhook; fetched webhooks cannot edit messages.",
834
+ { code: import_util2.ErrorCodes.WebhookTokenRequired }
835
+ );
836
+ }
837
+ const body = { ...options };
838
+ if (options.embeds !== void 0) {
839
+ body.embeds = options.embeds.map((e) => e instanceof import_builders3.EmbedBuilder ? e.toJSON() : e);
840
+ }
841
+ const data = await this.client.rest.patch(
842
+ import_types3.Routes.webhookMessage(this.id, this.token, messageId),
843
+ { body, auth: false }
844
+ );
845
+ return new Message(this.client, data);
846
+ }
847
+ /**
848
+ * Fetch a message sent by this webhook.
849
+ * Requires the webhook token.
850
+ */
851
+ async fetchMessage(messageId) {
852
+ if (!this.token) {
853
+ throw new import_util.FluxerError(
854
+ "Webhook token is required to fetch messages. The token is only returned when creating a webhook; fetched webhooks cannot fetch messages.",
855
+ { code: import_util2.ErrorCodes.WebhookTokenRequired }
856
+ );
857
+ }
858
+ const data = await this.client.rest.get(
859
+ import_types3.Routes.webhookMessage(this.id, this.token, messageId),
860
+ { auth: false }
861
+ );
862
+ return new Message(this.client, data);
863
+ }
864
+ /**
865
+ * Delete a message sent by this webhook.
866
+ * Requires the webhook token.
867
+ */
868
+ async deleteMessage(messageId) {
869
+ if (!this.token) {
870
+ throw new import_util.FluxerError(
871
+ "Webhook token is required to delete messages. The token is only returned when creating a webhook; fetched webhooks cannot delete messages.",
872
+ { code: import_util2.ErrorCodes.WebhookTokenRequired }
873
+ );
874
+ }
875
+ await this.client.rest.delete(import_types3.Routes.webhookMessage(this.id, this.token, messageId), {
876
+ auth: false
877
+ });
878
+ }
821
879
  /**
822
880
  * Fetch a webhook by ID using bot auth.
823
881
  * @param client - The client instance
@@ -850,7 +908,7 @@ var Webhook = class _Webhook extends Base {
850
908
 
851
909
  // src/structures/Invite.ts
852
910
  var import_types4 = require("@fluxerjs/types");
853
- var Invite = class extends Base {
911
+ var Invite = class _Invite extends Base {
854
912
  client;
855
913
  code;
856
914
  type;
@@ -865,6 +923,41 @@ var Invite = class extends Base {
865
923
  uses;
866
924
  maxUses;
867
925
  maxAge;
926
+ /**
927
+ * Normalize invite input to a raw code (plain code or URL such as https://fluxer.gg/{code}).
928
+ */
929
+ static normalizeCode(codeOrUrl) {
930
+ const input = codeOrUrl.trim();
931
+ if (!input) {
932
+ throw new import_util.FluxerError("Invite code cannot be empty", { code: import_util2.ErrorCodes.InvalidInvite });
933
+ }
934
+ const parseInviteCodeFromUrl = (value) => {
935
+ if (!URL.canParse(value)) return null;
936
+ let url;
937
+ try {
938
+ url = new URL(value);
939
+ } catch {
940
+ return null;
941
+ }
942
+ const segments = url.pathname.split("/").filter(Boolean);
943
+ if (segments.length === 0) return null;
944
+ const inviteSegmentIdx = segments.findIndex((segment) => {
945
+ const lower = segment.toLowerCase();
946
+ return lower === "invite" || lower === "invites";
947
+ });
948
+ const code2 = inviteSegmentIdx >= 0 && segments[inviteSegmentIdx + 1] ? segments[inviteSegmentIdx + 1] : segments[segments.length - 1];
949
+ return decodeURIComponent(code2).trim();
950
+ };
951
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input);
952
+ const fromAbsolute = hasScheme ? parseInviteCodeFromUrl(input) : null;
953
+ const fromHostLike = !hasScheme && URL.canParse(`https://${input}`) ? parseInviteCodeFromUrl(`https://${input}`) : null;
954
+ const directCode = decodeURIComponent(input).trim();
955
+ const code = fromAbsolute ?? fromHostLike ?? directCode;
956
+ if (!code || /[\s/?#]/.test(code)) {
957
+ throw new import_util.FluxerError("Invalid invite code or URL", { code: import_util2.ErrorCodes.InvalidInvite });
958
+ }
959
+ return code;
960
+ }
868
961
  /** @param data - API invite from GET /invites/{code}, channel/guild invite list, or gateway INVITE_CREATE */
869
962
  constructor(client, data) {
870
963
  super();
@@ -883,6 +976,14 @@ var Invite = class extends Base {
883
976
  this.maxUses = data.max_uses ?? null;
884
977
  this.maxAge = data.max_age ?? null;
885
978
  }
979
+ /**
980
+ * Fetch invite metadata by code or URL (does not join the guild).
981
+ */
982
+ static async fetch(client, codeOrUrl) {
983
+ const code = _Invite.normalizeCode(codeOrUrl);
984
+ const data = await client.rest.get(import_types4.Routes.invite(code));
985
+ return new _Invite(client, data);
986
+ }
886
987
  /** Full invite URL (https://fluxer.gg/{code} or instance-specific). */
887
988
  get url() {
888
989
  return `https://fluxer.gg/${this.code}`;
@@ -1086,7 +1187,7 @@ var GuildChannel = class extends Channel {
1086
1187
  const me = guild.members.me;
1087
1188
  if (!me) return false;
1088
1189
  const perms = me.permissionsIn(this);
1089
- return perms.has(import_util.PermissionFlags.ViewChannel) && perms.has(import_util.PermissionFlags.SendMessages);
1190
+ return perms.has(import_util3.PermissionFlags.ViewChannel) && perms.has(import_util3.PermissionFlags.SendMessages);
1090
1191
  }
1091
1192
  /**
1092
1193
  * Send a message to this guild channel.
@@ -1202,7 +1303,7 @@ var TextChannel = class extends GuildChannel {
1202
1303
  * @deprecated Use channel.messages.fetch(messageId) instead.
1203
1304
  */
1204
1305
  async fetchMessage(messageId) {
1205
- (0, import_util2.emitDeprecationWarning)(
1306
+ (0, import_util4.emitDeprecationWarning)(
1206
1307
  "Channel.fetchMessage()",
1207
1308
  "Use channel.messages.fetch(messageId) instead."
1208
1309
  );
@@ -1289,7 +1390,7 @@ var DMChannel = class extends Channel {
1289
1390
  * @deprecated Use channel.messages.fetch(messageId) instead.
1290
1391
  */
1291
1392
  async fetchMessage(messageId) {
1292
- (0, import_util2.emitDeprecationWarning)(
1393
+ (0, import_util4.emitDeprecationWarning)(
1293
1394
  "Channel.fetchMessage()",
1294
1395
  "Use channel.messages.fetch(messageId) instead."
1295
1396
  );
@@ -1361,8 +1462,8 @@ var ChannelManager = class extends import_collection4.Collection {
1361
1462
  const data = await this.client.rest.get(import_types6.Routes.channel(channelId));
1362
1463
  const channel = Channel.fromOrCreate(this.client, data);
1363
1464
  if (!channel) {
1364
- throw new FluxerError("Channel data invalid or unsupported type", {
1365
- code: ErrorCodes.ChannelNotFound
1465
+ throw new import_util.FluxerError("Channel data invalid or unsupported type", {
1466
+ code: import_util2.ErrorCodes.ChannelNotFound
1366
1467
  });
1367
1468
  }
1368
1469
  this.set(channel.id, channel);
@@ -1374,12 +1475,12 @@ var ChannelManager = class extends import_collection4.Collection {
1374
1475
  } catch (err) {
1375
1476
  if (err instanceof import_rest2.RateLimitError) throw err;
1376
1477
  if (err instanceof import_rest2.FluxerAPIError && err.statusCode === 404) {
1377
- throw new FluxerError(`Channel ${channelId} not found`, {
1378
- code: ErrorCodes.ChannelNotFound,
1478
+ throw new import_util.FluxerError(`Channel ${channelId} not found`, {
1479
+ code: import_util2.ErrorCodes.ChannelNotFound,
1379
1480
  cause: err
1380
1481
  });
1381
1482
  }
1382
- throw err instanceof FluxerError ? err : new FluxerError(String(err), { cause: err });
1483
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError(String(err), { cause: err });
1383
1484
  }
1384
1485
  }
1385
1486
  /**
@@ -1394,7 +1495,7 @@ var ChannelManager = class extends import_collection4.Collection {
1394
1495
  * const message = await channel?.messages?.fetch(messageId);
1395
1496
  */
1396
1497
  async fetchMessage(channelId, messageId) {
1397
- (0, import_util3.emitDeprecationWarning)(
1498
+ (0, import_util5.emitDeprecationWarning)(
1398
1499
  "ChannelManager.fetchMessage()",
1399
1500
  "Use channel.messages.fetch(messageId). Prefer (await client.channels.resolve(channelId))?.messages?.fetch(messageId)."
1400
1501
  );
@@ -1406,12 +1507,12 @@ var ChannelManager = class extends import_collection4.Collection {
1406
1507
  } catch (err) {
1407
1508
  if (err instanceof import_rest2.RateLimitError) throw err;
1408
1509
  if (err instanceof import_rest2.FluxerAPIError && err.statusCode === 404) {
1409
- throw new FluxerError(`Message ${messageId} not found in channel ${channelId}`, {
1410
- code: ErrorCodes.MessageNotFound,
1510
+ throw new import_util.FluxerError(`Message ${messageId} not found in channel ${channelId}`, {
1511
+ code: import_util2.ErrorCodes.MessageNotFound,
1411
1512
  cause: err
1412
1513
  });
1413
1514
  }
1414
- throw err instanceof FluxerError ? err : new FluxerError(String(err), { cause: err });
1515
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError(String(err), { cause: err });
1415
1516
  }
1416
1517
  }
1417
1518
  /**
@@ -1441,7 +1542,7 @@ var import_collection8 = require("@fluxerjs/collection");
1441
1542
  var import_types16 = require("@fluxerjs/types");
1442
1543
 
1443
1544
  // src/structures/Guild.ts
1444
- var import_util7 = require("@fluxerjs/util");
1545
+ var import_util9 = require("@fluxerjs/util");
1445
1546
  var import_rest3 = require("@fluxerjs/rest");
1446
1547
  var import_collection7 = require("@fluxerjs/collection");
1447
1548
 
@@ -1450,14 +1551,14 @@ var import_collection6 = require("@fluxerjs/collection");
1450
1551
  var import_types10 = require("@fluxerjs/types");
1451
1552
 
1452
1553
  // src/structures/GuildMember.ts
1453
- var import_util5 = require("@fluxerjs/util");
1554
+ var import_util7 = require("@fluxerjs/util");
1454
1555
  var import_types9 = require("@fluxerjs/types");
1455
1556
 
1456
1557
  // src/util/permissions.ts
1457
1558
  var import_types7 = require("@fluxerjs/types");
1458
- var import_util4 = require("@fluxerjs/util");
1559
+ var import_util6 = require("@fluxerjs/util");
1459
1560
  function computePermissions(basePermissions, overwrites, memberRoles, memberId, isOwner) {
1460
- if (isOwner) return import_util4.ALL_PERMISSIONS_BIGINT;
1561
+ if (isOwner) return import_util6.ALL_PERMISSIONS_BIGINT;
1461
1562
  let perms = basePermissions;
1462
1563
  for (const overwrite of overwrites ?? []) {
1463
1564
  const applies = overwrite.type === import_types7.OverwriteType.Role && memberRoles.includes(overwrite.id) || overwrite.type === import_types7.OverwriteType.Member && overwrite.id === memberId;
@@ -1466,7 +1567,7 @@ function computePermissions(basePermissions, overwrites, memberRoles, memberId,
1466
1567
  const deny = BigInt(overwrite.deny || "0");
1467
1568
  perms = perms & ~deny | allow;
1468
1569
  }
1469
- return (perms & import_util4.PermissionFlags.Administrator) !== 0n ? import_util4.ALL_PERMISSIONS_BIGINT : perms;
1570
+ return (perms & import_util6.PermissionFlags.Administrator) !== 0n ? import_util6.ALL_PERMISSIONS_BIGINT : perms;
1470
1571
  }
1471
1572
 
1472
1573
  // src/structures/GuildMemberRoleManager.ts
@@ -1668,7 +1769,7 @@ var GuildMember = class extends Base {
1668
1769
  const ownerId = this.guild.ownerId;
1669
1770
  const isOwner = ownerId != null && ownerId !== "" && String(ownerId) === String(this.id);
1670
1771
  const perms = computePermissions(base, [], [], this.id, isOwner);
1671
- return new import_util5.BitField(perms);
1772
+ return new import_util7.BitField(perms);
1672
1773
  }
1673
1774
  /**
1674
1775
  * Compute the member's effective permissions in a guild channel.
@@ -1690,7 +1791,7 @@ var GuildMember = class extends Base {
1690
1791
  this.id,
1691
1792
  isOwner
1692
1793
  );
1693
- return new import_util5.BitField(perms);
1794
+ return new import_util7.BitField(perms);
1694
1795
  }
1695
1796
  /**
1696
1797
  * Move this member to a different voice channel or disconnect them from voice.
@@ -1761,7 +1862,7 @@ var GuildMemberManager = class extends import_collection6.Collection {
1761
1862
  * Fetch the current bot user as a GuildMember in this guild.
1762
1863
  * Caches the result in guild.members.
1763
1864
  *
1764
- * @throws Error if client.user is null (client not ready)
1865
+ * @throws FluxerError with CLIENT_NOT_READY if client.user is null
1765
1866
  * @example
1766
1867
  * const me = await guild.members.fetchMe();
1767
1868
  * console.log(me.displayName);
@@ -1769,7 +1870,9 @@ var GuildMemberManager = class extends import_collection6.Collection {
1769
1870
  async fetchMe() {
1770
1871
  const userId = this.guild.client.user?.id;
1771
1872
  if (!userId) {
1772
- throw new Error("Cannot fetch me: client.user is null (client not ready)");
1873
+ throw new import_util.FluxerError("Cannot fetch me: client.user is null (client not ready)", {
1874
+ code: import_util2.ErrorCodes.ClientNotReady
1875
+ });
1773
1876
  }
1774
1877
  return this.guild.fetchMember(userId);
1775
1878
  }
@@ -1802,7 +1905,7 @@ var GuildMemberManager = class extends import_collection6.Collection {
1802
1905
 
1803
1906
  // src/structures/Role.ts
1804
1907
  var import_types11 = require("@fluxerjs/types");
1805
- var import_util6 = require("@fluxerjs/util");
1908
+ var import_util8 = require("@fluxerjs/util");
1806
1909
  var Role = class extends Base {
1807
1910
  client;
1808
1911
  id;
@@ -1835,8 +1938,8 @@ var Role = class extends Base {
1835
1938
  }
1836
1939
  get permissions() {
1837
1940
  const bits = BigInt(this._permissions);
1838
- return new import_util6.PermissionsBitField(
1839
- (bits & import_util6.PermissionFlags.Administrator) !== 0n ? import_util6.ALL_PERMISSIONS_BIGINT : bits
1941
+ return new import_util8.PermissionsBitField(
1942
+ (bits & import_util8.PermissionFlags.Administrator) !== 0n ? import_util8.ALL_PERMISSIONS_BIGINT : bits
1840
1943
  );
1841
1944
  }
1842
1945
  /** Update mutable fields from fresh API data. Used by edit and gateway events. */
@@ -1866,7 +1969,7 @@ var Role = class extends Base {
1866
1969
  const body = {};
1867
1970
  if (options.name !== void 0) body.name = options.name;
1868
1971
  if (options.permissions !== void 0) {
1869
- body.permissions = typeof options.permissions === "string" ? options.permissions : (0, import_util6.resolvePermissionsToBitfield)(options.permissions);
1972
+ body.permissions = typeof options.permissions === "string" ? options.permissions : (0, import_util8.resolvePermissionsToBitfield)(options.permissions);
1870
1973
  }
1871
1974
  if (options.color !== void 0) body.color = options.color;
1872
1975
  if (options.hoist !== void 0) body.hoist = options.hoist;
@@ -2059,6 +2162,7 @@ var Guild = class extends Base {
2059
2162
  channels = new import_collection7.Collection();
2060
2163
  roles = new import_collection7.Collection();
2061
2164
  emojis = new import_collection7.Collection();
2165
+ stickers = new import_collection7.Collection();
2062
2166
  /** @param data - API guild from GET /guilds/{id} or gateway GUILD_CREATE */
2063
2167
  constructor(client, data) {
2064
2168
  super();
@@ -2137,7 +2241,7 @@ var Guild = class extends Base {
2137
2241
  const body = {};
2138
2242
  if (options.name !== void 0) body.name = options.name;
2139
2243
  if (options.permissions !== void 0) {
2140
- body.permissions = typeof options.permissions === "string" ? options.permissions : (0, import_util7.resolvePermissionsToBitfield)(options.permissions);
2244
+ body.permissions = typeof options.permissions === "string" ? options.permissions : (0, import_util9.resolvePermissionsToBitfield)(options.permissions);
2141
2245
  }
2142
2246
  if (options.color !== void 0) body.color = options.color;
2143
2247
  if (options.hoist !== void 0) body.hoist = options.hoist;
@@ -2185,12 +2289,12 @@ var Guild = class extends Base {
2185
2289
  } catch (err) {
2186
2290
  const statusCode = err instanceof import_rest3.FluxerAPIError ? err.statusCode : err?.statusCode;
2187
2291
  if (statusCode === 404) {
2188
- throw new FluxerError(`Role ${roleId} not found in guild`, {
2189
- code: ErrorCodes.RoleNotFound,
2292
+ throw new import_util.FluxerError(`Role ${roleId} not found in guild`, {
2293
+ code: import_util2.ErrorCodes.RoleNotFound,
2190
2294
  cause: err
2191
2295
  });
2192
2296
  }
2193
- throw err instanceof FluxerError ? err : new FluxerError("Failed to fetch guild role", { cause: err });
2297
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError("Failed to fetch guild role", { cause: err });
2194
2298
  }
2195
2299
  }
2196
2300
  /**
@@ -2200,7 +2304,7 @@ var Guild = class extends Base {
2200
2304
  * @returns The role ID, or null if not found
2201
2305
  */
2202
2306
  async resolveRoleId(arg) {
2203
- const parsed = (0, import_util7.parseRoleMention)(arg);
2307
+ const parsed = (0, import_util9.parseRoleMention)(arg);
2204
2308
  if (parsed) return parsed;
2205
2309
  if (/^\d{17,19}$/.test(arg.trim())) return arg.trim();
2206
2310
  const cached = this.roles.find(
@@ -2280,12 +2384,12 @@ var Guild = class extends Base {
2280
2384
  } catch (err) {
2281
2385
  const statusCode = err instanceof import_rest3.FluxerAPIError ? err.statusCode : err?.statusCode;
2282
2386
  if (statusCode === 404) {
2283
- throw new FluxerError(`Member ${userId} not found in guild`, {
2284
- code: ErrorCodes.MemberNotFound,
2387
+ throw new import_util.FluxerError(`Member ${userId} not found in guild`, {
2388
+ code: import_util2.ErrorCodes.MemberNotFound,
2285
2389
  cause: err
2286
2390
  });
2287
2391
  }
2288
- throw err instanceof FluxerError ? err : new FluxerError("Failed to fetch guild member", { cause: err });
2392
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError("Failed to fetch guild member", { cause: err });
2289
2393
  }
2290
2394
  }
2291
2395
  /**
@@ -2309,6 +2413,24 @@ var Guild = class extends Base {
2309
2413
  const list = Array.isArray(data) ? data : Object.values(data ?? {});
2310
2414
  return list.map((w) => new Webhook(this.client, w));
2311
2415
  }
2416
+ /**
2417
+ * Fetch all invites in this guild.
2418
+ * Requires Manage Guild permission.
2419
+ */
2420
+ async fetchInvites() {
2421
+ const data = await this.client.rest.get(
2422
+ import_types15.Routes.guildInvites(this.id)
2423
+ );
2424
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2425
+ return list.map((invite) => new Invite(this.client, invite));
2426
+ }
2427
+ /**
2428
+ * Fetch a guild invite by code or URL.
2429
+ * @see Invite.fetch
2430
+ */
2431
+ async fetchInvite(codeOrUrl) {
2432
+ return Invite.fetch(this.client, codeOrUrl);
2433
+ }
2312
2434
  /**
2313
2435
  * Create a channel in this guild.
2314
2436
  * @param data - Channel data: type (0=text, 2=voice, 4=category, 5=link), name, and optional parent_id, topic, bitrate, user_limit, nsfw, permission_overwrites
@@ -2505,12 +2627,12 @@ var Guild = class extends Base {
2505
2627
  } catch (err) {
2506
2628
  const statusCode = err instanceof import_rest3.FluxerAPIError ? err.statusCode : err?.statusCode;
2507
2629
  if (statusCode === 404) {
2508
- throw new FluxerError(`Emoji ${emojiId} not found in guild`, {
2509
- code: ErrorCodes.EmojiNotFound,
2630
+ throw new import_util.FluxerError(`Emoji ${emojiId} not found in guild`, {
2631
+ code: import_util2.ErrorCodes.EmojiNotFound,
2510
2632
  cause: err
2511
2633
  });
2512
2634
  }
2513
- throw err instanceof FluxerError ? err : new FluxerError("Failed to fetch guild emoji", { cause: err });
2635
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError("Failed to fetch guild emoji", { cause: err });
2514
2636
  }
2515
2637
  }
2516
2638
  /**
@@ -2543,7 +2665,39 @@ var Guild = class extends Base {
2543
2665
  }
2544
2666
  );
2545
2667
  const list = Array.isArray(data) ? data : data?.stickers ?? [];
2546
- return list.map((s) => new GuildSticker(this.client, { ...s, guild_id: this.id }, this.id));
2668
+ const created = list.map(
2669
+ (s) => new GuildSticker(this.client, { ...s, guild_id: this.id }, this.id)
2670
+ );
2671
+ for (const sticker of created) {
2672
+ this.stickers.set(sticker.id, sticker);
2673
+ }
2674
+ return created;
2675
+ }
2676
+ /**
2677
+ * Fetch all stickers in this guild.
2678
+ * @returns GuildSticker instances (cached on guild.stickers)
2679
+ */
2680
+ async fetchStickers() {
2681
+ const data = await this.client.rest.get(
2682
+ import_types15.Routes.guildStickers(this.id)
2683
+ );
2684
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2685
+ const stickers = [];
2686
+ for (const s of list) {
2687
+ const sticker = new GuildSticker(this.client, { ...s, guild_id: this.id }, this.id);
2688
+ this.stickers.set(sticker.id, sticker);
2689
+ stickers.push(sticker);
2690
+ }
2691
+ return stickers;
2692
+ }
2693
+ /**
2694
+ * Fetch a single guild sticker by ID.
2695
+ */
2696
+ async fetchSticker(stickerId) {
2697
+ const data = await this.client.rest.get(import_types15.Routes.guildSticker(this.id, stickerId));
2698
+ const sticker = new GuildSticker(this.client, { ...data, guild_id: this.id }, this.id);
2699
+ this.stickers.set(sticker.id, sticker);
2700
+ return sticker;
2547
2701
  }
2548
2702
  };
2549
2703
 
@@ -2737,7 +2891,7 @@ var ClientUser = class extends User {
2737
2891
  };
2738
2892
 
2739
2893
  // src/client/Client.ts
2740
- var import_util8 = require("@fluxerjs/util");
2894
+ var import_util10 = require("@fluxerjs/util");
2741
2895
 
2742
2896
  // src/client/UsersManager.ts
2743
2897
  var import_collection9 = require("@fluxerjs/collection");
@@ -2814,6 +2968,156 @@ var UsersManager = class extends import_collection9.Collection {
2814
2968
  }
2815
2969
  };
2816
2970
 
2971
+ // src/structures/interactions/BaseInteraction.ts
2972
+ var BaseInteraction = class {
2973
+ constructor(client, raw) {
2974
+ this.client = client;
2975
+ this.raw = raw;
2976
+ }
2977
+ get id() {
2978
+ return this.raw.id;
2979
+ }
2980
+ get applicationId() {
2981
+ return this.raw.application_id;
2982
+ }
2983
+ get token() {
2984
+ return this.raw.token;
2985
+ }
2986
+ get type() {
2987
+ return this.raw.type;
2988
+ }
2989
+ get channelId() {
2990
+ return this.raw.channel_id;
2991
+ }
2992
+ get guildId() {
2993
+ return this.raw.guild_id;
2994
+ }
2995
+ };
2996
+
2997
+ // src/structures/interactions/ChatInputCommandInteraction.ts
2998
+ var CommandOptionType = {
2999
+ SubCommand: 1,
3000
+ SubCommandGroup: 2,
3001
+ String: 3,
3002
+ Integer: 4,
3003
+ Boolean: 5,
3004
+ Number: 10
3005
+ };
3006
+ function findOptionDeep(options, name) {
3007
+ if (!options?.length) return void 0;
3008
+ for (const o of options) {
3009
+ if (o.name === name && o.value !== void 0) return o;
3010
+ const nested = findOptionDeep(o.options, name);
3011
+ if (nested) return nested;
3012
+ }
3013
+ return void 0;
3014
+ }
3015
+ var ChatInputCommandInteraction = class extends BaseInteraction {
3016
+ constructor(client, raw) {
3017
+ super(client, raw);
3018
+ if (raw.data?.name == null) {
3019
+ throw new import_util.FluxerError(
3020
+ "ChatInputCommandInteraction requires interaction data with a command name",
3021
+ {
3022
+ code: import_util2.ErrorCodes.InteractionInvalidPayload
3023
+ }
3024
+ );
3025
+ }
3026
+ }
3027
+ /** Command name (e.g. `ping`). */
3028
+ get commandName() {
3029
+ return this.raw.data.name;
3030
+ }
3031
+ /** Resolved option leaf by name (searches nested subcommand options). */
3032
+ getOption(name) {
3033
+ const opt = findOptionDeep(this.raw.data?.options, name);
3034
+ if (!opt) {
3035
+ throw new import_util.FluxerError(`Interaction option "${name}" was not provided`, {
3036
+ code: import_util2.ErrorCodes.InteractionOptionNotFound
3037
+ });
3038
+ }
3039
+ return opt;
3040
+ }
3041
+ getString(name) {
3042
+ const o = this.getOption(name);
3043
+ if (o.type !== CommandOptionType.String) {
3044
+ throw new import_util.FluxerError(`Option "${name}" is not a string`, {
3045
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3046
+ });
3047
+ }
3048
+ return String(o.value);
3049
+ }
3050
+ getInteger(name) {
3051
+ const o = this.getOption(name);
3052
+ if (o.type !== CommandOptionType.Integer) {
3053
+ throw new import_util.FluxerError(`Option "${name}" is not an integer`, {
3054
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3055
+ });
3056
+ }
3057
+ const v = o.value;
3058
+ if (typeof v !== "number" || !Number.isInteger(v)) {
3059
+ throw new import_util.FluxerError(`Option "${name}" has invalid integer value`, {
3060
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3061
+ });
3062
+ }
3063
+ return v;
3064
+ }
3065
+ getNumber(name) {
3066
+ const o = this.getOption(name);
3067
+ if (o.type !== CommandOptionType.Number && o.type !== CommandOptionType.Integer) {
3068
+ throw new import_util.FluxerError(`Option "${name}" is not a number`, {
3069
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3070
+ });
3071
+ }
3072
+ const v = o.value;
3073
+ if (typeof v !== "number") {
3074
+ throw new import_util.FluxerError(`Option "${name}" has invalid number value`, {
3075
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3076
+ });
3077
+ }
3078
+ return v;
3079
+ }
3080
+ getBoolean(name) {
3081
+ const o = this.getOption(name);
3082
+ if (o.type !== CommandOptionType.Boolean) {
3083
+ throw new import_util.FluxerError(`Option "${name}" is not a boolean`, {
3084
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3085
+ });
3086
+ }
3087
+ if (typeof o.value !== "boolean") {
3088
+ throw new import_util.FluxerError(`Option "${name}" has invalid boolean value`, {
3089
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3090
+ });
3091
+ }
3092
+ return o.value;
3093
+ }
3094
+ /** Name of the invoked subcommand (when using subcommands). */
3095
+ getSubcommand(fallback) {
3096
+ const opts = this.raw.data?.options;
3097
+ const first = opts?.[0];
3098
+ if (first?.type === CommandOptionType.SubCommand) return first.name;
3099
+ if (first?.type === CommandOptionType.SubCommandGroup) {
3100
+ const inner = first.options?.[0];
3101
+ if (inner?.type === CommandOptionType.SubCommand) return inner.name;
3102
+ }
3103
+ if (fallback !== void 0) return fallback;
3104
+ throw new import_util.FluxerError("No subcommand in this interaction", {
3105
+ code: import_util2.ErrorCodes.InteractionOptionNotFound
3106
+ });
3107
+ }
3108
+ };
3109
+
3110
+ // src/structures/interactions/createInteraction.ts
3111
+ function createInteraction(client, data) {
3112
+ if (data.data?.name != null) {
3113
+ return new ChatInputCommandInteraction(client, data);
3114
+ }
3115
+ return new BaseInteraction(client, data);
3116
+ }
3117
+ function isChatInputCommandInteraction(interaction) {
3118
+ return interaction instanceof ChatInputCommandInteraction;
3119
+ }
3120
+
2817
3121
  // src/util/guildUtils.ts
2818
3122
  function normalizeGuildPayload(raw) {
2819
3123
  if (!raw || typeof raw !== "object") {
@@ -2871,18 +3175,54 @@ var MessageReaction = class extends Base {
2871
3175
  } catch (err) {
2872
3176
  if (err instanceof import_rest4.RateLimitError) throw err;
2873
3177
  if (err instanceof import_rest4.FluxerAPIError && err.statusCode === 404) {
2874
- throw new FluxerError(`Message ${this.messageId} not found in channel ${this.channelId}`, {
2875
- code: ErrorCodes.MessageNotFound,
3178
+ throw new import_util.FluxerError(`Message ${this.messageId} not found in channel ${this.channelId}`, {
3179
+ code: import_util2.ErrorCodes.MessageNotFound,
2876
3180
  cause: err
2877
3181
  });
2878
3182
  }
2879
- throw err instanceof FluxerError ? err : new FluxerError(String(err), { cause: err });
3183
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError(String(err), { cause: err });
2880
3184
  }
2881
3185
  }
2882
3186
  };
2883
3187
 
2884
3188
  // src/client/EventHandlerRegistry.ts
2885
3189
  var handlers = /* @__PURE__ */ new Map();
3190
+ function normalizeInviteCreatePayload(client, payload) {
3191
+ if (!payload?.code) return null;
3192
+ const guildId = payload.guild?.id ?? payload.guild_id ?? "0";
3193
+ const cachedGuild = guildId !== "0" ? client.guilds.get(guildId) : null;
3194
+ const guild = {
3195
+ id: guildId,
3196
+ name: payload.guild?.name ?? cachedGuild?.name ?? "Unknown Guild",
3197
+ icon: payload.guild?.icon ?? null,
3198
+ banner: payload.guild?.banner ?? null,
3199
+ splash: payload.guild?.splash ?? null,
3200
+ features: payload.guild?.features
3201
+ };
3202
+ const channelId = payload.channel?.id ?? payload.channel_id ?? "0";
3203
+ const cachedChannel = channelId !== "0" ? client.channels.get(channelId) : null;
3204
+ const channel = {
3205
+ id: channelId,
3206
+ type: payload.channel?.type ?? cachedChannel?.type ?? 0,
3207
+ name: payload.channel?.name ?? cachedChannel?.name ?? null,
3208
+ icon: payload.channel?.icon ?? null
3209
+ };
3210
+ return {
3211
+ code: payload.code,
3212
+ type: typeof payload.type === "number" ? payload.type : 0,
3213
+ guild,
3214
+ channel,
3215
+ inviter: payload.inviter ?? null,
3216
+ member_count: payload.member_count,
3217
+ presence_count: payload.presence_count,
3218
+ expires_at: payload.expires_at,
3219
+ temporary: payload.temporary,
3220
+ created_at: payload.created_at,
3221
+ uses: payload.uses,
3222
+ max_uses: payload.max_uses,
3223
+ max_age: payload.max_age
3224
+ };
3225
+ }
2886
3226
  handlers.set("MESSAGE_CREATE", async (client, d) => {
2887
3227
  const data = d;
2888
3228
  if (data.guild_id && data.member && data.author) {
@@ -3074,8 +3414,25 @@ handlers.set("GUILD_MEMBER_REMOVE", async (client, d) => {
3074
3414
  }
3075
3415
  client.emit(Events.GuildMemberRemove, member);
3076
3416
  });
3417
+ handlers.set("GUILD_MEMBERS_CHUNK", async (client, d) => {
3418
+ const data = d;
3419
+ const guild = client.guilds.get(data.guild_id);
3420
+ if (guild) {
3421
+ for (const m of data.members ?? []) {
3422
+ if (m?.user?.id) {
3423
+ const memberData = { ...m, guild_id: guild.id };
3424
+ const member = new GuildMember(client, memberData, guild);
3425
+ guild.members.set(member.id, member);
3426
+ }
3427
+ }
3428
+ }
3429
+ client.emit(Events.GuildMembersChunk, data);
3430
+ });
3077
3431
  handlers.set("INTERACTION_CREATE", async (client, d) => {
3078
- client.emit(Events.InteractionCreate, d);
3432
+ client.emit(
3433
+ Events.InteractionCreate,
3434
+ createInteraction(client, d)
3435
+ );
3079
3436
  });
3080
3437
  handlers.set("VOICE_STATE_UPDATE", async (client, d) => {
3081
3438
  client.emit(Events.VoiceStateUpdate, d);
@@ -3170,7 +3527,14 @@ handlers.set("CHANNEL_PINS_UPDATE", async (client, d) => {
3170
3527
  client.emit(Events.ChannelPinsUpdate, d);
3171
3528
  });
3172
3529
  handlers.set("INVITE_CREATE", async (client, d) => {
3173
- const data = d;
3530
+ const data = normalizeInviteCreatePayload(client, d);
3531
+ if (!data) {
3532
+ client.emit(
3533
+ Events.Debug,
3534
+ "[Gateway] INVITE_CREATE payload had no invite code (documented as possibly empty)"
3535
+ );
3536
+ return;
3537
+ }
3174
3538
  client.emit(Events.InviteCreate, new Invite(client, data));
3175
3539
  });
3176
3540
  handlers.set("INVITE_DELETE", async (client, d) => {
@@ -3214,6 +3578,7 @@ var Client = class extends import_events3.EventEmitter {
3214
3578
  constructor(options = {}) {
3215
3579
  super();
3216
3580
  this.options = options;
3581
+ this.setMaxListeners(0);
3217
3582
  this.events = createEventMethods(this);
3218
3583
  Object.defineProperty(this.channels, "cache", {
3219
3584
  get: () => this.channels,
@@ -3248,8 +3613,25 @@ var Client = class extends import_events3.EventEmitter {
3248
3613
  _pendingGuildIds = null;
3249
3614
  /** Timeout for guild stream when READY has no guilds (gateway sends only GUILD_CREATE). Cleared in finally. */
3250
3615
  _guildStreamSettleTimeout = null;
3616
+ /**
3617
+ * When waitForGuilds delays Ready, gateway dispatches (except GUILD_CREATE) are queued and replayed after Ready.
3618
+ * Ensures user handlers that assume post-Ready setup (e.g. DB in Ready) do not run during the guild sync window.
3619
+ */
3620
+ _deferredGatewayDispatches = [];
3251
3621
  /** Per-channel message cache (channelId -> messageId -> APIMessage). Used when options.cache.messages > 0. */
3252
3622
  _messageCaches = null;
3623
+ on(event, listener) {
3624
+ return super.on(event, listener);
3625
+ }
3626
+ once(event, listener) {
3627
+ return super.once(event, listener);
3628
+ }
3629
+ off(event, listener) {
3630
+ return super.off(event, listener);
3631
+ }
3632
+ emit(event, ...args) {
3633
+ return super.emit(event, ...args);
3634
+ }
3253
3635
  /**
3254
3636
  * Resolve an emoji argument to the API format (unicode or "name:id").
3255
3637
  * Supports: <:name:id>, :name:, name:id, { name, id }, unicode.
@@ -3264,33 +3646,37 @@ var Client = class extends import_events3.EventEmitter {
3264
3646
  if (guildId) {
3265
3647
  await this.assertEmojiInGuild(emoji.id, guildId);
3266
3648
  }
3267
- return (0, import_util8.formatEmoji)({ name: emoji.name, id: emoji.id, animated: emoji.animated });
3649
+ return (0, import_util10.formatEmoji)({ name: emoji.name, id: emoji.id, animated: emoji.animated });
3268
3650
  }
3269
- const parsed = (0, import_util8.parseEmoji)(
3651
+ const parsed = (0, import_util10.parseEmoji)(
3270
3652
  typeof emoji === "string" ? emoji : emoji.id ? `:${emoji.name}:` : emoji.name
3271
3653
  );
3272
- if (!parsed) throw new Error("Invalid emoji");
3654
+ if (!parsed) {
3655
+ throw new import_util.FluxerError("Invalid emoji", { code: import_util2.ErrorCodes.InvalidEmoji });
3656
+ }
3273
3657
  if (parsed.id) {
3274
3658
  if (guildId) {
3275
3659
  await this.assertEmojiInGuild(parsed.id, guildId);
3276
3660
  }
3277
- return (0, import_util8.formatEmoji)(parsed);
3661
+ return (0, import_util10.formatEmoji)(parsed);
3278
3662
  }
3279
3663
  if (!/^\w+$/.test(parsed.name)) return parsed.name;
3280
- const unicodeFromShortcode = (0, import_util8.getUnicodeFromShortcode)(parsed.name);
3664
+ const unicodeFromShortcode = (0, import_util10.getUnicodeFromShortcode)(parsed.name);
3281
3665
  if (unicodeFromShortcode) return unicodeFromShortcode;
3282
3666
  if (guildId) {
3283
3667
  const emojis = await this.rest.get(import_types21.Routes.guildEmojis(guildId));
3284
3668
  const list = Array.isArray(emojis) ? emojis : Object.values(emojis ?? {});
3285
3669
  const found = list.find((e) => e.name && e.name.toLowerCase() === parsed.name.toLowerCase());
3286
- if (found) return (0, import_util8.formatEmoji)({ ...parsed, id: found.id, animated: found.animated });
3287
- throw new Error(
3288
- `Custom emoji ":${parsed.name}:" not found in guild. Use name:id or <:name:id> format.`
3670
+ if (found) return (0, import_util10.formatEmoji)({ ...parsed, id: found.id, animated: found.animated });
3671
+ throw new import_util.FluxerError(
3672
+ `Custom emoji ":${parsed.name}:" not found in guild. Use name:id or <:name:id> format.`,
3673
+ { code: import_util2.ErrorCodes.EmojiNotFound }
3289
3674
  );
3290
3675
  }
3291
3676
  if (/^\w+$/.test(parsed.name)) {
3292
- throw new Error(
3293
- `Custom emoji ":${parsed.name}:" requires guild context. Use message.react() in a guild channel, or pass guildId to client.resolveEmoji().`
3677
+ throw new import_util.FluxerError(
3678
+ `Custom emoji ":${parsed.name}:" requires guild context. Use message.react() in a guild channel, or pass guildId to client.resolveEmoji().`,
3679
+ { code: import_util2.ErrorCodes.EmojiRequiresGuild }
3294
3680
  );
3295
3681
  }
3296
3682
  return parsed.name;
@@ -3305,8 +3691,8 @@ var Client = class extends import_events3.EventEmitter {
3305
3691
  const list = Array.isArray(emojis) ? emojis : Object.values(emojis ?? {});
3306
3692
  const found = list.some((e) => e.id === emojiId);
3307
3693
  if (!found) {
3308
- throw new FluxerError("Custom emoji is from another server. Use an emoji from this server.", {
3309
- code: ErrorCodes.EmojiNotInGuild
3694
+ throw new import_util.FluxerError("Custom emoji is from another server. Use an emoji from this server.", {
3695
+ code: import_util2.ErrorCodes.EmojiNotInGuild
3310
3696
  });
3311
3697
  }
3312
3698
  }
@@ -3317,6 +3703,20 @@ var Client = class extends import_events3.EventEmitter {
3317
3703
  async fetchInstance() {
3318
3704
  return this.rest.get(import_types21.Routes.instance(), { auth: false });
3319
3705
  }
3706
+ /**
3707
+ * Fetch instance discovery document (API URL, gateway URL, features). GET /.well-known/fluxer.
3708
+ * Does not require authentication.
3709
+ */
3710
+ async fetchInstanceDiscovery() {
3711
+ return this.rest.get(import_types21.Routes.instanceDiscovery(), { auth: false });
3712
+ }
3713
+ /**
3714
+ * Fetch gateway connection metadata (WebSocket URL, recommended shards, session limits).
3715
+ * GET /gateway/bot (authenticated).
3716
+ */
3717
+ async fetchGatewayInfo() {
3718
+ return this.rest.get(import_types21.Routes.gatewayBot());
3719
+ }
3320
3720
  /**
3321
3721
  * Fetch a message by channel and message ID. Use when you have IDs (e.g. from a DB).
3322
3722
  * @param channelId - Snowflake of the channel
@@ -3329,7 +3729,7 @@ var Client = class extends import_events3.EventEmitter {
3329
3729
  * const message = await channel?.messages?.fetch(messageId);
3330
3730
  */
3331
3731
  async fetchMessage(channelId, messageId) {
3332
- (0, import_util8.emitDeprecationWarning)(
3732
+ (0, import_util10.emitDeprecationWarning)(
3333
3733
  "Client.fetchMessage()",
3334
3734
  "Use channel.messages.fetch(messageId). For IDs-only: (await client.channels.resolve(channelId))?.messages?.fetch(messageId)"
3335
3735
  );
@@ -3341,7 +3741,7 @@ var Client = class extends import_events3.EventEmitter {
3341
3741
  * @deprecated Use client.channels.send(channelId, payload).
3342
3742
  */
3343
3743
  async sendToChannel(channelId, payload) {
3344
- (0, import_util8.emitDeprecationWarning)(
3744
+ (0, import_util10.emitDeprecationWarning)(
3345
3745
  "Client.sendToChannel()",
3346
3746
  "Use client.channels.send(channelId, payload)."
3347
3747
  );
@@ -3400,7 +3800,11 @@ var Client = class extends import_events3.EventEmitter {
3400
3800
  }
3401
3801
  /** WebSocket manager. Throws if not logged in. */
3402
3802
  get ws() {
3403
- if (!this._ws) throw new Error("Client is not logged in");
3803
+ if (!this._ws) {
3804
+ throw new import_util.FluxerError("Client is not logged in. Call login() first.", {
3805
+ code: import_util2.ErrorCodes.NotLoggedIn
3806
+ });
3807
+ }
3404
3808
  return this._ws;
3405
3809
  }
3406
3810
  /**
@@ -3411,14 +3815,62 @@ var Client = class extends import_events3.EventEmitter {
3411
3815
  sendToGateway(shardId, payload) {
3412
3816
  this.ws.send(shardId, payload);
3413
3817
  }
3414
- async handleDispatch(payload) {
3415
- if (payload.op !== 0 || !payload.t) return;
3416
- const { t: event, d } = payload;
3417
- try {
3418
- const handler = eventHandlers.get(event);
3419
- if (handler) await handler(this, d);
3420
- } catch (err) {
3421
- this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)));
3818
+ /**
3819
+ * While {@link ClientOptions.waitForGuilds} delays Ready, defer user-facing dispatch handling until Ready fires.
3820
+ * GUILD_CREATE must still run immediately so guild cache and {@link Client._onGuildReceived} can finish the handshake.
3821
+ */
3822
+ _shouldDeferGatewayDispatchUntilReady(payload) {
3823
+ if (this.options.waitForGuilds !== true || this.readyAt !== null) return false;
3824
+ if (payload.op !== 0 || !payload.t) return false;
3825
+ if (payload.t === "GUILD_CREATE") return false;
3826
+ return true;
3827
+ }
3828
+ /**
3829
+ * Run gateway event handlers. By default (see {@link ClientOptions.gatewayDeferHandlers}) work is deferred to the next
3830
+ * macrotask so user code does not block the WebSocket `message` callback.
3831
+ */
3832
+ handleDispatch(payload) {
3833
+ if (payload.op !== 0 || !payload.t) return Promise.resolve();
3834
+ if (this._shouldDeferGatewayDispatchUntilReady(payload)) {
3835
+ this._deferredGatewayDispatches.push(payload);
3836
+ return Promise.resolve();
3837
+ }
3838
+ return this._dispatchGatewayPayload(payload);
3839
+ }
3840
+ _dispatchGatewayPayload(payload) {
3841
+ const event = payload.t;
3842
+ if (!event) return Promise.resolve();
3843
+ const { d } = payload;
3844
+ const handler = eventHandlers.get(event);
3845
+ if (!handler) return Promise.resolve();
3846
+ const run = async () => {
3847
+ try {
3848
+ await handler(this, d);
3849
+ } catch (err) {
3850
+ this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)));
3851
+ }
3852
+ };
3853
+ if (this.options.gatewayDeferHandlers === false) {
3854
+ return run();
3855
+ }
3856
+ return new Promise((resolve, reject) => {
3857
+ const start = () => {
3858
+ void run().then(resolve).catch(reject);
3859
+ };
3860
+ if (typeof setImmediate === "function") {
3861
+ setImmediate(start);
3862
+ } else {
3863
+ setTimeout(start, 0);
3864
+ }
3865
+ });
3866
+ }
3867
+ async _flushDeferredGatewayDispatches() {
3868
+ while (this._deferredGatewayDispatches.length > 0) {
3869
+ const batch = this._deferredGatewayDispatches;
3870
+ this._deferredGatewayDispatches = [];
3871
+ for (const p of batch) {
3872
+ await this._dispatchGatewayPayload(p);
3873
+ }
3422
3874
  }
3423
3875
  }
3424
3876
  /**
@@ -3427,8 +3879,8 @@ var Client = class extends import_events3.EventEmitter {
3427
3879
  */
3428
3880
  async login(token) {
3429
3881
  if (this._ws) {
3430
- throw new FluxerError("Client is already logged in. Call destroy() first.", {
3431
- code: ErrorCodes.AlreadyLoggedIn
3882
+ throw new import_util.FluxerError("Client is already logged in. Call destroy() first.", {
3883
+ code: import_util2.ErrorCodes.AlreadyLoggedIn
3432
3884
  });
3433
3885
  }
3434
3886
  this.rest.setToken(token);
@@ -3451,6 +3903,7 @@ var Client = class extends import_events3.EventEmitter {
3451
3903
  presence: this.options.presence,
3452
3904
  rest: { get: (route) => this.rest.get(route) },
3453
3905
  version: this.options.rest?.version ?? "1",
3906
+ debug: this.options.gatewayDebug !== false,
3454
3907
  WebSocket: this.options.WebSocket
3455
3908
  });
3456
3909
  this._ws.on("dispatch", ({ payload }) => {
@@ -3518,6 +3971,9 @@ var Client = class extends import_events3.EventEmitter {
3518
3971
  this._pendingGuildIds = null;
3519
3972
  this.readyAt = /* @__PURE__ */ new Date();
3520
3973
  this.emit(Events.Ready);
3974
+ void this._flushDeferredGatewayDispatches().catch(
3975
+ (err) => this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)))
3976
+ );
3521
3977
  }
3522
3978
  /**
3523
3979
  * Called by GUILD_CREATE handler when waitForGuilds is enabled.
@@ -3535,6 +3991,7 @@ var Client = class extends import_events3.EventEmitter {
3535
3991
  clearTimeout(this._guildStreamSettleTimeout);
3536
3992
  this._guildStreamSettleTimeout = null;
3537
3993
  }
3994
+ this._deferredGatewayDispatches = [];
3538
3995
  if (this._ws) {
3539
3996
  this._ws.destroy();
3540
3997
  this._ws = null;
@@ -3557,10 +4014,10 @@ var Client = class extends import_events3.EventEmitter {
3557
4014
  */
3558
4015
  assertReady() {
3559
4016
  if (!this.isReady()) {
3560
- throw new FluxerError(
4017
+ throw new import_util.FluxerError(
3561
4018
  "Client is not ready yet. Wait for the Ready event before accessing client.user.",
3562
4019
  {
3563
- code: ErrorCodes.ClientNotReady
4020
+ code: import_util2.ErrorCodes.ClientNotReady
3564
4021
  }
3565
4022
  );
3566
4023
  }
@@ -3571,18 +4028,20 @@ var Client = class extends import_events3.EventEmitter {
3571
4028
  };
3572
4029
 
3573
4030
  // src/index.ts
3574
- var import_builders3 = require("@fluxerjs/builders");
4031
+ var import_builders4 = require("@fluxerjs/builders");
3575
4032
  var import_types22 = require("@fluxerjs/types");
3576
- var import_util9 = require("@fluxerjs/util");
3577
- var import_util10 = require("@fluxerjs/util");
4033
+ var import_util11 = require("@fluxerjs/util");
4034
+ var import_util12 = require("@fluxerjs/util");
3578
4035
  // Annotate the CommonJS export names for ESM import in node:
3579
4036
  0 && (module.exports = {
3580
4037
  AttachmentBuilder,
3581
4038
  Base,
4039
+ BaseInteraction,
3582
4040
  CDN_URL,
3583
4041
  CategoryChannel,
3584
4042
  Channel,
3585
4043
  ChannelManager,
4044
+ ChatInputCommandInteraction,
3586
4045
  Client,
3587
4046
  ClientUser,
3588
4047
  DMChannel,
@@ -3626,6 +4085,8 @@ var import_util10 = require("@fluxerjs/util");
3626
4085
  cdnDisplayAvatarURL,
3627
4086
  cdnMemberAvatarURL,
3628
4087
  cdnMemberBannerURL,
4088
+ createInteraction,
4089
+ isChatInputCommandInteraction,
3629
4090
  parsePrefixCommand,
3630
4091
  parseUserMention,
3631
4092
  resolvePermissionsToBitfield,