@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.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,156 @@ 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(
2953
+ "ChatInputCommandInteraction requires interaction data with a command name",
2954
+ {
2955
+ code: ErrorCodes.InteractionInvalidPayload
2956
+ }
2957
+ );
2958
+ }
2959
+ }
2960
+ /** Command name (e.g. `ping`). */
2961
+ get commandName() {
2962
+ return this.raw.data.name;
2963
+ }
2964
+ /** Resolved option leaf by name (searches nested subcommand options). */
2965
+ getOption(name) {
2966
+ const opt = findOptionDeep(this.raw.data?.options, name);
2967
+ if (!opt) {
2968
+ throw new FluxerError(`Interaction option "${name}" was not provided`, {
2969
+ code: ErrorCodes.InteractionOptionNotFound
2970
+ });
2971
+ }
2972
+ return opt;
2973
+ }
2974
+ getString(name) {
2975
+ const o = this.getOption(name);
2976
+ if (o.type !== CommandOptionType.String) {
2977
+ throw new FluxerError(`Option "${name}" is not a string`, {
2978
+ code: ErrorCodes.InteractionOptionTypeMismatch
2979
+ });
2980
+ }
2981
+ return String(o.value);
2982
+ }
2983
+ getInteger(name) {
2984
+ const o = this.getOption(name);
2985
+ if (o.type !== CommandOptionType.Integer) {
2986
+ throw new FluxerError(`Option "${name}" is not an integer`, {
2987
+ code: ErrorCodes.InteractionOptionTypeMismatch
2988
+ });
2989
+ }
2990
+ const v = o.value;
2991
+ if (typeof v !== "number" || !Number.isInteger(v)) {
2992
+ throw new FluxerError(`Option "${name}" has invalid integer value`, {
2993
+ code: ErrorCodes.InteractionOptionTypeMismatch
2994
+ });
2995
+ }
2996
+ return v;
2997
+ }
2998
+ getNumber(name) {
2999
+ const o = this.getOption(name);
3000
+ if (o.type !== CommandOptionType.Number && o.type !== CommandOptionType.Integer) {
3001
+ throw new FluxerError(`Option "${name}" is not a number`, {
3002
+ code: ErrorCodes.InteractionOptionTypeMismatch
3003
+ });
3004
+ }
3005
+ const v = o.value;
3006
+ if (typeof v !== "number") {
3007
+ throw new FluxerError(`Option "${name}" has invalid number value`, {
3008
+ code: ErrorCodes.InteractionOptionTypeMismatch
3009
+ });
3010
+ }
3011
+ return v;
3012
+ }
3013
+ getBoolean(name) {
3014
+ const o = this.getOption(name);
3015
+ if (o.type !== CommandOptionType.Boolean) {
3016
+ throw new FluxerError(`Option "${name}" is not a boolean`, {
3017
+ code: ErrorCodes.InteractionOptionTypeMismatch
3018
+ });
3019
+ }
3020
+ if (typeof o.value !== "boolean") {
3021
+ throw new FluxerError(`Option "${name}" has invalid boolean value`, {
3022
+ code: ErrorCodes.InteractionOptionTypeMismatch
3023
+ });
3024
+ }
3025
+ return o.value;
3026
+ }
3027
+ /** Name of the invoked subcommand (when using subcommands). */
3028
+ getSubcommand(fallback) {
3029
+ const opts = this.raw.data?.options;
3030
+ const first = opts?.[0];
3031
+ if (first?.type === CommandOptionType.SubCommand) return first.name;
3032
+ if (first?.type === CommandOptionType.SubCommandGroup) {
3033
+ const inner = first.options?.[0];
3034
+ if (inner?.type === CommandOptionType.SubCommand) return inner.name;
3035
+ }
3036
+ if (fallback !== void 0) return fallback;
3037
+ throw new FluxerError("No subcommand in this interaction", {
3038
+ code: ErrorCodes.InteractionOptionNotFound
3039
+ });
3040
+ }
3041
+ };
3042
+
3043
+ // src/structures/interactions/createInteraction.ts
3044
+ function createInteraction(client, data) {
3045
+ if (data.data?.name != null) {
3046
+ return new ChatInputCommandInteraction(client, data);
3047
+ }
3048
+ return new BaseInteraction(client, data);
3049
+ }
3050
+ function isChatInputCommandInteraction(interaction) {
3051
+ return interaction instanceof ChatInputCommandInteraction;
3052
+ }
3053
+
2754
3054
  // src/util/guildUtils.ts
