@fluxerjs/core 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -13,29 +13,10 @@ import { emitDeprecationWarning as emitDeprecationWarning2 } from "@fluxerjs/uti
13
13
  import { FluxerAPIError as FluxerAPIError2, RateLimitError as RateLimitError2 } from "@fluxerjs/rest";
14
14
 
15
15
  // src/errors/FluxerError.ts
16
- var FluxerError = class _FluxerError extends Error {
17
- code;
18
- constructor(message, options) {
19
- super(message, options?.cause ? { cause: options.cause } : void 0);
20
- this.name = "FluxerError";
21
- this.code = options?.code;
22
- Object.setPrototypeOf(this, _FluxerError.prototype);
23
- }
24
- };
16
+ import { FluxerError } from "@fluxerjs/util";
25
17
 
26
18
  // src/errors/ErrorCodes.ts
27
- var ErrorCodes = {
28
- ClientNotReady: "CLIENT_NOT_READY",
29
- InvalidToken: "INVALID_TOKEN",
30
- AlreadyLoggedIn: "ALREADY_LOGGED_IN",
31
- ChannelNotFound: "CHANNEL_NOT_FOUND",
32
- MessageNotFound: "MESSAGE_NOT_FOUND",
33
- GuildNotFound: "GUILD_NOT_FOUND",
34
- MemberNotFound: "MEMBER_NOT_FOUND",
35
- RoleNotFound: "ROLE_NOT_FOUND",
36
- EmojiNotInGuild: "EMOJI_NOT_IN_GUILD",
37
- EmojiNotFound: "EMOJI_NOT_FOUND"
38
- };
19
+ import { ErrorCodes } from "@fluxerjs/util";
39
20
 
40
21
  // src/util/messageUtils.ts
41
22
  import { EmbedBuilder } from "@fluxerjs/builders";
@@ -47,20 +28,37 @@ async function resolveMessageFiles(files) {
47
28
  const filename = f.filename ?? f.name;
48
29
  if ("url" in f && f.url) {
49
30
  if (!URL.canParse(f.url)) {
50
- throw new Error(`Invalid file URL at index ${i}: ${f.url}`);
31
+ throw new FluxerError(`Invalid file URL at index ${i}: ${f.url}`, {
32
+ code: ErrorCodes.InvalidFileUrl
33
+ });
34
+ }
35
+ let res;
36
+ try {
37
+ res = await fetch(f.url, {
38
+ signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS)
39
+ });
40
+ } catch (err) {
41
+ throw new FluxerError(`Failed to fetch file from ${f.url}`, {
42
+ code: ErrorCodes.FileFetchFailed,
43
+ cause: err instanceof Error ? err : void 0
44
+ });
51
45
  }
52
- const res = await fetch(f.url, {
53
- signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS)
54
- });
55
46
  if (!res.ok) {
56
- throw new Error(`Failed to fetch file from ${f.url}: ${res.status} ${res.statusText}`);
47
+ throw new FluxerError(
48
+ `Failed to fetch file from ${f.url}: ${res.status} ${res.statusText}`,
49
+ {
50
+ code: ErrorCodes.FileFetchFailed
51
+ }
52
+ );
57
53
  }
58
54
  const data = await res.arrayBuffer();
59
55
  result.push({ name: f.name, data, filename });
60
56
  } else if ("data" in f && f.data != null) {
61
57
  result.push({ name: f.name, data: f.data, filename });
62
58
  } else {
63
- throw new Error(`File at index ${i} must have either "data" or "url"`);
59
+ throw new FluxerError(`File at index ${i} must have either "data" or "url"`, {
60
+ code: ErrorCodes.InvalidAttachment
61
+ });
64
62
  }
65
63
  }
66
64
  return result;
