@fluxerjs/core 3.2.0 → 3.4.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
@@ -7,8 +7,11 @@ import {
7
7
  } from "@fluxerjs/builders";
8
8
  import {
9
9
  AuditLogActionType,
10
- ChannelType as ChannelType5,
10
+ ChannelType as ChannelType11,
11
11
  ContentWarningLevel,
12
+ ForumLayout,
13
+ ForumSortOrder,
14
+ ForumTagSetting,
12
15
  GatewayOpcodes as GatewayOpcodes3,
13
16
  GuildMemberProfileFlags,
14
17
  GuildNSFWLevel as GuildNSFWLevel2,
@@ -21,9 +24,11 @@ import {
21
24
  OverwriteType as OverwriteType2,
22
25
  PublicUserFlags,
23
26
  RelationshipType,
24
- Routes as Routes35,
27
+ Routes as Routes38,
25
28
  SplashCardAlignment,
26
- SystemChannelFlags
29
+ SystemChannelFlags,
30
+ ThreadAutoArchiveDuration,
31
+ ThreadMemberFlags
27
32
  } from "@fluxerjs/types";
28
33
  import {
29
34
  createLogger as createLogger2,
@@ -181,10 +186,10 @@ var CacheController = class {
181
186
 
182
187
  // src/ClientCore/ChannelManager.ts
183
188
  import { LimitedCollection } from "@fluxerjs/collection";
184
- import { Routes as Routes19 } from "@fluxerjs/types";
189
+ import { Routes as Routes22 } from "@fluxerjs/types";
185
190
 
186
191
  // src/Domain/Channel/Base.ts
187
- import { ChannelType, Routes as Routes7 } from "@fluxerjs/types";
192
+ import { ChannelType as ChannelType3, Routes as Routes7 } from "@fluxerjs/types";
188
193
  import { SnowflakeUtil as SnowflakeUtil3 } from "@fluxerjs/util";
189
194
 
190
195
  // src/ClientCore/MessageManager.ts
@@ -265,7 +270,132 @@ function toAttachmentUploadPlanResponse(data) {
265
270
  }
266
271
 
267
272
  // src/ClientCore/SdkOptions/Channels.ts
273
+ import { ChannelType as ChannelType2 } from "@fluxerjs/types";
268
274
  import { resolvePermissionsToBitfield } from "@fluxerjs/util";
275
+
276
+ // src/ClientCore/SdkOptions/Threads.ts
277
+ import {
278
+ ChannelType
279
+ } from "@fluxerjs/types";
280
+ function toThreadEditBody(type, options) {
281
+ const body = {};
282
+ if (options.name !== void 0) body.name = options.name;
283
+ if (options.archived !== void 0) body.archived = options.archived;
284
+ if (options.autoArchiveDuration !== void 0) {
285
+ body.auto_archive_duration = options.autoArchiveDuration;
286
+ }
287
+ if (options.locked !== void 0) body.locked = options.locked;
288
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
289
+ if (options.flags !== void 0) body.flags = options.flags;
290
+ if (options.appliedTags !== void 0 && type !== ChannelType.PrivateThread) {
291
+ body.applied_tags = options.appliedTags;
292
+ }
293
+ if (options.invitable !== void 0 && type === ChannelType.PrivateThread) {
294
+ body.invitable = options.invitable;
295
+ }
296
+ return body;
297
+ }
298
+ function toThreadParentEditBody(options) {
299
+ const body = {};
300
+ if (options.autoArchiveDuration !== void 0) {
301
+ body.default_auto_archive_duration = options.autoArchiveDuration;
302
+ }
303
+ if (options.rateLimitPerUser !== void 0) {
304
+ body.default_thread_rate_limit_per_user = options.rateLimitPerUser;
305
+ }
306
+ return body;
307
+ }
308
+ function toStartThreadBody(channelType, options) {
309
+ const type = options.type ?? (channelType === ChannelType.GuildAnnouncement ? ChannelType.AnnouncementThread : ChannelType.PublicThread);
310
+ const body = { name: options.name, type };
311
+ if (options.autoArchiveDuration !== void 0) {
312
+ body.auto_archive_duration = options.autoArchiveDuration;
313
+ }
314
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
315
+ if (options.invitable !== void 0) body.invitable = options.invitable;
316
+ return body;
317
+ }
318
+ function toStartThreadFromMessageBody(options) {
319
+ const body = { name: options.name };
320
+ if (options.autoArchiveDuration !== void 0) {
321
+ body.auto_archive_duration = options.autoArchiveDuration;
322
+ }
323
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
324
+ return body;
325
+ }
326
+ function toForumThreadMessage(body) {
327
+ const message = {};
328
+ if (body.content !== void 0) message.content = body.content;
329
+ if (body.embeds !== void 0) message.embeds = body.embeds;
330
+ if (body.attachments !== void 0) message.attachments = body.attachments;
331
+ if (body.allowed_mentions !== void 0) message.allowed_mentions = body.allowed_mentions;
332
+ if (body.flags !== void 0) message.flags = body.flags;
333
+ if (body.sticker_ids !== void 0) message.sticker_ids = body.sticker_ids;
334
+ return message;
335
+ }
336
+ function toForumTagBody(options) {
337
+ const body = { name: options.name };
338
+ if ("id" in options && options.id !== void 0) body.id = options.id;
339
+ if (options.moderated !== void 0) body.moderated = options.moderated;
340
+ if (options.emojiId !== void 0) body.emoji_id = options.emojiId;
341
+ if (options.emojiName !== void 0) body.emoji_name = options.emojiName;
342
+ return body;
343
+ }
344
+ function forumParentWire(options, includeLayout) {
345
+ const body = {};
346
+ if (options.availableTags !== void 0) {
347
+ body.available_tags = options.availableTags.map((tag) => toForumTagBody(tag));
348
+ }
349
+ if (options.defaultReactionEmoji !== void 0) {
350
+ body.default_reaction_emoji = options.defaultReactionEmoji === null ? null : reactionEmojiWire(options.defaultReactionEmoji);
351
+ }
352
+ if (options.defaultSortOrder !== void 0) body.default_sort_order = options.defaultSortOrder;
353
+ if (options.defaultTagSetting !== void 0) body.default_tag_setting = options.defaultTagSetting;
354
+ if (options.flags !== void 0) body.flags = options.flags;
355
+ if (options.defaultAutoArchiveDuration !== void 0) {
356
+ body.default_auto_archive_duration = options.defaultAutoArchiveDuration;
357
+ }
358
+ if (options.defaultThreadRateLimitPerUser !== void 0) {
359
+ body.default_thread_rate_limit_per_user = options.defaultThreadRateLimitPerUser;
360
+ }
361
+ if (includeLayout && options.defaultForumLayout !== void 0) {
362
+ body.default_forum_layout = options.defaultForumLayout;
363
+ }
364
+ return body;
365
+ }
366
+ function reactionEmojiWire(emoji) {
367
+ const body = {};
368
+ if (emoji.emojiId !== void 0) body.emoji_id = emoji.emojiId;
369
+ if (emoji.emojiName !== void 0) body.emoji_name = emoji.emojiName;
370
+ return body;
371
+ }
372
+ function toThreadMemberSettingsBody(options) {
373
+ const body = {};
374
+ if (options.flags !== void 0) body.flags = options.flags;
375
+ if (options.muted !== void 0) body.muted = options.muted;
376
+ if (options.muteConfig !== void 0) {
377
+ body.mute_config = options.muteConfig === null ? null : {
378
+ ...options.muteConfig.endTime !== void 0 ? { end_time: options.muteConfig.endTime } : {},
379
+ selected_time_window: options.muteConfig.selectedTimeWindow
380
+ };
381
+ }
382
+ return body;
383
+ }
384
+ function withQuery(path, params) {
385
+ const query = new URLSearchParams();
386
+ for (const [key, value] of Object.entries(params)) {
387
+ if (value === void 0) continue;
388
+ if (Array.isArray(value)) {
389
+ for (const item of value) query.append(key, item);
390
+ continue;
391
+ }
392
+ query.set(key, String(value));
393
+ }
394
+ const text = query.toString();
395
+ return text ? `${path}?${text}` : path;
396
+ }
397
+
398
+ // src/ClientCore/SdkOptions/Channels.ts
269
399
  function toOverwriteWire(overwrite) {
270
400
  return {
271
401
  id: overwrite.id,
@@ -326,6 +456,16 @@ function toChannelCreateBody(options) {
326
456
  body.content_warning_text = options.contentWarningText;
327
457
  }
328
458
  if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
459
+ if (options.defaultAutoArchiveDuration !== void 0) {
460
+ body.default_auto_archive_duration = options.defaultAutoArchiveDuration;
461
+ }
462
+ if (options.defaultThreadRateLimitPerUser !== void 0) {
463
+ body.default_thread_rate_limit_per_user = options.defaultThreadRateLimitPerUser;
464
+ }
465
+ const forumParent = options.type === ChannelType2.GuildForum || options.type === ChannelType2.GuildMedia;
466
+ if (forumParent) {
467
+ Object.assign(body, forumParentWire(options, options.type === ChannelType2.GuildForum));
468
+ }
329
469
  return body;
330
470
  }
331
471
  function toChannelInviteBody(options) {
@@ -1006,6 +1146,7 @@ var Events = {
1006
1146
  GuildEmojisUpdate: "guildEmojisUpdate",
1007
1147
  GuildStickersUpdate: "guildStickersUpdate",
1008
1148
  GuildCountsUpdate: "guildCountsUpdate",
1149
+ GuildHealthUpdate: "guildHealthUpdate",
1009
1150
  ChannelMemberCountsUpdate: "channelMemberCountsUpdate",
1010
1151
  GuildMemberAdd: "guildMemberAdd",
1011
1152
  GuildMemberUpdate: "guildMemberUpdate",
@@ -1017,6 +1158,14 @@ var Events = {
1017
1158
  ChannelCreate: "channelCreate",
1018
1159
  ChannelUpdate: "channelUpdate",
1019
1160
  ChannelDelete: "channelDelete",
1161
+ ThreadCreate: "threadCreate",
1162
+ ThreadUpdate: "threadUpdate",
1163
+ ThreadDelete: "threadDelete",
1164
+ ThreadListSync: "threadListSync",
1165
+ ThreadMemberUpdate: "threadMemberUpdate",
1166
+ ThreadMembersUpdate: "threadMembersUpdate",
1167
+ ThreadMemberListUpdate: "threadMemberListUpdate",
1168
+ ForumUnreads: "forumUnreads",
1020
1169
  ChannelPinsUpdate: "channelPinsUpdate",
1021
1170
  ChannelRecipientAdd: "channelRecipientAdd",
1022
1171
  ChannelRecipientRemove: "channelRecipientRemove",
@@ -1032,6 +1181,8 @@ var Events = {
1032
1181
  VoiceStateAck: "voiceStateAck",
1033
1182
  VoiceServerUpdate: "voiceServerUpdate",
1034
1183
  EntranceSoundPlay: "entranceSoundPlay",
1184
+ VoiceSignal: "voiceSignal",
1185
+ OperatorPassUpdate: "operatorPassUpdate",
1035
1186
  VoiceStatesSync: "voiceStatesSync",
1036
1187
  WebhooksUpdate: "webhooksUpdate",
1037
1188
  Resumed: "resumed",
@@ -1154,6 +1305,30 @@ var ReactionCollector = class _ReactionCollector extends EventEmitter {
1154
1305
  }
1155
1306
  };
1156
1307
 
1308
+ // src/Domain/Channel/ThreadCache.ts
1309
+ function cacheThread(client, data) {
1310
+ const existing = client.channels.get(data.id);
1311
+ if (existing?.isThread() && existing.type === data.type) {
1312
+ existing._patch(data);
1313
+ placeThread(client, existing);
1314
+ return existing;
1315
+ }
1316
+ const created = Channel.from(client, data);
1317
+ if (!created.isThread()) {
1318
+ throw new FluxerError(`Channel ${data.id} is not a thread`, {
1319
+ code: ErrorCodes.InvalidChannelType
1320
+ });
1321
+ }
1322
+ placeThread(client, created);
1323
+ return created;
1324
+ }
1325
+ function placeThread(client, thread) {
1326
+ client.channels.set(thread.id, thread);
1327
+ if (!thread.guildId) return;
1328
+ const guild = client.guilds.get(thread.guildId);
1329
+ if (guild) guild.channels.set(thread.id, thread);
1330
+ }
1331
+
1157
1332
  // src/Domain/Message/Attachment.ts
1158
1333
  function toMessageAttachment(data) {
1159
1334
  return {
@@ -1625,6 +1800,8 @@ var Message = class _Message extends Base {
1625
1800
  nonce;
1626
1801
  /** IDs of custom emojis in the message classified as explicit. */
1627
1802
  nsfwEmojis;
1803
+ /** Thread started from this message, when the payload included one. */
1804
+ thread;
1628
1805
  /**
1629
1806
  * Cached text-capable channel (guild text, guild voice, or DM), or null if uncached / not text-based.
1630
1807
  * Narrowed type has {@link Channel.send} and {@link Channel.delete}.
@@ -1672,10 +1849,10 @@ var Message = class _Message extends Base {
1672
1849
  this.channelId = data.channel_id;
1673
1850
  this.guildId = data.guild_id ?? null;
1674
1851
  this.author = client.getOrCreateUser(data.author);
1675
- this.content = data.content;
1676
- this.createdAt = new Date(data.timestamp);
1852
+ this.content = data.content ?? "";
1853
+ this.createdAt = data.timestamp ? new Date(data.timestamp) : /* @__PURE__ */ new Date(0);
1677
1854
  this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
1678
- this.pinned = data.pinned;
1855
+ this.pinned = data.pinned ?? false;
1679
1856
  this.attachments = new Collection3();
1680
1857
  for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
1681
1858
  this.type = data.type ?? MessageType.Default;
@@ -1700,39 +1877,55 @@ var Message = class _Message extends Base {
1700
1877
  this.mentionRoles = data.mention_roles ?? [];
1701
1878
  this.nonce = data.nonce ?? null;
1702
1879
  this.nsfwEmojis = data.nsfw_emojis ?? [];
1880
+ this.thread = data.thread ? cacheThread(client, data.thread) : null;
1703
1881
  }
1704
1882
  /**
1705
1883
  * Apply an API message payload in place (cache identity / MESSAGE_UPDATE).
1706
1884
  * @internal
1707
1885
  */
1708
1886
  _patch(data) {
1709
- this.content = data.content;
1710
- this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
1711
- this.pinned = data.pinned;
1712
- this.attachments.clear();
1713
- for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
1714
- this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
1715
- this.mentionEveryone = data.mention_everyone ?? false;
1716
- this.tts = data.tts ?? false;
1717
- this.embeds = (data.embeds ?? []).map(toMessageEmbed);
1718
- this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(this.client, s));
1719
- this.reactions._patch(data.reactions);
1720
- this.messageReference = data.message_reference ? {
1721
- channelId: data.message_reference.channel_id,
1722
- messageId: data.message_reference.message_id,
1723
- guildId: data.message_reference.guild_id ?? null,
1724
- ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
1725
- } : null;
1726
- this.messageSnapshots = (data.message_snapshots ?? []).map(
1727
- (s) => toMessageSnapshot(this.client, s)
1728
- );
1729
- this.call = data.call ? toMessageCall(data.call) : null;
1730
- this.referencedMessage = data.referenced_message ? new _Message(this.client, data.referenced_message) : null;
1731
- this.webhookId = data.webhook_id ?? null;
1732
- this.mentions = (data.mentions ?? []).map((u) => this.client.getOrCreateUser(u));
1733
- this.mentionRoles = data.mention_roles ?? [];
1734
- this.nonce = data.nonce ?? null;
1735
- this.nsfwEmojis = data.nsfw_emojis ?? [];
1887
+ if (data.content !== void 0) this.content = data.content ?? "";
1888
+ if (data.edited_timestamp !== void 0) {
1889
+ this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
1890
+ }
1891
+ if (data.pinned !== void 0) this.pinned = data.pinned;
1892
+ if (data.attachments !== void 0) {
1893
+ this.attachments.clear();
1894
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
1895
+ }
1896
+ if (data.flags !== void 0) this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
1897
+ if (data.mention_everyone !== void 0) this.mentionEveryone = data.mention_everyone;
1898
+ if (data.tts !== void 0) this.tts = data.tts;
1899
+ if (data.embeds !== void 0) this.embeds = (data.embeds ?? []).map(toMessageEmbed);
1900
+ if (data.stickers !== void 0) {
1901
+ this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(this.client, s));
1902
+ }
1903
+ if (data.reactions !== void 0) this.reactions._patch(data.reactions);
1904
+ if (data.message_reference !== void 0) {
1905
+ this.messageReference = data.message_reference ? {
1906
+ channelId: data.message_reference.channel_id,
1907
+ messageId: data.message_reference.message_id,
1908
+ guildId: data.message_reference.guild_id ?? null,
1909
+ ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
1910
+ } : null;
1911
+ }
1912
+ if (data.message_snapshots !== void 0) {
1913
+ this.messageSnapshots = (data.message_snapshots ?? []).map(
1914
+ (s) => toMessageSnapshot(this.client, s)
1915
+ );
1916
+ }
1917
+ if (data.call !== void 0) this.call = data.call ? toMessageCall(data.call) : null;
1918
+ if (data.referenced_message !== void 0) {
1919
+ this.referencedMessage = data.referenced_message ? new _Message(this.client, data.referenced_message) : null;
1920
+ }
1921
+ if (data.webhook_id !== void 0) this.webhookId = data.webhook_id ?? null;
1922
+ if (data.mentions !== void 0) {
1923
+ this.mentions = (data.mentions ?? []).map((u) => this.client.getOrCreateUser(u));
1924
+ }
1925
+ if (data.mention_roles !== void 0) this.mentionRoles = data.mention_roles ?? [];
1926
+ if (data.nonce !== void 0) this.nonce = data.nonce ?? null;
1927
+ if (data.nsfw_emojis !== void 0) this.nsfwEmojis = data.nsfw_emojis ?? [];
1928
+ if (data.thread) this.thread = cacheThread(this.client, data.thread);
1736
1929
  }
1737
1930
  /**
1738
1931
  * Send a standalone message in this channel (not a reply).
@@ -1811,10 +2004,44 @@ var Message = class _Message extends Base {
1811
2004
  awaitReactions(options) {
1812
2005
  return ReactionCollector.awaitReactions(this.client, this.id, this.channelId, options);
1813
2006
  }
2007
+ /**
2008
+ * Start a thread from this message.
2009
+ * Fluxer chooses a public or announcement thread from the parent channel.
2010
+ */
2011
+ async startThread(options) {
2012
+ const data = await this.client.rest.post(
2013
+ Routes4.channelMessageThreads(this.channelId, this.id),
2014
+ {
2015
+ body: toStartThreadFromMessageBody(options),
2016
+ auth: true,
2017
+ ...auditReasonHeaders(options.reason)
2018
+ }
2019
+ );
2020
+ const thread = cacheThread(this.client, data);
2021
+ this.thread = thread;
2022
+ return thread;
2023
+ }
1814
2024
  /** Fetch the latest version of this message from the API. */
1815
2025
  async fetch() {
1816
2026
  return this.client.channels.fetchMessage(this.channelId, this.id);
1817
2027
  }
2028
+ /** Publish this announcement message to channels following its channel. */
2029
+ async crosspost() {
2030
+ const data = await this.client.rest.post(
2031
+ Routes4.channelMessageCrosspost(this.channelId, this.id),
2032
+ { auth: true }
2033
+ );
2034
+ const published = new _Message(this.client, data);
2035
+ this.client._addMessageToCache(this.channelId, data);
2036
+ return published;
2037
+ }
2038
+ /** Fetch the source guild of a crossposted (followed-channel) message. */
2039
+ async fetchCrosspostSource() {
2040
+ return this.client.rest.get(
2041
+ Routes4.channelMessageCrosspostSource(this.channelId, this.id),
2042
+ { auth: true }
2043
+ );
2044
+ }
1818
2045
  /** Delete this message. */
1819
2046
  async delete(reason) {
1820
2047
  await this.client.rest.delete(Routes4.channelMessage(this.channelId, this.id), {
@@ -1917,6 +2144,43 @@ var PartialMessage = class {
1917
2144
  }
1918
2145
  };
1919
2146
 
2147
+ // src/ClientCore/Resolve.ts
2148
+ function normalizeSnowflakeId(value, label) {
2149
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
2150
+ throw new TypeError(
2151
+ `${label} received an unsafe numeric ID; pass snowflakes as strings to avoid precision loss`
2152
+ );
2153
+ }
2154
+ const id = typeof value === "bigint" ? value.toString() : String(value ?? "").trim();
2155
+ if (!id || id === "undefined" || id === "null" || id === "[object Object]") {
2156
+ throw new TypeError(`${label} requires a non-empty ID`);
2157
+ }
2158
+ return id;
2159
+ }
2160
+ function assertApiObjectWithId(data, label) {
2161
+ if (!data || typeof data !== "object" || typeof data.id !== "string" || data.id.length === 0) {
2162
+ throw new TypeError(`${label} received an invalid API payload (missing string id)`);
2163
+ }
2164
+ return data;
2165
+ }
2166
+ function assertApiArray(data, label) {
2167
+ if (!Array.isArray(data)) {
2168
+ throw new TypeError(`${label} received an invalid API payload (expected an array)`);
2169
+ }
2170
+ return data;
2171
+ }
2172
+ async function dedupeFetch(pending, key, fn) {
2173
+ const existing = pending.get(key);
2174
+ if (existing) return existing;
2175
+ const request = fn();
2176
+ pending.set(key, request);
2177
+ try {
2178
+ return await request;
2179
+ } finally {
2180
+ if (pending.get(key) === request) pending.delete(key);
2181
+ }
2182
+ }
2183
+
1920
2184
  // src/ClientCore/MessageManager.ts
1921
2185
  var BULK = {
1922
2186
  requests: { min: 1, max: 25 },
@@ -1953,25 +2217,32 @@ var MessageManager = class {
1953
2217
  }
1954
2218
  /** Structure cache keyed by message id (identity for {@link get}). */
1955
2219
  _structures = new Collection4();
2220
+ pendingFetches = /* @__PURE__ */ new Map();
1956
2221
  /** Retrieve a cached message by ID, or `undefined` if missing / caching disabled. */
1957
2222
  get(messageId) {
1958
- const data = this.client._getMessageCache(this.channelId)?.get(messageId);
2223
+ const id = String(messageId ?? "").trim();
2224
+ if (!id) return void 0;
2225
+ const data = this.client._getMessageCache(this.channelId)?.get(id);
1959
2226
  if (!data) {
1960
- this._structures.delete(messageId);
2227
+ this._structures.delete(id);
1961
2228
  return void 0;
1962
2229
  }
1963
- const existing = this._structures.get(messageId);
1964
- if (existing) return existing;
2230
+ const existing = this._structures.get(id);
2231
+ if (existing) {
2232
+ existing._patch(data);
2233
+ return existing;
2234
+ }
1965
2235
  const message = new Message(this.client, data);
1966
- this._structures.set(messageId, message);
2236
+ this._structures.set(id, message);
1967
2237
  return message;
1968
2238
  }
1969
2239
  /** Retrieve from cache, otherwise {@link fetch}. */
1970
2240
  async resolve(messageId) {
1971
- return this.get(messageId) ?? this.fetch(messageId);
2241
+ const id = normalizeSnowflakeId(messageId, "messages.resolve()");
2242
+ return this.get(id) ?? this.fetch(id);
1972
2243
  }
1973
2244
  async fetch(idOrOptions) {
1974
- return typeof idOrOptions === "string" ? this.fetchOne(idOrOptions) : this.fetchMany(idOrOptions);
2245
+ return typeof idOrOptions === "string" || typeof idOrOptions === "number" ? this.fetchOne(normalizeSnowflakeId(idOrOptions, "messages.fetch()")) : this.fetchMany(idOrOptions);
1975
2246
  }
1976
2247
  /** Cache API data and return a {@link Message} (reusing identity when present). */
1977
2248
  wrap(data) {
@@ -1988,9 +2259,13 @@ var MessageManager = class {
1988
2259
  }
1989
2260
  /** Fetch a single message from the API. */
1990
2261
  async fetchOne(messageId) {
2262
+ return dedupeFetch(this.pendingFetches, messageId, async () => this.fetchOneFresh(messageId));
2263
+ }
2264
+ async fetchOneFresh(messageId) {
1991
2265
  try {
1992
- const data = await this.client.rest.get(
1993
- Routes5.channelMessage(this.channelId, messageId)
2266
+ const data = assertApiObjectWithId(
2267
+ await this.client.rest.get(Routes5.channelMessage(this.channelId, messageId)),
2268
+ "messages.fetch()"
1994
2269
  );
1995
2270
  return this.wrap(data);
1996
2271
  } catch (err) {
@@ -2016,9 +2291,15 @@ var MessageManager = class {
2016
2291
  if (value != null && value !== "") qs2.set(key, String(value));
2017
2292
  }
2018
2293
  const base = Routes5.channelMessages(this.channelId);
2019
- const data = await this.client.rest.get(qs2.size > 0 ? `${base}?${qs2}` : base);
2294
+ const data = assertApiArray(
2295
+ await this.client.rest.get(qs2.size > 0 ? `${base}?${qs2}` : base),
2296
+ "messages.fetch()"
2297
+ );
2020
2298
  const collection = new Collection4();
2021
- for (const msg of data) collection.set(msg.id, this.wrap(msg));
2299
+ for (const msg of data) {
2300
+ if (!msg?.id) continue;
2301
+ collection.set(msg.id, this.wrap(msg));
2302
+ }
2022
2303
  return collection;
2023
2304
  }
2024
2305
  };
@@ -2222,6 +2503,9 @@ async function uploadAttachmentsForSend(client, channelId, files) {
2222
2503
  }
2223
2504
 
2224
2505
  // src/Domain/Channel/Base.ts
2506
+ function isFullChannelData(data) {
2507
+ return "guild_id" in data || "permission_overwrites" in data || "position" in data || "last_message_id" in data || "topic" in data || "thread_metadata" in data || "available_tags" in data;
2508
+ }
2225
2509
  var Channel = class extends Base {
2226
2510
  #messages;
2227
2511
  /** The {@link Client} that instantiated this channel. */
@@ -2236,6 +2520,11 @@ var Channel = class extends Base {
2236
2520
  icon;
2237
2521
  /** ISO8601 timestamp of the last pinned message update. */
2238
2522
  lastPinTimestamp;
2523
+ /**
2524
+ * True when built from a partial payload (e.g. a DM stub) and not yet hydrated
2525
+ * with a full channel object. `channels.resolve()` refetches partial channels.
2526
+ */
2527
+ partial;
2239
2528
  constructor(client, data) {
2240
2529
  super();
2241
2530
  this.client = client;
@@ -2244,6 +2533,7 @@ var Channel = class extends Base {
2244
2533
  this.name = data.name ?? null;
2245
2534
  this.icon = data.icon ?? null;
2246
2535
  this.lastPinTimestamp = data.last_pin_timestamp ?? null;
2536
+ this.partial = !isFullChannelData(data);
2247
2537
  }
2248
2538
  /** Unix timestamp (ms) when this channel was created, derived from its snowflake ID. */
2249
2539
  get createdTimestamp() {
@@ -2264,6 +2554,7 @@ var Channel = class extends Base {
2264
2554
  if ("last_pin_timestamp" in data && data.last_pin_timestamp !== void 0) {
2265
2555
  this.lastPinTimestamp = data.last_pin_timestamp ?? null;
2266
2556
  }
2557
+ if (isFullChannelData(data)) this.partial = false;
2267
2558
  }
2268
2559
  /** @internal Factory wired after subclasses load. */
2269
2560
  static from(_c, _d) {
@@ -2278,43 +2569,56 @@ var Channel = class extends Base {
2278
2569
  throw new Error("Channel.createDM not initialized");
2279
2570
  }
2280
2571
  /**
2281
- * Whether this channel type can carry messages (text, announcement, voice, DM, group DM, notes).
2572
+ * Whether this channel type can carry messages (text, announcement, voice, threads, DM, group DM, notes).
2573
+ * Forum and media channels contain threads and do not accept `send`.
2282
2574
  * Checks {@link ChannelType}, not whether `send` exists on the instance.
2283
2575
  */
2284
2576
  isTextBased() {
2285
- return this.type === ChannelType.GuildText || this.type === ChannelType.GuildAnnouncement || this.type === ChannelType.GuildVoice || this.type === ChannelType.DM || this.type === ChannelType.GroupDM || this.type === ChannelType.DMPersonalNotes;
2577
+ return this.type === ChannelType3.GuildText || this.type === ChannelType3.GuildAnnouncement || this.type === ChannelType3.GuildVoice || this.type === ChannelType3.DM || this.type === ChannelType3.GroupDM || this.type === ChannelType3.DMPersonalNotes || this.type === ChannelType3.AnnouncementThread || this.type === ChannelType3.PublicThread || this.type === ChannelType3.PrivateThread;
2286
2578
  }
2287
- /** Check if this is a guild channel (text, announcement, voice, category, or link). */
2579
+ /** Check if this is a guild channel, including threads, forums, and media channels. */
2288
2580
  isGuild() {
2289
- return this.type === ChannelType.GuildText || this.type === ChannelType.GuildAnnouncement || this.type === ChannelType.GuildVoice || this.type === ChannelType.GuildCategory || this.type === ChannelType.GuildLink;
2581
+ return this.type === ChannelType3.GuildText || this.type === ChannelType3.GuildAnnouncement || this.type === ChannelType3.GuildVoice || this.type === ChannelType3.GuildCategory || this.type === ChannelType3.GuildLink || this.type === ChannelType3.AnnouncementThread || this.type === ChannelType3.PublicThread || this.type === ChannelType3.PrivateThread || this.type === ChannelType3.GuildForum || this.type === ChannelType3.GuildMedia;
2582
+ }
2583
+ /** Check if this is a thread (public, private, or announcement). */
2584
+ isThread() {
2585
+ return this.type === ChannelType3.AnnouncementThread || this.type === ChannelType3.PublicThread || this.type === ChannelType3.PrivateThread;
2586
+ }
2587
+ /** Check if this is a forum channel. */
2588
+ isForum() {
2589
+ return this.type === ChannelType3.GuildForum;
2590
+ }
2591
+ /** Check if this is a media channel. */
2592
+ isMedia() {
2593
+ return this.type === ChannelType3.GuildMedia;
2290
2594
  }
2291
2595
  /** Check if this is a guild text channel. */
2292
2596
  isText() {
2293
- return this.type === ChannelType.GuildText;
2597
+ return this.type === ChannelType3.GuildText;
2294
2598
  }
2295
2599
  /** Check if this is a guild announcement channel. */
2296
2600
  isAnnouncement() {
2297
- return this.type === ChannelType.GuildAnnouncement;
2601
+ return this.type === ChannelType3.GuildAnnouncement;
2298
2602
  }
2299
2603
  /** Check if this is a category channel. */
2300
2604
  isCategory() {
2301
- return this.type === ChannelType.GuildCategory;
2605
+ return this.type === ChannelType3.GuildCategory;
2302
2606
  }
2303
2607
  /** Check if this is a DM, group DM, or personal notes channel. */
2304
2608
  isDM() {
2305
- return this.type === ChannelType.DM || this.type === ChannelType.GroupDM || this.type === ChannelType.DMPersonalNotes;
2609
+ return this.type === ChannelType3.DM || this.type === ChannelType3.GroupDM || this.type === ChannelType3.DMPersonalNotes;
2306
2610
  }
2307
2611
  /** Check if this is a personal notes channel. */
2308
2612
  isPersonalNotes() {
2309
- return this.type === ChannelType.DMPersonalNotes;
2613
+ return this.type === ChannelType3.DMPersonalNotes;
2310
2614
  }
2311
2615
  /** Check if this is a voice channel. */
2312
2616
  isVoice() {
2313
- return this.type === ChannelType.GuildVoice;
2617
+ return this.type === ChannelType3.GuildVoice;
2314
2618
  }
2315
2619
  /** Check if this is a link channel. */
2316
2620
  isLink() {
2317
- return this.type === ChannelType.GuildLink;
2621
+ return this.type === ChannelType3.GuildLink;
2318
2622
  }
2319
2623
  /**
2320
2624
  * Delete recent messages or an explicit ID list.
@@ -2486,7 +2790,7 @@ var Channel = class extends Base {
2486
2790
  };
2487
2791
 
2488
2792
  // src/Domain/Channel/Dm.ts
2489
- import { ChannelType as ChannelType2, Routes as Routes9 } from "@fluxerjs/types";
2793
+ import { ChannelType as ChannelType4, Routes as Routes9 } from "@fluxerjs/types";
2490
2794
 
2491
2795
  // src/Domain/Channel/TextCapable.ts
2492
2796
  import { Routes as Routes8 } from "@fluxerjs/types";
@@ -2542,7 +2846,7 @@ var DMChannel = class extends TextCapable(Channel) {
2542
2846
  const full = data;
2543
2847
  this.lastMessageId = full.last_message_id ?? null;
2544
2848
  this.ownerId = full.owner_id ?? null;
2545
- this.recipients = (full.recipients ?? []).map((u) => client.getOrCreateUser(u));
2849
+ this.recipients = (full.recipients ?? []).filter((u) => typeof u?.id === "string").map((u) => client.getOrCreateUser(u));
2546
2850
  this.nicks = full.nicks ?? {};
2547
2851
  }
2548
2852
  /**
@@ -2557,7 +2861,7 @@ var DMChannel = class extends TextCapable(Channel) {
2557
2861
  }
2558
2862
  if ("owner_id" in full && full.owner_id !== void 0) this.ownerId = full.owner_id ?? null;
2559
2863
  if ("recipients" in full && full.recipients !== void 0) {
2560
- this.recipients = (full.recipients ?? []).map((u) => this.client.getOrCreateUser(u));
2864
+ this.recipients = (full.recipients ?? []).filter((u) => typeof u?.id === "string").map((u) => this.client.getOrCreateUser(u));
2561
2865
  }
2562
2866
  if ("nicks" in full && full.nicks !== void 0) this.nicks = full.nicks ?? {};
2563
2867
  }
@@ -2578,7 +2882,7 @@ var DMChannel = class extends TextCapable(Channel) {
2578
2882
  * Notes-only; bots usually skip this.
2579
2883
  */
2580
2884
  async purgeMessages() {
2581
- if (this.type !== ChannelType2.DMPersonalNotes) {
2885
+ if (this.type !== ChannelType4.DMPersonalNotes) {
2582
2886
  throw new FluxerError("purgeMessages is only available on personal notes channels", {
2583
2887
  code: ErrorCodes.InvalidChannelType
2584
2888
  });
@@ -2621,6 +2925,12 @@ var DMChannel = class extends TextCapable(Channel) {
2621
2925
  }
2622
2926
  };
2623
2927
 
2928
+ // src/Domain/Channel/Forum.ts
2929
+ import {
2930
+ ChannelType as ChannelType7,
2931
+ Routes as Routes16
2932
+ } from "@fluxerjs/types";
2933
+
2624
2934
  // src/Domain/Channel/Guild.ts
2625
2935
  import { Routes as Routes13 } from "@fluxerjs/types";
2626
2936
  import { PermissionFlags } from "@fluxerjs/util";
@@ -2636,17 +2946,19 @@ import {
2636
2946
  // src/Helpers/Instance.ts
2637
2947
  import { isRecord } from "@fluxerjs/util";
2638
2948
  var DEFAULT_INSTANCE_ENDPOINTS = Object.freeze({
2639
- api: "https://web.fluxer.app/api",
2640
- api_client: "https://web.fluxer.app/api",
2641
- api_public: "https://api.fluxer.app",
2642
- gateway: "wss://gateway.fluxer.app",
2949
+ api: "https://fluxer.com/api",
2950
+ api_client: "https://fluxer.com/api",
2951
+ api_public: "https://fluxer.com/api",
2952
+ gateway: "wss://gateway.fluxer.com",
2643
2953
  media: CDN_URL,
2954
+ upload_relay: "https://uploads.fluxer.app",
2644
2955
  static_cdn: STATIC_CDN_URL,
2645
- marketing: "https://fluxer.app",
2956
+ marketing: "https://fluxer.com",
2957
+ docs: "https://docs.fluxer.com",
2646
2958
  admin: "https://admin.fluxer.app",
2647
2959
  invite: "https://fluxer.gg",
2648
2960
  gift: "https://fluxer.gift",
2649
- webapp: "https://web.fluxer.app"
2961
+ webapp: "https://fluxer.com"
2650
2962
  });
2651
2963
  var ENDPOINT_KEYS = [
2652
2964
  "api",
@@ -2661,6 +2973,11 @@ var ENDPOINT_KEYS = [
2661
2973
  "gift",
2662
2974
  "webapp"
2663
2975
  ];
2976
+ var OPTIONAL_ENDPOINT_KEYS = [
2977
+ "api_transport",
2978
+ "upload_relay",
2979
+ "docs"
2980
+ ];
2664
2981
  function requireString(obj, key, path) {
2665
2982
  const value = obj[key];
2666
2983
  if (typeof value !== "string" || value.length === 0) {
@@ -2701,6 +3018,10 @@ function parseInstanceDiscovery(raw) {
2701
3018
  for (const key of ENDPOINT_KEYS) {
2702
3019
  endpoints[key] = requireString(raw.endpoints, key, "endpoints");
2703
3020
  }
3021
+ for (const key of OPTIONAL_ENDPOINT_KEYS) {
3022
+ const value = raw.endpoints[key];
3023
+ if (typeof value === "string" && value.length > 0) endpoints[key] = value;
3024
+ }
2704
3025
  endpoints.api = normalizeApiOrigin(endpoints.api);
2705
3026
  endpoints.api_client = normalizeApiOrigin(endpoints.api_client);
2706
3027
  endpoints.api_public = normalizeApiOrigin(endpoints.api_public);
@@ -2754,7 +3075,21 @@ function parseInstanceDiscovery(raw) {
2754
3075
  defaultsHash: ""
2755
3076
  },
2756
3077
  push: raw.push ?? { public_vapid_key: null },
2757
- app_public: raw.app_public ?? {}
3078
+ app_public: raw.app_public ?? {},
3079
+ ...typeof raw.codename === "string" ? { codename: raw.codename } : {},
3080
+ age_policy: isRecord(raw.age_policy) ? raw.age_policy : { geos: [] },
3081
+ ...raw.notice === null || isRecord(raw.notice) ? { notice: raw.notice } : {},
3082
+ ...isRecord(raw.domain_migration) ? { domain_migration: raw.domain_migration } : {},
3083
+ ...Array.isArray(raw.guild_badges) ? { guild_badges: raw.guild_badges } : {},
3084
+ ...typeof raw.guild_badges_partial === "boolean" ? { guild_badges_partial: raw.guild_badges_partial } : {},
3085
+ ...typeof raw.custom_badges_version === "string" ? { custom_badges_version: raw.custom_badges_version } : {},
3086
+ ...isRecord(raw.built_in_guild_badge_images) ? {
3087
+ built_in_guild_badge_images: raw.built_in_guild_badge_images
3088
+ } : {},
3089
+ ...Array.isArray(raw.hidden_built_in_guild_badges) ? {
3090
+ hidden_built_in_guild_badges: raw.hidden_built_in_guild_badges
3091
+ } : {},
3092
+ ...Array.isArray(raw.voice_origins) ? { voice_origins: raw.voice_origins } : {}
2758
3093
  };
2759
3094
  }
2760
3095
  function resolveInstanceEndpoints(input) {
@@ -2774,7 +3109,7 @@ function resolveInstanceEndpoints(input) {
2774
3109
  }
2775
3110
  const partial = input;
2776
3111
  const merged = { ...DEFAULT_INSTANCE_ENDPOINTS };
2777
- for (const key of ENDPOINT_KEYS) {
3112
+ for (const key of [...ENDPOINT_KEYS, ...OPTIONAL_ENDPOINT_KEYS]) {
2778
3113
  const value = partial[key];
2779
3114
  if (typeof value === "string" && value.length > 0) {
2780
3115
  merged[key] = value;
@@ -2932,7 +3267,8 @@ var Invite = class _Invite extends Base {
2932
3267
  // src/Domain/Webhook.ts
2933
3268
  import { EmbedBuilder as EmbedBuilder3 } from "@fluxerjs/builders";
2934
3269
  import {
2935
- Routes as Routes11
3270
+ Routes as Routes11,
3271
+ WebhookType
2936
3272
  } from "@fluxerjs/types";
2937
3273
  import { SnowflakeUtil as SnowflakeUtil4 } from "@fluxerjs/util";
2938
3274
  var Webhook = class _Webhook extends Base {
@@ -2952,6 +3288,8 @@ var Webhook = class _Webhook extends Base {
2952
3288
  token;
2953
3289
  /** The user that created this webhook. */
2954
3290
  user;
3291
+ /** Incoming or channel-follower webhook. */
3292
+ type;
2955
3293
  constructor(client, data) {
2956
3294
  super();
2957
3295
  this.client = client;
@@ -2962,6 +3300,7 @@ var Webhook = class _Webhook extends Base {
2962
3300
  this.avatar = data.avatar ?? null;
2963
3301
  this.token = data.token ?? null;
2964
3302
  this.user = client.getOrCreateUser(data.user);
3303
+ this.type = data.type ?? WebhookType.Incoming;
2965
3304
  }
2966
3305
  avatarURL(options) {
2967
3306
  return cdnAvatarURL(this.id, this.avatar, {
@@ -3072,6 +3411,7 @@ var Webhook = class _Webhook extends Base {
3072
3411
  name: options?.name ?? "Webhook",
3073
3412
  avatar: null,
3074
3413
  token,
3414
+ type: WebhookType.Incoming,
3075
3415
  user: {
3076
3416
  id: "",
3077
3417
  username: "webhook",
@@ -3191,6 +3531,23 @@ var PermissionOverwriteManager = class {
3191
3531
  }
3192
3532
  };
3193
3533
 
3534
+ // src/Domain/Channel/ThreadBind.ts
3535
+ var factory;
3536
+ var managers = /* @__PURE__ */ new WeakMap();
3537
+ function bindThreadManager(next) {
3538
+ factory = next;
3539
+ }
3540
+ function threadManagerFor(channel) {
3541
+ const existing = managers.get(channel);
3542
+ if (existing) return existing;
3543
+ if (!factory) {
3544
+ throw new Error("ThreadManager is not initialized");
3545
+ }
3546
+ const created = factory(channel);
3547
+ managers.set(channel, created);
3548
+ return created;
3549
+ }
3550
+
3194
3551
  // src/Domain/Channel/Guild.ts
3195
3552
  var GuildChannel = class extends Channel {
3196
3553
  /** Guild ID this channel belongs to, or null if missing from the payload. */
@@ -3311,6 +3668,10 @@ var TextChannel = class extends TextCapable(GuildChannel) {
3311
3668
  contentWarningLevel;
3312
3669
  /** Custom content warning text. */
3313
3670
  contentWarningText;
3671
+ /** Default auto-archive duration in minutes for new threads. */
3672
+ defaultAutoArchiveDuration;
3673
+ /** Slowmode in seconds copied onto new threads. */
3674
+ defaultThreadRateLimitPerUser;
3314
3675
  constructor(client, data) {
3315
3676
  super(client, data);
3316
3677
  this.topic = data.topic ?? null;
@@ -3320,6 +3681,12 @@ var TextChannel = class extends TextCapable(GuildChannel) {
3320
3681
  this.lastMessageId = data.last_message_id ?? null;
3321
3682
  this.contentWarningLevel = data.content_warning_level ?? null;
3322
3683
  this.contentWarningText = data.content_warning_text ?? null;
3684
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3685
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3686
+ }
3687
+ /** Create, list, and search threads in this channel. */
3688
+ get threads() {
3689
+ return threadManagerFor(this);
3323
3690
  }
3324
3691
  /**
3325
3692
  * Set slowmode (seconds between messages). Pass `0` to disable.
@@ -3340,9 +3707,45 @@ var TextChannel = class extends TextCapable(GuildChannel) {
3340
3707
  if ("content_warning_text" in data) {
3341
3708
  this.contentWarningText = data.content_warning_text ?? null;
3342
3709
  }
3710
+ if ("default_auto_archive_duration" in data) {
3711
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3712
+ }
3713
+ if ("default_thread_rate_limit_per_user" in data) {
3714
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3715
+ }
3716
+ }
3717
+ /**
3718
+ * Set the auto-archive and slowmode defaults copied onto new threads.
3719
+ * Sends only those fields. The thread-parent update body does not accept a channel rename.
3720
+ */
3721
+ async editThreadDefaults(options) {
3722
+ const data = await this.client.rest.patch(Routes13.channel(this.id), {
3723
+ body: toThreadParentEditBody(options),
3724
+ auth: true,
3725
+ ...auditReasonHeaders(options.reason)
3726
+ });
3727
+ this._patch(data);
3728
+ return this;
3343
3729
  }
3344
3730
  };
3345
3731
  var AnnouncementChannel = class extends TextChannel {
3732
+ /**
3733
+ * Follow this announcement channel into `webhookChannelId` (a channel in a guild
3734
+ * where the bot can manage webhooks). Published messages are copied there.
3735
+ */
3736
+ async follow(webhookChannelId) {
3737
+ return this.client.rest.post(
3738
+ Routes13.channelFollowers(this.id),
3739
+ { body: { webhook_channel_id: webhookChannelId }, auth: true }
3740
+ );
3741
+ }
3742
+ /** Fetch follower counts for this announcement channel. */
3743
+ async fetchFollowerStats() {
3744
+ return this.client.rest.get(
3745
+ Routes13.channelFollowerStats(this.id),
3746
+ { auth: true }
3747
+ );
3748
+ }
3346
3749
  };
3347
3750
  var CategoryChannel = class extends GuildChannel {
3348
3751
  };
@@ -3369,6 +3772,8 @@ var VoiceChannel = class extends TextCapable(GuildChannel) {
3369
3772
  voiceConnectionLimit;
3370
3773
  /** RTC region override for this channel. */
3371
3774
  rtcRegion;
3775
+ /** Whether voice in this channel is peer-to-peer (`rtc_p2p`). */
3776
+ rtcP2p;
3372
3777
  constructor(client, data) {
3373
3778
  super(client, data);
3374
3779
  this.topic = data.topic ?? null;
@@ -3382,6 +3787,7 @@ var VoiceChannel = class extends TextCapable(GuildChannel) {
3382
3787
  this.userLimit = data.user_limit ?? null;
3383
3788
  this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3384
3789
  this.rtcRegion = data.rtc_region ?? null;
3790
+ this.rtcP2p = data.rtc_p2p ?? false;
3385
3791
  }
3386
3792
  /**
3387
3793
  * Set slowmode (seconds between messages). Pass `0` to disable.
@@ -3408,40 +3814,537 @@ var VoiceChannel = class extends TextCapable(GuildChannel) {
3408
3814
  this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3409
3815
  }
3410
3816
  if ("rtc_region" in data) this.rtcRegion = data.rtc_region ?? null;
3817
+ if ("rtc_p2p" in data) this.rtcP2p = data.rtc_p2p ?? false;
3818
+ }
3819
+ };
3820
+ var LinkChannel = class extends GuildChannel {
3821
+ /** External URL this channel links to. */
3822
+ url;
3823
+ constructor(client, data) {
3824
+ super(client, data);
3825
+ this.url = data.url ?? null;
3826
+ }
3827
+ applyEditPatch(data) {
3828
+ if ("url" in data) this.url = data.url ?? null;
3829
+ }
3830
+ };
3831
+
3832
+ // src/Domain/Channel/ThreadManager.ts
3833
+ import { ChannelType as ChannelType6, Routes as Routes15 } from "@fluxerjs/types";
3834
+
3835
+ // src/Domain/Channel/ThreadChannel.ts
3836
+ import { ChannelType as ChannelType5, Routes as Routes14 } from "@fluxerjs/types";
3837
+ var ThreadMember = class {
3838
+ /** Thread ID. */
3839
+ id;
3840
+ /** User ID. */
3841
+ userId;
3842
+ /** When the user last joined the thread. */
3843
+ joinedAt;
3844
+ /** Thread member flags bitfield. */
3845
+ flags;
3846
+ /** Whether the current user has muted the thread. */
3847
+ muted;
3848
+ /** ISO-8601 timestamp when the mute expires, if set. */
3849
+ muteEndTime;
3850
+ /** Selected mute duration in seconds, if set. */
3851
+ muteWindow;
3852
+ constructor(data) {
3853
+ this.id = data.id ?? null;
3854
+ this.userId = data.user_id ?? data.member?.user?.id ?? null;
3855
+ this.joinedAt = new Date(data.join_timestamp);
3856
+ this.flags = data.flags;
3857
+ this.muted = data.muted ?? null;
3858
+ this.muteEndTime = data.mute_config?.end_time ?? null;
3859
+ this.muteWindow = data.mute_config?.selected_time_window ?? null;
3860
+ }
3861
+ };
3862
+ function threadEditFields(options) {
3863
+ const source = options;
3864
+ return {
3865
+ name: typeof source.name === "string" ? source.name : void 0,
3866
+ archived: source.archived,
3867
+ autoArchiveDuration: source.autoArchiveDuration,
3868
+ locked: source.locked,
3869
+ rateLimitPerUser: source.rateLimitPerUser,
3870
+ flags: source.flags,
3871
+ appliedTags: source.appliedTags,
3872
+ invitable: source.invitable,
3873
+ reason: source.reason
3874
+ };
3875
+ }
3876
+ function readMetadata(data) {
3877
+ return {
3878
+ archived: data?.archived ?? false,
3879
+ autoArchiveDuration: data?.auto_archive_duration ?? 0,
3880
+ archiveTimestamp: data?.archive_timestamp ?? null,
3881
+ locked: data?.locked ?? false,
3882
+ invitable: data?.invitable ?? null
3883
+ };
3884
+ }
3885
+ var ThreadChannel = class extends TextCapable(GuildChannel) {
3886
+ /** User who created the thread. */
3887
+ ownerId;
3888
+ /** Whether the thread is archived. */
3889
+ archived;
3890
+ /** Minutes of inactivity before the thread archives. */
3891
+ autoArchiveDuration;
3892
+ /** ISO-8601 timestamp when the archive status last changed. */
3893
+ archiveTimestamp;
3894
+ /** Whether only moderators can unarchive the thread. */
3895
+ locked;
3896
+ /** Whether non-moderators can add other non-moderators. Private threads only. */
3897
+ invitable;
3898
+ /** Slowmode in seconds. */
3899
+ rateLimitPerUser;
3900
+ /** ID of the last message sent in this thread. */
3901
+ lastMessageId;
3902
+ /** Messages in the thread, excluding the starter and deleted messages. */
3903
+ messageCount;
3904
+ /** Messages ever sent in the thread. This count is never decremented. */
3905
+ totalMessageSent;
3906
+ /** Approximate member count, capped at 50. */
3907
+ memberCount;
3908
+ /** Tag IDs applied to a forum or media post. */
3909
+ appliedTags;
3910
+ /** Channel flags bitfield. */
3911
+ flags;
3912
+ /** The current user's membership, when the payload included it. */
3913
+ member;
3914
+ /** Add, remove, and list members of this thread. */
3915
+ members;
3916
+ constructor(client, data) {
3917
+ super(client, data);
3918
+ const metadata = readMetadata(data.thread_metadata);
3919
+ this.ownerId = data.owner_id ?? null;
3920
+ this.archived = metadata.archived;
3921
+ this.autoArchiveDuration = metadata.autoArchiveDuration;
3922
+ this.archiveTimestamp = metadata.archiveTimestamp;
3923
+ this.locked = metadata.locked;
3924
+ this.invitable = metadata.invitable;
3925
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3926
+ this.lastMessageId = data.last_message_id ?? null;
3927
+ this.messageCount = data.message_count ?? 0;
3928
+ this.totalMessageSent = data.total_message_sent ?? 0;
3929
+ this.memberCount = data.member_count ?? 0;
3930
+ this.appliedTags = data.applied_tags ?? [];
3931
+ this.flags = data.flags ?? 0;
3932
+ this.member = data.member ? new ThreadMember(data.member) : null;
3933
+ this.members = new ThreadMemberManager(this);
3934
+ }
3935
+ /** @internal */
3936
+ _patch(data) {
3937
+ super._patch(data);
3938
+ if (data.owner_id !== void 0) this.ownerId = data.owner_id ?? null;
3939
+ if (data.thread_metadata) {
3940
+ const metadata = readMetadata(data.thread_metadata);
3941
+ this.archived = metadata.archived;
3942
+ this.autoArchiveDuration = metadata.autoArchiveDuration;
3943
+ this.archiveTimestamp = metadata.archiveTimestamp;
3944
+ this.locked = metadata.locked;
3945
+ this.invitable = metadata.invitable;
3946
+ }
3947
+ if ("rate_limit_per_user" in data && data.rate_limit_per_user !== void 0) {
3948
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3949
+ }
3950
+ if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3951
+ if (data.message_count !== void 0) this.messageCount = data.message_count;
3952
+ if (data.total_message_sent !== void 0) this.totalMessageSent = data.total_message_sent;
3953
+ if (data.member_count !== void 0) this.memberCount = data.member_count;
3954
+ if (data.applied_tags !== void 0) this.appliedTags = data.applied_tags ?? [];
3955
+ if (data.flags !== void 0) this.flags = data.flags;
3956
+ if (data.member !== void 0) this.member = data.member ? new ThreadMember(data.member) : null;
3957
+ }
3958
+ /**
3959
+ * Edit this thread. Requires Manage Threads on public threads, or ownership on private ones.
3960
+ * `appliedTags` is sent for public and announcement threads. `invitable` is sent for private threads.
3961
+ */
3962
+ async edit(options) {
3963
+ const data = await this.client.rest.patch(Routes14.channel(this.id), {
3964
+ body: toThreadEditBody(this.type, threadEditFields(options)),
3965
+ auth: true,
3966
+ ...auditReasonHeaders(options.reason)
3967
+ });
3968
+ this._patch(data);
3969
+ return this;
3970
+ }
3971
+ /** Archive or unarchive this thread. */
3972
+ async setArchived(archived, reason) {
3973
+ return this.edit({ archived, reason });
3974
+ }
3975
+ /** Lock or unlock this thread. Locked threads can only be unarchived by moderators. */
3976
+ async setLocked(locked, reason) {
3977
+ return this.edit({ locked, reason });
3978
+ }
3979
+ /** Join this thread. */
3980
+ async join() {
3981
+ await this.client.rest.put(Routes14.channelThreadMemberMe(this.id), { auth: true });
3982
+ }
3983
+ /** Leave this thread. */
3984
+ async leave() {
3985
+ await this.client.rest.delete(Routes14.channelThreadMemberMe(this.id), { auth: true });
3986
+ }
3987
+ /** Update the current user's notification settings for this thread. */
3988
+ async editSelf(options) {
3989
+ const data = await this.client.rest.patch(
3990
+ Routes14.channelThreadMemberMeSettings(this.id),
3991
+ { body: toThreadMemberSettingsBody(options), auth: true }
3992
+ );
3993
+ this.member = data ? new ThreadMember(data) : null;
3994
+ return this.member;
3995
+ }
3996
+ };
3997
+ var ThreadMemberManager = class {
3998
+ constructor(thread) {
3999
+ this.thread = thread;
4000
+ }
4001
+ /** List members of this thread. */
4002
+ async fetch(options) {
4003
+ const data = await this.thread.client.rest.get(
4004
+ withQuery(Routes14.channelThreadMembers(this.thread.id), {
4005
+ with_member: options?.withMember === void 0 ? void 0 : String(options.withMember),
4006
+ after: options?.after,
4007
+ limit: options?.limit
4008
+ })
4009
+ );
4010
+ return data.map((member) => new ThreadMember(member));
4011
+ }
4012
+ /** Fetch one member of this thread. */
4013
+ async fetchOne(userId, options) {
4014
+ const data = await this.thread.client.rest.get(
4015
+ withQuery(Routes14.channelThreadMember(this.thread.id, userId), {
4016
+ with_member: options?.withMember === void 0 ? void 0 : String(options.withMember)
4017
+ })
4018
+ );
4019
+ return new ThreadMember(data);
4020
+ }
4021
+ /** Add a user to this thread. Private threads only, unless the caller can manage the parent. */
4022
+ async add(userId) {
4023
+ await this.thread.client.rest.put(Routes14.channelThreadMember(this.thread.id, userId), {
4024
+ auth: true
4025
+ });
4026
+ }
4027
+ /** Remove a user from this thread. */
4028
+ async remove(userId) {
4029
+ await this.thread.client.rest.delete(Routes14.channelThreadMember(this.thread.id, userId), {
4030
+ auth: true
4031
+ });
4032
+ }
4033
+ };
4034
+ function isThreadType(type) {
4035
+ return type === ChannelType5.AnnouncementThread || type === ChannelType5.PublicThread || type === ChannelType5.PrivateThread;
4036
+ }
4037
+
4038
+ // src/Domain/Channel/ThreadManager.ts
4039
+ var ThreadManager = class {
4040
+ constructor(channel) {
4041
+ this.channel = channel;
4042
+ }
4043
+ /**
4044
+ * Start a thread in a text or announcement channel.
4045
+ * Forum and media channels must use {@link createPost}.
4046
+ */
4047
+ async create(options) {
4048
+ if (this.channel.type === ChannelType6.GuildForum || this.channel.type === ChannelType6.GuildMedia) {
4049
+ throw new FluxerError("Forum and media channels start posts with createPost", {
4050
+ code: ErrorCodes.InvalidChannelType
4051
+ });
4052
+ }
4053
+ const data = await this.channel.client.rest.post(
4054
+ Routes15.channelThreads(this.channel.id),
4055
+ {
4056
+ body: toStartThreadBody(this.channel.type, options),
4057
+ auth: true,
4058
+ ...auditReasonHeaders(options.reason)
4059
+ }
4060
+ );
4061
+ return cacheThread(this.channel.client, data);
4062
+ }
4063
+ /**
4064
+ * Start a post in a forum or media channel.
4065
+ * The post is a public thread. `message` is its first message.
4066
+ */
4067
+ async createPost(options) {
4068
+ if (this.channel.type !== ChannelType6.GuildForum && this.channel.type !== ChannelType6.GuildMedia) {
4069
+ throw new FluxerError("createPost is for forum and media channels", {
4070
+ code: ErrorCodes.InvalidChannelType
4071
+ });
4072
+ }
4073
+ const prepared = await prepareMessagePostPayload(options.message, {
4074
+ defaultAllowedMentions: this.channel.client.options.defaultAllowedMentions
4075
+ });
4076
+ const body = {
4077
+ name: options.name,
4078
+ type: ChannelType6.PublicThread,
4079
+ message: toForumThreadMessage(prepared.body)
4080
+ };
4081
+ if (options.autoArchiveDuration !== void 0) {
4082
+ body.auto_archive_duration = options.autoArchiveDuration;
4083
+ }
4084
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
4085
+ if (options.appliedTags !== void 0) body.applied_tags = options.appliedTags;
4086
+ const data = await this.channel.client.rest.post(
4087
+ Routes15.channelThreads(this.channel.id),
4088
+ {
4089
+ body,
4090
+ files: prepared.files,
4091
+ auth: true,
4092
+ ...auditReasonHeaders(options.reason)
4093
+ }
4094
+ );
4095
+ const thread = cacheThread(this.channel.client, data);
4096
+ if (data.message) {
4097
+ this.channel.client._addMessageToCache(data.message.channel_id, data.message);
4098
+ }
4099
+ return thread;
4100
+ }
4101
+ /**
4102
+ * List archived threads in this channel.
4103
+ * `before` is an ISO-8601 archive timestamp.
4104
+ */
4105
+ async fetchArchived(options) {
4106
+ const path = options.type === "private" ? Routes15.channelThreadsArchivedPrivate(this.channel.id) : Routes15.channelThreadsArchivedPublic(this.channel.id);
4107
+ const data = await this.channel.client.rest.get(
4108
+ withQuery(path, { before: options.before, limit: options.limit })
4109
+ );
4110
+ return fetchedThreadsFrom(this.channel.client, data);
4111
+ }
4112
+ /**
4113
+ * List private archived threads in this channel that the current user has joined.
4114
+ * `before` is a thread snowflake.
4115
+ */
4116
+ async fetchJoinedPrivateArchived(options) {
4117
+ const data = await this.channel.client.rest.get(
4118
+ withQuery(Routes15.channelJoinedArchivedPrivateThreads(this.channel.id), {
4119
+ before: options?.before,
4120
+ limit: options?.limit
4121
+ })
4122
+ );
4123
+ return fetchedThreadsFrom(this.channel.client, data);
4124
+ }
4125
+ /**
4126
+ * Search threads in this channel.
4127
+ * Returns `{ indexing: true }` while the search index is still building.
4128
+ */
4129
+ async search(options) {
4130
+ const data = await this.channel.client.rest.get(
4131
+ withQuery(Routes15.channelThreadSearch(this.channel.id), {
4132
+ name: options?.name,
4133
+ tag: options?.tag,
4134
+ tag_setting: options?.tagSetting,
4135
+ archived: options?.archived === void 0 ? void 0 : String(options.archived),
4136
+ sort_by: options?.sortBy,
4137
+ sort_order: options?.sortOrder,
4138
+ limit: options?.limit,
4139
+ offset: options?.offset,
4140
+ max_id: options?.maxId,
4141
+ min_id: options?.minId
4142
+ })
4143
+ );
4144
+ if (isSearchNotReady(data)) {
4145
+ return { indexing: true, retryAfter: data.retry_after, message: data.message };
4146
+ }
4147
+ const page = fetchedThreadsFrom(this.channel.client, data);
4148
+ return {
4149
+ ...page,
4150
+ hasMore: data.has_more,
4151
+ totalResults: data.total_results,
4152
+ firstMessages: (data.first_messages ?? []).map(
4153
+ (message) => new Message(this.channel.client, message)
4154
+ )
4155
+ };
4156
+ }
4157
+ /** Set the auto-archive and slowmode defaults copied onto new threads. */
4158
+ async editDefaults(options) {
4159
+ return this.channel.client.rest.patch(Routes15.channel(this.channel.id), {
4160
+ body: toThreadParentEditBody(options),
4161
+ auth: true,
4162
+ ...auditReasonHeaders(options.reason)
4163
+ });
4164
+ }
4165
+ };
4166
+ function fetchedThreadsFrom(client, data) {
4167
+ return {
4168
+ threads: (data.threads ?? []).map((thread) => cacheThread(client, thread)),
4169
+ members: (data.members ?? []).map((member) => new ThreadMember(member)),
4170
+ hasMore: data.has_more ?? false
4171
+ };
4172
+ }
4173
+ function isSearchNotReady(data) {
4174
+ return "code" in data && data.code === "SEARCH_INDEX_NOT_READY";
4175
+ }
4176
+ async function fetchActiveThreads(client, guildId) {
4177
+ const data = await client.rest.get(Routes15.guildActiveThreads(guildId));
4178
+ return fetchedThreadsFrom(client, data);
4179
+ }
4180
+
4181
+ // src/Domain/Channel/Forum.ts
4182
+ function tagsFrom(data) {
4183
+ return data ?? [];
4184
+ }
4185
+ var ThreadOnlyChannel = class extends GuildChannel {
4186
+ /** Tags that can be applied to posts. */
4187
+ availableTags;
4188
+ /** Default reaction for new posts. */
4189
+ defaultReactionEmoji;
4190
+ /** Default sort order for posts. */
4191
+ defaultSortOrder;
4192
+ /** How posts are filtered when searching by several tags. */
4193
+ defaultTagSetting;
4194
+ /** Default auto-archive duration in minutes for new posts. */
4195
+ defaultAutoArchiveDuration;
4196
+ /** Slowmode in seconds copied onto new posts. */
4197
+ defaultThreadRateLimitPerUser;
4198
+ /** Channel flags bitfield. */
4199
+ flags;
4200
+ /** Create, list, and search posts in this channel. */
4201
+ threads;
4202
+ constructor(client, data) {
4203
+ super(client, data);
4204
+ this.availableTags = tagsFrom(data.available_tags);
4205
+ this.defaultReactionEmoji = data.default_reaction_emoji ?? null;
4206
+ this.defaultSortOrder = data.default_sort_order ?? null;
4207
+ this.defaultTagSetting = data.default_tag_setting ?? null;
4208
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
4209
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
4210
+ this.flags = data.flags ?? 0;
4211
+ this.threads = new ThreadManager(this);
4212
+ }
4213
+ /** @internal */
4214
+ _patch(data) {
4215
+ super._patch(data);
4216
+ if (data.available_tags !== void 0) this.availableTags = tagsFrom(data.available_tags);
4217
+ if ("default_reaction_emoji" in data) {
4218
+ this.defaultReactionEmoji = data.default_reaction_emoji ?? null;
4219
+ }
4220
+ if ("default_sort_order" in data) this.defaultSortOrder = data.default_sort_order ?? null;
4221
+ if ("default_tag_setting" in data) this.defaultTagSetting = data.default_tag_setting ?? null;
4222
+ if ("default_auto_archive_duration" in data) {
4223
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
4224
+ }
4225
+ if ("default_thread_rate_limit_per_user" in data) {
4226
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
4227
+ }
4228
+ if (data.flags !== void 0) this.flags = data.flags;
4229
+ }
4230
+ /**
4231
+ * Edit this channel.
4232
+ * Tag, sort, reaction, and thread-default fields are sent with the usual channel fields.
4233
+ * `defaultForumLayout` is sent only for forum channels.
4234
+ */
4235
+ async edit(options) {
4236
+ const data = await this.client.rest.patch(Routes16.channel(this.id), {
4237
+ body: {
4238
+ ...toChannelEditBody(options),
4239
+ ...forumParentWire(options, this.type === ChannelType7.GuildForum)
4240
+ },
4241
+ auth: true,
4242
+ ...auditReasonHeaders(options.reason)
4243
+ });
4244
+ this._patch(data);
4245
+ return this;
4246
+ }
4247
+ /** Replace the tags that can be applied to posts (max 20). */
4248
+ async setAvailableTags(tags, reason) {
4249
+ return this.edit({ availableTags: tags, reason });
4250
+ }
4251
+ /** Set or clear the default reaction on new posts. */
4252
+ async setDefaultReactionEmoji(emoji, reason) {
4253
+ return this.edit({ defaultReactionEmoji: emoji, reason });
4254
+ }
4255
+ /** Set or clear the default post sort order. */
4256
+ async setDefaultSortOrder(order, reason) {
4257
+ return this.edit({ defaultSortOrder: order, reason });
4258
+ }
4259
+ /** Set or clear how posts match when several tags are selected. */
4260
+ async setDefaultTagSetting(setting, reason) {
4261
+ return this.edit({ defaultTagSetting: setting, reason });
4262
+ }
4263
+ /** Set the auto-archive and slowmode defaults copied onto new posts. */
4264
+ async editThreadDefaults(options) {
4265
+ const data = await this.client.rest.patch(Routes16.channel(this.id), {
4266
+ body: toThreadParentEditBody(options),
4267
+ auth: true,
4268
+ ...auditReasonHeaders(options.reason)
4269
+ });
4270
+ this._patch(data);
4271
+ return this;
4272
+ }
4273
+ /** Create a tag. The response replaces {@link availableTags}. */
4274
+ async createTag(options) {
4275
+ const data = await this.client.rest.post(Routes16.channelTags(this.id), {
4276
+ body: toForumTagBody(options),
4277
+ auth: true,
4278
+ ...auditReasonHeaders(options.reason)
4279
+ });
4280
+ this._patch(data);
4281
+ return this;
4282
+ }
4283
+ /** Replace a tag. The response replaces {@link availableTags}. */
4284
+ async editTag(tagId, options) {
4285
+ const data = await this.client.rest.put(Routes16.channelTag(this.id, tagId), {
4286
+ body: toForumTagBody(options),
4287
+ auth: true,
4288
+ ...auditReasonHeaders(options.reason)
4289
+ });
4290
+ this._patch(data);
4291
+ return this;
4292
+ }
4293
+ /** Delete a tag. The response replaces {@link availableTags}. */
4294
+ async deleteTag(tagId, reason) {
4295
+ const data = await this.client.rest.delete(Routes16.channelTag(this.id, tagId), {
4296
+ auth: true,
4297
+ ...auditReasonHeaders(reason)
4298
+ });
4299
+ this._patch(data);
4300
+ return this;
3411
4301
  }
3412
4302
  };
3413
- var LinkChannel = class extends GuildChannel {
3414
- /** External URL this channel links to. */
3415
- url;
4303
+ var ForumChannel = class extends ThreadOnlyChannel {
4304
+ /** Default layout for posts. */
4305
+ defaultForumLayout;
4306
+ /** Set or clear the default post layout. */
4307
+ async setDefaultForumLayout(layout, reason) {
4308
+ return this.edit({ defaultForumLayout: layout, reason });
4309
+ }
3416
4310
  constructor(client, data) {
3417
4311
  super(client, data);
3418
- this.url = data.url ?? null;
4312
+ this.defaultForumLayout = data.default_forum_layout ?? null;
3419
4313
  }
3420
- applyEditPatch(data) {
3421
- if ("url" in data) this.url = data.url ?? null;
4314
+ /** @internal */
4315
+ _patch(data) {
4316
+ super._patch(data);
4317
+ if ("default_forum_layout" in data) this.defaultForumLayout = data.default_forum_layout ?? null;
3422
4318
  }
3423
4319
  };
4320
+ var MediaChannel = class extends ThreadOnlyChannel {
4321
+ };
3424
4322
 
3425
4323
  // src/Domain/Channel/Factory.ts
3426
- import { ChannelType as ChannelType3 } from "@fluxerjs/types";
4324
+ import { ChannelType as ChannelType8 } from "@fluxerjs/types";
3427
4325
  var GUILD_FACTORIES = {
3428
- [ChannelType3.GuildText]: (c, d) => new TextChannel(c, d),
3429
- [ChannelType3.GuildAnnouncement]: (c, d) => new AnnouncementChannel(c, d),
3430
- [ChannelType3.GuildCategory]: (c, d) => new CategoryChannel(c, d),
3431
- [ChannelType3.GuildVoice]: (c, d) => new VoiceChannel(c, d),
3432
- [ChannelType3.GuildLink]: (c, d) => new LinkChannel(c, d)
4326
+ [ChannelType8.GuildText]: (c, d) => new TextChannel(c, d),
4327
+ [ChannelType8.GuildAnnouncement]: (c, d) => new AnnouncementChannel(c, d),
4328
+ [ChannelType8.GuildCategory]: (c, d) => new CategoryChannel(c, d),
4329
+ [ChannelType8.GuildVoice]: (c, d) => new VoiceChannel(c, d),
4330
+ [ChannelType8.GuildLink]: (c, d) => new LinkChannel(c, d),
4331
+ [ChannelType8.AnnouncementThread]: (c, d) => new ThreadChannel(c, d),
4332
+ [ChannelType8.PublicThread]: (c, d) => new ThreadChannel(c, d),
4333
+ [ChannelType8.PrivateThread]: (c, d) => new ThreadChannel(c, d),
4334
+ [ChannelType8.GuildForum]: (c, d) => new ForumChannel(c, d),
4335
+ [ChannelType8.GuildMedia]: (c, d) => new MediaChannel(c, d)
3433
4336
  };
3434
4337
  var DM_TYPES = /* @__PURE__ */ new Set([
3435
- ChannelType3.DM,
3436
- ChannelType3.GroupDM,
3437
- ChannelType3.DMPersonalNotes
4338
+ ChannelType8.DM,
4339
+ ChannelType8.GroupDM,
4340
+ ChannelType8.DMPersonalNotes
3438
4341
  ]);
3439
4342
  function createDM(client, data) {
3440
4343
  return new DMChannel(client, data);
3441
4344
  }
3442
4345
  function channelFrom(client, data) {
3443
- const factory = GUILD_FACTORIES[data.type ?? 0];
3444
- return factory ? factory(client, data) : new GuildChannel(client, data);
4346
+ const factory2 = GUILD_FACTORIES[data.type ?? 0];
4347
+ return factory2 ? factory2(client, data) : new GuildChannel(client, data);
3445
4348
  }
3446
4349
  function channelFromOrCreate(client, data) {
3447
4350
  return DM_TYPES.has(data.type ?? 0) ? createDM(client, data) : channelFrom(client, data);
@@ -3451,9 +4354,13 @@ function channelFromOrCreate(client, data) {
3451
4354
  Channel.from = channelFrom;
3452
4355
  Channel.fromOrCreate = channelFromOrCreate;
3453
4356
  Channel.createDM = createDM;
4357
+ bindThreadManager((channel) => new ThreadManager(channel));
4358
+
4359
+ // src/Domain/Guild/Cache.ts
4360
+ import { ChannelType as ChannelType9 } from "@fluxerjs/types";
3454
4361
 
3455
4362
  // src/Domain/Guild/GuildEmoji.ts
3456
- import { Routes as Routes14 } from "@fluxerjs/types";
4363
+ import { Routes as Routes17 } from "@fluxerjs/types";
3457
4364
  import { SnowflakeUtil as SnowflakeUtil5 } from "@fluxerjs/util";
3458
4365
  var GuildEmoji = class extends Base {
3459
4366
  client;
@@ -3502,7 +4409,7 @@ var GuildEmoji = class extends Base {
3502
4409
  }
3503
4410
  /** Delete this emoji. Requires Manage Emojis and Stickers permission. */
3504
4411
  async delete(reason) {
3505
- await this.client.rest.delete(Routes14.guildEmoji(this.guildId, this.id), {
4412
+ await this.client.rest.delete(Routes17.guildEmoji(this.guildId, this.id), {
3506
4413
  auth: true,
3507
4414
  ...auditReasonHeaders(reason)
3508
4415
  });
@@ -3515,7 +4422,7 @@ var GuildEmoji = class extends Base {
3515
4422
  */
3516
4423
  async edit(options) {
3517
4424
  const { reason, name } = options;
3518
- const data = await this.client.rest.patch(Routes14.guildEmoji(this.guildId, this.id), {
4425
+ const data = await this.client.rest.patch(Routes17.guildEmoji(this.guildId, this.id), {
3519
4426
  body: { name },
3520
4427
  auth: true,
3521
4428
  ...auditReasonHeaders(reason)
@@ -3526,7 +4433,7 @@ var GuildEmoji = class extends Base {
3526
4433
  };
3527
4434
 
3528
4435
  // src/Domain/Guild/GuildMember.ts
3529
- import { Routes as Routes16 } from "@fluxerjs/types";
4436
+ import { Routes as Routes19 } from "@fluxerjs/types";
3530
4437
  import { PermissionFlags as PermissionFlags3, PermissionsBitField as PermissionsBitField2 } from "@fluxerjs/util";
3531
4438
 
3532
4439
  // src/Helpers/Permissions.ts
@@ -3550,7 +4457,7 @@ function computePermissions(basePermissions, overwrites, memberRoles, memberId,
3550
4457
 
3551
4458
  // src/Domain/Guild/GuildMemberRoleManager.ts
3552
4459
  import { Collection as Collection7 } from "@fluxerjs/collection";
3553
- import { Routes as Routes15 } from "@fluxerjs/types";
4460
+ import { Routes as Routes18 } from "@fluxerjs/types";
3554
4461
  function roleId(roleOrId) {
3555
4462
  return typeof roleOrId === "string" ? roleOrId : roleOrId.id;
3556
4463
  }
@@ -3579,7 +4486,7 @@ var GuildMemberRoleManager = class {
3579
4486
  const id = roleId(roleOrId);
3580
4487
  if (this.ids.includes(id)) return;
3581
4488
  await this.member.client.rest.put(
3582
- Routes15.guildMemberRole(this.member.guild.id, this.member.id, id)
4489
+ Routes18.guildMemberRole(this.member.guild.id, this.member.id, id)
3583
4490
  );
3584
4491
  this.ids.push(id);
3585
4492
  }
@@ -3588,13 +4495,13 @@ var GuildMemberRoleManager = class {
3588
4495
  const idx = this.ids.indexOf(id);
3589
4496
  if (idx === -1) return;
3590
4497
  await this.member.client.rest.delete(
3591
- Routes15.guildMemberRole(this.member.guild.id, this.member.id, id)
4498
+ Routes18.guildMemberRole(this.member.guild.id, this.member.id, id)
3592
4499
  );
3593
4500
  this.ids.splice(idx, 1);
3594
4501
  }
3595
4502
  async set(roleIds) {
3596
4503
  const data = await this.member.client.rest.patch(
3597
- Routes15.guildMember(this.member.guild.id, this.member.id),
4504
+ Routes18.guildMember(this.member.guild.id, this.member.id),
3598
4505
  { body: { roles: roleIds }, auth: true }
3599
4506
  );
3600
4507
  this.ids = data.roles ? [...data.roles] : [];
@@ -3748,7 +4655,7 @@ var GuildMember = class _GuildMember extends Base {
3748
4655
  */
3749
4656
  async edit(options) {
3750
4657
  const isMe = this.client.user?.id === this.id;
3751
- const route = isMe ? Routes16.guildMemberMe(this.guild.id) : Routes16.guildMember(this.guild.id, this.id);
4658
+ const route = isMe ? Routes19.guildMemberMe(this.guild.id) : Routes19.guildMember(this.guild.id, this.id);
3752
4659
  const data = await this.client.rest.patch(route, {
3753
4660
  body: toMemberEditBody(options),
3754
4661
  auth: true,
@@ -3861,7 +4768,7 @@ var GuildMember = class _GuildMember extends Base {
3861
4768
  };
3862
4769
 
3863
4770
  // src/Domain/Guild/GuildSticker.ts
3864
- import { Routes as Routes17 } from "@fluxerjs/types";
4771
+ import { Routes as Routes20 } from "@fluxerjs/types";
3865
4772
  import { SnowflakeUtil as SnowflakeUtil6 } from "@fluxerjs/util";
3866
4773
  var GuildSticker = class extends Base {
3867
4774
  client;
@@ -3912,7 +4819,7 @@ var GuildSticker = class extends Base {
3912
4819
  }
3913
4820
  /** Delete this sticker. Requires Manage Emojis and Stickers permission. */
3914
4821
  async delete(reason) {
3915
- await this.client.rest.delete(Routes17.guildSticker(this.guildId, this.id), {
4822
+ await this.client.rest.delete(Routes20.guildSticker(this.guildId, this.id), {
3916
4823
  auth: true,
3917
4824
  ...auditReasonHeaders(reason)
3918
4825
  });
@@ -3925,7 +4832,7 @@ var GuildSticker = class extends Base {
3925
4832
  */
3926
4833
  async edit(options) {
3927
4834
  const { reason, ...body } = options;
3928
- const data = await this.client.rest.patch(Routes17.guildSticker(this.guildId, this.id), {
4835
+ const data = await this.client.rest.patch(Routes20.guildSticker(this.guildId, this.id), {
3929
4836
  body,
3930
4837
  auth: true,
3931
4838
  ...auditReasonHeaders(reason)
@@ -3938,7 +4845,7 @@ var GuildSticker = class extends Base {
3938
4845
  };
3939
4846
 
3940
4847
  // src/Domain/Guild/Role.ts
3941
- import { Routes as Routes18 } from "@fluxerjs/types";
4848
+ import { Routes as Routes21 } from "@fluxerjs/types";
3942
4849
  import {
3943
4850
  ALL_PERMISSIONS_BIGINT as ALL_PERMISSIONS_BIGINT2,
3944
4851
  PermissionFlags as PermissionFlags4,
@@ -3966,6 +4873,8 @@ var Role = class _Role extends Base {
3966
4873
  mentionable;
3967
4874
  /** Unicode emoji for this role (null = none). */
3968
4875
  unicodeEmoji;
4876
+ /** Role icon image hash (null = none). */
4877
+ icon;
3969
4878
  /** Hoist position (null = not hoisted). */
3970
4879
  hoistPosition;
3971
4880
  constructor(client, data, guildId) {
@@ -3973,20 +4882,26 @@ var Role = class _Role extends Base {
3973
4882
  this.client = client;
3974
4883
  this.id = data.id;
3975
4884
  this.guildId = guildId;
3976
- this.name = data.name;
3977
- this.color = data.color;
3978
- this.position = data.position;
3979
- this._permissions = data.permissions;
4885
+ this.name = data.name ?? "";
4886
+ this.color = data.color ?? 0;
4887
+ this.position = data.position ?? 0;
4888
+ this._permissions = data.permissions ?? "0";
3980
4889
  this.hoist = !!data.hoist;
3981
4890
  this.mentionable = !!data.mentionable;
3982
4891
  this.unicodeEmoji = data.unicode_emoji ?? null;
4892
+ this.icon = data.icon ?? null;
3983
4893
  this.hoistPosition = data.hoist_position ?? null;
3984
4894
  }
3985
4895
  /**
3986
4896
  * Permissions bitfield (Administrator grants all permissions).
3987
4897
  */
3988
4898
  get permissions() {
3989
- const bits = BigInt(this._permissions);
4899
+ let bits;
4900
+ try {
4901
+ bits = BigInt(this._permissions ?? "0");
4902
+ } catch {
4903
+ bits = 0n;
4904
+ }
3990
4905
  return new PermissionsBitField3(
3991
4906
  (bits & PermissionFlags4.Administrator) !== 0n ? ALL_PERMISSIONS_BIGINT2 : bits
3992
4907
  );
@@ -4016,14 +4931,15 @@ var Role = class _Role extends Base {
4016
4931
  }
4017
4932
  /** @internal */
4018
4933
  _patch(data) {
4019
- this.name = data.name;
4020
- this.color = data.color;
4021
- this.position = data.position;
4022
- this._permissions = data.permissions;
4023
- this.hoist = !!data.hoist;
4024
- this.mentionable = !!data.mentionable;
4025
- this.unicodeEmoji = data.unicode_emoji ?? null;
4026
- this.hoistPosition = data.hoist_position ?? null;
4934
+ if (data.name !== void 0) this.name = data.name;
4935
+ if (data.color !== void 0) this.color = data.color;
4936
+ if (data.position !== void 0) this.position = data.position;
4937
+ if (data.permissions !== void 0) this._permissions = data.permissions;
4938
+ if (data.hoist !== void 0) this.hoist = !!data.hoist;
4939
+ if (data.mentionable !== void 0) this.mentionable = !!data.mentionable;
4940
+ if (data.unicode_emoji !== void 0) this.unicodeEmoji = data.unicode_emoji ?? null;
4941
+ if (data.icon !== void 0) this.icon = data.icon ?? null;
4942
+ if (data.hoist_position !== void 0) this.hoistPosition = data.hoist_position ?? null;
4027
4943
  }
4028
4944
  /**
4029
4945
  * Snapshot for role-update events (before in-place patch).
@@ -4041,6 +4957,7 @@ var Role = class _Role extends Base {
4041
4957
  hoist: this.hoist,
4042
4958
  mentionable: this.mentionable,
4043
4959
  unicode_emoji: this.unicodeEmoji,
4960
+ icon: this.icon,
4044
4961
  hoist_position: this.hoistPosition
4045
4962
  },
4046
4963
  this.guildId
@@ -4053,7 +4970,7 @@ var Role = class _Role extends Base {
4053
4970
  */
4054
4971
  async edit(options) {
4055
4972
  const body = toRoleEditBody(options);
4056
- const data = await this.client.rest.patch(Routes18.guildRole(this.guildId, this.id), {
4973
+ const data = await this.client.rest.patch(Routes21.guildRole(this.guildId, this.id), {
4057
4974
  body: Object.keys(body).length ? body : void 0,
4058
4975
  auth: true,
4059
4976
  ...auditReasonHeaders(options.reason)
@@ -4066,7 +4983,7 @@ var Role = class _Role extends Base {
4066
4983
  * @param reason - Audit log reason (`X-Audit-Log-Reason`)
4067
4984
  */
4068
4985
  async delete(reason) {
4069
- await this.client.rest.delete(Routes18.guildRole(this.guildId, this.id), {
4986
+ await this.client.rest.delete(Routes21.guildRole(this.guildId, this.id), {
4070
4987
  auth: true,
4071
4988
  ...auditReasonHeaders(reason)
4072
4989
  });
@@ -4161,11 +5078,30 @@ function syncChannels(guild, channels) {
4161
5078
  const keep = new Set(channels.map((c) => c.id));
4162
5079
  for (const data of channels) cacheChannel(guild, data);
4163
5080
  for (const [id, channel] of [...guild.channels.entries()]) {
4164
- if (keep.has(id)) continue;
5081
+ if (keep.has(id) || channel.isThread()) continue;
4165
5082
  Map.prototype.delete.call(guild.channels, id);
4166
5083
  guild.client.cache.cascadeChannel(channel, "guild");
4167
5084
  }
4168
5085
  }
5086
+ function isThreadChannelType(type) {
5087
+ return type === ChannelType9.AnnouncementThread || type === ChannelType9.PublicThread || type === ChannelType9.PrivateThread;
5088
+ }
5089
+ function syncThreads(guild, threads, alsoKeep = /* @__PURE__ */ new Set()) {
5090
+ const keep = new Set(alsoKeep);
5091
+ for (const data of threads) {
5092
+ if (!isThreadChannelType(data.type)) continue;
5093
+ const withGuild = data.guild_id ? data : { ...data, guild_id: guild.id };
5094
+ cacheThread(guild.client, withGuild);
5095
+ keep.add(data.id);
5096
+ }
5097
+ const seen = /* @__PURE__ */ new Set();
5098
+ for (const channel of [...guild.channels.values(), ...guild.client.channels.values()]) {
5099
+ if (seen.has(channel.id)) continue;
5100
+ seen.add(channel.id);
5101
+ if (!channel.isThread() || channel.guildId !== guild.id || keep.has(channel.id)) continue;
5102
+ guild.client.cache.cascadeChannel(channel);
5103
+ }
5104
+ }
4169
5105
  function mergeMembers(guild, members) {
4170
5106
  for (const m of members) {
4171
5107
  if (!m.user?.id) continue;
@@ -4199,6 +5135,7 @@ var ChannelManager = class extends LimitedCollection {
4199
5135
  });
4200
5136
  this.client = client;
4201
5137
  }
5138
+ pendingFetches = /* @__PURE__ */ new Map();
4202
5139
  /**
4203
5140
  * Remove a channel from cache. Does not delete it on the API.
4204
5141
  * Use {@link Channel.delete} after {@link fetch} to delete the channel.
@@ -4211,9 +5148,11 @@ var ChannelManager = class extends LimitedCollection {
4211
5148
  }
4212
5149
  return deleted;
4213
5150
  }
4214
- /** Retrieve from cache, otherwise {@link fetch}. */
5151
+ /** Retrieve from cache (hydrating partial stubs), otherwise {@link fetch}. */
4215
5152
  async resolve(channelId) {
4216
- return this.get(channelId) ?? this.fetch(channelId);
5153
+ const id = normalizeSnowflakeId(channelId, "channels.resolve()");
5154
+ const cached = this.get(id);
5155
+ return cached && !cached.partial ? cached : this.fetch(id);
4217
5156
  }
4218
5157
  /**
4219
5158
  * Fetch a channel by ID. The returned {@link Channel} has {@link Channel.delete}
@@ -4226,10 +5165,23 @@ var ChannelManager = class extends LimitedCollection {
4226
5165
  * @throws {@link FluxerError} with CHANNEL_NOT_FOUND if missing
4227
5166
  */
4228
5167
  async fetch(channelId, options) {
4229
- const cached = this.get(channelId);
4230
- if (cached && !options?.force) return cached;
5168
+ const id = normalizeSnowflakeId(channelId, "channels.fetch()");
5169
+ const cached = this.get(id);
5170
+ if (cached && !cached.partial && !options?.force) return cached;
5171
+ return dedupeFetch(this.pendingFetches, id, async () => this.fetchFresh(id));
5172
+ }
5173
+ async fetchFresh(channelId) {
4231
5174
  try {
4232
- const data = await this.client.rest.get(Routes19.channel(channelId));
5175
+ const data = assertApiObjectWithId(
5176
+ await this.client.rest.get(Routes22.channel(channelId)),
5177
+ "channels.fetch()"
5178
+ );
5179
+ const existing = this.get(channelId);
5180
+ if (existing && existing.type === data.type) {
5181
+ existing._patch(data);
5182
+ putChannel(this.client, existing);
5183
+ return existing;
5184
+ }
4233
5185
  const guildId = "guild_id" in data ? data.guild_id : void 0;
4234
5186
  if (guildId) {
4235
5187
  const guild = this.client.guilds.get(guildId);
@@ -4274,7 +5226,7 @@ var ChannelManager = class extends LimitedCollection {
4274
5226
  defaultAllowedMentions: this.client.options.defaultAllowedMentions
4275
5227
  });
4276
5228
  const data = await this.client.rest.post(
4277
- Routes19.channelMessages(channelId),
5229
+ Routes22.channelMessages(channelId),
4278
5230
  postPayload
4279
5231
  );
4280
5232
  this.client._addMessageToCache(channelId, data);
@@ -4285,11 +5237,11 @@ var ChannelManager = class extends LimitedCollection {
4285
5237
  // src/ClientCore/Client.ts
4286
5238
  import { EventEmitter as EventEmitter3 } from "events";
4287
5239
  import { REST } from "@fluxerjs/rest";
4288
- import { GatewayOpcodes as GatewayOpcodes2, Routes as Routes34 } from "@fluxerjs/types";
5240
+ import { GatewayOpcodes as GatewayOpcodes2, Routes as Routes37 } from "@fluxerjs/types";
4289
5241
  import { createLogger } from "@fluxerjs/util";
4290
5242
 
4291
5243
  // src/Domain/User.ts
4292
- import { Routes as Routes20 } from "@fluxerjs/types";
5244
+ import { Routes as Routes23 } from "@fluxerjs/types";
4293
5245
  import { SnowflakeUtil as SnowflakeUtil8 } from "@fluxerjs/util";
4294
5246
  var User = class extends Base {
4295
5247
  /** Parent client instance. */
@@ -4314,12 +5266,15 @@ var User = class extends Base {
4314
5266
  system;
4315
5267
  /** Banner hash for profile. */
4316
5268
  banner;
5269
+ /** True when this user was created from an ID-only stub and not yet hydrated from REST/gateway. */
5270
+ partial;
4317
5271
  constructor(client, data) {
4318
5272
  super();
4319
5273
  this.client = client;
4320
5274
  this.id = data.id;
4321
- this.username = data.username;
4322
- this.discriminator = data.discriminator;
5275
+ this.partial = typeof data.username !== "string" || data.username.length === 0;
5276
+ this.username = data.username ?? "Unknown";
5277
+ this.discriminator = data.discriminator ?? "0";
4323
5278
  this.globalName = data.global_name ?? null;
4324
5279
  this.avatar = data.avatar ?? null;
4325
5280
  this.bot = !!data.bot;
@@ -4330,13 +5285,18 @@ var User = class extends Base {
4330
5285
  }
4331
5286
  /** @internal */
4332
5287
  _patch(data) {
4333
- this.username = data.username;
4334
- this.discriminator = data.discriminator;
4335
- this.globalName = data.global_name ?? null;
4336
- this.avatar = data.avatar ?? null;
5288
+ if (data.username !== void 0) this.username = data.username;
5289
+ if (data.discriminator !== void 0) this.discriminator = data.discriminator;
5290
+ if (data.global_name !== void 0) this.globalName = data.global_name ?? null;
5291
+ if (data.avatar !== void 0) this.avatar = data.avatar ?? null;
4337
5292
  if (data.avatar_color !== void 0) this.avatarColor = data.avatar_color;
4338
5293
  if (data.flags !== void 0) this.flags = data.flags;
4339
5294
  if (data.banner !== void 0) this.banner = data.banner;
5295
+ if (typeof data.username === "string" && data.username.length > 0) this.partial = false;
5296
+ }
5297
+ /** Fetch the full user from REST when this instance is a partial stub. */
5298
+ async fetch() {
5299
+ return this.client.users.fetch(this.id, { force: true });
4340
5300
  }
4341
5301
  cdnOpts() {
4342
5302
  return {
@@ -4388,7 +5348,7 @@ var User = class extends Base {
4388
5348
  * @returns DM channel instance (cached if already open)
4389
5349
  */
4390
5350
  async createDM() {
4391
- const data = await this.client.rest.post(Routes20.userMeChannels(), {
5351
+ const data = await this.client.rest.post(Routes23.userMeChannels(), {
4392
5352
  body: { recipient_id: this.id },
4393
5353
  auth: true
4394
5354
  });
@@ -4466,7 +5426,7 @@ function resolveCacheLimits(input) {
4466
5426
 
4467
5427
  // src/ClientCore/ClientEmoji.ts
4468
5428
  import { Collection as Collection8 } from "@fluxerjs/collection";
4469
- import { Routes as Routes21 } from "@fluxerjs/types";
5429
+ import { Routes as Routes24 } from "@fluxerjs/types";
4470
5430
  import { formatEmoji, getUnicodeFromShortcode, parseEmoji } from "@fluxerjs/util";
4471
5431
  async function resolveClientEmoji(client, emoji, guildId) {
4472
5432
  if (typeof emoji === "object" && emoji.id) {
@@ -4485,7 +5445,7 @@ async function resolveClientEmoji(client, emoji, guildId) {
4485
5445
  const unicodeFromShortcode = getUnicodeFromShortcode(parsed.name);
4486
5446
  if (unicodeFromShortcode) return unicodeFromShortcode;
4487
5447
  if (guildId) {
4488
- const emojis = await client.rest.get(Routes21.guildEmojis(guildId));
5448
+ const emojis = await client.rest.get(Routes24.guildEmojis(guildId));
4489
5449
  const found = emojis.find((e) => e.name && e.name.toLowerCase() === parsed.name.toLowerCase());
4490
5450
  if (found) return formatEmoji({ ...parsed, id: found.id, animated: found.animated });
4491
5451
  throw new FluxerError(
@@ -4502,26 +5462,26 @@ async function resolveClientEmoji(client, emoji, guildId) {
4502
5462
  return parsed.name;
4503
5463
  }
4504
5464
  async function fetchInstance(client) {
4505
- const raw = await client.rest.get(Routes21.instanceDiscovery(), {
5465
+ const raw = await client.rest.get(Routes24.instanceDiscovery(), {
4506
5466
  auth: false,
4507
5467
  unversioned: true
4508
5468
  });
4509
5469
  return parseInstanceDiscovery(raw);
4510
5470
  }
4511
5471
  function fetchGatewayInfo(client) {
4512
- return client.rest.get(Routes21.gatewayBot());
5472
+ return client.rest.get(Routes24.gatewayBot());
4513
5473
  }
4514
5474
  function fetchEmojiMetadata(client, emojiId) {
4515
- return client.rest.get(Routes21.emojiMetadata(emojiId), { auth: true });
5475
+ return client.rest.get(Routes24.emojiMetadata(emojiId), { auth: true });
4516
5476
  }
4517
5477
  function fetchStickerMetadata(client, stickerId) {
4518
- return client.rest.get(Routes21.stickerMetadata(stickerId), { auth: true });
5478
+ return client.rest.get(Routes24.stickerMetadata(stickerId), { auth: true });
4519
5479
  }
4520
5480
  function fetchApplication(client) {
4521
- return client.rest.get(Routes21.applicationsMe(), { auth: true });
5481
+ return client.rest.get(Routes24.applicationsMe(), { auth: true });
4522
5482
  }
4523
5483
  async function fetchOAuthApplications(client) {
4524
- const data = await client.rest.get(Routes21.oauth2ApplicationsMe(), { auth: true });
5484
+ const data = await client.rest.get(Routes24.oauth2ApplicationsMe(), { auth: true });
4525
5485
  if (Array.isArray(data)) return data;
4526
5486
  if (data && typeof data === "object" && "applications" in data && Array.isArray(data.applications)) {
4527
5487
  return data.applications;
@@ -4540,14 +5500,14 @@ function assertChannelIdBatch(name, channelIds) {
4540
5500
  }
4541
5501
  function preloadMessages(client, channelIds) {
4542
5502
  assertChannelIdBatch("preloadMessages", channelIds);
4543
- return client.rest.post(Routes21.preloadMessages(), {
5503
+ return client.rest.post(Routes24.preloadMessages(), {
4544
5504
  body: { channels: channelIds },
4545
5505
  auth: true
4546
5506
  });
4547
5507
  }
4548
5508
  function preloadMessagesAlt(client, channelIds) {
4549
5509
  assertChannelIdBatch("preloadMessagesAlt", channelIds);
4550
- return client.rest.post(Routes21.preloadMessagesAlt(), {
5510
+ return client.rest.post(Routes24.preloadMessagesAlt(), {
4551
5511
  body: { channels: channelIds },
4552
5512
  auth: true
4553
5513
  });
@@ -4555,7 +5515,7 @@ function preloadMessagesAlt(client, channelIds) {
4555
5515
  async function bulkFetchMessages(client, requests, options = {}) {
4556
5516
  validateBulkMessageFetchRequests(requests);
4557
5517
  const wire = toBulkFetchWire(requests);
4558
- const data = await client.rest.post(Routes21.channelsMessagesBulk(), {
5518
+ const data = await client.rest.post(Routes24.channelsMessagesBulk(), {
4559
5519
  body: { requests: wire },
4560
5520
  auth: true
4561
5521
  });
@@ -4572,12 +5532,74 @@ async function bulkFetchMessages(client, requests, options = {}) {
4572
5532
  };
4573
5533
  }
4574
5534
  async function searchMessages(client, options = {}) {
4575
- const data = await client.rest.post(Routes21.searchMessages(), {
5535
+ const data = await client.rest.post(Routes24.searchMessages(), {
4576
5536
  body: toMessageSearchBody(options),
4577
5537
  auth: true
4578
5538
  });
4579
5539
  return toMessageSearchResponse(data);
4580
5540
  }
5541
+ function fetchEmojiSource(client, emojiId) {
5542
+ return client.rest.get(
5543
+ Routes24.emojiSource(emojiId),
5544
+ { auth: true }
5545
+ );
5546
+ }
5547
+ function fetchStickerSource(client, stickerId) {
5548
+ return client.rest.get(
5549
+ Routes24.stickerSource(stickerId),
5550
+ { auth: true }
5551
+ );
5552
+ }
5553
+ function fetchDiscoveryCategories(client) {
5554
+ return client.rest.get(
5555
+ Routes24.discoveryCategories(),
5556
+ { auth: true }
5557
+ );
5558
+ }
5559
+ function searchDiscoveryGuilds(client, options = {}) {
5560
+ const params = new URLSearchParams();
5561
+ if (options.query !== void 0) params.set("query", options.query);
5562
+ if (options.category !== void 0) params.set("category", String(options.category));
5563
+ if (options.language !== void 0) params.set("language", options.language);
5564
+ if (options.tag !== void 0) params.set("tag", options.tag);
5565
+ if (options.sort_by !== void 0) params.set("sort_by", options.sort_by);
5566
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
5567
+ if (options.offset !== void 0) params.set("offset", String(options.offset));
5568
+ const qs2 = params.toString();
5569
+ return client.rest.get(
5570
+ qs2 ? `${Routes24.discoveryGuilds()}?${qs2}` : Routes24.discoveryGuilds(),
5571
+ { auth: true }
5572
+ );
5573
+ }
5574
+ function fetchExperiments(client) {
5575
+ return client.rest.get(Routes24.experiments(), {
5576
+ auth: true
5577
+ });
5578
+ }
5579
+ function refreshAttachmentUrls(client, attachmentUrls) {
5580
+ return client.rest.post(
5581
+ Routes24.attachmentsRefreshUrls(),
5582
+ { body: { attachment_urls: attachmentUrls }, auth: true }
5583
+ );
5584
+ }
5585
+ function fetchInstanceBadges(client, options = {}) {
5586
+ const params = new URLSearchParams();
5587
+ if (options.ids !== void 0) params.set("ids", options.ids);
5588
+ if (options.after !== void 0) params.set("after", options.after);
5589
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
5590
+ if (options.version !== void 0) params.set("version", options.version);
5591
+ const qs2 = params.toString();
5592
+ return client.rest.get(
5593
+ qs2 ? `${Routes24.instanceBadges()}?${qs2}` : Routes24.instanceBadges(),
5594
+ { auth: false }
5595
+ );
5596
+ }
5597
+ function fetchChannelPostData(client, channelId, threadIds) {
5598
+ return client.rest.post(
5599
+ Routes24.channelPostData(channelId),
5600
+ { body: { thread_ids: threadIds }, auth: true }
5601
+ );
5602
+ }
4581
5603
 
4582
5604
  // src/ClientCore/ClientEvents.ts
4583
5605
  function createEventMethods(client) {
@@ -4602,12 +5624,13 @@ import { SnowflakeUtil as SnowflakeUtil9 } from "@fluxerjs/util";
4602
5624
 
4603
5625
  // src/ClientCore/GuildMemberManager.ts
4604
5626
  import { LimitedCollection as LimitedCollection2 } from "@fluxerjs/collection";
4605
- import { Routes as Routes22 } from "@fluxerjs/types";
5627
+ import { Routes as Routes25 } from "@fluxerjs/types";
4606
5628
  var GuildMemberManager = class extends LimitedCollection2 {
4607
5629
  constructor(guild) {
4608
5630
  super({ maxSize: guild.client.cache.limits.members });
4609
5631
  this.guild = guild;
4610
5632
  }
5633
+ pendingFetches = /* @__PURE__ */ new Map();
4611
5634
  /**
4612
5635
  * Get a guild member from cache or fetch from the API if not present.
4613
5636
  * Convenience helper to avoid repeating `guild.members.get(userId) ?? (await guild.fetchMember(userId))`.
@@ -4619,7 +5642,9 @@ var GuildMemberManager = class extends LimitedCollection2 {
4619
5642
  * console.log(member.displayName);
4620
5643
  */
4621
5644
  async resolve(userId) {
4622
- return this.get(userId) ?? this.fetch(userId);
5645
+ const id = normalizeSnowflakeId(userId, "members.resolve()");
5646
+ const cached = this.get(id);
5647
+ return cached && !cached.user.partial ? cached : this.fetch(id);
4623
5648
  }
4624
5649
  /**
4625
5650
  * The current bot user as a GuildMember in this guild.
@@ -4647,10 +5672,11 @@ var GuildMemberManager = class extends LimitedCollection2 {
4647
5672
  return this.guild.fetchMe();
4648
5673
  }
4649
5674
  async fetch(userIdOrOptions, options) {
4650
- if (typeof userIdOrOptions === "string") {
4651
- const cached = this.get(userIdOrOptions);
4652
- if (cached && !options?.force) return cached;
4653
- return this.guild.fetchMember(userIdOrOptions);
5675
+ if (typeof userIdOrOptions === "string" || typeof userIdOrOptions === "number") {
5676
+ const id = normalizeSnowflakeId(userIdOrOptions, "members.fetch()");
5677
+ const cached = this.get(id);
5678
+ if (cached && !cached.user.partial && !options?.force) return cached;
5679
+ return dedupeFetch(this.pendingFetches, id, async () => this.guild.fetchMember(id));
4654
5680
  }
4655
5681
  return this.fetchMany(userIdOrOptions);
4656
5682
  }
@@ -4659,10 +5685,14 @@ var GuildMemberManager = class extends LimitedCollection2 {
4659
5685
  if (options?.limit != null) params.set("limit", String(options.limit));
4660
5686
  if (options?.after) params.set("after", options.after);
4661
5687
  const qs2 = params.toString();
4662
- const url = Routes22.guildMembers(this.guild.id) + (qs2 ? `?${qs2}` : "");
4663
- const data = await this.guild.client.rest.get(url, { auth: true });
5688
+ const url = Routes25.guildMembers(this.guild.id) + (qs2 ? `?${qs2}` : "");
5689
+ const data = assertApiArray(
5690
+ await this.guild.client.rest.get(url, { auth: true }),
5691
+ "members.fetch()"
5692
+ );
4664
5693
  const members = [];
4665
5694
  for (const m of data) {
5695
+ if (!m?.user?.id) continue;
4666
5696
  const member = new GuildMember(
4667
5697
  this.guild.client,
4668
5698
  { ...m, guild_id: this.guild.id },
@@ -4682,7 +5712,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
4682
5712
  */
4683
5713
  async search(options = {}) {
4684
5714
  const data = await this.guild.client.rest.post(
4685
- Routes22.guildMembersSearch(this.guild.id),
5715
+ Routes25.guildMembersSearch(this.guild.id),
4686
5716
  { body: toMemberSearchBody(options), auth: true }
4687
5717
  );
4688
5718
  const offset = options.offset ?? 0;
@@ -4708,7 +5738,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
4708
5738
  };
4709
5739
 
4710
5740
  // src/Domain/Guild/Admin.ts
4711
- import { Routes as Routes23 } from "@fluxerjs/types";
5741
+ import { Routes as Routes26 } from "@fluxerjs/types";
4712
5742
  function toAuditLogEntryPayload(entry, guildId) {
4713
5743
  return {
4714
5744
  id: entry.id,
@@ -4729,7 +5759,7 @@ function toVanityPayload(data) {
4729
5759
  return { code: data.code ?? null, uses: data.uses };
4730
5760
  }
4731
5761
  async function fetchAuditLogs(guild, options) {
4732
- const url = Routes23.guildAuditLogs(guild.id) + qs({
5762
+ const url = Routes26.guildAuditLogs(guild.id) + qs({
4733
5763
  limit: options?.limit,
4734
5764
  before: options?.before,
4735
5765
  after: options?.after,
@@ -4753,7 +5783,7 @@ async function fetchAuditLogs(guild, options) {
4753
5783
  };
4754
5784
  }
4755
5785
  async function editGuild(guild, options) {
4756
- const data = await guild.client.rest.patch(Routes23.guild(guild.id), {
5786
+ const data = await guild.client.rest.patch(Routes26.guild(guild.id), {
4757
5787
  body: toGuildEditBody(options),
4758
5788
  auth: true
4759
5789
  });
@@ -4761,13 +5791,13 @@ async function editGuild(guild, options) {
4761
5791
  return guild;
4762
5792
  }
4763
5793
  async function fetchVanityURL(guild) {
4764
- const data = await guild.client.rest.get(Routes23.guildVanityUrl(guild.id), {
5794
+ const data = await guild.client.rest.get(Routes26.guildVanityUrl(guild.id), {
4765
5795
  auth: true
4766
5796
  });
4767
5797
  return toVanityPayload(data);
4768
5798
  }
4769
5799
  async function editVanityURL(guild, code) {
4770
- const data = await guild.client.rest.patch(Routes23.guildVanityUrl(guild.id), {
5800
+ const data = await guild.client.rest.patch(Routes26.guildVanityUrl(guild.id), {
4771
5801
  body: { code },
4772
5802
  auth: true
4773
5803
  });
@@ -4775,14 +5805,14 @@ async function editVanityURL(guild, code) {
4775
5805
  return toVanityPayload(data);
4776
5806
  }
4777
5807
  async function fetchDiscoveryStatus(guild) {
4778
- const data = await guild.client.rest.get(Routes23.guildDiscovery(guild.id), {
5808
+ const data = await guild.client.rest.get(Routes26.guildDiscovery(guild.id), {
4779
5809
  auth: true
4780
5810
  });
4781
5811
  return toDiscoveryStatusPayload(data);
4782
5812
  }
4783
5813
  async function applyForDiscovery(guild, options) {
4784
5814
  const data = await guild.client.rest.post(
4785
- Routes23.guildDiscovery(guild.id),
5815
+ Routes26.guildDiscovery(guild.id),
4786
5816
  {
4787
5817
  body: toDiscoveryBody(options),
4788
5818
  auth: true
@@ -4792,7 +5822,7 @@ async function applyForDiscovery(guild, options) {
4792
5822
  }
4793
5823
  async function editDiscoveryApplication(guild, options) {
4794
5824
  const data = await guild.client.rest.patch(
4795
- Routes23.guildDiscovery(guild.id),
5825
+ Routes26.guildDiscovery(guild.id),
4796
5826
  {
4797
5827
  body: toDiscoveryBody(options),
4798
5828
  auth: true
@@ -4801,34 +5831,39 @@ async function editDiscoveryApplication(guild, options) {
4801
5831
  return toDiscoveryApplicationPayload(data);
4802
5832
  }
4803
5833
  async function withdrawDiscoveryApplication(guild) {
4804
- await guild.client.rest.delete(Routes23.guildDiscovery(guild.id), { auth: true });
5834
+ await guild.client.rest.delete(Routes26.guildDiscovery(guild.id), { auth: true });
4805
5835
  }
4806
5836
  async function deleteGuild(guild, options) {
4807
5837
  const body = options ? toSudoBody(options) : {};
4808
- await guild.client.rest.post(Routes23.guildDelete(guild.id), {
5838
+ await guild.client.rest.post(Routes26.guildDelete(guild.id), {
4809
5839
  body,
4810
5840
  auth: true
4811
5841
  });
4812
5842
  guild.client.guilds.delete(guild.id);
4813
5843
  }
4814
5844
  async function transferOwnership(guild, newOwnerId, password) {
4815
- await guild.client.rest.post(Routes23.guildTransferOwnership(guild.id), {
5845
+ await guild.client.rest.post(Routes26.guildTransferOwnership(guild.id), {
4816
5846
  body: { new_owner_id: newOwnerId, ...password != null && { password } },
4817
5847
  auth: true
4818
5848
  });
4819
5849
  }
4820
5850
 
4821
5851
  // src/Domain/Guild/Channels.ts
4822
- import { Routes as Routes24 } from "@fluxerjs/types";
5852
+ import { Routes as Routes27 } from "@fluxerjs/types";
4823
5853
  async function createChannel(guild, options) {
4824
- const created = await guild.client.rest.post(Routes24.guildChannels(guild.id), {
5854
+ const created = await guild.client.rest.post(Routes27.guildChannels(guild.id), {
4825
5855
  body: toChannelCreateBody(options),
4826
5856
  auth: true
4827
5857
  });
4828
5858
  return cacheChannel(guild, created);
4829
5859
  }
4830
5860
  async function fetchChannels(guild) {
4831
- const data = await guild.client.rest.get(Routes24.guildChannels(guild.id));
5861
+ const raw = await guild.client.rest.get(Routes27.guildChannels(guild.id));
5862
+ if (!Array.isArray(raw))
5863
+ throw new TypeError(
5864
+ "guild.fetchChannels() received an invalid API payload (expected an array)"
5865
+ );
5866
+ const data = raw;
4832
5867
  const channels = [];
4833
5868
  for (const ch of data) {
4834
5869
  const channel = cacheChannel(guild, ch);
@@ -4837,17 +5872,17 @@ async function fetchChannels(guild) {
4837
5872
  return channels;
4838
5873
  }
4839
5874
  async function setChannelPositions(guild, updates) {
4840
- await guild.client.rest.patch(Routes24.guildChannels(guild.id), {
5875
+ await guild.client.rest.patch(Routes27.guildChannels(guild.id), {
4841
5876
  body: toChannelPositionBody(updates),
4842
5877
  auth: true
4843
5878
  });
4844
5879
  }
4845
5880
  async function fetchWebhooks(guild) {
4846
- const data = await guild.client.rest.get(Routes24.guildWebhooks(guild.id));
5881
+ const data = await guild.client.rest.get(Routes27.guildWebhooks(guild.id));
4847
5882
  return data.map((w) => new Webhook(guild.client, w));
4848
5883
  }
4849
5884
  async function fetchInvites(guild) {
4850
- const data = await guild.client.rest.get(Routes24.guildInvites(guild.id));
5885
+ const data = await guild.client.rest.get(Routes27.guildInvites(guild.id));
4851
5886
  return data.map((invite) => new Invite(guild.client, invite));
4852
5887
  }
4853
5888
  async function fetchInvite(guild, codeOrUrl) {
@@ -4867,14 +5902,14 @@ function resolveGuildOnlineCount(data) {
4867
5902
  }
4868
5903
 
4869
5904
  // src/Domain/Guild/Emojis.ts
4870
- import { Routes as Routes25 } from "@fluxerjs/types";
5905
+ import { Routes as Routes28 } from "@fluxerjs/types";
4871
5906
  async function fetchEmojis(guild) {
4872
- const data = await guild.client.rest.get(Routes25.guildEmojis(guild.id));
5907
+ const data = await guild.client.rest.get(Routes28.guildEmojis(guild.id));
4873
5908
  return data.map((e) => cacheEmoji(guild, e));
4874
5909
  }
4875
5910
  async function fetchEmoji(guild, emojiId) {
4876
5911
  try {
4877
- const data = await guild.client.rest.get(Routes25.guildEmoji(guild.id, emojiId));
5912
+ const data = await guild.client.rest.get(Routes28.guildEmoji(guild.id, emojiId));
4878
5913
  return cacheEmoji(guild, data);
4879
5914
  } catch (err) {
4880
5915
  rethrowMapped(err, {
@@ -4885,7 +5920,7 @@ async function fetchEmoji(guild, emojiId) {
4885
5920
  }
4886
5921
  async function createEmoji(guild, options) {
4887
5922
  const { reason, ...body } = options;
4888
- const data = await guild.client.rest.post(Routes25.guildEmojis(guild.id), {
5923
+ const data = await guild.client.rest.post(Routes28.guildEmojis(guild.id), {
4889
5924
  body,
4890
5925
  auth: true,
4891
5926
  ...auditReasonHeaders(reason)
@@ -4893,7 +5928,7 @@ async function createEmoji(guild, options) {
4893
5928
  return cacheEmoji(guild, data);
4894
5929
  }
4895
5930
  async function cloneEmoji(guild, sourceEmojiId) {
4896
- const data = await guild.client.rest.post(Routes25.guildEmojisClone(guild.id), {
5931
+ const data = await guild.client.rest.post(Routes28.guildEmojisClone(guild.id), {
4897
5932
  body: { source_emoji_id: sourceEmojiId },
4898
5933
  auth: true
4899
5934
  });
@@ -4901,7 +5936,7 @@ async function cloneEmoji(guild, sourceEmojiId) {
4901
5936
  }
4902
5937
  async function createEmojisBulk(guild, emojis) {
4903
5938
  const data = await guild.client.rest.post(
4904
- Routes25.guildEmojisBulk(guild.id),
5939
+ Routes28.guildEmojisBulk(guild.id),
4905
5940
  { body: { emojis }, auth: true }
4906
5941
  );
4907
5942
  return { success: data.success.map((e) => cacheEmoji(guild, e)), failed: data.failed };
@@ -4921,18 +5956,22 @@ var GuildRoleManager = class extends LimitedCollection3 {
4921
5956
  };
4922
5957
 
4923
5958
  // src/Domain/Guild/MemberHttp.ts
4924
- import { Routes as Routes26 } from "@fluxerjs/types";
5959
+ import { Routes as Routes29 } from "@fluxerjs/types";
4925
5960
  async function fetchMember(guild, userId) {
5961
+ const id = normalizeSnowflakeId(userId, "members.fetch()");
4926
5962
  try {
4927
5963
  const data = await guild.client.rest.get(
4928
- Routes26.guildMember(guild.id, userId)
5964
+ Routes29.guildMember(guild.id, id)
4929
5965
  );
5966
+ if (!data?.user?.id) {
5967
+ throw new TypeError("members.fetch() received an invalid API payload (missing user.id)");
5968
+ }
4930
5969
  return cacheMember(guild, data);
4931
5970
  } catch (err) {
4932
5971
  rethrowMapped(err, {
4933
5972
  notFound: {
4934
5973
  code: ErrorCodes.MemberNotFound,
4935
- message: `Member ${userId} not found in guild`
5974
+ message: `Member ${id} not found in guild`
4936
5975
  },
4937
5976
  fallback: "Failed to fetch guild member"
4938
5977
  });
@@ -4940,17 +5979,20 @@ async function fetchMember(guild, userId) {
4940
5979
  }
4941
5980
  async function fetchMe(guild) {
4942
5981
  const data = await guild.client.rest.get(
4943
- Routes26.guildMemberMe(guild.id),
5982
+ Routes29.guildMemberMe(guild.id),
4944
5983
  { auth: true }
4945
5984
  );
5985
+ if (!data?.user?.id) {
5986
+ throw new TypeError("members.fetchMe() received an invalid API payload (missing user.id)");
5987
+ }
4946
5988
  return cacheMember(guild, data);
4947
5989
  }
4948
5990
 
4949
5991
  // src/Domain/Guild/Moderation.ts
4950
- import { Routes as Routes28 } from "@fluxerjs/types";
5992
+ import { Routes as Routes31 } from "@fluxerjs/types";
4951
5993
 
4952
5994
  // src/Domain/Guild/GuildBan.ts
4953
- import { Routes as Routes27 } from "@fluxerjs/types";
5995
+ import { Routes as Routes30 } from "@fluxerjs/types";
4954
5996
  function parseOptionalDate2(value) {
4955
5997
  if (value == null || value === "") return null;
4956
5998
  const date = new Date(value);
@@ -4977,7 +6019,7 @@ var GuildBan = class extends Base {
4977
6019
  * Requires Ban Members permission.
4978
6020
  */
4979
6021
  async unban(reason) {
4980
- await this.client.rest.delete(Routes27.guildBan(this.guildId, this.user.id), {
6022
+ await this.client.rest.delete(Routes30.guildBan(this.guildId, this.user.id), {
4981
6023
  auth: true,
4982
6024
  ...auditReasonHeaders(reason)
4983
6025
  });
@@ -4987,35 +6029,39 @@ var GuildBan = class extends Base {
4987
6029
  // src/Domain/Guild/Moderation.ts
4988
6030
  async function ban(guild, userId, options) {
4989
6031
  const body = options ? toGuildBanBody(options) : {};
4990
- await guild.client.rest.put(Routes28.guildBan(guild.id, userId), {
6032
+ await guild.client.rest.put(Routes31.guildBan(guild.id, userId), {
4991
6033
  body: Object.keys(body).length ? body : void 0,
4992
6034
  auth: true,
4993
6035
  ...auditReasonHeaders(options?.reason)
4994
6036
  });
4995
6037
  }
6038
+ async function fetchBan(guild, userId) {
6039
+ const data = await guild.client.rest.get(Routes31.guildBan(guild.id, userId));
6040
+ return new GuildBan(guild.client, { ...data, guild_id: guild.id }, guild.id);
6041
+ }
4996
6042
  async function fetchBans(guild) {
4997
- const data = await guild.client.rest.get(Routes28.guildBans(guild.id));
6043
+ const data = await guild.client.rest.get(Routes31.guildBans(guild.id));
4998
6044
  return data.map((b) => new GuildBan(guild.client, { ...b, guild_id: guild.id }, guild.id));
4999
6045
  }
5000
6046
  async function unban(guild, userId, reason) {
5001
- await guild.client.rest.delete(Routes28.guildBan(guild.id, userId), {
6047
+ await guild.client.rest.delete(Routes31.guildBan(guild.id, userId), {
5002
6048
  auth: true,
5003
6049
  ...auditReasonHeaders(reason)
5004
6050
  });
5005
6051
  }
5006
6052
  async function kick(guild, userId, reason) {
5007
- await guild.client.rest.delete(Routes28.guildMember(guild.id, userId), {
6053
+ await guild.client.rest.delete(Routes31.guildMember(guild.id, userId), {
5008
6054
  auth: true,
5009
6055
  ...auditReasonHeaders(reason)
5010
6056
  });
5011
6057
  }
5012
6058
 
5013
6059
  // src/Domain/Guild/Roles.ts
5014
- import { Routes as Routes29 } from "@fluxerjs/types";
6060
+ import { Routes as Routes32 } from "@fluxerjs/types";
5015
6061
  import { parseRoleMention } from "@fluxerjs/util";
5016
6062
  async function createRole(guild, options = {}) {
5017
6063
  const body = toRoleCreateBody(options);
5018
- const data = await guild.client.rest.post(Routes29.guildRoles(guild.id), {
6064
+ const data = await guild.client.rest.post(Routes32.guildRoles(guild.id), {
5019
6065
  body: Object.keys(body).length ? body : void 0,
5020
6066
  auth: true,
5021
6067
  ...auditReasonHeaders(options.reason)
@@ -5023,12 +6069,14 @@ async function createRole(guild, options = {}) {
5023
6069
  return cacheRole(guild, data);
5024
6070
  }
5025
6071
  async function fetchRoles(guild) {
5026
- const data = await guild.client.rest.get(Routes29.guildRoles(guild.id));
6072
+ const data = await guild.client.rest.get(Routes32.guildRoles(guild.id));
6073
+ if (!Array.isArray(data))
6074
+ throw new TypeError("guild.fetchRoles() received an invalid API payload (expected an array)");
5027
6075
  return data.map((r) => cacheRole(guild, r));
5028
6076
  }
5029
6077
  async function fetchRole(guild, roleId2) {
5030
6078
  try {
5031
- const data = await guild.client.rest.get(Routes29.guildRole(guild.id, roleId2));
6079
+ const data = await guild.client.rest.get(Routes32.guildRole(guild.id, roleId2));
5032
6080
  return cacheRole(guild, data);
5033
6081
  } catch (err) {
5034
6082
  rethrowMapped(err, {
@@ -5045,7 +6093,7 @@ async function resolveRoleId(guild, arg) {
5045
6093
  const needle = trimmed.toLowerCase();
5046
6094
  const cached = guild.roles.find((r) => r.name?.toLowerCase() === needle);
5047
6095
  if (cached) return cached.id;
5048
- const roles = await guild.client.rest.get(Routes29.guildRoles(guild.id));
6096
+ const roles = await guild.client.rest.get(Routes32.guildRoles(guild.id));
5049
6097
  const role = roles.find((r) => r.name?.toLowerCase() === needle);
5050
6098
  if (!role) return null;
5051
6099
  cacheRole(guild, role);
@@ -5054,7 +6102,7 @@ async function resolveRoleId(guild, arg) {
5054
6102
  async function setRolePositions(guild, updates) {
5055
6103
  return replaceRoles(
5056
6104
  guild,
5057
- await guild.client.rest.patch(Routes29.guildRoles(guild.id), {
6105
+ await guild.client.rest.patch(Routes32.guildRoles(guild.id), {
5058
6106
  body: updates,
5059
6107
  auth: true
5060
6108
  })
@@ -5063,7 +6111,7 @@ async function setRolePositions(guild, updates) {
5063
6111
  async function setRoleHoistPositions(guild, updates) {
5064
6112
  return replaceRoles(
5065
6113
  guild,
5066
- await guild.client.rest.patch(Routes29.guildRolesHoistPositions(guild.id), {
6114
+ await guild.client.rest.patch(Routes32.guildRolesHoistPositions(guild.id), {
5067
6115
  body: updates.map((u) => ({
5068
6116
  id: u.id,
5069
6117
  ...u.hoistPosition !== void 0 ? { hoist_position: u.hoistPosition } : {}
@@ -5075,17 +6123,17 @@ async function setRoleHoistPositions(guild, updates) {
5075
6123
  async function resetRoleHoistPositions(guild) {
5076
6124
  return replaceRoles(
5077
6125
  guild,
5078
- await guild.client.rest.delete(Routes29.guildRolesHoistPositions(guild.id), {
6126
+ await guild.client.rest.delete(Routes32.guildRolesHoistPositions(guild.id), {
5079
6127
  auth: true
5080
6128
  })
5081
6129
  );
5082
6130
  }
5083
6131
 
5084
6132
  // src/Domain/Guild/Stickers.ts
5085
- import { Routes as Routes30 } from "@fluxerjs/types";
6133
+ import { Routes as Routes33 } from "@fluxerjs/types";
5086
6134
  async function createSticker(guild, options) {
5087
6135
  const { reason, ...body } = options;
5088
- const data = await guild.client.rest.post(Routes30.guildStickers(guild.id), {
6136
+ const data = await guild.client.rest.post(Routes33.guildStickers(guild.id), {
5089
6137
  body,
5090
6138
  auth: true,
5091
6139
  ...auditReasonHeaders(reason)
@@ -5093,7 +6141,7 @@ async function createSticker(guild, options) {
5093
6141
  return cacheSticker(guild, data);
5094
6142
  }
5095
6143
  async function cloneSticker(guild, sourceStickerId) {
5096
- const data = await guild.client.rest.post(Routes30.guildStickersClone(guild.id), {
6144
+ const data = await guild.client.rest.post(Routes33.guildStickersClone(guild.id), {
5097
6145
  body: { source_sticker_id: sourceStickerId },
5098
6146
  auth: true
5099
6147
  });
@@ -5101,17 +6149,17 @@ async function cloneSticker(guild, sourceStickerId) {
5101
6149
  }
5102
6150
  async function createStickersBulk(guild, stickers) {
5103
6151
  const data = await guild.client.rest.post(
5104
- Routes30.guildStickersBulk(guild.id),
6152
+ Routes33.guildStickersBulk(guild.id),
5105
6153
  { body: { stickers }, auth: true }
5106
6154
  );
5107
6155
  return { success: data.success.map((s) => cacheSticker(guild, s)), failed: data.failed };
5108
6156
  }
5109
6157
  async function fetchStickers(guild) {
5110
- const data = await guild.client.rest.get(Routes30.guildStickers(guild.id));
6158
+ const data = await guild.client.rest.get(Routes33.guildStickers(guild.id));
5111
6159
  return data.map((s) => cacheSticker(guild, s));
5112
6160
  }
5113
6161
  async function fetchSticker(guild, stickerId) {
5114
- const data = await guild.client.rest.get(Routes30.guildSticker(guild.id, stickerId));
6162
+ const data = await guild.client.rest.get(Routes33.guildSticker(guild.id, stickerId));
5115
6163
  return cacheSticker(guild, data);
5116
6164
  }
5117
6165
 
@@ -5123,6 +6171,11 @@ var Guild = class extends Base {
5123
6171
  id;
5124
6172
  /** Whether the guild is currently available through the gateway. */
5125
6173
  available = true;
6174
+ /**
6175
+ * True when only guild metadata is known (e.g. created from `GET /guilds/{id}`)
6176
+ * and nested channels/roles have not been synced yet. `guilds.resolve()` hydrates partial guilds.
6177
+ */
6178
+ partial = true;
5126
6179
  /** Guild name. */
5127
6180
  name;
5128
6181
  /** Icon hash (use {@link iconURL} to get full CDN URL). */
@@ -5343,7 +6396,7 @@ var Guild = class extends Base {
5343
6396
  });
5344
6397
  }
5345
6398
  /**
5346
- * Create a channel. `type`: 0=text, 2=voice, 4=category, 998=link (set `url`).
6399
+ * Create a channel. `type`: 0=text, 2=voice, 4=category, 5=announcement, 15=forum, 16=media, 998=link (set `url`).
5347
6400
  * Requires Manage Channels.
5348
6401
  */
5349
6402
  createChannel(options) {
@@ -5353,6 +6406,10 @@ var Guild = class extends Base {
5353
6406
  fetchChannels() {
5354
6407
  return fetchChannels(this);
5355
6408
  }
6409
+ /** Fetch active threads in this guild. */
6410
+ fetchActiveThreads() {
6411
+ return fetchActiveThreads(this.client, this.id);
6412
+ }
5356
6413
  /** Update channel positions (reordering). */
5357
6414
  setChannelPositions(updates) {
5358
6415
  return setChannelPositions(this, updates);
@@ -5413,6 +6470,10 @@ var Guild = class extends Base {
5413
6470
  ban(userId, options) {
5414
6471
  return ban(this, userId, options);
5415
6472
  }
6473
+ /** Fetch a single ban by user ID. Requires Ban Members. */
6474
+ fetchBan(userId) {
6475
+ return fetchBan(this, userId);
6476
+ }
5416
6477
  /** Fetch all bans in this guild. Requires Ban Members. */
5417
6478
  fetchBans() {
5418
6479
  return fetchBans(this);
@@ -5583,9 +6644,17 @@ function upsertGuildFromSnapshot(client, guildData, resources = {}) {
5583
6644
  client.guilds.set(guild.id, guild);
5584
6645
  if (resources.roles !== void 0) syncRoles(guild, resources.roles);
5585
6646
  if (resources.channels !== void 0) syncChannels(guild, resources.channels);
6647
+ if (resources.threads !== void 0) {
6648
+ syncThreads(
6649
+ guild,
6650
+ resources.threads,
6651
+ new Set((resources.channels ?? []).map((channel) => channel.id))
6652
+ );
6653
+ }
5586
6654
  if (resources.members !== void 0) mergeMembers(guild, resources.members);
5587
6655
  if (resources.emojis !== void 0) syncEmojis(guild, resources.emojis);
5588
6656
  if (resources.stickers !== void 0) syncStickers(guild, resources.stickers);
6657
+ if (resources.channels !== void 0) guild.partial = false;
5589
6658
  return { guild, created, recovered };
5590
6659
  }
5591
6660
  function applyGuildSnapshotFromGateway(client, raw) {
@@ -5597,7 +6666,9 @@ function applyGuildSnapshotFromGateway(client, raw) {
5597
6666
  channels: g.channels,
5598
6667
  members: g.members,
5599
6668
  emojis: g.emojis,
5600
- stickers: g.stickers
6669
+ stickers: g.stickers,
6670
+ // A channel list without `threads` means this session has no viewable threads.
6671
+ threads: g.channels !== void 0 ? g.threads ?? [] : g.threads
5601
6672
  });
5602
6673
  if (g.voice_states?.length) {
5603
6674
  client.emit(Events.VoiceStatesSync, {
@@ -5609,7 +6680,7 @@ function applyGuildSnapshotFromGateway(client, raw) {
5609
6680
  }
5610
6681
 
5611
6682
  // src/ClientCore/ClientUser.ts
5612
- import { GatewayOpcodes, Routes as Routes31 } from "@fluxerjs/types";
6683
+ import { GatewayOpcodes, Routes as Routes34 } from "@fluxerjs/types";
5613
6684
  var ClientUser = class extends User {
5614
6685
  /** Broadcast presence (gateway opcode 3) on all shards. */
5615
6686
  setPresence(presence) {
@@ -5619,13 +6690,13 @@ var ClientUser = class extends User {
5619
6690
  }
5620
6691
  /** GET /users/@me — refresh the logged-in user from REST and patch this instance. */
5621
6692
  async fetch() {
5622
- const data = await this.client.rest.get(Routes31.currentUser(), { auth: true });
6693
+ const data = await this.client.rest.get(Routes34.currentUser(), { auth: true });
5623
6694
  this._patch(data);
5624
6695
  return this;
5625
6696
  }
5626
6697
  /** GET /users/@me/guilds — returns camelCase partial guilds. */
5627
6698
  async fetchGuilds(options) {
5628
- const path = Routes31.currentUserGuilds() + (options?.withCounts ? "?with_counts=true" : "");
6699
+ const path = Routes34.currentUserGuilds() + (options?.withCounts ? "?with_counts=true" : "");
5629
6700
  const data = await this.client.rest.get(path, { auth: true });
5630
6701
  return data.map((g) => ({
5631
6702
  id: g.id,
@@ -5649,7 +6720,7 @@ var ClientUser = class extends User {
5649
6720
  */
5650
6721
  async leaveGuild(guildId, options) {
5651
6722
  const body = options ? toSudoBody(options) : void 0;
5652
- await this.client.rest.delete(Routes31.leaveGuild(guildId), {
6723
+ await this.client.rest.delete(Routes34.leaveGuild(guildId), {
5653
6724
  body: body && Object.keys(body).length ? body : void 0,
5654
6725
  auth: true
5655
6726
  });
@@ -5657,7 +6728,7 @@ var ClientUser = class extends User {
5657
6728
  /** Delete every message authored by the caller across a guild (sudo). */
5658
6729
  async bulkDeleteMyMessagesInGuild(guildId, options) {
5659
6730
  const body = options ? toSudoBody(options) : void 0;
5660
- await this.client.rest.post(Routes31.guildBulkDeleteMine(guildId), {
6731
+ await this.client.rest.post(Routes34.guildBulkDeleteMine(guildId), {
5661
6732
  body: body && Object.keys(body).length ? body : void 0,
5662
6733
  auth: true
5663
6734
  });
@@ -5667,15 +6738,7 @@ var ClientUser = class extends User {
5667
6738
  // src/ClientCore/EventHandlers/Helpers.ts
5668
6739
  import { asRecord, num, str } from "@fluxerjs/util";
5669
6740
  function unknownUser(id) {
5670
- return {
5671
- id,
5672
- username: "Unknown",
5673
- discriminator: "0",
5674
- global_name: null,
5675
- avatar: null,
5676
- avatar_color: null,
5677
- flags: 0
5678
- };
6741
+ return { id };
5679
6742
  }
5680
6743
  function indexMember(_client, guild, data) {
5681
6744
  if (!data.user?.id) return null;
@@ -5692,6 +6755,7 @@ var channelHandlers = {
5692
6755
  if (!ch) return;
5693
6756
  indexChannel(client, ch);
5694
6757
  client.emit(Events.ChannelCreate, ch);
6758
+ if (ch.isThread()) client.emit(Events.ThreadCreate, ch);
5695
6759
  },
5696
6760
  CHANNEL_UPDATE(client, d) {
5697
6761
  const data = d;
@@ -5704,12 +6768,14 @@ var channelHandlers = {
5704
6768
  existing._patch(data);
5705
6769
  indexChannel(client, existing);
5706
6770
  client.emit(Events.ChannelUpdate, oldCh, existing);
6771
+ if (existing.isThread()) client.emit(Events.ThreadUpdate, oldCh, existing);
5707
6772
  return;
5708
6773
  }
5709
6774
  const newCh = Channel.from(client, data);
5710
6775
  if (!newCh) return;
5711
6776
  indexChannel(client, newCh);
5712
6777
  client.emit(Events.ChannelUpdate, existing ?? newCh, newCh);
6778
+ if (newCh.isThread()) client.emit(Events.ThreadUpdate, existing ?? newCh, newCh);
5713
6779
  },
5714
6780
  CHANNEL_UPDATE_BULK(client, d) {
5715
6781
  const data = d;
@@ -5731,7 +6797,11 @@ var channelHandlers = {
5731
6797
  }
5732
6798
  if (!channel) return;
5733
6799
  client.channels.delete(id);
6800
+ if (channel.isGuild() && channel.guildId) {
6801
+ client.guilds.get(channel.guildId)?.channels.delete(id);
6802
+ }
5734
6803
  client.emit(Events.ChannelDelete, channel);
6804
+ if (channel.isThread()) client.emit(Events.ThreadDelete, channel);
5735
6805
  },
5736
6806
  CHANNEL_PINS_UPDATE(client, d) {
5737
6807
  const data = d;
@@ -5921,6 +6991,10 @@ var guildHandlers = {
5921
6991
  }
5922
6992
  client._onGuildReceived(guild.id);
5923
6993
  },
6994
+ /** Same snapshot as Guild Create, including `threads`. Cache only: this is not a join. */
6995
+ GUILD_SYNC(client, d) {
6996
+ applyGuildSnapshotFromGateway(client, d);
6997
+ },
5924
6998
  GUILD_UPDATE(client, d) {
5925
6999
  const guildData = normalizeGuildUpdatePayload(d);
5926
7000
  if (!guildData) return;
@@ -5970,7 +7044,7 @@ var guildHandlers = {
5970
7044
 
5971
7045
  // src/ClientCore/EventHandlers/Invites.ts
5972
7046
  import {
5973
- ChannelType as ChannelType4,
7047
+ ChannelType as ChannelType10,
5974
7048
  InviteType as InviteType2
5975
7049
  } from "@fluxerjs/types";
5976
7050
  function normalizeInviteCreate(client, payload) {
@@ -5995,11 +7069,11 @@ function normalizeInviteCreate(client, payload) {
5995
7069
  const guildId = str(guildObj?.id) ?? str(raw.guild_id) ?? "0";
5996
7070
  const channelId = str(channelObj?.id) ?? str(raw.channel_id) ?? "0";
5997
7071
  const cachedGuild = guildId !== "0" ? client.guilds.get(guildId) : null;
5998
- const cachedChannel = channelId !== "0" ? client.channels.get(channelId) : null;
7072
+ const cachedChannel2 = channelId !== "0" ? client.channels.get(channelId) : null;
5999
7073
  const channel = {
6000
7074
  id: channelId,
6001
- type: num(channelObj?.type) ?? cachedChannel?.type ?? ChannelType4.GuildText,
6002
- name: str(channelObj?.name) ?? cachedChannel?.name ?? null,
7075
+ type: num(channelObj?.type) ?? cachedChannel2?.type ?? ChannelType10.GuildText,
7076
+ name: str(channelObj?.name) ?? cachedChannel2?.name ?? null,
6003
7077
  icon: channelObj?.icon ?? null
6004
7078
  };
6005
7079
  if (type === InviteType2.GroupDM) return { ...shared, type, channel };
@@ -6348,6 +7422,9 @@ var passthroughHandlers = {
6348
7422
  VOICE_SERVER_UPDATE: pass(Events.VoiceServerUpdate),
6349
7423
  VOICE_STATE_ACK: pass(Events.VoiceStateAck),
6350
7424
  ENTRANCE_SOUND_PLAY: pass(Events.EntranceSoundPlay),
7425
+ VOICE_SIGNAL: pass(Events.VoiceSignal),
7426
+ GUILD_HEALTH_UPDATE: pass(Events.GuildHealthUpdate),
7427
+ OPERATOR_PASS_UPDATE: pass(Events.OperatorPassUpdate),
6351
7428
  TYPING_START(client, d) {
6352
7429
  const data = d;
6353
7430
  const payload = {
@@ -6403,6 +7480,107 @@ var passthroughHandlers = {
6403
7480
  WEBAUTHN_CREDENTIALS_UPDATE: pass(Events.WebAuthnCredentialsUpdate)
6404
7481
  };
6405
7482
 
7483
+ // src/ClientCore/EventHandlers/Threads.ts
7484
+ function cachedChannel(client, id) {
7485
+ const direct = client.channels.get(id);
7486
+ if (direct) return direct;
7487
+ for (const guild of client.guilds.values()) {
7488
+ const nested = guild.channels.get(id);
7489
+ if (nested) return nested;
7490
+ }
7491
+ return null;
7492
+ }
7493
+ var threadHandlers = {
7494
+ THREAD_CREATE(client, d) {
7495
+ channelHandlers.CHANNEL_CREATE(client, d);
7496
+ },
7497
+ THREAD_UPDATE(client, d) {
7498
+ channelHandlers.CHANNEL_UPDATE(client, d);
7499
+ },
7500
+ THREAD_DELETE(client, d) {
7501
+ const data = d;
7502
+ const existing = data.id ? cachedChannel(client, data.id) : null;
7503
+ if (existing?.isThread()) {
7504
+ channelHandlers.CHANNEL_DELETE(client, data);
7505
+ return;
7506
+ }
7507
+ if (!data.id || !isThreadType(data.type)) return;
7508
+ const thread = Channel.from(client, {
7509
+ id: data.id,
7510
+ type: data.type,
7511
+ guild_id: data.guild_id,
7512
+ parent_id: data.parent_id
7513
+ });
7514
+ if (!thread.isThread()) return;
7515
+ client.emit(Events.ChannelDelete, thread);
7516
+ client.emit(Events.ThreadDelete, thread);
7517
+ },
7518
+ THREAD_LIST_SYNC(client, d) {
7519
+ const data = d;
7520
+ const { threads } = fetchedThreadsFrom(client, {
7521
+ threads: data.threads ?? [],
7522
+ members: data.members ?? []
7523
+ });
7524
+ const payload = {
7525
+ guildId: data.guild_id,
7526
+ channelIds: data.channel_ids ?? [],
7527
+ threads
7528
+ };
7529
+ client.emit(Events.ThreadListSync, payload);
7530
+ },
7531
+ THREAD_MEMBER_UPDATE(client, d) {
7532
+ const data = d;
7533
+ const member = new ThreadMember(data);
7534
+ const thread = member.id ? client.channels.get(member.id) : void 0;
7535
+ if (thread?.isThread() && member.userId && member.userId === client.user?.id) {
7536
+ thread.member = member;
7537
+ }
7538
+ client.emit(Events.ThreadMemberUpdate, member);
7539
+ },
7540
+ THREAD_MEMBERS_UPDATE(client, d) {
7541
+ const data = d;
7542
+ const thread = client.channels.get(data.id);
7543
+ if (thread?.isThread()) thread.memberCount = data.member_count;
7544
+ const payload = {
7545
+ id: data.id,
7546
+ guildId: data.guild_id,
7547
+ memberCount: data.member_count,
7548
+ addedMembers: (data.added_members ?? []).map((member) => new ThreadMember(member)),
7549
+ removedMemberIds: data.removed_member_ids ?? []
7550
+ };
7551
+ client.emit(Events.ThreadMembersUpdate, payload);
7552
+ },
7553
+ THREAD_MEMBER_LIST_UPDATE(client, d) {
7554
+ const data = d;
7555
+ const guild = data.guild_id ? client.guilds.get(data.guild_id) : void 0;
7556
+ const payload = {
7557
+ guildId: data.guild_id,
7558
+ threadId: data.thread_id,
7559
+ members: (data.members ?? []).map((entry) => ({
7560
+ userId: entry.user_id,
7561
+ joinTimestamp: entry.join_timestamp,
7562
+ flags: entry.flags,
7563
+ member: guild && entry.member?.user?.id ? cacheMember(guild, entry.member) : null,
7564
+ presence: entry.presence ? { status: entry.presence.status ?? null } : null
7565
+ }))
7566
+ };
7567
+ client.emit(Events.ThreadMemberListUpdate, payload);
7568
+ },
7569
+ FORUM_UNREADS(client, d) {
7570
+ const data = d;
7571
+ const payload = {
7572
+ guildId: data.guild_id,
7573
+ channelId: data.channel_id,
7574
+ threads: (data.threads ?? []).map((entry) => ({
7575
+ threadId: entry.thread_id,
7576
+ count: entry.count ?? null,
7577
+ missing: entry.missing === true
7578
+ }))
7579
+ };
7580
+ client.emit(Events.ForumUnreads, payload);
7581
+ }
7582
+ };
7583
+
6406
7584
  // src/ClientCore/EventHandlers/index.ts
6407
7585
  var eventHandlers = buildRegistry(
6408
7586
  messageHandlers,
@@ -6411,7 +7589,8 @@ var eventHandlers = buildRegistry(
6411
7589
  memberHandlers,
6412
7590
  inviteHandlers,
6413
7591
  guildResourceHandlers,
6414
- passthroughHandlers
7592
+ passthroughHandlers,
7593
+ threadHandlers
6415
7594
  );
6416
7595
 
6417
7596
  // src/ClientCore/GatewayDispatch.ts
@@ -6436,29 +7615,63 @@ function handleGatewayDispatch(client, payload, deferred) {
6436
7615
  }
6437
7616
  return dispatchGatewayPayload(client, payload);
6438
7617
  }
6439
- function dispatchGatewayPayload(client, payload) {
7618
+ var dispatchQueues = /* @__PURE__ */ new WeakMap();
7619
+ function queueFor(client) {
7620
+ let queue = dispatchQueues.get(client);
7621
+ if (!queue) {
7622
+ queue = { tail: Promise.resolve(), pending: 0 };
7623
+ dispatchQueues.set(client, queue);
7624
+ }
7625
+ return queue;
7626
+ }
7627
+ async function runGatewayHandler(client, payload) {
6440
7628
  const event = payload.t;
6441
- if (!event) return Promise.resolve();
7629
+ if (!event) return;
6442
7630
  const handler = eventHandlers.get(event);
6443
7631
  if (!handler) {
6444
7632
  client.emit(Events.Debug, `[Gateway] Unhandled dispatch: ${event}`);
6445
- return Promise.resolve();
7633
+ return;
6446
7634
  }
6447
- const run = async () => {
6448
- try {
6449
- await handler(client, payload.d);
6450
- } catch (err) {
6451
- emitClientError(client, err);
6452
- }
6453
- };
6454
- if (client.options.gatewayDeferHandlers === false) return run();
6455
- return new Promise((resolve, reject) => {
6456
- const start = () => {
6457
- void run().then(resolve).catch(reject);
6458
- };
6459
- if (typeof setImmediate === "function") setImmediate(start);
6460
- else setTimeout(start, 0);
7635
+ if (payload.d !== null && payload.d !== void 0 && typeof payload.d !== "object") {
7636
+ client.emit(
7637
+ Events.Debug,
7638
+ `[Gateway] Ignoring malformed dispatch ${event}: payload is not an object`
7639
+ );
7640
+ return;
7641
+ }
7642
+ if (client.options.gatewayDeferHandlers !== false) {
7643
+ await new Promise((resolve) => {
7644
+ if (typeof setImmediate === "function") setImmediate(resolve);
7645
+ else setTimeout(resolve, 0);
7646
+ });
7647
+ }
7648
+ try {
7649
+ await handler(client, payload.d);
7650
+ } catch (err) {
7651
+ emitClientError(client, err);
7652
+ }
7653
+ }
7654
+ function dispatchGatewayPayload(client, payload) {
7655
+ const queue = queueFor(client);
7656
+ if (client.options.gatewayDeferHandlers === false && queue.pending === 0) {
7657
+ queue.pending++;
7658
+ const run = runGatewayHandler(client, payload).finally(() => {
7659
+ queue.pending--;
7660
+ });
7661
+ queue.tail = run.catch(() => {
7662
+ });
7663
+ return run;
7664
+ }
7665
+ queue.pending++;
7666
+ const next = queue.tail.then(
7667
+ () => runGatewayHandler(client, payload),
7668
+ () => runGatewayHandler(client, payload)
7669
+ ).finally(() => {
7670
+ queue.pending--;
7671
+ });
7672
+ queue.tail = next.catch(() => {
6461
7673
  });
7674
+ return next;
6462
7675
  }
6463
7676
  async function flushDeferredGatewayDispatches(client, deferred) {
6464
7677
  while (deferred.length > 0) {
@@ -6637,7 +7850,7 @@ async function connectClientGateway(client, token, signal) {
6637
7850
 
6638
7851
  // src/ClientCore/GuildManager.ts
6639
7852
  import { LimitedCollection as LimitedCollection5 } from "@fluxerjs/collection";
6640
- import { Routes as Routes32 } from "@fluxerjs/types";
7853
+ import { Routes as Routes35 } from "@fluxerjs/types";
6641
7854
  var GuildManager = class extends LimitedCollection5 {
6642
7855
  constructor(client) {
6643
7856
  super({
@@ -6646,6 +7859,7 @@ var GuildManager = class extends LimitedCollection5 {
6646
7859
  });
6647
7860
  this.client = client;
6648
7861
  }
7862
+ pendingFetches = /* @__PURE__ */ new Map();
6649
7863
  /**
6650
7864
  * Remove a guild from cache and cascade its channels / message caches.
6651
7865
  * Does not leave the guild. Use {@link ClientUser.leaveGuild} for that.
@@ -6660,35 +7874,73 @@ var GuildManager = class extends LimitedCollection5 {
6660
7874
  }
6661
7875
  /**
6662
7876
  * Get a guild from cache or fetch from the API if not present.
7877
+ * Partial (metadata-only) cached guilds are hydrated first.
6663
7878
  * @param guildId - Snowflake of the guild
6664
7879
  * @returns The guild
6665
7880
  * @throws FluxerError with GUILD_NOT_FOUND if missing
6666
7881
  */
6667
7882
  async resolve(guildId) {
6668
- return this.get(guildId) ?? this.fetch(guildId);
7883
+ const id = normalizeSnowflakeId(guildId, "guilds.resolve()");
7884
+ const cached = this.get(id);
7885
+ if (cached && !cached.partial) return cached;
7886
+ if (cached) {
7887
+ await dedupeFetch(this.pendingFetches, id, async () => {
7888
+ await this.hydrate(cached);
7889
+ return cached;
7890
+ });
7891
+ return cached;
7892
+ }
7893
+ const guild = await this.fetch(id);
7894
+ await dedupeFetch(this.pendingFetches, id, async () => {
7895
+ await this.hydrate(guild);
7896
+ return guild;
7897
+ });
7898
+ return guild;
6669
7899
  }
6670
7900
  /**
6671
7901
  * Fetch a guild by ID.
6672
- * Returns the cached guild unless `force` is set, in which case REST metadata is applied via `_patch`.
7902
+ * Returns the cached guild unless `force` is set, in which case REST metadata
7903
+ * is applied via `_patch`. Use {@link resolve} to also hydrate nested caches.
6673
7904
  * @throws FluxerError with GUILD_NOT_FOUND if missing
6674
7905
  */
6675
7906
  async fetch(guildId, options) {
6676
- const cached = this.get(guildId);
7907
+ const id = normalizeSnowflakeId(guildId, "guilds.fetch()");
7908
+ const cached = this.get(id);
6677
7909
  if (cached && !options?.force) return cached;
6678
- try {
6679
- const data = await this.client.rest.get(Routes32.guild(guildId));
6680
- if (cached) {
6681
- cached._patch(data);
6682
- return cached;
7910
+ return dedupeFetch(this.pendingFetches, id, async () => {
7911
+ try {
7912
+ const data = assertApiObjectWithId(
7913
+ await this.client.rest.get(Routes35.guild(id)),
7914
+ "guilds.fetch()"
7915
+ );
7916
+ let guild;
7917
+ const existing = this.get(id);
7918
+ if (existing) {
7919
+ existing._patch(data);
7920
+ guild = existing;
7921
+ } else {
7922
+ guild = new Guild(this.client, data);
7923
+ this.set(guild.id, guild);
7924
+ }
7925
+ return guild;
7926
+ } catch (err) {
7927
+ rethrowMapped(err, {
7928
+ notFound: { code: ErrorCodes.GuildNotFound, message: `Guild ${id} not found` },
7929
+ fallback: `Failed to fetch guild ${id}`
7930
+ });
6683
7931
  }
6684
- const guild = new Guild(this.client, data);
6685
- this.set(guild.id, guild);
6686
- return guild;
7932
+ });
7933
+ }
7934
+ /** Best-effort nested sync for a metadata-only guild. Failures keep `partial` set. */
7935
+ async hydrate(guild) {
7936
+ try {
7937
+ await Promise.all([guild.fetchChannels(), guild.fetchRoles()]);
7938
+ guild.partial = false;
6687
7939
  } catch (err) {
6688
- rethrowMapped(err, {
6689
- notFound: { code: ErrorCodes.GuildNotFound, message: `Guild ${guildId} not found` },
6690
- fallback: `Failed to fetch guild ${guildId}`
6691
- });
7940
+ this.client.emit(
7941
+ Events.Debug,
7942
+ `[GuildManager] Could not fully hydrate guild ${guild.id}: ${err instanceof Error ? err.message : String(err)}`
7943
+ );
6692
7944
  }
6693
7945
  }
6694
7946
  };
@@ -6713,6 +7965,10 @@ var MessageCache = class {
6713
7965
  if (limit === false) return;
6714
7966
  if (!this.caches) this.caches = /* @__PURE__ */ new Map();
6715
7967
  let cache = this.caches.get(channelId);
7968
+ if (cache) {
7969
+ this.caches.delete(channelId);
7970
+ this.caches.set(channelId, cache);
7971
+ }
6716
7972
  if (!cache) {
6717
7973
  const channelLimit = this.getChannelLimit();
6718
7974
  if (Number.isFinite(channelLimit) && channelLimit > 0 && this.caches.size >= channelLimit) {
@@ -6764,7 +8020,7 @@ var MessageCache = class {
6764
8020
  // src/ClientCore/UserManager.ts
6765
8021
  import { LimitedCollection as LimitedCollection6 } from "@fluxerjs/collection";
6766
8022
  import {
6767
- Routes as Routes33
8023
+ Routes as Routes36
6768
8024
  } from "@fluxerjs/types";
6769
8025
  var soft = (p) => p.catch(() => null);
6770
8026
  var UserManager = class extends LimitedCollection6 {
@@ -6772,6 +8028,7 @@ var UserManager = class extends LimitedCollection6 {
6772
8028
  super({ maxSize: client.cache.limits.users });
6773
8029
  this.client = client;
6774
8030
  }
8031
+ pendingFetches = /* @__PURE__ */ new Map();
6775
8032
  /** Remove matching users (skips `client.user`). Returns count removed. */
6776
8033
  sweep(filter) {
6777
8034
  let removed = 0;
@@ -6785,16 +8042,30 @@ var UserManager = class extends LimitedCollection6 {
6785
8042
  }
6786
8043
  return removed;
6787
8044
  }
6788
- /** Fetch a user by ID and update cache. Returns cache unless `force` is set. */
8045
+ /**
8046
+ * Fetch a user by ID and update cache. Returns the cached user unless `force` is set
8047
+ * or the cached entry is only a partial stub (e.g. from a reaction event).
8048
+ */
6789
8049
  async fetch(userId, options) {
6790
- const cached = this.get(userId);
6791
- if (cached && !options?.force) return cached;
6792
- const data = await this.client.rest.get(Routes33.user(userId));
6793
- return this.client.getOrCreateUser(data);
8050
+ const id = normalizeSnowflakeId(userId, "users.fetch()");
8051
+ const cached = this.get(id);
8052
+ if (cached && !cached.partial && !options?.force) return cached;
8053
+ return dedupeFetch(
8054
+ this.pendingFetches,
8055
+ id,
8056
+ async () => this.client.getOrCreateUser(
8057
+ assertApiObjectWithId(
8058
+ await this.client.rest.get(Routes36.user(id)),
8059
+ "users.fetch()"
8060
+ )
8061
+ )
8062
+ );
6794
8063
  }
6795
- /** Return a cached user, otherwise {@link fetch}. */
8064
+ /** Return a cached (non-partial) user, otherwise {@link fetch}. */
6796
8065
  async resolve(userId) {
6797
- return this.get(userId) ?? this.fetch(userId);
8066
+ const id = normalizeSnowflakeId(userId, "users.resolve()");
8067
+ const cached = this.get(id);
8068
+ return cached && !cached.partial ? cached : this.fetch(id);
6798
8069
  }
6799
8070
  /**
6800
8071
  * Fetch user + profiles (+ optional guild member). Ideal for userinfo commands.
@@ -6807,10 +8078,10 @@ var UserManager = class extends LimitedCollection6 {
6807
8078
  async fetchWithProfile(userId, options) {
6808
8079
  const guildId = options?.guildId ?? void 0;
6809
8080
  const [userData, globalProfileRaw, serverProfileRaw, memberData] = await Promise.all([
6810
- this.client.rest.get(Routes33.user(userId)),
6811
- soft(this.client.rest.get(Routes33.userProfile(userId))),
6812
- guildId ? soft(this.client.rest.get(Routes33.userProfile(userId, guildId))) : null,
6813
- guildId ? soft(this.client.rest.get(Routes33.guildMember(guildId, userId))) : null
8081
+ this.client.rest.get(Routes36.user(userId)),
8082
+ soft(this.client.rest.get(Routes36.userProfile(userId))),
8083
+ guildId ? soft(this.client.rest.get(Routes36.userProfile(userId, guildId))) : null,
8084
+ guildId ? soft(this.client.rest.get(Routes36.guildMember(guildId, userId))) : null
6814
8085
  ]);
6815
8086
  const user = this.client.getOrCreateUser(userData);
6816
8087
  let member = null;
@@ -6935,7 +8206,7 @@ var Client = class _Client extends EventEmitter3 {
6935
8206
  * Wires REST from `endpoints.api_public`. `endpoints.api` / `api_client` stay on the instance for inspection.
6936
8207
  * Does not log in. Call {@link login} with a token afterward.
6937
8208
  *
6938
- * @param origin - Origin used only to fetch discovery (e.g. `https://fluxer.app` or `https://my.instance`)
8209
+ * @param origin - Origin used only to fetch discovery (e.g. `https://fluxer.com` or `https://my.instance`)
6939
8210
  * @param options - Client options (must not conflict with discovered `endpoints.api_public`)
6940
8211
  * @param connectOptions - Optional abort signal for the discovery request
6941
8212
  */
@@ -7012,6 +8283,38 @@ var Client = class _Client extends EventEmitter3 {
7012
8283
  fetchStickerMetadata(stickerId) {
7013
8284
  return fetchStickerMetadata(this, stickerId);
7014
8285
  }
8286
+ /** Fetch the source guild of a custom emoji. */
8287
+ fetchEmojiSource(emojiId) {
8288
+ return fetchEmojiSource(this, emojiId);
8289
+ }
8290
+ /** Fetch the source guild of a custom sticker. */
8291
+ fetchStickerSource(stickerId) {
8292
+ return fetchStickerSource(this, stickerId);
8293
+ }
8294
+ /** List discovery categories. */
8295
+ fetchDiscoveryCategories() {
8296
+ return fetchDiscoveryCategories(this);
8297
+ }
8298
+ /** Search discoverable guilds. */
8299
+ searchDiscoveryGuilds(options) {
8300
+ return searchDiscoveryGuilds(this, options);
8301
+ }
8302
+ /** Fetch experiment assignments for this account. */
8303
+ fetchExperiments() {
8304
+ return fetchExperiments(this);
8305
+ }
8306
+ /** Refresh expiring attachment CDN URLs. */
8307
+ refreshAttachmentUrls(attachmentUrls) {
8308
+ return refreshAttachmentUrls(this, attachmentUrls);
8309
+ }
8310
+ /** List instance custom guild badges (`GET /instance/badges`). */
8311
+ fetchInstanceBadges(options) {
8312
+ return fetchInstanceBadges(this, options);
8313
+ }
8314
+ /** Fetch forum/media thread post data for a channel. */
8315
+ fetchChannelPostData(channelId, threadIds) {
8316
+ return fetchChannelPostData(this, channelId, threadIds);
8317
+ }
7015
8318
  /**
7016
8319
  * Fetch the current application (`/applications/@me`).
7017
8320
  * @returns Application metadata (owner, flags, RPC origins, etc.)
@@ -7106,6 +8409,9 @@ var Client = class _Client extends EventEmitter3 {
7106
8409
  * @internal
7107
8410
  */
7108
8411
  getOrCreateUser(data) {
8412
+ if (!data || typeof data.id !== "string" || data.id.length === 0) {
8413
+ throw new TypeError("getOrCreateUser() requires user data with a non-empty string id");
8414
+ }
7109
8415
  const existing = this.users.get(data.id);
7110
8416
  if (existing) {
7111
8417
  existing._patch(data);
@@ -7189,6 +8495,72 @@ var Client = class _Client extends EventEmitter3 {
7189
8495
  if (options.nonce !== void 0) data.nonce = options.nonce;
7190
8496
  this._sendToAllShards({ op: GatewayOpcodes2.RequestChannelMemberCounts, d: data });
7191
8497
  }
8498
+ /**
8499
+ * Request unread counts for posts in one forum or media channel (opcode 28).
8500
+ * Listen for `forumUnreads`. The gateway keeps at most 40 posts and ignores a channel the session cannot view.
8501
+ */
8502
+ requestForumUnreads(options) {
8503
+ if (!options.guildId || !options.channelId) {
8504
+ throw new FluxerError("requestForumUnreads requires guildId and channelId", {
8505
+ code: ErrorCodes.InvalidGatewayRequest
8506
+ });
8507
+ }
8508
+ const threads = [];
8509
+ const seen = /* @__PURE__ */ new Set();
8510
+ for (const thread of options.threads) {
8511
+ if (!thread.threadId || seen.has(thread.threadId)) continue;
8512
+ seen.add(thread.threadId);
8513
+ const entry = { thread_id: thread.threadId };
8514
+ if (thread.ackMessageId !== void 0) entry.ack_message_id = thread.ackMessageId;
8515
+ threads.push(entry);
8516
+ }
8517
+ if (!threads.length) {
8518
+ throw new FluxerError("requestForumUnreads requires at least one thread", {
8519
+ code: ErrorCodes.InvalidGatewayRequest
8520
+ });
8521
+ }
8522
+ if (threads.length > 40) {
8523
+ throw new FluxerError("requestForumUnreads accepts at most 40 threads", {
8524
+ code: ErrorCodes.InvalidGatewayRequest
8525
+ });
8526
+ }
8527
+ const data = {
8528
+ guild_id: options.guildId,
8529
+ channel_id: options.channelId,
8530
+ threads
8531
+ };
8532
+ this._sendToAllShards({ op: GatewayOpcodes2.RequestForumUnreads, d: data });
8533
+ }
8534
+ /**
8535
+ * Subscribe to thread traffic in a guild (opcode 14).
8536
+ * `threads: true` receives every thread event in the guild.
8537
+ * `threadIds` (at most 10) subscribes to those member lists. Each one arrives as `threadMemberListUpdate`.
8538
+ */
8539
+ subscribeThreads(options) {
8540
+ if (!options.guildId) {
8541
+ throw new FluxerError("subscribeThreads requires guildId", {
8542
+ code: ErrorCodes.InvalidGatewayRequest
8543
+ });
8544
+ }
8545
+ if (options.threads === void 0 && options.threadIds === void 0) {
8546
+ throw new FluxerError("subscribeThreads requires threads or threadIds", {
8547
+ code: ErrorCodes.InvalidGatewayRequest
8548
+ });
8549
+ }
8550
+ const subscription = {};
8551
+ if (options.threads !== void 0) subscription.threads = options.threads;
8552
+ if (options.threadIds !== void 0) {
8553
+ const threadIds = [...new Set(options.threadIds.filter(Boolean))];
8554
+ if (threadIds.length > 10) {
8555
+ throw new FluxerError("subscribeThreads accepts at most 10 threadIds", {
8556
+ code: ErrorCodes.InvalidGatewayRequest
8557
+ });
8558
+ }
8559
+ subscription.thread_member_lists = threadIds;
8560
+ }
8561
+ const data = { subscriptions: { [options.guildId]: subscription } };
8562
+ this._sendToAllShards({ op: GatewayOpcodes2.LazyRequest, d: data });
8563
+ }
7192
8564
  /**
7193
8565
  * Broadcast a gateway payload to all shards.
7194
8566
  * @param payload - Gateway send payload
@@ -7292,7 +8664,7 @@ var Client = class _Client extends EventEmitter3 {
7292
8664
  * @see {@link Routes}
7293
8665
  */
7294
8666
  static get Routes() {
7295
- return Routes34;
8667
+ return Routes37;
7296
8668
  }
7297
8669
  };
7298
8670
 
@@ -7645,7 +9017,7 @@ export {
7645
9017
  CategoryChannel,
7646
9018
  Channel,
7647
9019
  ChannelManager,
7648
- ChannelType5 as ChannelType,
9020
+ ChannelType11 as ChannelType,
7649
9021
  Client,
7650
9022
  ClientCluster,
7651
9023
  ClientClusterEvents,
@@ -7658,6 +9030,10 @@ export {
7658
9030
  ErrorCodes,
7659
9031
  Events,
7660
9032
  FluxerError,
9033
+ ForumChannel,
9034
+ ForumLayout,
9035
+ ForumSortOrder,
9036
+ ForumTagSetting,
7661
9037
  GatewayOpcodes3 as GatewayOpcodes,
7662
9038
  Guild,
7663
9039
  GuildBan,
@@ -7676,6 +9052,7 @@ export {
7676
9052
  Invite,
7677
9053
  InviteType3 as InviteType,
7678
9054
  LinkChannel,
9055
+ MediaChannel,
7679
9056
  Message,
7680
9057
  MessageAttachmentFlags2 as MessageAttachmentFlags,
7681
9058
  MessageCollector,
@@ -7700,11 +9077,17 @@ export {
7700
9077
  ReactionCollector,
7701
9078
  RelationshipType,
7702
9079
  Role,
7703
- Routes35 as Routes,
9080
+ Routes38 as Routes,
7704
9081
  STATIC_CDN_URL,
7705
9082
  SplashCardAlignment,
7706
9083
  SystemChannelFlags,
7707
9084
  TextChannel,
9085
+ ThreadAutoArchiveDuration,
9086
+ ThreadChannel,
9087
+ ThreadManager,
9088
+ ThreadMember,
9089
+ ThreadMemberFlags,
9090
+ ThreadMemberManager,
7708
9091
  User,
7709
9092
  UserFlagsBitField,
7710
9093
  UserFlagsBits,
@@ -7721,6 +9104,7 @@ export {
7721
9104
  cdnMemberBannerURL,
7722
9105
  cdnStickerURL,
7723
9106
  createLogger2 as createLogger,
9107
+ fetchActiveThreads,
7724
9108
  instanceDiscoveryUrl,
7725
9109
  inviteUrl,
7726
9110
  normalizeApiOrigin,