@fluxerjs/core 1.2.4 → 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",
@@ -598,6 +597,7 @@ import { emitDeprecationWarning } from "@fluxerjs/util";
598
597
 
599
598
  // src/structures/Webhook.ts
600
599
  import { Routes as Routes3 } from "@fluxerjs/types";
600
+ import { EmbedBuilder as EmbedBuilder3 } from "@fluxerjs/builders";
601
601
 
602
602
  // src/util/Constants.ts
603
603
  var CDN_URL = "https://fluxerusercontent.com";
@@ -724,8 +724,9 @@ var Webhook = class _Webhook extends Base {
724
724
  */
725
725
  async send(options, wait) {
726
726
  if (!this.token) {
727
- throw new Error(
728
- "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 }
729
730
  );
730
731
  }
731
732
  const opts = typeof options === "string" ? { content: options } : options;
@@ -742,6 +743,59 @@ var Webhook = class _Webhook extends Base {
742
743
  }
743
744
  return void 0;
744
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
+ }
745
799
  /**
746
800
  * Fetch a webhook by ID using bot auth.
747
801
  * @param client - The client instance
@@ -774,7 +828,7 @@ var Webhook = class _Webhook extends Base {
774
828
 
775
829
  // src/structures/Invite.ts
776
830
  import { Routes as Routes4 } from "@fluxerjs/types";
777
- var Invite = class extends Base {
831
+ var Invite = class _Invite extends Base {
778
832
  client;
779
833
  code;
780
834
  type;
@@ -789,6 +843,41 @@ var Invite = class extends Base {
789
843
  uses;
790
844
  maxUses;
791
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
+ }
792
881
  /** @param data - API invite from GET /invites/{code}, channel/guild invite list, or gateway INVITE_CREATE */
793
882
  constructor(client, data) {
794
883
  super();
@@ -807,6 +896,14 @@ var Invite = class extends Base {
807
896
  this.maxUses = data.max_uses ?? null;
808
897
  this.maxAge = data.max_age ?? null;
809
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
+ }
810
907
  /** Full invite URL (https://fluxer.gg/{code} or instance-specific). */
811
908
  get url() {
812
909
  return `https://fluxer.gg/${this.code}`;
@@ -1688,7 +1785,7 @@ var GuildMemberManager = class extends Collection6 {
1688
1785
  * Fetch the current bot user as a GuildMember in this guild.
1689
1786
  * Caches the result in guild.members.
1690
1787
  *
1691
- * @throws Error if client.user is null (client not ready)
1788
+ * @throws FluxerError with CLIENT_NOT_READY if client.user is null
1692
1789
  * @example
1693
1790
  * const me = await guild.members.fetchMe();
1694
1791
  * console.log(me.displayName);
@@ -1696,7 +1793,9 @@ var GuildMemberManager = class extends Collection6 {
1696
1793
  async fetchMe() {
1697
1794
  const userId = this.guild.client.user?.id;
1698
1795
  if (!userId) {
1699
- 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
+ });
1700
1799
  }
1701
1800
  return this.guild.fetchMember(userId);
1702
1801
  }
@@ -1991,6 +2090,7 @@ var Guild = class extends Base {
1991
2090
  channels = new Collection7();
1992
2091
  roles = new Collection7();
1993
2092
  emojis = new Collection7();
2093
+ stickers = new Collection7();
1994
2094
  /** @param data - API guild from GET /guilds/{id} or gateway GUILD_CREATE */
1995
2095
  constructor(client, data) {
1996
2096
  super();
@@ -2241,6 +2341,24 @@ var Guild = class extends Base {
2241
2341
  const list = Array.isArray(data) ? data : Object.values(data ?? {});
2242
2342
  return list.map((w) => new Webhook(this.client, w));
2243
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
+ }
2244
2362
  /**
2245
2363
  * Create a channel in this guild.
2246
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
@@ -2475,7 +2593,39 @@ var Guild = class extends Base {
2475
2593
  }
2476
2594
  );
2477
2595
  const list = Array.isArray(data) ? data : data?.stickers ?? [];
2478
- 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;
2479
2629
  }
2480
2630
  };
2481
2631
 
@@ -2751,6 +2901,153 @@ var UsersManager = class extends Collection9 {
2751
2901
  }
2752
2902
  };
2753
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
+
2754
3051
  // src/util/guildUtils.ts
2755
3052
  function normalizeGuildPayload(raw) {
2756
3053
  if (!raw || typeof raw !== "object") {
@@ -2820,6 +3117,42 @@ var MessageReaction = class extends Base {
2820
3117
 
2821
3118
  // src/client/EventHandlerRegistry.ts
2822
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
+ }
2823
3156
  handlers.set("MESSAGE_CREATE", async (client, d) => {
2824
3157
  const data = d;
2825
3158
  if (data.guild_id && data.member && data.author) {
@@ -3011,8 +3344,25 @@ handlers.set("GUILD_MEMBER_REMOVE", async (client, d) => {
3011
3344
  }
3012
3345
  client.emit(Events.GuildMemberRemove, member);
3013
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
+ });
3014
3361
  handlers.set("INTERACTION_CREATE", async (client, d) => {
3015
- client.emit(Events.InteractionCreate, d);
3362
+ client.emit(
3363
+ Events.InteractionCreate,
3364
+ createInteraction(client, d)
3365
+ );
3016
3366
  });
3017
3367
  handlers.set("VOICE_STATE_UPDATE", async (client, d) => {
3018
3368
  client.emit(Events.VoiceStateUpdate, d);
@@ -3107,7 +3457,14 @@ handlers.set("CHANNEL_PINS_UPDATE", async (client, d) => {
3107
3457
  client.emit(Events.ChannelPinsUpdate, d);
3108
3458
  });
3109
3459
  handlers.set("INVITE_CREATE", async (client, d) => {
3110
- 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
+ }
3111
3468
  client.emit(Events.InviteCreate, new Invite(client, data));
3112
3469
  });
3113
3470
  handlers.set("INVITE_DELETE", async (client, d) => {
@@ -3151,6 +3508,7 @@ var Client = class extends EventEmitter3 {
3151
3508
  constructor(options = {}) {
3152
3509
  super();
3153
3510
  this.options = options;
3511
+ this.setMaxListeners(0);
3154
3512
  this.events = createEventMethods(this);
3155
3513
  Object.defineProperty(this.channels, "cache", {
3156
3514
  get: () => this.channels,
@@ -3187,6 +3545,18 @@ var Client = class extends EventEmitter3 {
3187
3545
  _guildStreamSettleTimeout = null;
3188
3546
  /** Per-channel message cache (channelId -> messageId -> APIMessage). Used when options.cache.messages > 0. */
3189
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
+ }
3190
3560
  /**
3191
3561
  * Resolve an emoji argument to the API format (unicode or "name:id").
3192
3562
  * Supports: <:name:id>, :name:, name:id, { name, id }, unicode.
@@ -3206,7 +3576,9 @@ var Client = class extends EventEmitter3 {
3206
3576
  const parsed = parseEmoji(
3207
3577
  typeof emoji === "string" ? emoji : emoji.id ? `:${emoji.name}:` : emoji.name
3208
3578
  );
3209
- if (!parsed) throw new Error("Invalid emoji");
3579
+ if (!parsed) {
3580
+ throw new FluxerError("Invalid emoji", { code: ErrorCodes.InvalidEmoji });
3581
+ }
3210
3582
  if (parsed.id) {
3211
3583
  if (guildId) {
3212
3584
  await this.assertEmojiInGuild(parsed.id, guildId);
@@ -3221,13 +3593,15 @@ var Client = class extends EventEmitter3 {
3221
3593
  const list = Array.isArray(emojis) ? emojis : Object.values(emojis ?? {});
3222
3594
  const found = list.find((e) => e.name && e.name.toLowerCase() === parsed.name.toLowerCase());
3223
3595
  if (found) return formatEmoji({ ...parsed, id: found.id, animated: found.animated });
3224
- throw new Error(
3225
- `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 }
3226
3599
  );
3227
3600
  }
3228
3601
  if (/^\w+$/.test(parsed.name)) {
3229
- throw new Error(
3230
- `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 }
3231
3605
  );
3232
3606
  }
3233
3607
  return parsed.name;
@@ -3254,6 +3628,20 @@ var Client = class extends EventEmitter3 {
3254
3628
  async fetchInstance() {
3255
3629
  return this.rest.get(Routes20.instance(), { auth: false });
3256
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
+ }
3257
3645
  /**
3258
3646
  * Fetch a message by channel and message ID. Use when you have IDs (e.g. from a DB).
3259
3647
  * @param channelId - Snowflake of the channel
@@ -3337,7 +3725,11 @@ var Client = class extends EventEmitter3 {
3337
3725
  }
3338
3726
  /** WebSocket manager. Throws if not logged in. */
3339
3727
  get ws() {
3340
- 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
+ }
3341
3733
  return this._ws;
3342
3734
  }
3343
3735
  /**
@@ -3348,15 +3740,35 @@ var Client = class extends EventEmitter3 {
3348
3740
  sendToGateway(shardId, payload) {
3349
3741
  this.ws.send(shardId, payload);
3350
3742
  }
3351
- async handleDispatch(payload) {
3352
- 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();
3353
3749
  const { t: event, d } = payload;
3354
- try {
3355
- const handler = eventHandlers.get(event);
3356
- if (handler) await handler(this, d);
3357
- } catch (err) {
3358
- this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)));
3359
- }
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();
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
+ });
3360
3772
  }
3361
3773
  /**
3362
3774
  * Connect to the Fluxer gateway and authenticate.
@@ -3388,6 +3800,7 @@ var Client = class extends EventEmitter3 {
3388
3800
  presence: this.options.presence,
3389
3801
  rest: { get: (route) => this.rest.get(route) },
3390
3802
  version: this.options.rest?.version ?? "1",
3803
+ debug: this.options.gatewayDebug !== false,
3391
3804
  WebSocket: this.options.WebSocket
3392
3805
  });
3393
3806
  this._ws.on("dispatch", ({ payload }) => {
@@ -3508,7 +3921,7 @@ var Client = class extends EventEmitter3 {
3508
3921
  };
3509
3922
 
3510
3923
  // src/index.ts
3511
- import { EmbedBuilder as EmbedBuilder3, MessagePayload, AttachmentBuilder } from "@fluxerjs/builders";
3924
+ import { EmbedBuilder as EmbedBuilder4, MessagePayload, AttachmentBuilder } from "@fluxerjs/builders";
3512
3925
  import { Routes as Routes21, GatewayOpcodes, MessageAttachmentFlags } from "@fluxerjs/types";
3513
3926
  import { resolveTenorToImageUrl, parseUserMention, parsePrefixCommand } from "@fluxerjs/util";
3514
3927
  import {
@@ -3521,14 +3934,16 @@ import {
3521
3934
  export {
3522
3935
  AttachmentBuilder,
3523
3936
  Base,
3937
+ BaseInteraction,
3524
3938
  CDN_URL,
3525
3939
  CategoryChannel,
3526
3940
  Channel,
3527
3941
  ChannelManager,
3942
+ ChatInputCommandInteraction,
3528
3943
  Client,
3529
3944
  ClientUser,
3530
3945
  DMChannel,
3531
- EmbedBuilder3 as EmbedBuilder,
3946
+ EmbedBuilder4 as EmbedBuilder,
3532
3947
  ErrorCodes,
3533
3948
  Events,
3534
3949
  FluxerError,
@@ -3568,6 +3983,8 @@ export {
3568
3983
  cdnDisplayAvatarURL,
3569
3984
  cdnMemberAvatarURL,
3570
3985
  cdnMemberBannerURL,
3986
+ createInteraction,
3987
+ isChatInputCommandInteraction,
3571
3988
  parsePrefixCommand,
3572
3989
  parseUserMention,
3573
3990
  resolvePermissionsToBitfield3 as resolvePermissionsToBitfield,