@@ -130,6 +128,7 @@ var Events = {
130
128
  GuildMemberAdd: "guildMemberAdd",
131
129
  GuildMemberUpdate: "guildMemberUpdate",
132
130
  GuildMemberRemove: "guildMemberRemove",
131
+ GuildMembersChunk: "guildMembersChunk",
133
132
  GuildRoleCreate: "guildRoleCreate",
134
133
  GuildRoleUpdate: "guildRoleUpdate",
135
134
  GuildRoleDelete: "guildRoleDelete",
@@ -330,7 +329,15 @@ var Message = class _Message extends Base {
330
329
  const opts = typeof options === "string" ? { content: options } : options;
331
330
  const mergedReply = replyOptions ?? (opts.ping !== void 0 || opts.replyTo !== void 0) ? { ping: opts.ping, replyTo: opts.replyTo } : void 0;
332
331
  const refMessage = mergedReply?.replyTo ?? this;
333
- const ref = refMessage instanceof _Message ? { channel_id: refMessage.channelId, message_id: refMessage.id, guild_id: refMessage.guildId ?? void 0 } : { channel_id: refMessage.channelId, message_id: refMessage.messageId, guild_id: void 0 };
332
+ const ref = refMessage instanceof _Message ? {
333
+ channel_id: refMessage.channelId,
334
+ message_id: refMessage.id,
335
+ guild_id: refMessage.guildId ?? void 0
336
+ } : {
337
+ channel_id: refMessage.channelId,
338
+ message_id: refMessage.messageId,
339
+ guild_id: void 0
340
+ };
334
341
  const payload = await _Message._createMessageBody(opts, ref, mergedReply?.ping !== false);
335
342
  return this._send(payload);
336
343
  }
@@ -590,6 +597,7 @@ import { emitDeprecationWarning } from "@fluxerjs/util";
590
597
 
591
598
  // src/structures/Webhook.ts
592
599
  import { Routes as Routes3 } from "@fluxerjs/types";
600
+ import { EmbedBuilder as EmbedBuilder3 } from "@fluxerjs/builders";
593
601
 
594
602
  // src/util/Constants.ts
595
603
  var CDN_URL = "https://fluxerusercontent.com";
@@ -716,8 +724,9 @@ var Webhook = class _Webhook extends Base {
716
724
  */
717
725
  async send(options, wait) {
718
726
  if (!this.token) {
719
- throw new Error(
720
- "Webhook token is required to send. The token is only returned when creating a webhook; fetched webhooks cannot send."
727
+ throw new FluxerError(
728
+ "Webhook token is required to send. The token is only returned when creating a webhook; fetched webhooks cannot send.",
729
+ { code: ErrorCodes.WebhookTokenRequired }
721
730
  );
722
731
  }
723
732
  const opts = typeof options === "string" ? { content: options } : options;
@@ -734,6 +743,59 @@ var Webhook = class _Webhook extends Base {
734
743
  }
735
744
  return void 0;
736
745
  }
746
+ /**
747
+ * Edit a message previously sent by this webhook.
748
+ * Requires the webhook token.
749
+ */
750
+ async editMessage(messageId, options) {
751
+ if (!this.token) {
752
+ throw new FluxerError(
753
+ "Webhook token is required to edit messages. The token is only returned when creating a webhook; fetched webhooks cannot edit messages.",
754
+ { code: ErrorCodes.WebhookTokenRequired }
755
+ );
756
+ }
757
+ const body = { ...options };
758
+ if (options.embeds !== void 0) {
759
+ body.embeds = options.embeds.map((e) => e instanceof EmbedBuilder3 ? e.toJSON() : e);
760
+ }
761
+ const data = await this.client.rest.patch(
762
+ Routes3.webhookMessage(this.id, this.token, messageId),
763
+ { body, auth: false }
764
+ );
765
+ return new Message(this.client, data);
766
+ }
767
+ /**
768
+ * Fetch a message sent by this webhook.
769
+ * Requires the webhook token.
770
+ */
771
+ async fetchMessage(messageId) {
772
+ if (!this.token) {
773
+ throw new FluxerError(
774
+ "Webhook token is required to fetch messages. The token is only returned when creating a webhook; fetched webhooks cannot fetch messages.",
775
+ { code: ErrorCodes.WebhookTokenRequired }
776
+ );
777
+ }
778
+ const data = await this.client.rest.get(
779
+ Routes3.webhookMessage(this.id, this.token, messageId),
780
+ { auth: false }
781
+ );
782
+ return new Message(this.client, data);
783
+ }
784
+ /**
785
+ * Delete a message sent by this webhook.
786
+ * Requires the webhook token.
787
+ */
788
+ async deleteMessage(messageId) {
789
+ if (!this.token) {
790
+ throw new FluxerError(
791
+ "Webhook token is required to delete messages. The token is only returned when creating a webhook; fetched webhooks cannot delete messages.",
792
+ { code: ErrorCodes.WebhookTokenRequired }
793
+ );
794
+ }
795
+ await this.client.rest.delete(Routes3.webhookMessage(this.id, this.token, messageId), {
796
+ auth: false
797
+ });
798
+ }
737
799
  /**
738
800
  * Fetch a webhook by ID using bot auth.
739
801
  * @param client - The client instance
@@ -766,7 +828,7 @@ var Webhook = class _Webhook extends Base {
766
828
 
767
829
  // src/structures/Invite.ts
768
830
  import { Routes as Routes4 } from "@fluxerjs/types";
769
- var Invite = class extends Base {
831
+ var Invite = class _Invite extends Base {
770
832
  client;
771
833
  code;
772
834
  type;
@@ -781,6 +843,41 @@ var Invite = class extends Base {
781
843
  uses;
782
844
  maxUses;
783
845
  maxAge;
846
+ /**
847
+ * Normalize invite input to a raw code (plain code or URL such as https://fluxer.gg/{code}).
848
+ */
849
+ static normalizeCode(codeOrUrl) {
850
+ const input = codeOrUrl.trim();
851
+ if (!input) {
852
+ throw new FluxerError("Invite code cannot be empty", { code: ErrorCodes.InvalidInvite });
853
+ }
854
+ const parseInviteCodeFromUrl = (value) => {
855
+ if (!URL.canParse(value)) return null;
856
+ let url;
857
+ try {
858
+ url = new URL(value);
859
+ } catch {
860
+ return null;
861
+ }
862
+ const segments = url.pathname.split("/").filter(Boolean);
863
+ if (segments.length === 0) return null;
864
+ const inviteSegmentIdx = segments.findIndex((segment) => {
865
+ const lower = segment.toLowerCase();
866
+ return lower === "invite" || lower === "invites";
867
+ });
868
+ const code2 = inviteSegmentIdx >= 0 && segments[inviteSegmentIdx + 1] ? segments[inviteSegmentIdx + 1] : segments[segments.length - 1];
869
+ return decodeURIComponent(code2).trim();
870
+ };
871
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input);
872
+ const fromAbsolute = hasScheme ? parseInviteCodeFromUrl(input) : null;
873
+ const fromHostLike = !hasScheme && URL.canParse(`https://${input}`) ? parseInviteCodeFromUrl(`https://${input}`) : null;
874
+ const directCode = decodeURIComponent(input).trim();
875
+ const code = fromAbsolute ?? fromHostLike ?? directCode;
876
+ if (!code || /[\s/?#]/.test(code)) {
877
+ throw new FluxerError("Invalid invite code or URL", { code: ErrorCodes.InvalidInvite });
878
+ }
879
+ return code;
880
+ }
784
881
  /** @param data - API invite from GET /invites/{code}, channel/guild invite list, or gateway INVITE_CREATE */
785
882
  constructor(client, data) {
786
883
  super();
@@ -799,6 +896,14 @@ var Invite = class extends Base {
799
896
  this.maxUses = data.max_uses ?? null;
800
897
  this.maxAge = data.max_age ?? null;
801
898
  }
899
+ /**
900
+ * Fetch invite metadata by code or URL (does not join the guild).
901
+ */
902
+ static async fetch(client, codeOrUrl) {
903
+ const code = _Invite.normalizeCode(codeOrUrl);
904
+ const data = await client.rest.get(Routes4.invite(code));
905
+ return new _Invite(client, data);
906
+ }
802
907
  /** Full invite URL (https://fluxer.gg/{code} or instance-specific). */
803
908
  get url() {
804
909
  return `https://fluxer.gg/${this.code}`;
@@ -1611,6 +1716,25 @@ var GuildMember = class extends Base {
1611
1716
  );
1612
1717
  return new BitField(perms);
1613
1718
  }
1719
+ /**
1720
+ * Move this member to a different voice channel or disconnect them from voice.
1721
+ * Requires Move Members permission.
1722
+ * @param channelId - The voice channel ID to move the member to, or null to disconnect
1723
+ * @param connectionId - Optional connection ID for the specific voice session (usually not needed)
1724
+ * @returns Promise that resolves when the member has been moved
1725
+ * @example
1726
+ * // Move member to a different voice channel
1727
+ * await member.move('123456789012345678');
1728
+ *
1729
+ * // Disconnect member from voice
1730
+ * await member.move(null);
1731
+ */
1732
+ async move(channelId, connectionId) {
1733
+ await this.edit({
1734
+ channel_id: channelId,
1735
+ connection_id: connectionId
1736
+ });
1737
+ }
1614
1738
  _computeBasePermissions() {
1615
1739
  let base = 0n;
1616
1740
  const everyone = this.guild.roles.get(this.guild.id);
@@ -1661,7 +1785,7 @@ var GuildMemberManager = class extends Collection6 {
1661
1785
  * Fetch the current bot user as a GuildMember in this guild.
1662
1786
  * Caches the result in guild.members.
1663
1787
  *
1664
- * @throws Error if client.user is null (client not ready)
1788
+ * @throws FluxerError with CLIENT_NOT_READY if client.user is null
1665
1789
  * @example
1666
1790
  * const me = await guild.members.fetchMe();
1667
1791
  * console.log(me.displayName);
@@ -1669,7 +1793,9 @@ var GuildMemberManager = class extends Collection6 {
1669
1793
  async fetchMe() {
1670
1794
  const userId = this.guild.client.user?.id;
1671
1795
  if (!userId) {
1672
- throw new Error("Cannot fetch me: client.user is null (client not ready)");
1796
+ throw new FluxerError("Cannot fetch me: client.user is null (client not ready)", {
1797
+ code: ErrorCodes.ClientNotReady
1798
+ });
1673
1799
  }
1674
1800
  return this.guild.fetchMember(userId);
1675
1801
  }
@@ -1964,6 +2090,7 @@ var Guild = class extends Base {
1964
2090
  channels = new Collection7();
1965
2091
  roles = new Collection7();
1966
2092
  emojis = new Collection7();
2093
+ stickers = new Collection7();
1967
2094
  /** @param data - API guild from GET /guilds/{id} or gateway GUILD_CREATE */
1968
2095
  constructor(client, data) {
1969
2096
  super();
@@ -2214,6 +2341,24 @@ var Guild = class extends Base {
2214
2341
  const list = Array.isArray(data) ? data : Object.values(data ?? {});
2215
2342
  return list.map((w) => new Webhook(this.client, w));
2216
2343
  }
2344
+ /**
2345
+ * Fetch all invites in this guild.
2346
+ * Requires Manage Guild permission.
2347
+ */
2348
+ async fetchInvites() {
2349
+ const data = await this.client.rest.get(
2350
+ Routes14.guildInvites(this.id)
2351
+ );
2352
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2353
+ return list.map((invite) => new Invite(this.client, invite));
2354
+ }
2355
+ /**
2356
+ * Fetch a guild invite by code or URL.
2357
+ * @see Invite.fetch
2358
+ */
2359
+ async fetchInvite(codeOrUrl) {
2360
+ return Invite.fetch(this.client, codeOrUrl);
2361
+ }
2217
2362
  /**
2218
2363
  * Create a channel in this guild.
2219
2364
  * @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
@@ -2448,7 +2593,39 @@ var Guild = class extends Base {
2448
2593
  }
2449
2594
  );
2450
2595
  const list = Array.isArray(data) ? data : data?.stickers ?? [];
2451
- return list.map((s) => new GuildSticker(this.client, { ...s, guild_id: this.id }, this.id));
2596
+ const created = list.map(
2597
+ (s) => new GuildSticker(this.client, { ...s, guild_id: this.id }, this.id)
2598
+ );
2599
+ for (const sticker of created) {
2600
+ this.stickers.set(sticker.id, sticker);
2601
+ }
2602
+ return created;
2603
+ }
2604
+ /**
2605
+ * Fetch all stickers in this guild.
2606
+ * @returns GuildSticker instances (cached on guild.stickers)
2607
+ */
2608
+ async fetchStickers() {
2609
+ const data = await this.client.rest.get(
2610
+ Routes14.guildStickers(this.id)
2611
+ );
2612
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2613
+ const stickers = [];
2614
+ for (const s of list) {
2615
+ const sticker = new GuildSticker(this.client, { ...s, guild_id: this.id }, this.id);
2616
+ this.stickers.set(sticker.id, sticker);
2617
+ stickers.push(sticker);
2618
+ }
2619
+ return stickers;
2620
+ }
2621
+ /**
2622
+ * Fetch a single guild sticker by ID.
2623
+ */
2624
+ async fetchSticker(stickerId) {
2625
+ const data = await this.client.rest.get(Routes14.guildSticker(this.id, stickerId));
2626
+ const sticker = new GuildSticker(this.client, { ...data, guild_id: this.id }, this.id);
2627
+ this.stickers.set(sticker.id, sticker);
2628
+ return sticker;
2452
2629
  }
2453
2630
  };
2454
2631
 
@@ -2724,6 +2901,153 @@ var UsersManager = class extends Collection9 {
2724
2901
  }
2725
2902
  };
2726
2903
 
2904
+ // src/structures/interactions/BaseInteraction.ts
2905
+ var BaseInteraction = class {
2906
+ constructor(client, raw) {
2907
+ this.client = client;
2908
+ this.raw = raw;
2909
+ }
2910
+ get id() {
2911
+ return this.raw.id;
2912
+ }
2913
+ get applicationId() {
2914
+ return this.raw.application_id;
2915
+ }
2916
+ get token() {
2917
+ return this.raw.token;
2918
+ }
2919
+ get type() {
2920
+ return this.raw.type;
2921
+ }
2922
+ get channelId() {
2923
+ return this.raw.channel_id;
2924
+ }
2925
+ get guildId() {
2926
+ return this.raw.guild_id;
2927
+ }
2928
+ };
2929
+
2930
+ // src/structures/interactions/ChatInputCommandInteraction.ts
2931
+ var CommandOptionType = {
2932
+ SubCommand: 1,
2933
+ SubCommandGroup: 2,
2934
+ String: 3,
2935
+ Integer: 4,
2936
+ Boolean: 5,
2937
+ Number: 10
2938
+ };
2939
+ function findOptionDeep(options, name) {
2940
+ if (!options?.length) return void 0;
2941
+ for (const o of options) {
2942
+ if (o.name === name && o.value !== void 0) return o;
2943
+ const nested = findOptionDeep(o.options, name);
2944
+ if (nested) return nested;
2945
+ }
2946
+ return void 0;
2947
+ }
2948
+ var ChatInputCommandInteraction = class extends BaseInteraction {
2949
+ constructor(client, raw) {
2950
+ super(client, raw);
2951
+ if (raw.data?.name == null) {
2952
+ throw new FluxerError("ChatInputCommandInteraction requires interaction data with a command name", {
2953
+ code: ErrorCodes.InteractionInvalidPayload
2954
+ });
2955
+ }
2956
+ }
2957
+ /** Command name (e.g. `ping`). */
2958
+ get commandName() {
2959
+ return this.raw.data.name;
2960
+ }
2961
+ /** Resolved option leaf by name (searches nested subcommand options). */
2962
+ getOption(name) {
2963
+ const opt = findOptionDeep(this.raw.data?.options, name);
2964
+ if (!opt) {
2965
+ throw new FluxerError(`Interaction option "${name}" was not provided`, {
2966
+ code: ErrorCodes.InteractionOptionNotFound
2967
+ });
2968
+ }
2969
+ return opt;
2970
+ }
2971
+ getString(name) {
2972
+ const o = this.getOption(name);
2973
+ if (o.type !== CommandOptionType.String) {
2974
+ throw new FluxerError(`Option "${name}" is not a string`, {
2975
+ code: ErrorCodes.InteractionOptionTypeMismatch
2976
+ });
2977
+ }
2978
+ return String(o.value);
2979
+ }
2980
+ getInteger(name) {
2981
+ const o = this.getOption(name);
2982
+ if (o.type !== CommandOptionType.Integer) {
2983
+ throw new FluxerError(`Option "${name}" is not an integer`, {
2984
+ code: ErrorCodes.InteractionOptionTypeMismatch
2985
+ });
2986
+ }
2987
+ const v = o.value;
2988
+ if (typeof v !== "number" || !Number.isInteger(v)) {
2989
+ throw new FluxerError(`Option "${name}" has invalid integer value`, {
2990
+ code: ErrorCodes.InteractionOptionTypeMismatch
2991
+ });
2992
+ }
2993
+ return v;
2994
+ }
2995
+ getNumber(name) {
2996
+ const o = this.getOption(name);
2997
+ if (o.type !== CommandOptionType.Number && o.type !== CommandOptionType.Integer) {
2998
+ throw new FluxerError(`Option "${name}" is not a number`, {
2999
+ code: ErrorCodes.InteractionOptionTypeMismatch
3000
+ });
3001
+ }
3002
+ const v = o.value;
3003
+ if (typeof v !== "number") {
3004
+ throw new FluxerError(`Option "${name}" has invalid number value`, {
3005
+ code: ErrorCodes.InteractionOptionTypeMismatch
3006
+ });
3007
+ }
3008
+ return v;
3009
+ }
3010
+ getBoolean(name) {
3011
+ const o = this.getOption(name);
3012
+ if (o.type !== CommandOptionType.Boolean) {
3013
+ throw new FluxerError(`Option "${name}" is not a boolean`, {
3014
+ code: ErrorCodes.InteractionOptionTypeMismatch
3015
+ });
3016
+ }
3017
+ if (typeof o.value !== "boolean") {
3018
+ throw new FluxerError(`Option "${name}" has invalid boolean value`, {
3019
+ code: ErrorCodes.InteractionOptionTypeMismatch
3020
+ });
3021
+ }
3022
+ return o.value;
3023
+ }
3024
+ /** Name of the invoked subcommand (when using subcommands). */
3025
+ getSubcommand(fallback) {
3026
+ const opts = this.raw.data?.options;
3027
+ const first = opts?.[0];
3028
+ if (first?.type === CommandOptionType.SubCommand) return first.name;
3029
+ if (first?.type === CommandOptionType.SubCommandGroup) {
3030
+ const inner = first.options?.[0];
3031
+ if (inner?.type === CommandOptionType.SubCommand) return inner.name;
3032
+ }
3033
+ if (fallback !== void 0) return fallback;
3034
+ throw new FluxerError("No subcommand in this interaction", {
3035
+ code: ErrorCodes.InteractionOptionNotFound
3036
+ });
3037
+ }
3038
+ };
3039
+
3040
+ // src/structures/interactions/createInteraction.ts
3041
+ function createInteraction(client, data) {
3042
+ if (data.data?.name != null) {
3043
+ return new ChatInputCommandInteraction(client, data);
3044
+ }
3045
+ return new BaseInteraction(client, data);
3046
+ }
3047
+ function isChatInputCommandInteraction(interaction) {
3048
+ return interaction instanceof ChatInputCommandInteraction;
3049
+ }
3050
+
2727
3051
  // src/util/guildUtils.ts
2728
3052
  function normalizeGuildPayload(raw) {
2729
3053
  if (!raw || typeof raw !== "object") {
@@ -2793,6 +3117,42 @@ var MessageReaction = class extends Base {
2793
3117
 
2794
3118
  // src/client/EventHandlerRegistry.ts
2795
3119
  var handlers = /* @__PURE__ */ new Map();
3120
+ function normalizeInviteCreatePayload(client, payload) {
3121
+ if (!payload?.code) return null;
3122
+ const guildId = payload.guild?.id ?? payload.guild_id ?? "0";
3123
+ const cachedGuild = guildId !== "0" ? client.guilds.get(guildId) : null;
3124
+ const guild = {
3125
+ id: guildId,
3126
+ name: payload.guild?.name ?? cachedGuild?.name ?? "Unknown Guild",
3127
+ icon: payload.guild?.icon ?? null,
3128
+ banner: payload.guild?.banner ?? null,
3129
+ splash: payload.guild?.splash ?? null,
3130
+ features: payload.guild?.features
3131
+ };
3132
+ const channelId = payload.channel?.id ?? payload.channel_id ?? "0";
3133
+ const cachedChannel = channelId !== "0" ? client.channels.get(channelId) : null;
3134
+ const channel = {
3135
+ id: channelId,
3136
+ type: payload.channel?.type ?? cachedChannel?.type ?? 0,
3137
+ name: payload.channel?.name ?? cachedChannel?.name ?? null,
3138
+ icon: payload.channel?.icon ?? null
3139
+ };
3140
+ return {
3141
+ code: payload.code,
3142
+ type: typeof payload.type === "number" ? payload.type : 0,
3143
+ guild,
3144
+ channel,
3145
+ inviter: payload.inviter ?? null,
3146
+ member_count: payload.member_count,
3147
+ presence_count: payload.presence_count,
3148
+ expires_at: payload.expires_at,
3149
+ temporary: payload.temporary,
3150
+ created_at: payload.created_at,
3151
+ uses: payload.uses,
3152
+ max_uses: payload.max_uses,
3153
+ max_age: payload.max_age
3154
+ };
3155
+ }
2796
3156
  handlers.set("MESSAGE_CREATE", async (client, d) => {
2797
3157
  const data = d;
2798
3158
  if (data.guild_id && data.member && data.author) {
@@ -2984,8 +3344,25 @@ handlers.set("GUILD_MEMBER_REMOVE", async (client, d) => {
2984
3344
  }
2985
3345
  client.emit(Events.GuildMemberRemove, member);
2986
3346
  });
3347
+ handlers.set("GUILD_MEMBERS_CHUNK", async (client, d) => {
3348
+ const data = d;
3349
+ const guild = client.guilds.get(data.guild_id);
3350
+ if (guild) {
3351
+ for (const m of data.members ?? []) {
3352
+ if (m?.user?.id) {
3353
+ const memberData = { ...m, guild_id: guild.id };
3354
+ const member = new GuildMember(client, memberData, guild);
3355
+ guild.members.set(member.id, member);
3356
+ }
3357
+ }
3358
+ }
3359
+ client.emit(Events.GuildMembersChunk, data);
3360
+ });
2987
3361
  handlers.set("INTERACTION_CREATE", async (client, d) => {
2988
- client.emit(Events.InteractionCreate, d);
3362
+ client.emit(
3363
+ Events.InteractionCreate,
3364
+ createInteraction(client, d)
3365
+ );
2989
3366
  });
2990
3367
  handlers.set("VOICE_STATE_UPDATE", async (client, d) => {
2991
3368
  client.emit(Events.VoiceStateUpdate, d);
@@ -3080,7 +3457,14 @@ handlers.set("CHANNEL_PINS_UPDATE", async (client, d) => {
3080
3457
  client.emit(Events.ChannelPinsUpdate, d);
3081
3458
  });
3082
3459
  handlers.set("INVITE_CREATE", async (client, d) => {
3083
- const data = d;
3460
+ const data = normalizeInviteCreatePayload(client, d);
3461
+ if (!data) {
3462
+ client.emit(
3463
+ Events.Debug,
3464
+ "[Gateway] INVITE_CREATE payload had no invite code (documented as possibly empty)"
3465
+ );
3466
+ return;
3467
+ }
3084
3468
  client.emit(Events.InviteCreate, new Invite(client, data));
3085
3469
  });
3086
3470
  handlers.set("INVITE_DELETE", async (client, d) => {
@@ -3124,6 +3508,7 @@ var Client = class extends EventEmitter3 {
3124
3508
  constructor(options = {}) {
3125
3509
  super();
3126
3510
  this.options = options;
3511
+ this.setMaxListeners(0);
3127
3512
  this.events = createEventMethods(this);
3128
3513
  Object.defineProperty(this.channels, "cache", {
3129
3514
  get: () => this.channels,
@@ -3156,8 +3541,22 @@ var Client = class extends EventEmitter3 {
3156
3541
  _ws = null;
3157
3542
  /** When waitForGuilds, set of guild IDs we're waiting for GUILD_CREATE on. Null when not waiting. */
3158
3543
  _pendingGuildIds = null;
3544
+ /** Timeout for guild stream when READY has no guilds (gateway sends only GUILD_CREATE). Cleared in finally. */
3545
+ _guildStreamSettleTimeout = null;
3159
3546
  /** Per-channel message cache (channelId -> messageId -> APIMessage). Used when options.cache.messages > 0. */
3160
3547
  _messageCaches = null;
3548
+ on(event, listener) {
3549
+ return super.on(event, listener);
3550
+ }
3551
+ once(event, listener) {
3552
+ return super.once(event, listener);
3553
+ }
3554
+ off(event, listener) {
3555
+ return super.off(event, listener);
3556
+ }
3557
+ emit(event, ...args) {
3558
+ return super.emit(event, ...args);
3559
+ }
3161
3560
  /**
3162
3561
  * Resolve an emoji argument to the API format (unicode or "name:id").
3163
3562
  * Supports: <:name:id>, :name:, name:id, { name, id }, unicode.
@@ -3177,7 +3576,9 @@ var Client = class extends EventEmitter3 {
3177
3576
  const parsed = parseEmoji(
3178
3577
  typeof emoji === "string" ? emoji : emoji.id ? `:${emoji.name}:` : emoji.name
3179
3578
  );
3180
- if (!parsed) throw new Error("Invalid emoji");
3579
+ if (!parsed) {
3580
+ throw new FluxerError("Invalid emoji", { code: ErrorCodes.InvalidEmoji });
3581
+ }
3181
3582
  if (parsed.id) {
3182
3583
  if (guildId) {
3183
3584
  await this.assertEmojiInGuild(parsed.id, guildId);
@@ -3192,13 +3593,15 @@ var Client = class extends EventEmitter3 {
3192
3593
  const list = Array.isArray(emojis) ? emojis : Object.values(emojis ?? {});
3193
3594
  const found = list.find((e) => e.name && e.name.toLowerCase() === parsed.name.toLowerCase());
3194
3595
  if (found) return formatEmoji({ ...parsed, id: found.id, animated: found.animated });
3195
- throw new Error(
3196
- `Custom emoji ":${parsed.name}:" not found in guild. Use name:id or <:name:id> format.`
3596
+ throw new FluxerError(
3597
+ `Custom emoji ":${parsed.name}:" not found in guild. Use name:id or <:name:id> format.`,
3598
+ { code: ErrorCodes.EmojiNotFound }
3197
3599
  );
3198
3600
  }
3199
3601
  if (/^\w+$/.test(parsed.name)) {
3200
- throw new Error(
3201
- `Custom emoji ":${parsed.name}:" requires guild context. Use message.react() in a guild channel, or pass guildId to client.resolveEmoji().`
3602
+ throw new FluxerError(
3603
+ `Custom emoji ":${parsed.name}:" requires guild context. Use message.react() in a guild channel, or pass guildId to client.resolveEmoji().`,
3604
+ { code: ErrorCodes.EmojiRequiresGuild }
3202
3605
  );
3203
3606
  }
3204
3607
  return parsed.name;
@@ -3225,6 +3628,20 @@ var Client = class extends EventEmitter3 {
3225
3628
  async fetchInstance() {
3226
3629
  return this.rest.get(Routes20.instance(), { auth: false });
3227
3630
  }
3631
+ /**
3632
+ * Fetch instance discovery document (API URL, gateway URL, features). GET /.well-known/fluxer.
3633
+ * Does not require authentication.
3634
+ */
3635
+ async fetchInstanceDiscovery() {
3636
+ return this.rest.get(Routes20.instanceDiscovery(), { auth: false });
3637
+ }
3638
+ /**
3639
+ * Fetch gateway connection metadata (WebSocket URL, recommended shards, session limits).
3640
+ * GET /gateway/bot (authenticated).
3641
+ */
3642
+ async fetchGatewayInfo() {
3643
+ return this.rest.get(Routes20.gatewayBot());
3644
+ }
3228
3645
  /**
3229
3646
  * Fetch a message by channel and message ID. Use when you have IDs (e.g. from a DB).
3230
3647
  * @param channelId - Snowflake of the channel
@@ -3308,7 +3725,11 @@ var Client = class extends EventEmitter3 {
3308
3725
  }
3309
3726
  /** WebSocket manager. Throws if not logged in. */
3310
3727
  get ws() {
3311
- if (!this._ws) throw new Error("Client is not logged in");
3728
+ if (!this._ws) {
3729
+ throw new FluxerError("Client is not logged in. Call login() first.", {
3730
+ code: ErrorCodes.NotLoggedIn
3731
+ });
3732
+ }
3312
3733
  return this._ws;
3313
3734
  }
3314
3735
  /**
@@ -3319,15 +3740,35 @@ var Client = class extends EventEmitter3 {
3319
3740
  sendToGateway(shardId, payload) {
3320
3741
  this.ws.send(shardId, payload);
3321
3742
  }
3322
- async handleDispatch(payload) {
3323
- if (payload.op !== 0 || !payload.t) return;
3743
+ /**
3744
+ * Run gateway event handlers. By default (see {@link ClientOptions.gatewayDeferHandlers}) work is deferred to the next
3745
+ * macrotask so user code does not block the WebSocket `message` callback.
3746
+ */
3747
+ handleDispatch(payload) {
3748
+ if (payload.op !== 0 || !payload.t) return Promise.resolve();
3324
3749
  const { t: event, d } = payload;
3325
- try {
3326
- const handler = eventHandlers.get(event);
3327
- if (handler) await handler(this, d);
3328
- } catch (err) {
3329
- this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)));
3750
+ const handler = eventHandlers.get(event);
3751
+ if (!handler) return Promise.resolve();
3752
+ const run = async () => {
3753
+ try {
3754
+ await handler(this, d);
3755
+ } catch (err) {
3756
+ this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)));
3757
+ }
3758
+ };
3759
+ if (this.options.gatewayDeferHandlers === false) {
3760
+ return run();
3330
3761
  }
3762
+ return new Promise((resolve, reject) => {
3763
+ const start = () => {
3764
+ void run().then(resolve).catch(reject);
3765
+ };
3766
+ if (typeof setImmediate === "function") {
3767
+ setImmediate(start);
3768
+ } else {
3769
+ setTimeout(start, 0);
3770
+ }
3771
+ });
3331
3772
  }
3332
3773
  /**
3333
3774
  * Connect to the Fluxer gateway and authenticate.
@@ -3359,6 +3800,7 @@ var Client = class extends EventEmitter3 {
3359
3800
  presence: this.options.presence,
3360
3801
  rest: { get: (route) => this.rest.get(route) },
3361
3802
  version: this.options.rest?.version ?? "1",
3803
+ debug: this.options.gatewayDebug !== false,
3362
3804
  WebSocket: this.options.WebSocket
3363
3805
  });
3364
3806
  this._ws.on("dispatch", ({ payload }) => {
@@ -3402,6 +3844,14 @@ var Client = class extends EventEmitter3 {
3402
3844
  this._pendingGuildIds = pending;
3403
3845
  return;
3404
3846
  }
3847
+ if (waitForGuilds && (data.guilds ?? []).length === 0) {
3848
+ const GUILD_STREAM_SETTLE_MS = 500;
3849
+ this._guildStreamSettleTimeout = setTimeout(() => {
3850
+ this._guildStreamSettleTimeout = null;
3851
+ this._finalizeReady();
3852
+ }, GUILD_STREAM_SETTLE_MS);
3853
+ return;
3854
+ }
3405
3855
  this._finalizeReady();
3406
3856
  }
3407
3857
  );
@@ -3431,6 +3881,10 @@ var Client = class extends EventEmitter3 {
3431
3881
  }
3432
3882
  /** Disconnect from the gateway and clear cached data. */
3433
3883
  async destroy() {
3884
+ if (this._guildStreamSettleTimeout !== null) {
3885
+ clearTimeout(this._guildStreamSettleTimeout);
3886
+ this._guildStreamSettleTimeout = null;
3887
+ }
3434
3888
  if (this._ws) {
3435
3889
  this._ws.destroy();
3436
3890
  this._ws = null;
@@ -3467,7 +3921,7 @@ var Client = class extends EventEmitter3 {
3467
3921
  };
3468
3922
 
3469
3923
  // src/index.ts
3470
- import { EmbedBuilder as EmbedBuilder3, MessagePayload, AttachmentBuilder } from "@fluxerjs/builders";
3924
+ import { EmbedBuilder as EmbedBuilder4, MessagePayload, AttachmentBuilder } from "@fluxerjs/builders";
3471
3925
  import { Routes as Routes21, GatewayOpcodes, MessageAttachmentFlags } from "@fluxerjs/types";
3472
3926
  import { resolveTenorToImageUrl, parseUserMention, parsePrefixCommand } from "@fluxerjs/util";
3473
3927
  import {
@@ -3480,14 +3934,16 @@ import {
3480
3934
  export {
3481
3935
  AttachmentBuilder,
3482
3936
  Base,
3937
+ BaseInteraction,
3483
3938
  CDN_URL,
3484
3939
  CategoryChannel,
3485
3940
  Channel,
3486
3941
  ChannelManager,
3942
+ ChatInputCommandInteraction,
3487
3943
  Client,
3488
3944
  ClientUser,
3489
3945
  DMChannel,
3490
- EmbedBuilder3 as EmbedBuilder,
3946
+ EmbedBuilder4 as EmbedBuilder,
3491
3947
  ErrorCodes,
3492
3948
  Events,
3493
3949
  FluxerError,
@@ -3527,6 +3983,8 @@ export {
3527
3983
  cdnDisplayAvatarURL,
3528
3984
  cdnMemberAvatarURL,
3529
3985
  cdnMemberBannerURL,
3986
+ createInteraction,
3987
+ isChatInputCommandInteraction,
3530
3988
  parsePrefixCommand,
3531
3989
  parseUserMention,
3532
3990
  resolvePermissionsToBitfield3 as resolvePermissionsToBitfield,