2755
3055
  function normalizeGuildPayload(raw) {
2756
3056
  if (!raw || typeof raw !== "object") {
@@ -2820,6 +3120,42 @@ var MessageReaction = class extends Base {
2820
3120
 
2821
3121
  // src/client/EventHandlerRegistry.ts
2822
3122
  var handlers = /* @__PURE__ */ new Map();
3123
+ function normalizeInviteCreatePayload(client, payload) {
3124
+ if (!payload?.code) return null;
3125
+ const guildId = payload.guild?.id ?? payload.guild_id ?? "0";
3126
+ const cachedGuild = guildId !== "0" ? client.guilds.get(guildId) : null;
3127
+ const guild = {
3128
+ id: guildId,
3129
+ name: payload.guild?.name ?? cachedGuild?.name ?? "Unknown Guild",
3130
+ icon: payload.guild?.icon ?? null,
3131
+ banner: payload.guild?.banner ?? null,
3132
+ splash: payload.guild?.splash ?? null,
3133
+ features: payload.guild?.features
3134
+ };
3135
+ const channelId = payload.channel?.id ?? payload.channel_id ?? "0";
3136
+ const cachedChannel = channelId !== "0" ? client.channels.get(channelId) : null;
3137
+ const channel = {
3138
+ id: channelId,
3139
+ type: payload.channel?.type ?? cachedChannel?.type ?? 0,
3140
+ name: payload.channel?.name ?? cachedChannel?.name ?? null,
3141
+ icon: payload.channel?.icon ?? null
3142
+ };
3143
+ return {
3144
+ code: payload.code,
3145
+ type: typeof payload.type === "number" ? payload.type : 0,
3146
+ guild,
3147
+ channel,
3148
+ inviter: payload.inviter ?? null,
3149
+ member_count: payload.member_count,
3150
+ presence_count: payload.presence_count,
3151
+ expires_at: payload.expires_at,
3152
+ temporary: payload.temporary,
3153
+ created_at: payload.created_at,
3154
+ uses: payload.uses,
3155
+ max_uses: payload.max_uses,
3156
+ max_age: payload.max_age
3157
+ };
3158
+ }
2823
3159
  handlers.set("MESSAGE_CREATE", async (client, d) => {
2824
3160
  const data = d;
2825
3161
  if (data.guild_id && data.member && data.author) {
@@ -3011,8 +3347,25 @@ handlers.set("GUILD_MEMBER_REMOVE", async (client, d) => {
3011
3347
  }
3012
3348
  client.emit(Events.GuildMemberRemove, member);
3013
3349
  });
3350
+ handlers.set("GUILD_MEMBERS_CHUNK", async (client, d) => {
3351
+ const data = d;
3352
+ const guild = client.guilds.get(data.guild_id);
3353
+ if (guild) {
3354
+ for (const m of data.members ?? []) {
3355
+ if (m?.user?.id) {
3356
+ const memberData = { ...m, guild_id: guild.id };
3357
+ const member = new GuildMember(client, memberData, guild);
3358
+ guild.members.set(member.id, member);
3359
+ }
3360
+ }
3361
+ }
3362
+ client.emit(Events.GuildMembersChunk, data);
3363
+ });
3014
3364
  handlers.set("INTERACTION_CREATE", async (client, d) => {
3015
- client.emit(Events.InteractionCreate, d);
3365
+ client.emit(
3366
+ Events.InteractionCreate,
3367
+ createInteraction(client, d)
3368
+ );
3016
3369
  });
3017
3370
  handlers.set("VOICE_STATE_UPDATE", async (client, d) => {
3018
3371
  client.emit(Events.VoiceStateUpdate, d);
@@ -3107,7 +3460,14 @@ handlers.set("CHANNEL_PINS_UPDATE", async (client, d) => {
3107
3460
  client.emit(Events.ChannelPinsUpdate, d);
3108
3461
  });
3109
3462
  handlers.set("INVITE_CREATE", async (client, d) => {
3110
- const data = d;
3463
+ const data = normalizeInviteCreatePayload(client, d);
3464
+ if (!data) {
3465
+ client.emit(
3466
+ Events.Debug,
3467
+ "[Gateway] INVITE_CREATE payload had no invite code (documented as possibly empty)"
3468
+ );
3469
+ return;
3470
+ }
3111
3471
  client.emit(Events.InviteCreate, new Invite(client, data));
3112
3472
  });
3113
3473
  handlers.set("INVITE_DELETE", async (client, d) => {
@@ -3151,6 +3511,7 @@ var Client = class extends EventEmitter3 {
3151
3511
  constructor(options = {}) {
3152
3512
  super();
3153
3513
  this.options = options;
3514
+ this.setMaxListeners(0);
3154
3515
  this.events = createEventMethods(this);
3155
3516
  Object.defineProperty(this.channels, "cache", {
3156
3517
  get: () => this.channels,
@@ -3185,8 +3546,25 @@ var Client = class extends EventEmitter3 {
3185
3546
  _pendingGuildIds = null;
3186
3547
  /** Timeout for guild stream when READY has no guilds (gateway sends only GUILD_CREATE). Cleared in finally. */
3187
3548
  _guildStreamSettleTimeout = null;
3549
+ /**
3550
+ * When waitForGuilds delays Ready, gateway dispatches (except GUILD_CREATE) are queued and replayed after Ready.
3551
+ * Ensures user handlers that assume post-Ready setup (e.g. DB in Ready) do not run during the guild sync window.
3552
+ */
3553
+ _deferredGatewayDispatches = [];
3188
3554
  /** Per-channel message cache (channelId -> messageId -> APIMessage). Used when options.cache.messages > 0. */
3189
3555
  _messageCaches = null;
3556
+ on(event, listener) {
3557
+ return super.on(event, listener);
3558
+ }
3559
+ once(event, listener) {
3560
+ return super.once(event, listener);
3561
+ }
3562
+ off(event, listener) {
3563
+ return super.off(event, listener);
3564
+ }
3565
+ emit(event, ...args) {
3566
+ return super.emit(event, ...args);
3567
+ }
3190
3568
  /**
3191
3569
  * Resolve an emoji argument to the API format (unicode or "name:id").
3192
3570
  * Supports: <:name:id>, :name:, name:id, { name, id }, unicode.
@@ -3206,7 +3584,9 @@ var Client = class extends EventEmitter3 {
3206
3584
  const parsed = parseEmoji(
3207
3585
  typeof emoji === "string" ? emoji : emoji.id ? `:${emoji.name}:` : emoji.name
3208
3586
  );
3209
- if (!parsed) throw new Error("Invalid emoji");
3587
+ if (!parsed) {
3588
+ throw new FluxerError("Invalid emoji", { code: ErrorCodes.InvalidEmoji });
3589
+ }
3210
3590
  if (parsed.id) {
3211
3591
  if (guildId) {
3212
3592
  await this.assertEmojiInGuild(parsed.id, guildId);
@@ -3221,13 +3601,15 @@ var Client = class extends EventEmitter3 {
3221
3601
  const list = Array.isArray(emojis) ? emojis : Object.values(emojis ?? {});
3222
3602
  const found = list.find((e) => e.name && e.name.toLowerCase() === parsed.name.toLowerCase());
3223
3603
  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.`
3604
+ throw new FluxerError(
3605
+ `Custom emoji ":${parsed.name}:" not found in guild. Use name:id or <:name:id> format.`,
3606
+ { code: ErrorCodes.EmojiNotFound }
3226
3607
  );
3227
3608
  }
3228
3609
  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().`
3610
+ throw new FluxerError(
3611
+ `Custom emoji ":${parsed.name}:" requires guild context. Use message.react() in a guild channel, or pass guildId to client.resolveEmoji().`,
3612
+ { code: ErrorCodes.EmojiRequiresGuild }
3231
3613
  );
3232
3614
  }
3233
3615
  return parsed.name;
@@ -3254,6 +3636,20 @@ var Client = class extends EventEmitter3 {
3254
3636
  async fetchInstance() {
3255
3637
  return this.rest.get(Routes20.instance(), { auth: false });
3256
3638
  }
3639
+ /**
3640
+ * Fetch instance discovery document (API URL, gateway URL, features). GET /.well-known/fluxer.
3641
+ * Does not require authentication.
3642
+ */
3643
+ async fetchInstanceDiscovery() {
3644
+ return this.rest.get(Routes20.instanceDiscovery(), { auth: false });
3645
+ }
3646
+ /**
3647
+ * Fetch gateway connection metadata (WebSocket URL, recommended shards, session limits).
3648
+ * GET /gateway/bot (authenticated).
3649
+ */
3650
+ async fetchGatewayInfo() {
3651
+ return this.rest.get(Routes20.gatewayBot());
3652
+ }
3257
3653
  /**
3258
3654
  * Fetch a message by channel and message ID. Use when you have IDs (e.g. from a DB).
3259
3655
  * @param channelId - Snowflake of the channel
@@ -3337,7 +3733,11 @@ var Client = class extends EventEmitter3 {
3337
3733
  }
3338
3734
  /** WebSocket manager. Throws if not logged in. */
3339
3735
  get ws() {
3340
- if (!this._ws) throw new Error("Client is not logged in");
3736
+ if (!this._ws) {
3737
+ throw new FluxerError("Client is not logged in. Call login() first.", {
3738
+ code: ErrorCodes.NotLoggedIn
3739
+ });
3740
+ }
3341
3741
  return this._ws;
3342
3742
  }
3343
3743
  /**
@@ -3348,14 +3748,62 @@ var Client = class extends EventEmitter3 {
3348
3748
  sendToGateway(shardId, payload) {
3349
3749
  this.ws.send(shardId, payload);
3350
3750
  }
3351
- async handleDispatch(payload) {
3352
- if (payload.op !== 0 || !payload.t) return;
3353
- 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)));
3751
+ /**
3752
+ * While {@link ClientOptions.waitForGuilds} delays Ready, defer user-facing dispatch handling until Ready fires.
3753
+ * GUILD_CREATE must still run immediately so guild cache and {@link Client._onGuildReceived} can finish the handshake.
3754
+ */
3755
+ _shouldDeferGatewayDispatchUntilReady(payload) {
3756
+ if (this.options.waitForGuilds !== true || this.readyAt !== null) return false;
3757
+ if (payload.op !== 0 || !payload.t) return false;
3758
+ if (payload.t === "GUILD_CREATE") return false;
3759
+ return true;
3760
+ }
3761
+ /**
3762
+ * Run gateway event handlers. By default (see {@link ClientOptions.gatewayDeferHandlers}) work is deferred to the next
3763
+ * macrotask so user code does not block the WebSocket `message` callback.
3764
+ */
3765
+ handleDispatch(payload) {
3766
+ if (payload.op !== 0 || !payload.t) return Promise.resolve();
3767
+ if (this._shouldDeferGatewayDispatchUntilReady(payload)) {
3768
+ this._deferredGatewayDispatches.push(payload);
3769
+ return Promise.resolve();
3770
+ }
3771
+ return this._dispatchGatewayPayload(payload);
3772
+ }
3773
+ _dispatchGatewayPayload(payload) {
3774
+ const event = payload.t;
3775
+ if (!event) return Promise.resolve();
3776
+ const { d } = payload;
3777
+ const handler = eventHandlers.get(event);
3778
+ if (!handler) return Promise.resolve();
3779
+ const run = async () => {
3780
+ try {
3781
+ await handler(this, d);
3782
+ } catch (err) {
3783
+ this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)));
3784
+ }
3785
+ };
3786
+ if (this.options.gatewayDeferHandlers === false) {
3787
+ return run();
3788
+ }
3789
+ return new Promise((resolve, reject) => {
3790
+ const start = () => {
3791
+ void run().then(resolve).catch(reject);
3792
+ };
3793
+ if (typeof setImmediate === "function") {
3794
+ setImmediate(start);
3795
+ } else {
3796
+ setTimeout(start, 0);
3797
+ }
3798
+ });
3799
+ }
3800
+ async _flushDeferredGatewayDispatches() {
3801
+ while (this._deferredGatewayDispatches.length > 0) {
3802
+ const batch = this._deferredGatewayDispatches;
3803
+ this._deferredGatewayDispatches = [];
3804
+ for (const p of batch) {
3805
+ await this._dispatchGatewayPayload(p);
3806
+ }
3359
3807
  }
3360
3808
  }
3361
3809
  /**
@@ -3388,6 +3836,7 @@ var Client = class extends EventEmitter3 {
3388
3836
  presence: this.options.presence,
3389
3837
  rest: { get: (route) => this.rest.get(route) },
3390
3838
  version: this.options.rest?.version ?? "1",
3839
+ debug: this.options.gatewayDebug !== false,
3391
3840
  WebSocket: this.options.WebSocket
3392
3841
  });
3393
3842
  this._ws.on("dispatch", ({ payload }) => {
@@ -3455,6 +3904,9 @@ var Client = class extends EventEmitter3 {
3455
3904
  this._pendingGuildIds = null;
3456
3905
  this.readyAt = /* @__PURE__ */ new Date();
3457
3906
  this.emit(Events.Ready);
3907
+ void this._flushDeferredGatewayDispatches().catch(
3908
+ (err) => this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)))
3909
+ );
3458
3910
  }
3459
3911
  /**
3460
3912
  * Called by GUILD_CREATE handler when waitForGuilds is enabled.
@@ -3472,6 +3924,7 @@ var Client = class extends EventEmitter3 {
3472
3924
  clearTimeout(this._guildStreamSettleTimeout);
3473
3925
  this._guildStreamSettleTimeout = null;
3474
3926
  }
3927
+ this._deferredGatewayDispatches = [];
3475
3928
  if (this._ws) {
3476
3929
  this._ws.destroy();
3477
3930
  this._ws = null;
@@ -3508,7 +3961,7 @@ var Client = class extends EventEmitter3 {
3508
3961
  };
3509
3962
 
3510
3963
  // src/index.ts
3511
- import { EmbedBuilder as EmbedBuilder3, MessagePayload, AttachmentBuilder } from "@fluxerjs/builders";
3964
+ import { EmbedBuilder as EmbedBuilder4, MessagePayload, AttachmentBuilder } from "@fluxerjs/builders";
3512
3965
  import { Routes as Routes21, GatewayOpcodes, MessageAttachmentFlags } from "@fluxerjs/types";
3513
3966
  import { resolveTenorToImageUrl, parseUserMention, parsePrefixCommand } from "@fluxerjs/util";
3514
3967
  import {
@@ -3521,14 +3974,16 @@ import {
3521
3974
  export {
3522
3975
  AttachmentBuilder,
3523
3976
  Base,
3977
+ BaseInteraction,
3524
3978
  CDN_URL,
3525
3979
  CategoryChannel,
3526
3980
  Channel,
3527
3981
  ChannelManager,
3982
+ ChatInputCommandInteraction,
3528
3983
  Client,
3529
3984
  ClientUser,
3530
3985
  DMChannel,
3531
- EmbedBuilder3 as EmbedBuilder,
3986
+ EmbedBuilder4 as EmbedBuilder,
3532
3987
  ErrorCodes,
3533
3988
  Events,
3534
3989
  FluxerError,
@@ -3568,6 +4023,8 @@ export {
3568
4023
  cdnDisplayAvatarURL,
3569
4024
  cdnMemberAvatarURL,
3570
4025
  cdnMemberBannerURL,
4026
+ createInteraction,
4027
+ isChatInputCommandInteraction,
3571
4028
  parsePrefixCommand,
3572
4029
  parseUserMention,
3573
4030
  resolvePermissionsToBitfield3 as resolvePermissionsToBitfield,