@fluxerjs/core 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  // src/ClientCore/Client.ts
2
2
  import { EventEmitter as EventEmitter3 } from "events";
3
3
  import { REST } from "@fluxerjs/rest";
4
- import { GatewayOpcodes as GatewayOpcodes2, Routes as Routes34 } from "@fluxerjs/types";
4
+ import { GatewayOpcodes as GatewayOpcodes2, Routes as Routes37 } from "@fluxerjs/types";
5
5
  import { createLogger } from "@fluxerjs/util";
6
6
 
7
7
  // src/Domain/Message/Message.ts
8
8
  import { EmbedBuilder as EmbedBuilder2 } from "@fluxerjs/builders";
9
- import { Collection as Collection3 } from "@fluxerjs/collection";
9
+ import { Collection as Collection5 } from "@fluxerjs/collection";
10
10
  import {
11
11
  MessageType,
12
- Routes as Routes4
12
+ Routes as Routes7
13
13
  } from "@fluxerjs/types";
14
14
  import { MessageFlagsBitField } from "@fluxerjs/util";
15
15
 
@@ -78,7 +78,132 @@ function toAttachmentUploadPlanResponse(data) {
78
78
  }
79
79
 
80
80
  // src/ClientCore/SdkOptions/Channels.ts
81
+ import { ChannelType as ChannelType2 } from "@fluxerjs/types";
81
82
  import { resolvePermissionsToBitfield } from "@fluxerjs/util";
83
+
84
+ // src/ClientCore/SdkOptions/Threads.ts
85
+ import {
86
+ ChannelType
87
+ } from "@fluxerjs/types";
88
+ function toThreadEditBody(type, options) {
89
+ const body = {};
90
+ if (options.name !== void 0) body.name = options.name;
91
+ if (options.archived !== void 0) body.archived = options.archived;
92
+ if (options.autoArchiveDuration !== void 0) {
93
+ body.auto_archive_duration = options.autoArchiveDuration;
94
+ }
95
+ if (options.locked !== void 0) body.locked = options.locked;
96
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
97
+ if (options.flags !== void 0) body.flags = options.flags;
98
+ if (options.appliedTags !== void 0 && type !== ChannelType.PrivateThread) {
99
+ body.applied_tags = options.appliedTags;
100
+ }
101
+ if (options.invitable !== void 0 && type === ChannelType.PrivateThread) {
102
+ body.invitable = options.invitable;
103
+ }
104
+ return body;
105
+ }
106
+ function toThreadParentEditBody(options) {
107
+ const body = {};
108
+ if (options.autoArchiveDuration !== void 0) {
109
+ body.default_auto_archive_duration = options.autoArchiveDuration;
110
+ }
111
+ if (options.rateLimitPerUser !== void 0) {
112
+ body.default_thread_rate_limit_per_user = options.rateLimitPerUser;
113
+ }
114
+ return body;
115
+ }
116
+ function toStartThreadBody(channelType, options) {
117
+ const type = options.type ?? (channelType === ChannelType.GuildAnnouncement ? ChannelType.AnnouncementThread : ChannelType.PublicThread);
118
+ const body = { name: options.name, type };
119
+ if (options.autoArchiveDuration !== void 0) {
120
+ body.auto_archive_duration = options.autoArchiveDuration;
121
+ }
122
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
123
+ if (options.invitable !== void 0) body.invitable = options.invitable;
124
+ return body;
125
+ }
126
+ function toStartThreadFromMessageBody(options) {
127
+ const body = { name: options.name };
128
+ if (options.autoArchiveDuration !== void 0) {
129
+ body.auto_archive_duration = options.autoArchiveDuration;
130
+ }
131
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
132
+ return body;
133
+ }
134
+ function toForumThreadMessage(body) {
135
+ const message = {};
136
+ if (body.content !== void 0) message.content = body.content;
137
+ if (body.embeds !== void 0) message.embeds = body.embeds;
138
+ if (body.attachments !== void 0) message.attachments = body.attachments;
139
+ if (body.allowed_mentions !== void 0) message.allowed_mentions = body.allowed_mentions;
140
+ if (body.flags !== void 0) message.flags = body.flags;
141
+ if (body.sticker_ids !== void 0) message.sticker_ids = body.sticker_ids;
142
+ return message;
143
+ }
144
+ function toForumTagBody(options) {
145
+ const body = { name: options.name };
146
+ if ("id" in options && options.id !== void 0) body.id = options.id;
147
+ if (options.moderated !== void 0) body.moderated = options.moderated;
148
+ if (options.emojiId !== void 0) body.emoji_id = options.emojiId;
149
+ if (options.emojiName !== void 0) body.emoji_name = options.emojiName;
150
+ return body;
151
+ }
152
+ function forumParentWire(options, includeLayout) {
153
+ const body = {};
154
+ if (options.availableTags !== void 0) {
155
+ body.available_tags = options.availableTags.map((tag) => toForumTagBody(tag));
156
+ }
157
+ if (options.defaultReactionEmoji !== void 0) {
158
+ body.default_reaction_emoji = options.defaultReactionEmoji === null ? null : reactionEmojiWire(options.defaultReactionEmoji);
159
+ }
160
+ if (options.defaultSortOrder !== void 0) body.default_sort_order = options.defaultSortOrder;
161
+ if (options.defaultTagSetting !== void 0) body.default_tag_setting = options.defaultTagSetting;
162
+ if (options.flags !== void 0) body.flags = options.flags;
163
+ if (options.defaultAutoArchiveDuration !== void 0) {
164
+ body.default_auto_archive_duration = options.defaultAutoArchiveDuration;
165
+ }
166
+ if (options.defaultThreadRateLimitPerUser !== void 0) {
167
+ body.default_thread_rate_limit_per_user = options.defaultThreadRateLimitPerUser;
168
+ }
169
+ if (includeLayout && options.defaultForumLayout !== void 0) {
170
+ body.default_forum_layout = options.defaultForumLayout;
171
+ }
172
+ return body;
173
+ }
174
+ function reactionEmojiWire(emoji) {
175
+ const body = {};
176
+ if (emoji.emojiId !== void 0) body.emoji_id = emoji.emojiId;
177
+ if (emoji.emojiName !== void 0) body.emoji_name = emoji.emojiName;
178
+ return body;
179
+ }
180
+ function toThreadMemberSettingsBody(options) {
181
+ const body = {};
182
+ if (options.flags !== void 0) body.flags = options.flags;
183
+ if (options.muted !== void 0) body.muted = options.muted;
184
+ if (options.muteConfig !== void 0) {
185
+ body.mute_config = options.muteConfig === null ? null : {
186
+ ...options.muteConfig.endTime !== void 0 ? { end_time: options.muteConfig.endTime } : {},
187
+ selected_time_window: options.muteConfig.selectedTimeWindow
188
+ };
189
+ }
190
+ return body;
191
+ }
192
+ function withQuery(path, params) {
193
+ const query = new URLSearchParams();
194
+ for (const [key, value] of Object.entries(params)) {
195
+ if (value === void 0) continue;
196
+ if (Array.isArray(value)) {
197
+ for (const item of value) query.append(key, item);
198
+ continue;
199
+ }
200
+ query.set(key, String(value));
201
+ }
202
+ const text = query.toString();
203
+ return text ? `${path}?${text}` : path;
204
+ }
205
+
206
+ // src/ClientCore/SdkOptions/Channels.ts
82
207
  function toOverwriteWire(overwrite) {
83
208
  return {
84
209
  id: overwrite.id,
@@ -139,6 +264,16 @@ function toChannelCreateBody(options) {
139
264
  body.content_warning_text = options.contentWarningText;
140
265
  }
141
266
  if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
267
+ if (options.defaultAutoArchiveDuration !== void 0) {
268
+ body.default_auto_archive_duration = options.defaultAutoArchiveDuration;
269
+ }
270
+ if (options.defaultThreadRateLimitPerUser !== void 0) {
271
+ body.default_thread_rate_limit_per_user = options.defaultThreadRateLimitPerUser;
272
+ }
273
+ const forumParent = options.type === ChannelType2.GuildForum || options.type === ChannelType2.GuildMedia;
274
+ if (forumParent) {
275
+ Object.assign(body, forumParentWire(options, options.type === ChannelType2.GuildForum));
276
+ }
142
277
  return body;
143
278
  }
144
279
  function toChannelInviteBody(options) {
@@ -823,6 +958,14 @@ var Events = {
823
958
  ChannelCreate: "channelCreate",
824
959
  ChannelUpdate: "channelUpdate",
825
960
  ChannelDelete: "channelDelete",
961
+ ThreadCreate: "threadCreate",
962
+ ThreadUpdate: "threadUpdate",
963
+ ThreadDelete: "threadDelete",
964
+ ThreadListSync: "threadListSync",
965
+ ThreadMemberUpdate: "threadMemberUpdate",
966
+ ThreadMembersUpdate: "threadMembersUpdate",
967
+ ThreadMemberListUpdate: "threadMemberListUpdate",
968
+ ForumUnreads: "forumUnreads",
826
969
  ChannelPinsUpdate: "channelPinsUpdate",
827
970
  ChannelRecipientAdd: "channelRecipientAdd",
828
971
  ChannelRecipientRemove: "channelRecipientRemove",
@@ -960,1346 +1103,1404 @@ var ReactionCollector = class _ReactionCollector extends EventEmitter {
960
1103
  }
961
1104
  };
962
1105
 
963
- // src/Domain/Message/Attachment.ts
964
- function toMessageAttachment(data) {
965
- return {
966
- id: data.id,
967
- filename: data.filename,
968
- title: data.title ?? null,
969
- description: data.description ?? null,
970
- contentType: data.content_type ?? null,
971
- contentHash: data.content_hash ?? null,
972
- size: data.size,
973
- url: data.url ?? null,
974
- proxyUrl: data.proxy_url ?? null,
975
- width: data.width ?? null,
976
- height: data.height ?? null,
977
- placeholder: data.placeholder ?? null,
978
- flags: data.flags ?? 0,
979
- nsfw: data.nsfw ?? false,
980
- duration: data.duration ?? null,
981
- waveform: data.waveform ?? null,
982
- expiresAt: data.expires_at ? new Date(data.expires_at) : null,
983
- expired: data.expired ?? false
984
- };
985
- }
986
-
987
- // src/Domain/Message/Embed.ts
988
- function toMessageEmbedAuthor(data) {
989
- return {
990
- name: data.name ?? null,
991
- url: data.url ?? null,
992
- iconUrl: data.icon_url ?? null,
993
- proxyIconUrl: data.proxy_icon_url ?? null
994
- };
995
- }
996
- function toMessageEmbedFooter(data) {
997
- return {
998
- text: data.text,
999
- iconUrl: data.icon_url ?? null,
1000
- proxyIconUrl: data.proxy_icon_url ?? null
1001
- };
1002
- }
1003
- function toMessageEmbedMedia(data) {
1004
- return {
1005
- url: data.url,
1006
- proxyUrl: data.proxy_url ?? null,
1007
- contentType: data.content_type ?? null,
1008
- contentHash: data.content_hash ?? null,
1009
- width: data.width ?? null,
1010
- height: data.height ?? null,
1011
- description: data.description ?? null,
1012
- placeholder: data.placeholder ?? null,
1013
- duration: data.duration ?? null,
1014
- flags: data.flags ?? null
1015
- };
1016
- }
1017
- function toMessageEmbed(data) {
1018
- const full = data;
1019
- return {
1020
- type: data.type ?? "rich",
1021
- url: data.url ?? null,
1022
- title: data.title ?? null,
1023
- color: data.color ?? null,
1024
- timestamp: data.timestamp ? new Date(data.timestamp) : null,
1025
- description: data.description ?? null,
1026
- author: data.author ? toMessageEmbedAuthor(data.author) : null,
1027
- image: data.image ? toMessageEmbedMedia(data.image) : null,
1028
- thumbnail: data.thumbnail ? toMessageEmbedMedia(data.thumbnail) : null,
1029
- footer: data.footer ? toMessageEmbedFooter(data.footer) : null,
1030
- fields: (data.fields ?? []).map((f) => ({
1031
- name: f.name,
1032
- value: f.value,
1033
- inline: f.inline ?? false
1034
- })),
1035
- provider: data.provider ? toMessageEmbedAuthor(data.provider) : null,
1036
- video: data.video ? toMessageEmbedMedia(data.video) : null,
1037
- audio: data.audio ? toMessageEmbedMedia(data.audio) : null,
1038
- nsfw: data.nsfw ?? false,
1039
- children: (full.children ?? []).map(toMessageEmbed),
1040
- html: full.html ?? null,
1041
- htmlWidth: full.html_width ?? null,
1042
- htmlHeight: full.html_height ?? null
1043
- };
1044
- }
1106
+ // src/Domain/Channel/Base.ts
1107
+ import { ChannelType as ChannelType3, Routes as Routes4 } from "@fluxerjs/types";
1108
+ import { SnowflakeUtil } from "@fluxerjs/util";
1045
1109
 
1046
- // src/Domain/Message/MessageReactionManager.ts
1110
+ // src/ClientCore/MessageManager.ts
1047
1111
  import { Collection as Collection2 } from "@fluxerjs/collection";
1048
- var MessageReactionManager = class {
1049
- constructor(message) {
1050
- this.message = message;
1112
+ import { Routes as Routes2 } from "@fluxerjs/types";
1113
+ var BULK = {
1114
+ requests: { min: 1, max: 25 },
1115
+ limit: { min: 1, max: 25 },
1116
+ totalMax: 250
1117
+ };
1118
+ function validateBulkMessageFetchRequests(requests) {
1119
+ const { requests: req, limit, totalMax } = BULK;
1120
+ if (requests.length < req.min || requests.length > req.max) {
1121
+ throw new FluxerError(`bulkFetchMessages requires between ${req.min} and ${req.max} requests`, {
1122
+ code: ErrorCodes.InvalidFetchLimit
1123
+ });
1051
1124
  }
1052
- _cache = new Collection2();
1053
- /** Reactions keyed by unicode name or `name:id`. */
1054
- get cache() {
1055
- return this._cache;
1125
+ let total = 0;
1126
+ for (const request of requests) {
1127
+ if (request.limit < limit.min || request.limit > limit.max) {
1128
+ throw new FluxerError(
1129
+ `limit must be between ${limit.min} and ${limit.max} for channel ${request.channelId}`,
1130
+ { code: ErrorCodes.InvalidFetchLimit }
1131
+ );
1132
+ }
1133
+ total += request.limit;
1056
1134
  }
1057
- get size() {
1058
- return this._cache.size;
1135
+ if (total > totalMax) {
1136
+ throw new FluxerError(`bulkFetchMessages total message limit must not exceed ${totalMax}`, {
1137
+ code: ErrorCodes.InvalidFetchLimit
1138
+ });
1059
1139
  }
1060
- [Symbol.iterator]() {
1061
- return this._cache.values();
1140
+ }
1141
+ var MessageManager = class {
1142
+ constructor(client, channelId) {
1143
+ this.client = client;
1144
+ this.channelId = channelId;
1062
1145
  }
1063
- /** @internal Sync from an API message payload. */
1064
- _patch(reactions) {
1065
- this._cache.clear();
1066
- for (const data of reactions ?? []) {
1067
- const reaction = MessageReaction.fromMessage(this.message, data);
1068
- this._cache.set(reaction.emojiIdentifier, reaction);
1146
+ /** Structure cache keyed by message id (identity for {@link get}). */
1147
+ _structures = new Collection2();
1148
+ /** Retrieve a cached message by ID, or `undefined` if missing / caching disabled. */
1149
+ get(messageId) {
1150
+ const data = this.client._getMessageCache(this.channelId)?.get(messageId);
1151
+ if (!data) {
1152
+ this._structures.delete(messageId);
1153
+ return void 0;
1154
+ }
1155
+ const existing = this._structures.get(messageId);
1156
+ if (existing) return existing;
1157
+ const message = new Message(this.client, data);
1158
+ this._structures.set(messageId, message);
1159
+ return message;
1160
+ }
1161
+ /** Retrieve from cache, otherwise {@link fetch}. */
1162
+ async resolve(messageId) {
1163
+ return this.get(messageId) ?? this.fetch(messageId);
1164
+ }
1165
+ async fetch(idOrOptions) {
1166
+ return typeof idOrOptions === "string" ? this.fetchOne(idOrOptions) : this.fetchMany(idOrOptions);
1167
+ }
1168
+ /** Cache API data and return a {@link Message} (reusing identity when present). */
1169
+ wrap(data) {
1170
+ this.client._addMessageToCache(this.channelId, data);
1171
+ const cached = this.client._getMessageCache(this.channelId)?.get(data.id) ?? data;
1172
+ const existing = this._structures.get(data.id);
1173
+ if (existing) {
1174
+ existing._patch(cached);
1175
+ return existing;
1176
+ }
1177
+ const message = new Message(this.client, cached);
1178
+ this._structures.set(data.id, message);
1179
+ return message;
1180
+ }
1181
+ /** Fetch a single message from the API. */
1182
+ async fetchOne(messageId) {
1183
+ try {
1184
+ const data = await this.client.rest.get(
1185
+ Routes2.channelMessage(this.channelId, messageId)
1186
+ );
1187
+ return this.wrap(data);
1188
+ } catch (err) {
1189
+ rethrowMapped(err, {
1190
+ notFound: {
1191
+ code: ErrorCodes.MessageNotFound,
1192
+ message: `Message ${messageId} not found in channel ${this.channelId}`
1193
+ },
1194
+ fallback: `Failed to fetch message ${messageId}`
1195
+ });
1196
+ }
1197
+ }
1198
+ /** Fetch multiple messages from the API with pagination/filtering. */
1199
+ async fetchMany(options) {
1200
+ if (options.limit != null && (options.limit < 1 || options.limit > 100)) {
1201
+ throw new FluxerError("limit must be between 1 and 100", {
1202
+ code: ErrorCodes.InvalidFetchLimit
1203
+ });
1204
+ }
1205
+ const qs2 = new URLSearchParams();
1206
+ for (const key of ["limit", "before", "after", "around"]) {
1207
+ const value = options[key];
1208
+ if (value != null && value !== "") qs2.set(key, String(value));
1069
1209
  }
1210
+ const base = Routes2.channelMessages(this.channelId);
1211
+ const data = await this.client.rest.get(qs2.size > 0 ? `${base}?${qs2}` : base);
1212
+ const collection = new Collection2();
1213
+ for (const msg of data) collection.set(msg.id, this.wrap(msg));
1214
+ return collection;
1070
1215
  }
1071
1216
  };
1072
1217
 
1073
- // src/Domain/Message/MessageSticker.ts
1074
- import { SnowflakeUtil } from "@fluxerjs/util";
1075
-
1076
- // src/Helpers/Constants.ts
1077
- import { DEFAULT_USER_AGENT } from "@fluxerjs/rest";
1078
- var CDN_URL = "https://fluxerusercontent.com";
1079
- var STATIC_CDN_URL = "https://fluxerstatic.com";
1080
-
1081
- // src/Helpers/Cdn.ts
1082
- var CDN_SIZE_LADDER = [
1083
- 16,
1084
- 20,
1085
- 22,
1086
- 24,
1087
- 28,
1088
- 32,
1089
- 40,
1090
- 44,
1091
- 48,
1092
- 56,
1093
- 60,
1094
- 64,
1095
- 80,
1096
- 96,
1097
- 100,
1098
- 128,
1099
- 160,
1100
- 240,
1101
- 256,
1102
- 300,
1103
- 320,
1104
- 480,
1105
- 512,
1106
- 600,
1107
- 640,
1108
- 1024,
1109
- 1280,
1110
- 1536,
1111
- 2048,
1112
- 3072,
1113
- 4096,
1114
- 8192,
1115
- 16384
1116
- ];
1117
- var CDN_ASSET_CLASS_RANGE = {
1118
- icon: { min: 128, max: 1024 },
1119
- banner: { min: 480, max: 2400 },
1120
- emoji: { min: 32, max: 512 },
1121
- sticker: { min: 128, max: 512 }
1122
- };
1123
- function nearestSize(requested, candidates) {
1124
- let best = candidates[0];
1125
- let bestDist = Math.abs(requested - best);
1126
- for (let i = 1; i < candidates.length; i++) {
1127
- const step = candidates[i];
1128
- const dist = Math.abs(requested - step);
1129
- if (dist < bestDist || dist === bestDist && step > best) {
1130
- best = step;
1131
- bestDist = dist;
1132
- }
1218
+ // src/Helpers/MessageCollector.ts
1219
+ import { EventEmitter as EventEmitter2 } from "events";
1220
+ import { Collection as Collection3 } from "@fluxerjs/collection";
1221
+ function requireCollectorBounds(options) {
1222
+ const time = options.time ?? 0;
1223
+ const max = options.max ?? 0;
1224
+ if (time <= 0 && max <= 0) {
1225
+ throw new FluxerError("MessageCollector requires `time` and/or `max`", {
1226
+ code: ErrorCodes.CollectorOptionsRequired
1227
+ });
1133
1228
  }
1134
- return best;
1135
- }
1136
- function snapCdnSize(requested, assetClass) {
1137
- const { min, max } = CDN_ASSET_CLASS_RANGE[assetClass];
1138
- const snapped = nearestSize(requested, CDN_SIZE_LADDER);
1139
- const clamped = Math.min(max, Math.max(min, snapped));
1140
- const allowed = CDN_SIZE_LADDER.filter((step) => step >= min && step <= max);
1141
- return nearestSize(clamped, allowed);
1142
- }
1143
- function mediaBase(options) {
1144
- return (options?.mediaBase ?? CDN_URL).replace(/\/+$/, "");
1145
- }
1146
- function staticBase(options) {
1147
- return (options?.staticCdnBase ?? STATIC_CDN_URL).replace(/\/+$/, "");
1148
- }
1149
- function getExtension(hash, options) {
1150
- const ext = options?.extension ?? "png";
1151
- if (hash?.startsWith("a_")) return "gif";
1152
- return ext;
1153
- }
1154
- function appendSize(options, assetClass) {
1155
- const size = options?.size;
1156
- if (size == null || !Number.isFinite(size) || size <= 0) return "";
1157
- return `?size=${snapCdnSize(size, assetClass)}`;
1158
- }
1159
- function cdnAvatarURL(userId, avatarHash, options) {
1160
- if (!avatarHash) return null;
1161
- const ext = getExtension(avatarHash, options);
1162
- const size = appendSize(options, "icon");
1163
- return `${mediaBase(options)}/avatars/${userId}/${avatarHash}.${ext}${size}`;
1164
- }
1165
- function cdnBannerURL(resourceId, bannerHash, options) {
1166
- if (!bannerHash) return null;
1167
- const ext = getExtension(bannerHash, options);
1168
- const size = appendSize(options, "banner");
1169
- return `${mediaBase(options)}/banners/${resourceId}/${bannerHash}.${ext}${size}`;
1170
- }
1171
- function cdnMemberAvatarURL(guildId, userId, avatarHash, options) {
1172
- if (!avatarHash) return null;
1173
- const ext = getExtension(avatarHash, options);
1174
- const size = appendSize(options, "icon");
1175
- return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/avatars/${avatarHash}.${ext}${size}`;
1176
- }
1177
- function cdnMemberBannerURL(guildId, userId, bannerHash, options) {
1178
- if (!bannerHash) return null;
1179
- const ext = getExtension(bannerHash, options);
1180
- const size = appendSize(options, "banner");
1181
- return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/banners/${bannerHash}.${ext}${size}`;
1182
- }
1183
- function cdnDefaultAvatarURL(userIdOrIndex, options) {
1184
- const index = typeof userIdOrIndex === "string" ? Number(BigInt(userIdOrIndex) % 6n) : Math.abs(Math.floor(userIdOrIndex) % 6);
1185
- return `${staticBase(options)}/avatars/${index}.png`;
1186
- }
1187
- function cdnGuildAssetURL(kind, id, hash, options) {
1188
- if (!hash) return null;
1189
- const assetClass = kind === "icons" ? "icon" : "banner";
1190
- const size = appendSize(options, assetClass);
1191
- return `${mediaBase(options)}/${kind}/${id}/${hash}.png${size}`;
1192
- }
1193
- function cdnEmojiURL(emojiId, animated, options) {
1194
- const ext = animated ? "gif" : "png";
1195
- const size = appendSize(options, "emoji");
1196
- return `${mediaBase(options)}/emojis/${emojiId}.${ext}${size}`;
1197
1229
  }
1198
- function cdnStickerURL(stickerId, animated, options) {
1199
- const ext = animated ? "gif" : "png";
1200
- const size = appendSize(options, "sticker");
1201
- return `${mediaBase(options)}/stickers/${stickerId}.${ext}${size}`;
1202
- }
1203
-
1204
- // src/Domain/Message/MessageSticker.ts
1205
- var MessageSticker = class extends Base {
1230
+ var MessageCollector = class _MessageCollector extends EventEmitter2 {
1206
1231
  client;
1207
- id;
1208
- name;
1209
- description;
1210
- tags;
1211
- animated;
1212
- constructor(client, data) {
1232
+ channelId;
1233
+ options;
1234
+ collected = new Collection3();
1235
+ _timeout = null;
1236
+ _ended = false;
1237
+ _listener;
1238
+ constructor(client, channelId, options = {}) {
1213
1239
  super();
1240
+ requireCollectorBounds(options);
1214
1241
  this.client = client;
1215
- this.id = data.id;
1216
- this.name = data.name;
1217
- this.description = data.description ?? "";
1218
- this.tags = data.tags ?? [];
1219
- this.animated = data.animated ?? false;
1242
+ this.channelId = channelId;
1243
+ this.options = {
1244
+ filter: options.filter ?? (() => true),
1245
+ time: options.time ?? 0,
1246
+ max: options.max ?? 0
1247
+ };
1248
+ this._listener = (message) => {
1249
+ if (this._ended || message.channelId !== this.channelId) return;
1250
+ if (!this.options.filter(message)) return;
1251
+ this.collected.set(message.id, message);
1252
+ this.emit("collect", message);
1253
+ if (this.options.max > 0 && this.collected.size >= this.options.max) {
1254
+ this.stop("limit");
1255
+ }
1256
+ };
1257
+ this.client.on(Events.MessageCreate, this._listener);
1258
+ if (this.options.time > 0) {
1259
+ this._timeout = setTimeout(() => this.stop("time"), this.options.time);
1260
+ }
1220
1261
  }
1221
- /** CDN URL for this sticker image. */
1222
- get url() {
1223
- return cdnStickerURL(this.id, this.animated, {
1224
- mediaBase: this.client.instance.endpoints.media
1262
+ stop(reason = "user") {
1263
+ if (this._ended) return;
1264
+ this._ended = true;
1265
+ this.client.off(Events.MessageCreate, this._listener);
1266
+ if (this._timeout) {
1267
+ clearTimeout(this._timeout);
1268
+ this._timeout = null;
1269
+ }
1270
+ this.emit("end", this.collected, reason);
1271
+ }
1272
+ /**
1273
+ * One-shot helper used by {@link Channel.awaitMessages}.
1274
+ * Resolves with the collected messages when the collector ends for `user` (or when
1275
+ * the end reason is not listed in `errors`).
1276
+ * By default, `time` and `limit` reject with {@link FluxerError}
1277
+ * (`CollectorIdle` / `CollectorMax`).
1278
+ */
1279
+ static awaitMessages(client, channelId, options) {
1280
+ const errors = options?.errors ?? ["time", "limit"];
1281
+ return new Promise((resolve, reject) => {
1282
+ const collector = new _MessageCollector(client, channelId, options);
1283
+ collector.on("end", (collected, reason) => {
1284
+ if (!errors.includes(reason)) {
1285
+ resolve(collected);
1286
+ return;
1287
+ }
1288
+ if (reason === "time") {
1289
+ reject(
1290
+ new FluxerError("Message collector timed out", {
1291
+ code: ErrorCodes.CollectorIdle
1292
+ })
1293
+ );
1294
+ return;
1295
+ }
1296
+ if (reason === "limit") {
1297
+ reject(
1298
+ new FluxerError("Message collector reached max", {
1299
+ code: ErrorCodes.CollectorMax
1300
+ })
1301
+ );
1302
+ return;
1303
+ }
1304
+ reject(collected);
1305
+ });
1225
1306
  });
1226
1307
  }
1227
- /** Unix timestamp (ms) when this sticker was created, derived from its snowflake ID. */
1228
- get createdTimestamp() {
1229
- return SnowflakeUtil.timestampFromSnowflake(this.id);
1308
+ on(event, listener) {
1309
+ return super.on(event, listener);
1230
1310
  }
1231
- /** Date when this sticker was created, derived from its snowflake ID. */
1232
- get createdAt() {
1233
- return SnowflakeUtil.dateFromSnowflake(this.id);
1311
+ emit(event, ...args) {
1312
+ return super.emit(event, ...args);
1234
1313
  }
1235
1314
  };
1236
1315
 
1237
- // src/Domain/Message/Reactions.ts
1238
- import { Routes as Routes2 } from "@fluxerjs/types";
1239
- async function emojiPath(message, emoji) {
1240
- return message.client.resolveEmoji(emoji, message.guildId);
1241
- }
1242
- async function reactToMessage(message, emoji) {
1243
- const wire = await emojiPath(message, emoji);
1244
- await message.client.rest.put(
1245
- Routes2.channelMessageReactionMe(message.channelId, message.id, wire)
1246
- );
1316
+ // src/Domain/Channel/Attachments.ts
1317
+ import { Routes as Routes3 } from "@fluxerjs/types";
1318
+ var BOT_ATTACHMENT_MAX_BYTES = 50 * 1024 * 1024;
1319
+ var ATTACHMENT_MULTIPART_THRESHOLD_BYTES = 10 * 1024 * 1024;
1320
+ function instanceLimitOverridesSnapshot(client) {
1321
+ const rules = client.instance.discovery?.limits?.rules;
1322
+ if (!rules?.length) return null;
1323
+ const snapshot = {};
1324
+ for (const rule of rules) {
1325
+ Object.assign(snapshot, rule.overrides);
1326
+ }
1327
+ return Object.keys(snapshot).length ? snapshot : null;
1247
1328
  }
1248
- async function removeMessageReaction(message, emoji, userId) {
1249
- const e = await emojiPath(message, emoji);
1250
- const route = userId ? Routes2.channelMessageReactionUser(message.channelId, message.id, e, userId) : Routes2.channelMessageReactionMe(message.channelId, message.id, e);
1251
- await message.client.rest.delete(route);
1252
- }
1253
- async function removeAllMessageReactions(message) {
1254
- await message.client.rest.delete(Routes2.channelMessageReactions(message.channelId, message.id));
1255
- }
1256
- async function removeMessageReactionEmoji(message, emoji) {
1257
- const e = await emojiPath(message, emoji);
1258
- await message.client.rest.delete(Routes2.channelMessageReaction(message.channelId, message.id, e));
1259
- }
1260
- async function fetchMessageReactionUsers(message, emoji, options) {
1261
- return (await fetchMessageReactionUsersPage(message, emoji, options)).users;
1262
- }
1263
- async function fetchMessageReactionUsersPage(message, emoji, options) {
1264
- const e = await emojiPath(message, emoji);
1265
- const params = new URLSearchParams();
1266
- if (options?.limit != null) params.set("limit", String(options.limit));
1267
- if (options?.after) params.set("after", options.after);
1268
- const qs2 = params.toString();
1269
- const route = Routes2.channelMessageReactionUsers(message.channelId, message.id, e) + (qs2 ? `?${qs2}` : "");
1270
- const data = await message.client.rest.get(route);
1271
- if (Array.isArray(data)) {
1272
- return {
1273
- users: data.map((u) => message.client.getOrCreateUser(u)),
1274
- hasMore: false,
1275
- nextAfter: null
1276
- };
1329
+ function assertBotAttachmentLimits(client, files) {
1330
+ const snapshot = instanceLimitOverridesSnapshot(client);
1331
+ for (const file of files) {
1332
+ const size = file.data.byteLength;
1333
+ if (size <= BOT_ATTACHMENT_MAX_BYTES) continue;
1334
+ const snapshotNote = snapshot ? ` Instance limit overrides: ${JSON.stringify(snapshot)}.` : "";
1335
+ throw new FluxerError(
1336
+ `Bot attachments are limited to 50 MiB (${BOT_ATTACHMENT_MAX_BYTES} bytes); "${file.filename}" is ${size} bytes.${snapshotNote}`,
1337
+ { code: ErrorCodes.AttachmentTooLarge }
1338
+ );
1277
1339
  }
1278
- const list = data.items ?? data.users ?? [];
1279
- return {
1280
- users: list.map((u) => message.client.getOrCreateUser(u)),
1281
- hasMore: data.has_more ?? false,
1282
- nextAfter: data.next_after ?? null
1283
- };
1284
1340
  }
1285
-
1286
- // src/Domain/Message/Send.ts
1287
- import { MessagePayload as MessagePayloadBuilder } from "@fluxerjs/builders";
1288
- import { Routes as Routes3 } from "@fluxerjs/types";
1289
- function toReplyTarget(ref) {
1290
- return {
1291
- channelId: ref.channel_id,
1292
- messageId: ref.message_id,
1293
- ...ref.guild_id != null ? { guildId: ref.guild_id } : {}
1294
- };
1295
- }
1296
- function toSendOptions(content) {
1297
- if (typeof content === "string") return { content };
1298
- if (content instanceof MessagePayloadBuilder) return messagePayloadToSendOptions(content);
1299
- return { ...content };
1341
+ function asBytes(data) {
1342
+ const src = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data);
1343
+ const out = new Uint8Array(src.byteLength);
1344
+ out.set(src);
1345
+ return out;
1300
1346
  }
1301
- async function createMessageBody(content, referenced_message, ping) {
1302
- if (typeof content === "string" && content.length === 0) {
1303
- throw new FluxerError("Cannot send an empty message", { code: ErrorCodes.EmptyMessage });
1304
- }
1305
- const opts = toSendOptions(content);
1306
- if (referenced_message) {
1307
- opts.replyTo = toReplyTarget(referenced_message);
1308
- if (ping !== void 0) opts.ping = ping;
1347
+ async function putBlob(url, body, contentType) {
1348
+ const res = await fetch(url, {
1349
+ method: "PUT",
1350
+ headers: contentType ? { "Content-Type": contentType } : void 0,
1351
+ body
1352
+ });
1353
+ if (!res.ok) {
1354
+ throw new FluxerError(`Presigned upload failed: ${res.status}`, {
1355
+ code: ErrorCodes.AttachmentUploadFailed
1356
+ });
1309
1357
  }
1310
- return prepareMessagePostPayload(opts);
1311
1358
  }
1312
- function asReplyTarget(value) {
1313
- if ("messageId" in value) return value;
1314
- return {
1315
- channelId: value.channelId,
1316
- messageId: value.id,
1317
- guildId: value.guildId
1318
- };
1319
- }
1320
- async function sendPrepared(message, payload) {
1321
- const data = await message.client.rest.post(
1322
- Routes3.channelMessages(message.channelId),
1323
- payload
1324
- );
1325
- message.client._addMessageToCache(message.channelId, data);
1326
- return new message.constructor(message.client, data);
1327
- }
1328
- async function sendMessage(message, options) {
1329
- return message._send(
1330
- await prepareMessagePostPayload(options, {
1331
- defaultAllowedMentions: message.client.options.defaultAllowedMentions
1332
- })
1333
- );
1334
- }
1335
- async function sendMessageTo(message, channelId, options) {
1336
- return message.client.channels.send(channelId, options);
1337
- }
1338
- async function replyToMessage(message, options, replyOptions) {
1339
- const opts = typeof options === "string" ? { content: options } : { ...options };
1340
- const { replyTo: inlineReplyTo, ping: inlinePing, ...sendOpts } = opts;
1341
- const ping = replyOptions?.ping ?? inlinePing ?? message.client.options.defaultReplyPing;
1342
- const replyTo = asReplyTarget(replyOptions?.replyTo ?? inlineReplyTo ?? message);
1343
- return message._send(
1344
- await prepareMessagePostPayload(
1345
- { ...sendOpts, replyTo, ping },
1346
- { defaultAllowedMentions: message.client.options.defaultAllowedMentions }
1347
- )
1359
+ async function uploadAttachmentsForSend(client, channelId, files) {
1360
+ assertBotAttachmentLimits(client, files);
1361
+ const plan = await client.rest.post(
1362
+ Routes3.channelAttachments(channelId),
1363
+ {
1364
+ body: {
1365
+ attachments: files.map((f) => ({
1366
+ id: f.id,
1367
+ filename: f.filename,
1368
+ file_size: f.data.byteLength,
1369
+ content_type: f.contentType
1370
+ }))
1371
+ },
1372
+ auth: true
1373
+ }
1348
1374
  );
1375
+ const multipart = [];
1376
+ const uploaded = [];
1377
+ for (const item of plan.attachments) {
1378
+ const file = files.find((f) => f.id === item.id);
1379
+ if (!file) {
1380
+ throw new FluxerError(`No file data for planned attachment id ${item.id}`, {
1381
+ code: ErrorCodes.InvalidAttachmentInput
1382
+ });
1383
+ }
1384
+ const bytes = asBytes(file.data);
1385
+ if (item.upload_mode === "singlepart") {
1386
+ await putBlob(
1387
+ item.upload_url,
1388
+ new Blob([bytes], { type: file.contentType }),
1389
+ item.content_type
1390
+ );
1391
+ } else {
1392
+ for (const part of item.parts) {
1393
+ const start = (part.part_number - 1) * item.part_size;
1394
+ const chunk = bytes.subarray(start, Math.min(start + item.part_size, bytes.byteLength));
1395
+ await putBlob(part.upload_url, new Blob([asBytes(chunk)]));
1396
+ }
1397
+ multipart.push({ upload_filename: item.upload_filename, upload_id: item.upload_id });
1398
+ }
1399
+ uploaded.push({
1400
+ id: item.id,
1401
+ filename: item.filename,
1402
+ upload_filename: item.upload_filename,
1403
+ file_size: item.file_size,
1404
+ content_type: item.content_type
1405
+ });
1406
+ }
1407
+ if (multipart.length) {
1408
+ await client.rest.post(Routes3.channelAttachmentsComplete(channelId), {
1409
+ body: { uploads: multipart },
1410
+ auth: true
1411
+ });
1412
+ }
1413
+ return uploaded;
1349
1414
  }
1350
1415
 
1351
- // src/Domain/Message/Message.ts
1352
- function toMessageCall(data) {
1353
- return {
1354
- participants: data.participants,
1355
- endedAt: data.ended_timestamp ? new Date(data.ended_timestamp) : null
1356
- };
1357
- }
1358
- function toMessageSnapshot(client, data) {
1359
- return {
1360
- content: data.content ?? null,
1361
- createdAt: new Date(data.timestamp),
1362
- editedAt: data.edited_timestamp ? new Date(data.edited_timestamp) : null,
1363
- mentionUserIds: data.mentions ?? [],
1364
- mentionRoles: data.mention_roles ?? [],
1365
- embeds: (data.embeds ?? []).map(toMessageEmbed),
1366
- attachments: (data.attachments ?? []).map(toMessageAttachment),
1367
- stickers: (data.stickers ?? []).map((s) => new MessageSticker(client, s)),
1368
- ...data.type !== void 0 ? { type: data.type } : {}
1369
- };
1370
- }
1371
- function resolveMessageFlags(flags) {
1372
- if (flags === void 0) return void 0;
1373
- if (typeof flags === "number") return flags;
1374
- return Number(MessageFlagsBitField.resolve(flags));
1375
- }
1376
- var Message = class _Message extends Base {
1377
- /** Discriminant vs {@link PartialMessage}: always `false` on a hydrated Message. */
1378
- partial = false;
1379
- /** The {@link Client} that instantiated this message. */
1416
+ // src/Domain/Channel/Base.ts
1417
+ var Channel = class extends Base {
1418
+ #messages;
1419
+ /** The {@link Client} that instantiated this channel. */
1380
1420
  client;
1381
- /** Snowflake ID of this message. */
1421
+ /** Snowflake ID of this channel. */
1382
1422
  id;
1383
- /** Channel ID where this message was sent. */
1384
- channelId;
1385
- /** Guild ID if in a guild channel, null for DMs. */
1386
- guildId;
1387
- /** The user who sent this message. */
1388
- author;
1389
- /** Text content of the message. */
1390
- content;
1391
- /** When the message was created. */
1392
- createdAt;
1393
- /** When the message was last edited, or null if never edited. */
1394
- editedAt;
1395
- /** Whether the message is pinned. */
1396
- pinned;
1397
- /** Attached files (images, videos, etc.). */
1398
- attachments;
1399
- /** Message type (Default, Reply, etc.). */
1423
+ /** Channel type (text, voice, category, etc.). */
1400
1424
  type;
1401
- /** Message flags bitfield. */
1402
- flags;
1403
- /** Whether `@everyone` or `@here` was mentioned. */
1404
- mentionEveryone;
1405
- /** Whether this is a text-to-speech message. */
1406
- tts;
1407
- /** Embedded content (camelCase read view; send with {@link EmbedBuilder}). */
1408
- embeds;
1409
- /** Stickers sent with the message. */
1410
- stickers;
1411
- /** Reactions on the message. */
1412
- reactions;
1413
- /** Reference to a replied-to message, if any. */
1414
- messageReference;
1415
- /** Message snapshots for forwarded messages. */
1416
- messageSnapshots;
1417
- /** Call data if this message represents a call event. */
1418
- call;
1419
- /** The full referenced (replied-to) message, or null. */
1420
- referencedMessage;
1421
- /** Webhook ID if sent by a webhook. */
1422
- webhookId;
1423
- /** Users mentioned in the message. */
1424
- mentions;
1425
- /** Role IDs mentioned in the message. */
1426
- mentionRoles;
1427
- /** Client-side nonce for deduplication. */
1428
- nonce;
1429
- /** IDs of custom emojis in the message classified as explicit. */
1430
- nsfwEmojis;
1431
- /**
1432
- * Cached text-capable channel (guild text, guild voice, or DM), or null if uncached / not text-based.
1433
- * Narrowed type has {@link Channel.send} and {@link Channel.delete}.
1434
- */
1435
- get channel() {
1436
- const channel = this.client.channels.get(this.channelId) ?? null;
1437
- return channel?.isTextBased() ? channel : null;
1438
- }
1439
- /** Cached guild, or null for DMs / uncached. */
1440
- get guild() {
1441
- return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
1442
- }
1443
- /** Cached guild member for the author, or null in DMs / if uncached. */
1444
- get member() {
1445
- return this.guild?.members.get(this.author.id) ?? null;
1446
- }
1447
- /**
1448
- * Fetch this message's channel (cache first). The returned {@link Channel}
1449
- * has {@link Channel.delete} and {@link Channel.send}.
1450
- * @example
1451
- * const channel = await message.resolveChannel();
1452
- * await channel.delete();
1453
- */
1454
- async resolveChannel() {
1455
- return this.client.channels.resolve(this.channelId);
1456
- }
1457
- /**
1458
- * Fetch and resolve the guild, or null if a DM.
1459
- * Propagates network/auth errors; only returns null when there is no guildId.
1460
- * @example
1461
- * const guild = await message.resolveGuild();
1462
- */
1463
- async resolveGuild() {
1464
- if (!this.guildId) return null;
1465
- return this.client.guilds.resolve(this.guildId);
1466
- }
1467
- /**
1468
- * Construct a message from API data.
1469
- * @param data - API message from REST or MESSAGE_CREATE
1470
- */
1425
+ /** Channel name (null for some channel types). */
1426
+ name;
1427
+ /** Channel icon hash (null for most channel types). */
1428
+ icon;
1429
+ /** ISO8601 timestamp of the last pinned message update. */
1430
+ lastPinTimestamp;
1471
1431
  constructor(client, data) {
1472
1432
  super();
1473
1433
  this.client = client;
1474
1434
  this.id = data.id;
1475
- this.channelId = data.channel_id;
1476
- this.guildId = data.guild_id ?? null;
1477
- this.author = client.getOrCreateUser(data.author);
1478
- this.content = data.content;
1479
- this.createdAt = new Date(data.timestamp);
1480
- this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
1481
- this.pinned = data.pinned;
1482
- this.attachments = new Collection3();
1483
- for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
1484
- this.type = data.type ?? MessageType.Default;
1485
- this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
1486
- this.mentionEveryone = data.mention_everyone ?? false;
1487
- this.tts = data.tts ?? false;
1488
- this.embeds = (data.embeds ?? []).map(toMessageEmbed);
1489
- this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(client, s));
1490
- this.reactions = new MessageReactionManager(this);
1491
- this.reactions._patch(data.reactions);
1492
- this.messageReference = data.message_reference ? {
1493
- channelId: data.message_reference.channel_id,
1494
- messageId: data.message_reference.message_id,
1495
- guildId: data.message_reference.guild_id ?? null,
1496
- ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
1497
- } : null;
1498
- this.messageSnapshots = (data.message_snapshots ?? []).map((s) => toMessageSnapshot(client, s));
1499
- this.call = data.call ? toMessageCall(data.call) : null;
1500
- this.referencedMessage = data.referenced_message ? new _Message(client, data.referenced_message) : null;
1501
- this.webhookId = data.webhook_id ?? null;
1502
- this.mentions = (data.mentions ?? []).map((u) => client.getOrCreateUser(u));
1503
- this.mentionRoles = data.mention_roles ?? [];
1504
- this.nonce = data.nonce ?? null;
1505
- this.nsfwEmojis = data.nsfw_emojis ?? [];
1435
+ this.type = data.type;
1436
+ this.name = data.name ?? null;
1437
+ this.icon = data.icon ?? null;
1438
+ this.lastPinTimestamp = data.last_pin_timestamp ?? null;
1439
+ }
1440
+ /** Unix timestamp (ms) when this channel was created, derived from its snowflake ID. */
1441
+ get createdTimestamp() {
1442
+ return SnowflakeUtil.timestampFromSnowflake(this.id);
1443
+ }
1444
+ /** Date when this channel was created, derived from its snowflake ID. */
1445
+ get createdAt() {
1446
+ return SnowflakeUtil.dateFromSnowflake(this.id);
1506
1447
  }
1507
1448
  /**
1508
- * Apply an API message payload in place (cache identity / MESSAGE_UPDATE).
1449
+ * Apply shared channel fields in place (gateway CHANNEL_UPDATE when type is unchanged).
1509
1450
  * @internal
1510
1451
  */
1511
1452
  _patch(data) {
1512
- this.content = data.content;
1513
- this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
1514
- this.pinned = data.pinned;
1515
- this.attachments.clear();
1516
- for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
1517
- this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
1518
- this.mentionEveryone = data.mention_everyone ?? false;
1519
- this.tts = data.tts ?? false;
1520
- this.embeds = (data.embeds ?? []).map(toMessageEmbed);
1521
- this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(this.client, s));
1522
- this.reactions._patch(data.reactions);
1523
- this.messageReference = data.message_reference ? {
1524
- channelId: data.message_reference.channel_id,
1525
- messageId: data.message_reference.message_id,
1526
- guildId: data.message_reference.guild_id ?? null,
1527
- ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
1528
- } : null;
1529
- this.messageSnapshots = (data.message_snapshots ?? []).map(
1530
- (s) => toMessageSnapshot(this.client, s)
1531
- );
1532
- this.call = data.call ? toMessageCall(data.call) : null;
1533
- this.referencedMessage = data.referenced_message ? new _Message(this.client, data.referenced_message) : null;
1534
- this.webhookId = data.webhook_id ?? null;
1535
- this.mentions = (data.mentions ?? []).map((u) => this.client.getOrCreateUser(u));
1536
- this.mentionRoles = data.mention_roles ?? [];
1537
- this.nonce = data.nonce ?? null;
1538
- this.nsfwEmojis = data.nsfw_emojis ?? [];
1453
+ if (data.type !== void 0) this.type = data.type;
1454
+ if (data.name !== void 0) this.name = data.name ?? null;
1455
+ if (data.icon !== void 0) this.icon = data.icon ?? null;
1456
+ if ("last_pin_timestamp" in data && data.last_pin_timestamp !== void 0) {
1457
+ this.lastPinTimestamp = data.last_pin_timestamp ?? null;
1458
+ }
1539
1459
  }
1540
- /**
1541
- * Send a standalone message in this channel (not a reply).
1542
- * Prefer {@link Channel.send} or {@link reply} when you already have the channel or are answering.
1543
- */
1544
- async send(options) {
1545
- return sendMessage(this, options);
1460
+ /** @internal Factory wired after subclasses load. */
1461
+ static from(_c, _d) {
1462
+ throw new Error("Channel.from not initialized");
1546
1463
  }
1547
- /**
1548
- * Send a message to another channel by ID.
1549
- * Prefer `client.channels.fetch(channelId)` then {@link Channel.send}.
1550
- */
1551
- async sendTo(channelId, options) {
1552
- return sendMessageTo(this, channelId, options);
1464
+ /** @internal Factory wired after subclasses load. */
1465
+ static fromOrCreate(_c, _d) {
1466
+ throw new Error("Channel.fromOrCreate not initialized");
1553
1467
  }
1554
- /**
1555
- * Reply to this message.
1556
- * @example
1557
- * await message.reply('Pong!');
1558
- * await message.reply('No ping!', { ping: false });
1559
- * await message.reply({ content: 'Silent', allowedMentions: AllowedMentions.suppressReplyPing });
1560
- */
1561
- async reply(options, replyOptions) {
1562
- return replyToMessage(this, options, replyOptions);
1468
+ /** @internal Factory wired after subclasses load. */
1469
+ static createDM(_c, _d) {
1470
+ throw new Error("Channel.createDM not initialized");
1563
1471
  }
1564
1472
  /**
1565
- * Hydrate a partial message, or return the message as-is.
1566
- * @example
1567
- * client.on(Events.MessageUpdate, async (_old, msg) => {
1568
- * const message = await Message.resolve(msg);
1569
- * });
1473
+ * Whether this channel type can carry messages (text, announcement, voice, threads, DM, group DM, notes).
1474
+ * Forum and media channels contain threads and do not accept `send`.
1475
+ * Checks {@link ChannelType}, not whether `send` exists on the instance.
1570
1476
  */
1571
- static async resolve(message) {
1572
- return message.partial ? message.fetch() : message;
1477
+ isTextBased() {
1478
+ 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;
1573
1479
  }
1574
- /** Test helper — prefer {@link reply} / `prepareMessagePostPayload()`. */
1575
- static async _createMessageBody(content, referenced_message, ping) {
1576
- return createMessageBody(content, referenced_message, ping);
1480
+ /** Check if this is a guild channel, including threads, forums, and media channels. */
1481
+ isGuild() {
1482
+ 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;
1577
1483
  }
1578
- /** Send a prepared payload (internal helper). */
1579
- async _send(payload) {
1580
- return sendPrepared(this, payload);
1484
+ /** Check if this is a thread (public, private, or announcement). */
1485
+ isThread() {
1486
+ return this.type === ChannelType3.AnnouncementThread || this.type === ChannelType3.PublicThread || this.type === ChannelType3.PrivateThread;
1581
1487
  }
1582
- /** Edit this message (requires author or admin permissions). */
1583
- async edit(options) {
1584
- const body = {};
1585
- if (options.content !== void 0) body.content = options.content;
1586
- if (options.embeds !== void 0) {
1587
- body.embeds = options.embeds.map(
1588
- (e) => e instanceof EmbedBuilder2 ? e.toJSON() : e
1589
- );
1488
+ /** Check if this is a forum channel. */
1489
+ isForum() {
1490
+ return this.type === ChannelType3.GuildForum;
1491
+ }
1492
+ /** Check if this is a media channel. */
1493
+ isMedia() {
1494
+ return this.type === ChannelType3.GuildMedia;
1495
+ }
1496
+ /** Check if this is a guild text channel. */
1497
+ isText() {
1498
+ return this.type === ChannelType3.GuildText;
1499
+ }
1500
+ /** Check if this is a guild announcement channel. */
1501
+ isAnnouncement() {
1502
+ return this.type === ChannelType3.GuildAnnouncement;
1503
+ }
1504
+ /** Check if this is a category channel. */
1505
+ isCategory() {
1506
+ return this.type === ChannelType3.GuildCategory;
1507
+ }
1508
+ /** Check if this is a DM, group DM, or personal notes channel. */
1509
+ isDM() {
1510
+ return this.type === ChannelType3.DM || this.type === ChannelType3.GroupDM || this.type === ChannelType3.DMPersonalNotes;
1511
+ }
1512
+ /** Check if this is a personal notes channel. */
1513
+ isPersonalNotes() {
1514
+ return this.type === ChannelType3.DMPersonalNotes;
1515
+ }
1516
+ /** Check if this is a voice channel. */
1517
+ isVoice() {
1518
+ return this.type === ChannelType3.GuildVoice;
1519
+ }
1520
+ /** Check if this is a link channel. */
1521
+ isLink() {
1522
+ return this.type === ChannelType3.GuildLink;
1523
+ }
1524
+ /**
1525
+ * Delete recent messages or an explicit ID list.
1526
+ * - `bulkDelete(5)` — fetch last 5 via {@link MessageManager} then delete (1–100)
1527
+ * - `bulkDelete(['id1'])` — single DELETE; 2–100 uses bulk-delete route
1528
+ */
1529
+ async bulkDelete(countOrIds) {
1530
+ let ids;
1531
+ if (typeof countOrIds === "number") {
1532
+ if (!Number.isInteger(countOrIds) || countOrIds < 1 || countOrIds > 100) {
1533
+ throw new FluxerError("bulkDelete count must be between 1 and 100", {
1534
+ code: ErrorCodes.InvalidBulkDelete
1535
+ });
1536
+ }
1537
+ ids = [
1538
+ ...(await new MessageManager(this.client, this.id).fetch({ limit: countOrIds })).keys()
1539
+ ];
1540
+ } else {
1541
+ ids = [...countOrIds];
1590
1542
  }
1591
- if (options.allowedMentions) {
1592
- body.allowed_mentions = toAPIAllowedMentions(options.allowedMentions);
1543
+ if (ids.length === 0) return [];
1544
+ if (ids.length === 1) {
1545
+ await this.client.rest.delete(Routes4.channelMessage(this.id, ids[0]), { auth: true });
1546
+ this.client._removeMessageFromCache(this.id, ids[0]);
1547
+ return ids;
1593
1548
  }
1594
- const flags = resolveMessageFlags(options.flags);
1595
- if (flags !== void 0) body.flags = flags;
1596
- if (options.attachments !== void 0) {
1597
- body.attachments = toMessageAttachmentEditWire(options.attachments);
1549
+ if (ids.length > 100) {
1550
+ throw new FluxerError("bulkDelete requires at most 100 message IDs", {
1551
+ code: ErrorCodes.InvalidBulkDelete
1552
+ });
1598
1553
  }
1599
- const data = await this.client.rest.patch(Routes4.channelMessage(this.channelId, this.id), {
1600
- body
1554
+ await this.client.rest.post(Routes4.channelBulkDelete(this.id), {
1555
+ body: { message_ids: ids },
1556
+ auth: true
1557
+ });
1558
+ for (const id of ids) this.client._removeMessageFromCache(this.id, id);
1559
+ return ids;
1560
+ }
1561
+ /** Delete all messages sent by the bot in this channel. Sudo auto-passes for bots. */
1562
+ async bulkDeleteMyMessages(options) {
1563
+ const body = options ? toSudoBody(options) : void 0;
1564
+ await this.client.rest.post(Routes4.channelBulkDeleteMine(this.id), {
1565
+ body: body && Object.keys(body).length ? body : void 0,
1566
+ auth: true
1601
1567
  });
1602
- const updated = new _Message(this.client, data);
1603
- this.client._addMessageToCache(this.channelId, data);
1604
- return updated;
1605
1568
  }
1606
- /** Create a {@link ReactionCollector} for this message. */
1607
- createReactionCollector(options) {
1608
- return new ReactionCollector(this.client, this.id, this.channelId, options);
1569
+ /**
1570
+ * Mark all pinned messages as read in this channel.
1571
+ * Session-token helper; bots usually skip this.
1572
+ */
1573
+ async acknowledgePins() {
1574
+ await this.client.rest.post(Routes4.channelPinsAck(this.id), { auth: true });
1609
1575
  }
1610
1576
  /**
1611
- * Wait for reactions matching the filter, then resolve the collected set.
1612
- * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
1577
+ * Clear the read state for this channel.
1578
+ * Session-token helper; bots usually skip this.
1613
1579
  */
1614
- awaitReactions(options) {
1615
- return ReactionCollector.awaitReactions(this.client, this.id, this.channelId, options);
1580
+ async clearReadState() {
1581
+ await this.client.rest.delete(Routes4.channelMessagesAck(this.id), { auth: true });
1616
1582
  }
1617
- /** Fetch the latest version of this message from the API. */
1618
- async fetch() {
1619
- return this.client.channels.fetchMessage(this.channelId, this.id);
1583
+ /** Request upload URLs for attachments before sending a message. */
1584
+ async requestAttachmentUploads(attachments) {
1585
+ const data = await this.client.rest.post(
1586
+ Routes4.channelAttachments(this.id),
1587
+ {
1588
+ body: toAttachmentUploadPlanBody(attachments),
1589
+ auth: true
1590
+ }
1591
+ );
1592
+ return toAttachmentUploadPlanResponse(data);
1620
1593
  }
1621
- /** Delete this message. */
1622
- async delete(reason) {
1623
- await this.client.rest.delete(Routes4.channelMessage(this.channelId, this.id), {
1624
- ...auditReasonHeaders(reason)
1594
+ /** Complete the attachment upload flow after uploading to the CDN. */
1595
+ async completeAttachmentUploads(uploads) {
1596
+ const data = await this.client.rest.post(
1597
+ Routes4.channelAttachmentsComplete(this.id),
1598
+ {
1599
+ body: toAttachmentUploadCompleteBody(uploads),
1600
+ auth: true
1601
+ }
1602
+ );
1603
+ return {
1604
+ uploads: data.uploads.map((u) => ({ uploadFilename: u.upload_filename }))
1605
+ };
1606
+ }
1607
+ /** Upload files for sending in a message (helper). */
1608
+ async uploadAttachmentsForSend(files) {
1609
+ return uploadAttachmentsForSend(this.client, this.id, files);
1610
+ }
1611
+ /** Trigger the typing indicator in this channel. */
1612
+ async sendTyping() {
1613
+ await this.client.rest.post(Routes4.channelTyping(this.id), { auth: true });
1614
+ }
1615
+ /**
1616
+ * Fetch available RTC regions for voice channels.
1617
+ * User-account only (`DefaultUserOnly`); bots receive `AccessDeniedError`.
1618
+ * Bots should skip this and join voice with `@fluxerjs/voice` instead.
1619
+ */
1620
+ async fetchRtcRegions() {
1621
+ const data = await this.client.rest.get(Routes4.channelRtcRegions(this.id), {
1622
+ auth: true
1625
1623
  });
1626
- this.client._removeMessageFromCache(this.channelId, this.id);
1624
+ return data.map((r) => ({ id: r.id, name: r.name, emoji: r.emoji }));
1627
1625
  }
1628
- /** Delete a specific attachment from this message. */
1629
- async deleteAttachment(attachmentId) {
1630
- await this.client.rest.delete(
1631
- Routes4.channelMessageAttachment(this.channelId, this.id, attachmentId),
1626
+ /** Fetch slowmode state for this channel. */
1627
+ async fetchSlowmode() {
1628
+ const data = await this.client.rest.get(
1629
+ Routes4.channelSlowmode(this.id),
1632
1630
  { auth: true }
1633
1631
  );
1634
- this.attachments.delete(attachmentId);
1632
+ return {
1633
+ rateLimitPerUser: data.rate_limit_per_user,
1634
+ retryAfterMs: data.retry_after_ms,
1635
+ nextSendAllowedAt: data.next_send_allowed_at
1636
+ };
1635
1637
  }
1636
- /** Pin this message in the channel. */
1637
- async pin() {
1638
- await this.client.rest.put(Routes4.channelPinMessage(this.channelId, this.id));
1639
- this.pinned = true;
1638
+ /** Whether this channel type can carry messages (does not check permissions). */
1639
+ canSendMessage() {
1640
+ return this.isTextBased();
1640
1641
  }
1641
- /** Unpin this message from the channel. */
1642
- async unpin() {
1643
- await this.client.rest.delete(Routes4.channelPinMessage(this.channelId, this.id));
1644
- this.pinned = false;
1642
+ /** Per-channel message cache + fetch. */
1643
+ get messages() {
1644
+ if (!this.#messages) {
1645
+ this.#messages = new MessageManager(this.client, this.id);
1646
+ }
1647
+ return this.#messages;
1645
1648
  }
1646
- /** React to this message with an emoji. */
1647
- async react(emoji) {
1648
- return reactToMessage(this, emoji);
1649
+ /** Collect messages in this channel until time/max/stop. */
1650
+ createMessageCollector(options) {
1651
+ return new MessageCollector(this.client, this.id, options);
1649
1652
  }
1650
- /** Remove a reaction (bot's own or a user's if ID is provided). */
1651
- async removeReaction(emoji, userId) {
1652
- return removeMessageReaction(this, emoji, userId);
1653
+ /**
1654
+ * Wait for messages matching the filter, then resolve the collected set.
1655
+ * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
1656
+ * @example
1657
+ * const collected = await channel.awaitMessages({ max: 1, time: 15_000 });
1658
+ */
1659
+ awaitMessages(options) {
1660
+ return MessageCollector.awaitMessages(this.client, this.id, options);
1653
1661
  }
1654
- /** Remove all reactions from this message. */
1655
- async removeAllReactions() {
1656
- return removeAllMessageReactions(this);
1662
+ /**
1663
+ * Delete this channel (or close it if it is a DM).
1664
+ * Guild channels require Manage Channels. `silent` / `deleteMessages` are Fluxer query params.
1665
+ * @example
1666
+ * const channel = await client.channels.fetch(channelId);
1667
+ * await channel.delete();
1668
+ */
1669
+ async delete(options) {
1670
+ const params = new URLSearchParams();
1671
+ if (options?.silent) params.set("silent", "true");
1672
+ if (options?.deleteMessages) params.set("delete_messages", "true");
1673
+ const qs2 = params.toString();
1674
+ const { silent: _s, deleteMessages: _d, reason: _reason, ...sudo } = options ?? {};
1675
+ const body = Object.keys(sudo).length ? toSudoBody(sudo) : void 0;
1676
+ await this.client.rest.delete(Routes4.channel(this.id) + (qs2 ? `?${qs2}` : ""), {
1677
+ body,
1678
+ auth: true,
1679
+ ...auditReasonHeaders(_reason)
1680
+ });
1681
+ this.client.channels.delete(this.id);
1682
+ this.client._clearMessageCache(this.id);
1683
+ if (this.isGuild() && this.guildId) {
1684
+ this.client.guilds.get(this.guildId)?.channels.delete(this.id);
1685
+ }
1657
1686
  }
1658
- /** Remove all reactions of a specific emoji. */
1659
- async removeReactionEmoji(emoji) {
1660
- return removeMessageReactionEmoji(this, emoji);
1687
+ /** Channel mention (`<#id>`). */
1688
+ toString() {
1689
+ return `<#${this.id}>`;
1661
1690
  }
1662
- /** Fetch users who reacted with a specific emoji. */
1663
- async fetchReactionUsers(emoji, options) {
1664
- return fetchMessageReactionUsers(this, emoji, options);
1691
+ };
1692
+
1693
+ // src/Domain/Channel/ThreadCache.ts
1694
+ function cacheThread(client, data) {
1695
+ const existing = client.channels.get(data.id);
1696
+ if (existing?.isThread() && existing.type === data.type) {
1697
+ existing._patch(data);
1698
+ placeThread(client, existing);
1699
+ return existing;
1665
1700
  }
1666
- /** Fetch reaction users with pagination metadata. */
1667
- async fetchReactionUsersPage(emoji, options) {
1668
- return fetchMessageReactionUsersPage(this, emoji, options);
1701
+ const created = Channel.from(client, data);
1702
+ if (!created.isThread()) {
1703
+ throw new FluxerError(`Channel ${data.id} is not a thread`, {
1704
+ code: ErrorCodes.InvalidChannelType
1705
+ });
1669
1706
  }
1670
- };
1707
+ placeThread(client, created);
1708
+ return created;
1709
+ }
1710
+ function placeThread(client, thread) {
1711
+ client.channels.set(thread.id, thread);
1712
+ if (!thread.guildId) return;
1713
+ const guild = client.guilds.get(thread.guildId);
1714
+ if (guild) guild.channels.set(thread.id, thread);
1715
+ }
1671
1716
 
1672
- // src/Domain/Message/PartialMessage.ts
1673
- import { SnowflakeUtil as SnowflakeUtil2 } from "@fluxerjs/util";
1674
- var PartialMessage = class {
1675
- partial = true;
1676
- client;
1677
- id;
1678
- channelId;
1679
- guildId;
1680
- content;
1681
- authorId;
1682
- author;
1683
- createdAt;
1684
- constructor(client, data) {
1685
- this.client = client;
1686
- this.id = data.id;
1687
- this.channelId = data.channelId;
1688
- this.guildId = data.guildId ?? null;
1689
- this.content = data.content ?? null;
1690
- this.authorId = data.authorId ?? null;
1691
- this.author = data.author ?? null;
1692
- this.createdAt = data.createdAt ?? (SnowflakeUtil2.isValid(data.id) ? SnowflakeUtil2.dateFromSnowflake(data.id) : null);
1717
+ // src/Domain/Message/Attachment.ts
1718
+ function toMessageAttachment(data) {
1719
+ return {
1720
+ id: data.id,
1721
+ filename: data.filename,
1722
+ title: data.title ?? null,
1723
+ description: data.description ?? null,
1724
+ contentType: data.content_type ?? null,
1725
+ contentHash: data.content_hash ?? null,
1726
+ size: data.size,
1727
+ url: data.url ?? null,
1728
+ proxyUrl: data.proxy_url ?? null,
1729
+ width: data.width ?? null,
1730
+ height: data.height ?? null,
1731
+ placeholder: data.placeholder ?? null,
1732
+ flags: data.flags ?? 0,
1733
+ nsfw: data.nsfw ?? false,
1734
+ duration: data.duration ?? null,
1735
+ waveform: data.waveform ?? null,
1736
+ expiresAt: data.expires_at ? new Date(data.expires_at) : null,
1737
+ expired: data.expired ?? false
1738
+ };
1739
+ }
1740
+
1741
+ // src/Domain/Message/Embed.ts
1742
+ function toMessageEmbedAuthor(data) {
1743
+ return {
1744
+ name: data.name ?? null,
1745
+ url: data.url ?? null,
1746
+ iconUrl: data.icon_url ?? null,
1747
+ proxyIconUrl: data.proxy_icon_url ?? null
1748
+ };
1749
+ }
1750
+ function toMessageEmbedFooter(data) {
1751
+ return {
1752
+ text: data.text,
1753
+ iconUrl: data.icon_url ?? null,
1754
+ proxyIconUrl: data.proxy_icon_url ?? null
1755
+ };
1756
+ }
1757
+ function toMessageEmbedMedia(data) {
1758
+ return {
1759
+ url: data.url,
1760
+ proxyUrl: data.proxy_url ?? null,
1761
+ contentType: data.content_type ?? null,
1762
+ contentHash: data.content_hash ?? null,
1763
+ width: data.width ?? null,
1764
+ height: data.height ?? null,
1765
+ description: data.description ?? null,
1766
+ placeholder: data.placeholder ?? null,
1767
+ duration: data.duration ?? null,
1768
+ flags: data.flags ?? null
1769
+ };
1770
+ }
1771
+ function toMessageEmbed(data) {
1772
+ const full = data;
1773
+ return {
1774
+ type: data.type ?? "rich",
1775
+ url: data.url ?? null,
1776
+ title: data.title ?? null,
1777
+ color: data.color ?? null,
1778
+ timestamp: data.timestamp ? new Date(data.timestamp) : null,
1779
+ description: data.description ?? null,
1780
+ author: data.author ? toMessageEmbedAuthor(data.author) : null,
1781
+ image: data.image ? toMessageEmbedMedia(data.image) : null,
1782
+ thumbnail: data.thumbnail ? toMessageEmbedMedia(data.thumbnail) : null,
1783
+ footer: data.footer ? toMessageEmbedFooter(data.footer) : null,
1784
+ fields: (data.fields ?? []).map((f) => ({
1785
+ name: f.name,
1786
+ value: f.value,
1787
+ inline: f.inline ?? false
1788
+ })),
1789
+ provider: data.provider ? toMessageEmbedAuthor(data.provider) : null,
1790
+ video: data.video ? toMessageEmbedMedia(data.video) : null,
1791
+ audio: data.audio ? toMessageEmbedMedia(data.audio) : null,
1792
+ nsfw: data.nsfw ?? false,
1793
+ children: (full.children ?? []).map(toMessageEmbed),
1794
+ html: full.html ?? null,
1795
+ htmlWidth: full.html_width ?? null,
1796
+ htmlHeight: full.html_height ?? null
1797
+ };
1798
+ }
1799
+
1800
+ // src/Domain/Message/MessageReactionManager.ts
1801
+ import { Collection as Collection4 } from "@fluxerjs/collection";
1802
+ var MessageReactionManager = class {
1803
+ constructor(message) {
1804
+ this.message = message;
1693
1805
  }
1694
- /**
1695
- * Live text-capable channel from cache, or null if uncached / not text-based.
1696
- * Same contract as {@link Message.channel}.
1697
- */
1698
- get channel() {
1699
- const channel = this.client.channels.get(this.channelId) ?? null;
1700
- return channel?.isTextBased() ? channel : null;
1806
+ _cache = new Collection4();
1807
+ /** Reactions keyed by unicode name or `name:id`. */
1808
+ get cache() {
1809
+ return this._cache;
1701
1810
  }
1702
- /**
1703
- * Fetch this message's channel (cache first). The returned {@link Channel}
1704
- * has {@link Channel.delete} and {@link Channel.send}.
1705
- * @example
1706
- * const channel = await message.resolveChannel();
1707
- * await channel.delete();
1708
- */
1709
- async resolveChannel() {
1710
- return this.client.channels.resolve(this.channelId);
1811
+ get size() {
1812
+ return this._cache.size;
1711
1813
  }
1712
- /**
1713
- * Fetch the full message from the API.
1714
- * @example
1715
- * const message = await partial.fetch();
1716
- * await message.reply('Pong!');
1717
- */
1718
- async fetch() {
1719
- return this.client.channels.fetchMessage(this.channelId, this.id);
1814
+ [Symbol.iterator]() {
1815
+ return this._cache.values();
1816
+ }
1817
+ /** @internal Sync from an API message payload. */
1818
+ _patch(reactions) {
1819
+ this._cache.clear();
1820
+ for (const data of reactions ?? []) {
1821
+ const reaction = MessageReaction.fromMessage(this.message, data);
1822
+ this._cache.set(reaction.emojiIdentifier, reaction);
1823
+ }
1720
1824
  }
1721
1825
  };
1722
1826
 
1723
- // src/Domain/User.ts
1724
- import { Routes as Routes14 } from "@fluxerjs/types";
1725
- import { SnowflakeUtil as SnowflakeUtil5 } from "@fluxerjs/util";
1827
+ // src/Domain/Message/MessageSticker.ts
1828
+ import { SnowflakeUtil as SnowflakeUtil2 } from "@fluxerjs/util";
1726
1829
 
1727
- // src/Domain/Channel/Base.ts
1728
- import { ChannelType, Routes as Routes7 } from "@fluxerjs/types";
1729
- import { SnowflakeUtil as SnowflakeUtil3 } from "@fluxerjs/util";
1830
+ // src/Helpers/Constants.ts
1831
+ import { DEFAULT_USER_AGENT } from "@fluxerjs/rest";
1832
+ var CDN_URL = "https://fluxerusercontent.com";
1833
+ var STATIC_CDN_URL = "https://fluxerstatic.com";
1730
1834
 
1731
- // src/ClientCore/MessageManager.ts
1732
- import { Collection as Collection4 } from "@fluxerjs/collection";
1733
- import { Routes as Routes5 } from "@fluxerjs/types";
1734
- var BULK = {
1735
- requests: { min: 1, max: 25 },
1736
- limit: { min: 1, max: 25 },
1737
- totalMax: 250
1835
+ // src/Helpers/Cdn.ts
1836
+ var CDN_SIZE_LADDER = [
1837
+ 16,
1838
+ 20,
1839
+ 22,
1840
+ 24,
1841
+ 28,
1842
+ 32,
1843
+ 40,
1844
+ 44,
1845
+ 48,
1846
+ 56,
1847
+ 60,
1848
+ 64,
1849
+ 80,
1850
+ 96,
1851
+ 100,
1852
+ 128,
1853
+ 160,
1854
+ 240,
1855
+ 256,
1856
+ 300,
1857
+ 320,
1858
+ 480,
1859
+ 512,
1860
+ 600,
1861
+ 640,
1862
+ 1024,
1863
+ 1280,
1864
+ 1536,
1865
+ 2048,
1866
+ 3072,
1867
+ 4096,
1868
+ 8192,
1869
+ 16384
1870
+ ];
1871
+ var CDN_ASSET_CLASS_RANGE = {
1872
+ icon: { min: 128, max: 1024 },
1873
+ banner: { min: 480, max: 2400 },
1874
+ emoji: { min: 32, max: 512 },
1875
+ sticker: { min: 128, max: 512 }
1738
1876
  };
1739
- function validateBulkMessageFetchRequests(requests) {
1740
- const { requests: req, limit, totalMax } = BULK;
1741
- if (requests.length < req.min || requests.length > req.max) {
1742
- throw new FluxerError(`bulkFetchMessages requires between ${req.min} and ${req.max} requests`, {
1743
- code: ErrorCodes.InvalidFetchLimit
1744
- });
1745
- }
1746
- let total = 0;
1747
- for (const request of requests) {
1748
- if (request.limit < limit.min || request.limit > limit.max) {
1749
- throw new FluxerError(
1750
- `limit must be between ${limit.min} and ${limit.max} for channel ${request.channelId}`,
1751
- { code: ErrorCodes.InvalidFetchLimit }
1752
- );
1877
+ function nearestSize(requested, candidates) {
1878
+ let best = candidates[0];
1879
+ let bestDist = Math.abs(requested - best);
1880
+ for (let i = 1; i < candidates.length; i++) {
1881
+ const step = candidates[i];
1882
+ const dist = Math.abs(requested - step);
1883
+ if (dist < bestDist || dist === bestDist && step > best) {
1884
+ best = step;
1885
+ bestDist = dist;
1753
1886
  }
1754
- total += request.limit;
1755
- }
1756
- if (total > totalMax) {
1757
- throw new FluxerError(`bulkFetchMessages total message limit must not exceed ${totalMax}`, {
1758
- code: ErrorCodes.InvalidFetchLimit
1759
- });
1760
1887
  }
1888
+ return best;
1761
1889
  }
1762
- var MessageManager = class {
1763
- constructor(client, channelId) {
1764
- this.client = client;
1765
- this.channelId = channelId;
1766
- }
1767
- /** Structure cache keyed by message id (identity for {@link get}). */
1768
- _structures = new Collection4();
1769
- /** Retrieve a cached message by ID, or `undefined` if missing / caching disabled. */
1770
- get(messageId) {
1771
- const data = this.client._getMessageCache(this.channelId)?.get(messageId);
1772
- if (!data) {
1773
- this._structures.delete(messageId);
1774
- return void 0;
1775
- }
1776
- const existing = this._structures.get(messageId);
1777
- if (existing) return existing;
1778
- const message = new Message(this.client, data);
1779
- this._structures.set(messageId, message);
1780
- return message;
1781
- }
1782
- /** Retrieve from cache, otherwise {@link fetch}. */
1783
- async resolve(messageId) {
1784
- return this.get(messageId) ?? this.fetch(messageId);
1785
- }
1786
- async fetch(idOrOptions) {
1787
- return typeof idOrOptions === "string" ? this.fetchOne(idOrOptions) : this.fetchMany(idOrOptions);
1788
- }
1789
- /** Cache API data and return a {@link Message} (reusing identity when present). */
1790
- wrap(data) {
1791
- this.client._addMessageToCache(this.channelId, data);
1792
- const cached = this.client._getMessageCache(this.channelId)?.get(data.id) ?? data;
1793
- const existing = this._structures.get(data.id);
1794
- if (existing) {
1795
- existing._patch(cached);
1796
- return existing;
1797
- }
1798
- const message = new Message(this.client, cached);
1799
- this._structures.set(data.id, message);
1800
- return message;
1801
- }
1802
- /** Fetch a single message from the API. */
1803
- async fetchOne(messageId) {
1804
- try {
1805
- const data = await this.client.rest.get(
1806
- Routes5.channelMessage(this.channelId, messageId)
1807
- );
1808
- return this.wrap(data);
1809
- } catch (err) {
1810
- rethrowMapped(err, {
1811
- notFound: {
1812
- code: ErrorCodes.MessageNotFound,
1813
- message: `Message ${messageId} not found in channel ${this.channelId}`
1814
- },
1815
- fallback: `Failed to fetch message ${messageId}`
1816
- });
1817
- }
1818
- }
1819
- /** Fetch multiple messages from the API with pagination/filtering. */
1820
- async fetchMany(options) {
1821
- if (options.limit != null && (options.limit < 1 || options.limit > 100)) {
1822
- throw new FluxerError("limit must be between 1 and 100", {
1823
- code: ErrorCodes.InvalidFetchLimit
1824
- });
1825
- }
1826
- const qs2 = new URLSearchParams();
1827
- for (const key of ["limit", "before", "after", "around"]) {
1828
- const value = options[key];
1829
- if (value != null && value !== "") qs2.set(key, String(value));
1830
- }
1831
- const base = Routes5.channelMessages(this.channelId);
1832
- const data = await this.client.rest.get(qs2.size > 0 ? `${base}?${qs2}` : base);
1833
- const collection = new Collection4();
1834
- for (const msg of data) collection.set(msg.id, this.wrap(msg));
1835
- return collection;
1836
- }
1837
- };
1838
-
1839
- // src/Helpers/MessageCollector.ts
1840
- import { EventEmitter as EventEmitter2 } from "events";
1841
- import { Collection as Collection5 } from "@fluxerjs/collection";
1842
- function requireCollectorBounds(options) {
1843
- const time = options.time ?? 0;
1844
- const max = options.max ?? 0;
1845
- if (time <= 0 && max <= 0) {
1846
- throw new FluxerError("MessageCollector requires `time` and/or `max`", {
1847
- code: ErrorCodes.CollectorOptionsRequired
1848
- });
1849
- }
1890
+ function snapCdnSize(requested, assetClass) {
1891
+ const { min, max } = CDN_ASSET_CLASS_RANGE[assetClass];
1892
+ const snapped = nearestSize(requested, CDN_SIZE_LADDER);
1893
+ const clamped = Math.min(max, Math.max(min, snapped));
1894
+ const allowed = CDN_SIZE_LADDER.filter((step) => step >= min && step <= max);
1895
+ return nearestSize(clamped, allowed);
1896
+ }
1897
+ function mediaBase(options) {
1898
+ return (options?.mediaBase ?? CDN_URL).replace(/\/+$/, "");
1899
+ }
1900
+ function staticBase(options) {
1901
+ return (options?.staticCdnBase ?? STATIC_CDN_URL).replace(/\/+$/, "");
1902
+ }
1903
+ function getExtension(hash, options) {
1904
+ const ext = options?.extension ?? "png";
1905
+ if (hash?.startsWith("a_")) return "gif";
1906
+ return ext;
1907
+ }
1908
+ function appendSize(options, assetClass) {
1909
+ const size = options?.size;
1910
+ if (size == null || !Number.isFinite(size) || size <= 0) return "";
1911
+ return `?size=${snapCdnSize(size, assetClass)}`;
1912
+ }
1913
+ function cdnAvatarURL(userId, avatarHash, options) {
1914
+ if (!avatarHash) return null;
1915
+ const ext = getExtension(avatarHash, options);
1916
+ const size = appendSize(options, "icon");
1917
+ return `${mediaBase(options)}/avatars/${userId}/${avatarHash}.${ext}${size}`;
1918
+ }
1919
+ function cdnBannerURL(resourceId, bannerHash, options) {
1920
+ if (!bannerHash) return null;
1921
+ const ext = getExtension(bannerHash, options);
1922
+ const size = appendSize(options, "banner");
1923
+ return `${mediaBase(options)}/banners/${resourceId}/${bannerHash}.${ext}${size}`;
1924
+ }
1925
+ function cdnMemberAvatarURL(guildId, userId, avatarHash, options) {
1926
+ if (!avatarHash) return null;
1927
+ const ext = getExtension(avatarHash, options);
1928
+ const size = appendSize(options, "icon");
1929
+ return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/avatars/${avatarHash}.${ext}${size}`;
1930
+ }
1931
+ function cdnMemberBannerURL(guildId, userId, bannerHash, options) {
1932
+ if (!bannerHash) return null;
1933
+ const ext = getExtension(bannerHash, options);
1934
+ const size = appendSize(options, "banner");
1935
+ return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/banners/${bannerHash}.${ext}${size}`;
1850
1936
  }
1851
- var MessageCollector = class _MessageCollector extends EventEmitter2 {
1937
+ function cdnDefaultAvatarURL(userIdOrIndex, options) {
1938
+ const index = typeof userIdOrIndex === "string" ? Number(BigInt(userIdOrIndex) % 6n) : Math.abs(Math.floor(userIdOrIndex) % 6);
1939
+ return `${staticBase(options)}/avatars/${index}.png`;
1940
+ }
1941
+ function cdnGuildAssetURL(kind, id, hash, options) {
1942
+ if (!hash) return null;
1943
+ const assetClass = kind === "icons" ? "icon" : "banner";
1944
+ const size = appendSize(options, assetClass);
1945
+ return `${mediaBase(options)}/${kind}/${id}/${hash}.png${size}`;
1946
+ }
1947
+ function cdnEmojiURL(emojiId, animated, options) {
1948
+ const ext = animated ? "gif" : "png";
1949
+ const size = appendSize(options, "emoji");
1950
+ return `${mediaBase(options)}/emojis/${emojiId}.${ext}${size}`;
1951
+ }
1952
+ function cdnStickerURL(stickerId, animated, options) {
1953
+ const ext = animated ? "gif" : "png";
1954
+ const size = appendSize(options, "sticker");
1955
+ return `${mediaBase(options)}/stickers/${stickerId}.${ext}${size}`;
1956
+ }
1957
+
1958
+ // src/Domain/Message/MessageSticker.ts
1959
+ var MessageSticker = class extends Base {
1852
1960
  client;
1853
- channelId;
1854
- options;
1855
- collected = new Collection5();
1856
- _timeout = null;
1857
- _ended = false;
1858
- _listener;
1859
- constructor(client, channelId, options = {}) {
1961
+ id;
1962
+ name;
1963
+ description;
1964
+ tags;
1965
+ animated;
1966
+ constructor(client, data) {
1860
1967
  super();
1861
- requireCollectorBounds(options);
1862
1968
  this.client = client;
1863
- this.channelId = channelId;
1864
- this.options = {
1865
- filter: options.filter ?? (() => true),
1866
- time: options.time ?? 0,
1867
- max: options.max ?? 0
1868
- };
1869
- this._listener = (message) => {
1870
- if (this._ended || message.channelId !== this.channelId) return;
1871
- if (!this.options.filter(message)) return;
1872
- this.collected.set(message.id, message);
1873
- this.emit("collect", message);
1874
- if (this.options.max > 0 && this.collected.size >= this.options.max) {
1875
- this.stop("limit");
1876
- }
1877
- };
1878
- this.client.on(Events.MessageCreate, this._listener);
1879
- if (this.options.time > 0) {
1880
- this._timeout = setTimeout(() => this.stop("time"), this.options.time);
1881
- }
1882
- }
1883
- stop(reason = "user") {
1884
- if (this._ended) return;
1885
- this._ended = true;
1886
- this.client.off(Events.MessageCreate, this._listener);
1887
- if (this._timeout) {
1888
- clearTimeout(this._timeout);
1889
- this._timeout = null;
1890
- }
1891
- this.emit("end", this.collected, reason);
1969
+ this.id = data.id;
1970
+ this.name = data.name;
1971
+ this.description = data.description ?? "";
1972
+ this.tags = data.tags ?? [];
1973
+ this.animated = data.animated ?? false;
1892
1974
  }
1893
- /**
1894
- * One-shot helper used by {@link Channel.awaitMessages}.
1895
- * Resolves with the collected messages when the collector ends for `user` (or when
1896
- * the end reason is not listed in `errors`).
1897
- * By default, `time` and `limit` reject with {@link FluxerError}
1898
- * (`CollectorIdle` / `CollectorMax`).
1899
- */
1900
- static awaitMessages(client, channelId, options) {
1901
- const errors = options?.errors ?? ["time", "limit"];
1902
- return new Promise((resolve, reject) => {
1903
- const collector = new _MessageCollector(client, channelId, options);
1904
- collector.on("end", (collected, reason) => {
1905
- if (!errors.includes(reason)) {
1906
- resolve(collected);
1907
- return;
1908
- }
1909
- if (reason === "time") {
1910
- reject(
1911
- new FluxerError("Message collector timed out", {
1912
- code: ErrorCodes.CollectorIdle
1913
- })
1914
- );
1915
- return;
1916
- }
1917
- if (reason === "limit") {
1918
- reject(
1919
- new FluxerError("Message collector reached max", {
1920
- code: ErrorCodes.CollectorMax
1921
- })
1922
- );
1923
- return;
1924
- }
1925
- reject(collected);
1926
- });
1975
+ /** CDN URL for this sticker image. */
1976
+ get url() {
1977
+ return cdnStickerURL(this.id, this.animated, {
1978
+ mediaBase: this.client.instance.endpoints.media
1927
1979
  });
1928
1980
  }
1929
- on(event, listener) {
1930
- return super.on(event, listener);
1981
+ /** Unix timestamp (ms) when this sticker was created, derived from its snowflake ID. */
1982
+ get createdTimestamp() {
1983
+ return SnowflakeUtil2.timestampFromSnowflake(this.id);
1931
1984
  }
1932
- emit(event, ...args) {
1933
- return super.emit(event, ...args);
1985
+ /** Date when this sticker was created, derived from its snowflake ID. */
1986
+ get createdAt() {
1987
+ return SnowflakeUtil2.dateFromSnowflake(this.id);
1934
1988
  }
1935
1989
  };
1936
1990
 
1937
- // src/Domain/Channel/Attachments.ts
1938
- import { Routes as Routes6 } from "@fluxerjs/types";
1939
- var BOT_ATTACHMENT_MAX_BYTES = 50 * 1024 * 1024;
1940
- var ATTACHMENT_MULTIPART_THRESHOLD_BYTES = 10 * 1024 * 1024;
1941
- function instanceLimitOverridesSnapshot(client) {
1942
- const rules = client.instance.discovery?.limits?.rules;
1943
- if (!rules?.length) return null;
1944
- const snapshot = {};
1945
- for (const rule of rules) {
1946
- Object.assign(snapshot, rule.overrides);
1947
- }
1948
- return Object.keys(snapshot).length ? snapshot : null;
1991
+ // src/Domain/Message/Reactions.ts
1992
+ import { Routes as Routes5 } from "@fluxerjs/types";
1993
+ async function emojiPath(message, emoji) {
1994
+ return message.client.resolveEmoji(emoji, message.guildId);
1949
1995
  }
1950
- function assertBotAttachmentLimits(client, files) {
1951
- const snapshot = instanceLimitOverridesSnapshot(client);
1952
- for (const file of files) {
1953
- const size = file.data.byteLength;
1954
- if (size <= BOT_ATTACHMENT_MAX_BYTES) continue;
1955
- const snapshotNote = snapshot ? ` Instance limit overrides: ${JSON.stringify(snapshot)}.` : "";
1956
- throw new FluxerError(
1957
- `Bot attachments are limited to 50 MiB (${BOT_ATTACHMENT_MAX_BYTES} bytes); "${file.filename}" is ${size} bytes.${snapshotNote}`,
1958
- { code: ErrorCodes.AttachmentTooLarge }
1959
- );
1960
- }
1996
+ async function reactToMessage(message, emoji) {
1997
+ const wire = await emojiPath(message, emoji);
1998
+ await message.client.rest.put(
1999
+ Routes5.channelMessageReactionMe(message.channelId, message.id, wire)
2000
+ );
1961
2001
  }
1962
- function asBytes(data) {
1963
- const src = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data);
1964
- const out = new Uint8Array(src.byteLength);
1965
- out.set(src);
1966
- return out;
2002
+ async function removeMessageReaction(message, emoji, userId) {
2003
+ const e = await emojiPath(message, emoji);
2004
+ const route = userId ? Routes5.channelMessageReactionUser(message.channelId, message.id, e, userId) : Routes5.channelMessageReactionMe(message.channelId, message.id, e);
2005
+ await message.client.rest.delete(route);
1967
2006
  }
1968
- async function putBlob(url, body, contentType) {
1969
- const res = await fetch(url, {
1970
- method: "PUT",
1971
- headers: contentType ? { "Content-Type": contentType } : void 0,
1972
- body
1973
- });
1974
- if (!res.ok) {
1975
- throw new FluxerError(`Presigned upload failed: ${res.status}`, {
1976
- code: ErrorCodes.AttachmentUploadFailed
1977
- });
2007
+ async function removeAllMessageReactions(message) {
2008
+ await message.client.rest.delete(Routes5.channelMessageReactions(message.channelId, message.id));
2009
+ }
2010
+ async function removeMessageReactionEmoji(message, emoji) {
2011
+ const e = await emojiPath(message, emoji);
2012
+ await message.client.rest.delete(Routes5.channelMessageReaction(message.channelId, message.id, e));
2013
+ }
2014
+ async function fetchMessageReactionUsers(message, emoji, options) {
2015
+ return (await fetchMessageReactionUsersPage(message, emoji, options)).users;
2016
+ }
2017
+ async function fetchMessageReactionUsersPage(message, emoji, options) {
2018
+ const e = await emojiPath(message, emoji);
2019
+ const params = new URLSearchParams();
2020
+ if (options?.limit != null) params.set("limit", String(options.limit));
2021
+ if (options?.after) params.set("after", options.after);
2022
+ const qs2 = params.toString();
2023
+ const route = Routes5.channelMessageReactionUsers(message.channelId, message.id, e) + (qs2 ? `?${qs2}` : "");
2024
+ const data = await message.client.rest.get(route);
2025
+ if (Array.isArray(data)) {
2026
+ return {
2027
+ users: data.map((u) => message.client.getOrCreateUser(u)),
2028
+ hasMore: false,
2029
+ nextAfter: null
2030
+ };
1978
2031
  }
2032
+ const list = data.items ?? data.users ?? [];
2033
+ return {
2034
+ users: list.map((u) => message.client.getOrCreateUser(u)),
2035
+ hasMore: data.has_more ?? false,
2036
+ nextAfter: data.next_after ?? null
2037
+ };
1979
2038
  }
1980
- async function uploadAttachmentsForSend(client, channelId, files) {
1981
- assertBotAttachmentLimits(client, files);
1982
- const plan = await client.rest.post(
1983
- Routes6.channelAttachments(channelId),
1984
- {
1985
- body: {
1986
- attachments: files.map((f) => ({
1987
- id: f.id,
1988
- filename: f.filename,
1989
- file_size: f.data.byteLength,
1990
- content_type: f.contentType
1991
- }))
1992
- },
1993
- auth: true
1994
- }
1995
- );
1996
- const multipart = [];
1997
- const uploaded = [];
1998
- for (const item of plan.attachments) {
1999
- const file = files.find((f) => f.id === item.id);
2000
- if (!file) {
2001
- throw new FluxerError(`No file data for planned attachment id ${item.id}`, {
2002
- code: ErrorCodes.InvalidAttachmentInput
2003
- });
2004
- }
2005
- const bytes = asBytes(file.data);
2006
- if (item.upload_mode === "singlepart") {
2007
- await putBlob(
2008
- item.upload_url,
2009
- new Blob([bytes], { type: file.contentType }),
2010
- item.content_type
2011
- );
2012
- } else {
2013
- for (const part of item.parts) {
2014
- const start = (part.part_number - 1) * item.part_size;
2015
- const chunk = bytes.subarray(start, Math.min(start + item.part_size, bytes.byteLength));
2016
- await putBlob(part.upload_url, new Blob([asBytes(chunk)]));
2017
- }
2018
- multipart.push({ upload_filename: item.upload_filename, upload_id: item.upload_id });
2019
- }
2020
- uploaded.push({
2021
- id: item.id,
2022
- filename: item.filename,
2023
- upload_filename: item.upload_filename,
2024
- file_size: item.file_size,
2025
- content_type: item.content_type
2026
- });
2039
+
2040
+ // src/Domain/Message/Send.ts
2041
+ import { MessagePayload as MessagePayloadBuilder } from "@fluxerjs/builders";
2042
+ import { Routes as Routes6 } from "@fluxerjs/types";
2043
+ function toReplyTarget(ref) {
2044
+ return {
2045
+ channelId: ref.channel_id,
2046
+ messageId: ref.message_id,
2047
+ ...ref.guild_id != null ? { guildId: ref.guild_id } : {}
2048
+ };
2049
+ }
2050
+ function toSendOptions(content) {
2051
+ if (typeof content === "string") return { content };
2052
+ if (content instanceof MessagePayloadBuilder) return messagePayloadToSendOptions(content);
2053
+ return { ...content };
2054
+ }
2055
+ async function createMessageBody(content, referenced_message, ping) {
2056
+ if (typeof content === "string" && content.length === 0) {
2057
+ throw new FluxerError("Cannot send an empty message", { code: ErrorCodes.EmptyMessage });
2027
2058
  }
2028
- if (multipart.length) {
2029
- await client.rest.post(Routes6.channelAttachmentsComplete(channelId), {
2030
- body: { uploads: multipart },
2031
- auth: true
2032
- });
2059
+ const opts = toSendOptions(content);
2060
+ if (referenced_message) {
2061
+ opts.replyTo = toReplyTarget(referenced_message);
2062
+ if (ping !== void 0) opts.ping = ping;
2033
2063
  }
2034
- return uploaded;
2064
+ return prepareMessagePostPayload(opts);
2065
+ }
2066
+ function asReplyTarget(value) {
2067
+ if ("messageId" in value) return value;
2068
+ return {
2069
+ channelId: value.channelId,
2070
+ messageId: value.id,
2071
+ guildId: value.guildId
2072
+ };
2073
+ }
2074
+ async function sendPrepared(message, payload) {
2075
+ const data = await message.client.rest.post(
2076
+ Routes6.channelMessages(message.channelId),
2077
+ payload
2078
+ );
2079
+ message.client._addMessageToCache(message.channelId, data);
2080
+ return new message.constructor(message.client, data);
2081
+ }
2082
+ async function sendMessage(message, options) {
2083
+ return message._send(
2084
+ await prepareMessagePostPayload(options, {
2085
+ defaultAllowedMentions: message.client.options.defaultAllowedMentions
2086
+ })
2087
+ );
2088
+ }
2089
+ async function sendMessageTo(message, channelId, options) {
2090
+ return message.client.channels.send(channelId, options);
2091
+ }
2092
+ async function replyToMessage(message, options, replyOptions) {
2093
+ const opts = typeof options === "string" ? { content: options } : { ...options };
2094
+ const { replyTo: inlineReplyTo, ping: inlinePing, ...sendOpts } = opts;
2095
+ const ping = replyOptions?.ping ?? inlinePing ?? message.client.options.defaultReplyPing;
2096
+ const replyTo = asReplyTarget(replyOptions?.replyTo ?? inlineReplyTo ?? message);
2097
+ return message._send(
2098
+ await prepareMessagePostPayload(
2099
+ { ...sendOpts, replyTo, ping },
2100
+ { defaultAllowedMentions: message.client.options.defaultAllowedMentions }
2101
+ )
2102
+ );
2035
2103
  }
2036
2104
 
2037
- // src/Domain/Channel/Base.ts
2038
- var Channel = class extends Base {
2039
- #messages;
2040
- /** The {@link Client} that instantiated this channel. */
2105
+ // src/Domain/Message/Message.ts
2106
+ function toMessageCall(data) {
2107
+ return {
2108
+ participants: data.participants,
2109
+ endedAt: data.ended_timestamp ? new Date(data.ended_timestamp) : null
2110
+ };
2111
+ }
2112
+ function toMessageSnapshot(client, data) {
2113
+ return {
2114
+ content: data.content ?? null,
2115
+ createdAt: new Date(data.timestamp),
2116
+ editedAt: data.edited_timestamp ? new Date(data.edited_timestamp) : null,
2117
+ mentionUserIds: data.mentions ?? [],
2118
+ mentionRoles: data.mention_roles ?? [],
2119
+ embeds: (data.embeds ?? []).map(toMessageEmbed),
2120
+ attachments: (data.attachments ?? []).map(toMessageAttachment),
2121
+ stickers: (data.stickers ?? []).map((s) => new MessageSticker(client, s)),
2122
+ ...data.type !== void 0 ? { type: data.type } : {}
2123
+ };
2124
+ }
2125
+ function resolveMessageFlags(flags) {
2126
+ if (flags === void 0) return void 0;
2127
+ if (typeof flags === "number") return flags;
2128
+ return Number(MessageFlagsBitField.resolve(flags));
2129
+ }
2130
+ var Message = class _Message extends Base {
2131
+ /** Discriminant vs {@link PartialMessage}: always `false` on a hydrated Message. */
2132
+ partial = false;
2133
+ /** The {@link Client} that instantiated this message. */
2041
2134
  client;
2042
- /** Snowflake ID of this channel. */
2135
+ /** Snowflake ID of this message. */
2043
2136
  id;
2044
- /** Channel type (text, voice, category, etc.). */
2137
+ /** Channel ID where this message was sent. */
2138
+ channelId;
2139
+ /** Guild ID if in a guild channel, null for DMs. */
2140
+ guildId;
2141
+ /** The user who sent this message. */
2142
+ author;
2143
+ /** Text content of the message. */
2144
+ content;
2145
+ /** When the message was created. */
2146
+ createdAt;
2147
+ /** When the message was last edited, or null if never edited. */
2148
+ editedAt;
2149
+ /** Whether the message is pinned. */
2150
+ pinned;
2151
+ /** Attached files (images, videos, etc.). */
2152
+ attachments;
2153
+ /** Message type (Default, Reply, etc.). */
2045
2154
  type;
2046
- /** Channel name (null for some channel types). */
2047
- name;
2048
- /** Channel icon hash (null for most channel types). */
2049
- icon;
2050
- /** ISO8601 timestamp of the last pinned message update. */
2051
- lastPinTimestamp;
2155
+ /** Message flags bitfield. */
2156
+ flags;
2157
+ /** Whether `@everyone` or `@here` was mentioned. */
2158
+ mentionEveryone;
2159
+ /** Whether this is a text-to-speech message. */
2160
+ tts;
2161
+ /** Embedded content (camelCase read view; send with {@link EmbedBuilder}). */
2162
+ embeds;
2163
+ /** Stickers sent with the message. */
2164
+ stickers;
2165
+ /** Reactions on the message. */
2166
+ reactions;
2167
+ /** Reference to a replied-to message, if any. */
2168
+ messageReference;
2169
+ /** Message snapshots for forwarded messages. */
2170
+ messageSnapshots;
2171
+ /** Call data if this message represents a call event. */
2172
+ call;
2173
+ /** The full referenced (replied-to) message, or null. */
2174
+ referencedMessage;
2175
+ /** Webhook ID if sent by a webhook. */
2176
+ webhookId;
2177
+ /** Users mentioned in the message. */
2178
+ mentions;
2179
+ /** Role IDs mentioned in the message. */
2180
+ mentionRoles;
2181
+ /** Client-side nonce for deduplication. */
2182
+ nonce;
2183
+ /** IDs of custom emojis in the message classified as explicit. */
2184
+ nsfwEmojis;
2185
+ /** Thread started from this message, when the payload included one. */
2186
+ thread;
2187
+ /**
2188
+ * Cached text-capable channel (guild text, guild voice, or DM), or null if uncached / not text-based.
2189
+ * Narrowed type has {@link Channel.send} and {@link Channel.delete}.
2190
+ */
2191
+ get channel() {
2192
+ const channel = this.client.channels.get(this.channelId) ?? null;
2193
+ return channel?.isTextBased() ? channel : null;
2194
+ }
2195
+ /** Cached guild, or null for DMs / uncached. */
2196
+ get guild() {
2197
+ return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
2198
+ }
2199
+ /** Cached guild member for the author, or null in DMs / if uncached. */
2200
+ get member() {
2201
+ return this.guild?.members.get(this.author.id) ?? null;
2202
+ }
2203
+ /**
2204
+ * Fetch this message's channel (cache first). The returned {@link Channel}
2205
+ * has {@link Channel.delete} and {@link Channel.send}.
2206
+ * @example
2207
+ * const channel = await message.resolveChannel();
2208
+ * await channel.delete();
2209
+ */
2210
+ async resolveChannel() {
2211
+ return this.client.channels.resolve(this.channelId);
2212
+ }
2213
+ /**
2214
+ * Fetch and resolve the guild, or null if a DM.
2215
+ * Propagates network/auth errors; only returns null when there is no guildId.
2216
+ * @example
2217
+ * const guild = await message.resolveGuild();
2218
+ */
2219
+ async resolveGuild() {
2220
+ if (!this.guildId) return null;
2221
+ return this.client.guilds.resolve(this.guildId);
2222
+ }
2223
+ /**
2224
+ * Construct a message from API data.
2225
+ * @param data - API message from REST or MESSAGE_CREATE
2226
+ */
2052
2227
  constructor(client, data) {
2053
2228
  super();
2054
2229
  this.client = client;
2055
2230
  this.id = data.id;
2056
- this.type = data.type;
2057
- this.name = data.name ?? null;
2058
- this.icon = data.icon ?? null;
2059
- this.lastPinTimestamp = data.last_pin_timestamp ?? null;
2231
+ this.channelId = data.channel_id;
2232
+ this.guildId = data.guild_id ?? null;
2233
+ this.author = client.getOrCreateUser(data.author);
2234
+ this.content = data.content;
2235
+ this.createdAt = new Date(data.timestamp);
2236
+ this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
2237
+ this.pinned = data.pinned;
2238
+ this.attachments = new Collection5();
2239
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
2240
+ this.type = data.type ?? MessageType.Default;
2241
+ this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
2242
+ this.mentionEveryone = data.mention_everyone ?? false;
2243
+ this.tts = data.tts ?? false;
2244
+ this.embeds = (data.embeds ?? []).map(toMessageEmbed);
2245
+ this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(client, s));
2246
+ this.reactions = new MessageReactionManager(this);
2247
+ this.reactions._patch(data.reactions);
2248
+ this.messageReference = data.message_reference ? {
2249
+ channelId: data.message_reference.channel_id,
2250
+ messageId: data.message_reference.message_id,
2251
+ guildId: data.message_reference.guild_id ?? null,
2252
+ ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
2253
+ } : null;
2254
+ this.messageSnapshots = (data.message_snapshots ?? []).map((s) => toMessageSnapshot(client, s));
2255
+ this.call = data.call ? toMessageCall(data.call) : null;
2256
+ this.referencedMessage = data.referenced_message ? new _Message(client, data.referenced_message) : null;
2257
+ this.webhookId = data.webhook_id ?? null;
2258
+ this.mentions = (data.mentions ?? []).map((u) => client.getOrCreateUser(u));
2259
+ this.mentionRoles = data.mention_roles ?? [];
2260
+ this.nonce = data.nonce ?? null;
2261
+ this.nsfwEmojis = data.nsfw_emojis ?? [];
2262
+ this.thread = data.thread ? cacheThread(client, data.thread) : null;
2060
2263
  }
2061
- /** Unix timestamp (ms) when this channel was created, derived from its snowflake ID. */
2062
- get createdTimestamp() {
2063
- return SnowflakeUtil3.timestampFromSnowflake(this.id);
2264
+ /**
2265
+ * Apply an API message payload in place (cache identity / MESSAGE_UPDATE).
2266
+ * @internal
2267
+ */
2268
+ _patch(data) {
2269
+ this.content = data.content;
2270
+ this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
2271
+ this.pinned = data.pinned;
2272
+ this.attachments.clear();
2273
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
2274
+ this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
2275
+ this.mentionEveryone = data.mention_everyone ?? false;
2276
+ this.tts = data.tts ?? false;
2277
+ this.embeds = (data.embeds ?? []).map(toMessageEmbed);
2278
+ this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(this.client, s));
2279
+ this.reactions._patch(data.reactions);
2280
+ this.messageReference = data.message_reference ? {
2281
+ channelId: data.message_reference.channel_id,
2282
+ messageId: data.message_reference.message_id,
2283
+ guildId: data.message_reference.guild_id ?? null,
2284
+ ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
2285
+ } : null;
2286
+ this.messageSnapshots = (data.message_snapshots ?? []).map(
2287
+ (s) => toMessageSnapshot(this.client, s)
2288
+ );
2289
+ this.call = data.call ? toMessageCall(data.call) : null;
2290
+ this.referencedMessage = data.referenced_message ? new _Message(this.client, data.referenced_message) : null;
2291
+ this.webhookId = data.webhook_id ?? null;
2292
+ this.mentions = (data.mentions ?? []).map((u) => this.client.getOrCreateUser(u));
2293
+ this.mentionRoles = data.mention_roles ?? [];
2294
+ this.nonce = data.nonce ?? null;
2295
+ this.nsfwEmojis = data.nsfw_emojis ?? [];
2296
+ if (data.thread) this.thread = cacheThread(this.client, data.thread);
2064
2297
  }
2065
- /** Date when this channel was created, derived from its snowflake ID. */
2066
- get createdAt() {
2067
- return SnowflakeUtil3.dateFromSnowflake(this.id);
2298
+ /**
2299
+ * Send a standalone message in this channel (not a reply).
2300
+ * Prefer {@link Channel.send} or {@link reply} when you already have the channel or are answering.
2301
+ */
2302
+ async send(options) {
2303
+ return sendMessage(this, options);
2068
2304
  }
2069
2305
  /**
2070
- * Apply shared channel fields in place (gateway CHANNEL_UPDATE when type is unchanged).
2071
- * @internal
2306
+ * Send a message to another channel by ID.
2307
+ * Prefer `client.channels.fetch(channelId)` then {@link Channel.send}.
2072
2308
  */
2073
- _patch(data) {
2074
- if (data.type !== void 0) this.type = data.type;
2075
- if (data.name !== void 0) this.name = data.name ?? null;
2076
- if (data.icon !== void 0) this.icon = data.icon ?? null;
2077
- if ("last_pin_timestamp" in data && data.last_pin_timestamp !== void 0) {
2078
- this.lastPinTimestamp = data.last_pin_timestamp ?? null;
2079
- }
2080
- }
2081
- /** @internal Factory wired after subclasses load. */
2082
- static from(_c, _d) {
2083
- throw new Error("Channel.from not initialized");
2084
- }
2085
- /** @internal Factory wired after subclasses load. */
2086
- static fromOrCreate(_c, _d) {
2087
- throw new Error("Channel.fromOrCreate not initialized");
2088
- }
2089
- /** @internal Factory wired after subclasses load. */
2090
- static createDM(_c, _d) {
2091
- throw new Error("Channel.createDM not initialized");
2309
+ async sendTo(channelId, options) {
2310
+ return sendMessageTo(this, channelId, options);
2092
2311
  }
2093
2312
  /**
2094
- * Whether this channel type can carry messages (text, announcement, voice, DM, group DM, notes).
2095
- * Checks {@link ChannelType}, not whether `send` exists on the instance.
2313
+ * Reply to this message.
2314
+ * @example
2315
+ * await message.reply('Pong!');
2316
+ * await message.reply('No ping!', { ping: false });
2317
+ * await message.reply({ content: 'Silent', allowedMentions: AllowedMentions.suppressReplyPing });
2096
2318
  */
2097
- isTextBased() {
2098
- 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;
2099
- }
2100
- /** Check if this is a guild channel (text, announcement, voice, category, or link). */
2101
- isGuild() {
2102
- return this.type === ChannelType.GuildText || this.type === ChannelType.GuildAnnouncement || this.type === ChannelType.GuildVoice || this.type === ChannelType.GuildCategory || this.type === ChannelType.GuildLink;
2103
- }
2104
- /** Check if this is a guild text channel. */
2105
- isText() {
2106
- return this.type === ChannelType.GuildText;
2107
- }
2108
- /** Check if this is a guild announcement channel. */
2109
- isAnnouncement() {
2110
- return this.type === ChannelType.GuildAnnouncement;
2111
- }
2112
- /** Check if this is a category channel. */
2113
- isCategory() {
2114
- return this.type === ChannelType.GuildCategory;
2115
- }
2116
- /** Check if this is a DM, group DM, or personal notes channel. */
2117
- isDM() {
2118
- return this.type === ChannelType.DM || this.type === ChannelType.GroupDM || this.type === ChannelType.DMPersonalNotes;
2319
+ async reply(options, replyOptions) {
2320
+ return replyToMessage(this, options, replyOptions);
2119
2321
  }
2120
- /** Check if this is a personal notes channel. */
2121
- isPersonalNotes() {
2122
- return this.type === ChannelType.DMPersonalNotes;
2322
+ /**
2323
+ * Hydrate a partial message, or return the message as-is.
2324
+ * @example
2325
+ * client.on(Events.MessageUpdate, async (_old, msg) => {
2326
+ * const message = await Message.resolve(msg);
2327
+ * });
2328
+ */
2329
+ static async resolve(message) {
2330
+ return message.partial ? message.fetch() : message;
2123
2331
  }
2124
- /** Check if this is a voice channel. */
2125
- isVoice() {
2126
- return this.type === ChannelType.GuildVoice;
2332
+ /** Test helper — prefer {@link reply} / `prepareMessagePostPayload()`. */
2333
+ static async _createMessageBody(content, referenced_message, ping) {
2334
+ return createMessageBody(content, referenced_message, ping);
2127
2335
  }
2128
- /** Check if this is a link channel. */
2129
- isLink() {
2130
- return this.type === ChannelType.GuildLink;
2336
+ /** Send a prepared payload (internal helper). */
2337
+ async _send(payload) {
2338
+ return sendPrepared(this, payload);
2131
2339
  }
2132
- /**
2133
- * Delete recent messages or an explicit ID list.
2134
- * - `bulkDelete(5)` — fetch last 5 via {@link MessageManager} then delete (1–100)
2135
- * - `bulkDelete(['id1'])` — single DELETE; 2–100 uses bulk-delete route
2136
- */
2137
- async bulkDelete(countOrIds) {
2138
- let ids;
2139
- if (typeof countOrIds === "number") {
2140
- if (!Number.isInteger(countOrIds) || countOrIds < 1 || countOrIds > 100) {
2141
- throw new FluxerError("bulkDelete count must be between 1 and 100", {
2142
- code: ErrorCodes.InvalidBulkDelete
2143
- });
2144
- }
2145
- ids = [
2146
- ...(await new MessageManager(this.client, this.id).fetch({ limit: countOrIds })).keys()
2147
- ];
2148
- } else {
2149
- ids = [...countOrIds];
2340
+ /** Edit this message (requires author or admin permissions). */
2341
+ async edit(options) {
2342
+ const body = {};
2343
+ if (options.content !== void 0) body.content = options.content;
2344
+ if (options.embeds !== void 0) {
2345
+ body.embeds = options.embeds.map(
2346
+ (e) => e instanceof EmbedBuilder2 ? e.toJSON() : e
2347
+ );
2150
2348
  }
2151
- if (ids.length === 0) return [];
2152
- if (ids.length === 1) {
2153
- await this.client.rest.delete(Routes7.channelMessage(this.id, ids[0]), { auth: true });
2154
- this.client._removeMessageFromCache(this.id, ids[0]);
2155
- return ids;
2349
+ if (options.allowedMentions) {
2350
+ body.allowed_mentions = toAPIAllowedMentions(options.allowedMentions);
2156
2351
  }
2157
- if (ids.length > 100) {
2158
- throw new FluxerError("bulkDelete requires at most 100 message IDs", {
2159
- code: ErrorCodes.InvalidBulkDelete
2160
- });
2352
+ const flags = resolveMessageFlags(options.flags);
2353
+ if (flags !== void 0) body.flags = flags;
2354
+ if (options.attachments !== void 0) {
2355
+ body.attachments = toMessageAttachmentEditWire(options.attachments);
2161
2356
  }
2162
- await this.client.rest.post(Routes7.channelBulkDelete(this.id), {
2163
- body: { message_ids: ids },
2164
- auth: true
2357
+ const data = await this.client.rest.patch(Routes7.channelMessage(this.channelId, this.id), {
2358
+ body
2165
2359
  });
2166
- for (const id of ids) this.client._removeMessageFromCache(this.id, id);
2167
- return ids;
2360
+ const updated = new _Message(this.client, data);
2361
+ this.client._addMessageToCache(this.channelId, data);
2362
+ return updated;
2168
2363
  }
2169
- /** Delete all messages sent by the bot in this channel. Sudo auto-passes for bots. */
2170
- async bulkDeleteMyMessages(options) {
2171
- const body = options ? toSudoBody(options) : void 0;
2172
- await this.client.rest.post(Routes7.channelBulkDeleteMine(this.id), {
2173
- body: body && Object.keys(body).length ? body : void 0,
2174
- auth: true
2175
- });
2364
+ /** Create a {@link ReactionCollector} for this message. */
2365
+ createReactionCollector(options) {
2366
+ return new ReactionCollector(this.client, this.id, this.channelId, options);
2176
2367
  }
2177
2368
  /**
2178
- * Mark all pinned messages as read in this channel.
2179
- * Session-token helper; bots usually skip this.
2369
+ * Wait for reactions matching the filter, then resolve the collected set.
2370
+ * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
2180
2371
  */
2181
- async acknowledgePins() {
2182
- await this.client.rest.post(Routes7.channelPinsAck(this.id), { auth: true });
2372
+ awaitReactions(options) {
2373
+ return ReactionCollector.awaitReactions(this.client, this.id, this.channelId, options);
2183
2374
  }
2184
2375
  /**
2185
- * Clear the read state for this channel.
2186
- * Session-token helper; bots usually skip this.
2376
+ * Start a thread from this message.
2377
+ * Fluxer chooses a public or announcement thread from the parent channel.
2187
2378
  */
2188
- async clearReadState() {
2189
- await this.client.rest.delete(Routes7.channelMessagesAck(this.id), { auth: true });
2190
- }
2191
- /** Request upload URLs for attachments before sending a message. */
2192
- async requestAttachmentUploads(attachments) {
2193
- const data = await this.client.rest.post(
2194
- Routes7.channelAttachments(this.id),
2195
- {
2196
- body: toAttachmentUploadPlanBody(attachments),
2197
- auth: true
2198
- }
2199
- );
2200
- return toAttachmentUploadPlanResponse(data);
2201
- }
2202
- /** Complete the attachment upload flow after uploading to the CDN. */
2203
- async completeAttachmentUploads(uploads) {
2379
+ async startThread(options) {
2204
2380
  const data = await this.client.rest.post(
2205
- Routes7.channelAttachmentsComplete(this.id),
2381
+ Routes7.channelMessageThreads(this.channelId, this.id),
2206
2382
  {
2207
- body: toAttachmentUploadCompleteBody(uploads),
2208
- auth: true
2383
+ body: toStartThreadFromMessageBody(options),
2384
+ auth: true,
2385
+ ...auditReasonHeaders(options.reason)
2209
2386
  }
2210
2387
  );
2211
- return {
2212
- uploads: data.uploads.map((u) => ({ uploadFilename: u.upload_filename }))
2213
- };
2214
- }
2215
- /** Upload files for sending in a message (helper). */
2216
- async uploadAttachmentsForSend(files) {
2217
- return uploadAttachmentsForSend(this.client, this.id, files);
2388
+ const thread = cacheThread(this.client, data);
2389
+ this.thread = thread;
2390
+ return thread;
2218
2391
  }
2219
- /** Trigger the typing indicator in this channel. */
2220
- async sendTyping() {
2221
- await this.client.rest.post(Routes7.channelTyping(this.id), { auth: true });
2392
+ /** Fetch the latest version of this message from the API. */
2393
+ async fetch() {
2394
+ return this.client.channels.fetchMessage(this.channelId, this.id);
2222
2395
  }
2223
- /**
2224
- * Fetch available RTC regions for voice channels.
2225
- * User-account only (`DefaultUserOnly`); bots receive `AccessDeniedError`.
2226
- * Bots should skip this and join voice with `@fluxerjs/voice` instead.
2227
- */
2228
- async fetchRtcRegions() {
2229
- const data = await this.client.rest.get(Routes7.channelRtcRegions(this.id), {
2230
- auth: true
2396
+ /** Delete this message. */
2397
+ async delete(reason) {
2398
+ await this.client.rest.delete(Routes7.channelMessage(this.channelId, this.id), {
2399
+ ...auditReasonHeaders(reason)
2231
2400
  });
2232
- return data.map((r) => ({ id: r.id, name: r.name, emoji: r.emoji }));
2401
+ this.client._removeMessageFromCache(this.channelId, this.id);
2233
2402
  }
2234
- /** Fetch slowmode state for this channel. */
2235
- async fetchSlowmode() {
2236
- const data = await this.client.rest.get(
2237
- Routes7.channelSlowmode(this.id),
2403
+ /** Delete a specific attachment from this message. */
2404
+ async deleteAttachment(attachmentId) {
2405
+ await this.client.rest.delete(
2406
+ Routes7.channelMessageAttachment(this.channelId, this.id, attachmentId),
2238
2407
  { auth: true }
2239
2408
  );
2240
- return {
2241
- rateLimitPerUser: data.rate_limit_per_user,
2242
- retryAfterMs: data.retry_after_ms,
2243
- nextSendAllowedAt: data.next_send_allowed_at
2244
- };
2409
+ this.attachments.delete(attachmentId);
2245
2410
  }
2246
- /** Whether this channel type can carry messages (does not check permissions). */
2247
- canSendMessage() {
2248
- return this.isTextBased();
2411
+ /** Pin this message in the channel. */
2412
+ async pin() {
2413
+ await this.client.rest.put(Routes7.channelPinMessage(this.channelId, this.id));
2414
+ this.pinned = true;
2249
2415
  }
2250
- /** Per-channel message cache + fetch. */
2251
- get messages() {
2252
- if (!this.#messages) {
2253
- this.#messages = new MessageManager(this.client, this.id);
2254
- }
2255
- return this.#messages;
2416
+ /** Unpin this message from the channel. */
2417
+ async unpin() {
2418
+ await this.client.rest.delete(Routes7.channelPinMessage(this.channelId, this.id));
2419
+ this.pinned = false;
2256
2420
  }
2257
- /** Collect messages in this channel until time/max/stop. */
2258
- createMessageCollector(options) {
2259
- return new MessageCollector(this.client, this.id, options);
2421
+ /** React to this message with an emoji. */
2422
+ async react(emoji) {
2423
+ return reactToMessage(this, emoji);
2424
+ }
2425
+ /** Remove a reaction (bot's own or a user's if ID is provided). */
2426
+ async removeReaction(emoji, userId) {
2427
+ return removeMessageReaction(this, emoji, userId);
2428
+ }
2429
+ /** Remove all reactions from this message. */
2430
+ async removeAllReactions() {
2431
+ return removeAllMessageReactions(this);
2432
+ }
2433
+ /** Remove all reactions of a specific emoji. */
2434
+ async removeReactionEmoji(emoji) {
2435
+ return removeMessageReactionEmoji(this, emoji);
2436
+ }
2437
+ /** Fetch users who reacted with a specific emoji. */
2438
+ async fetchReactionUsers(emoji, options) {
2439
+ return fetchMessageReactionUsers(this, emoji, options);
2440
+ }
2441
+ /** Fetch reaction users with pagination metadata. */
2442
+ async fetchReactionUsersPage(emoji, options) {
2443
+ return fetchMessageReactionUsersPage(this, emoji, options);
2444
+ }
2445
+ };
2446
+
2447
+ // src/Domain/Message/PartialMessage.ts
2448
+ import { SnowflakeUtil as SnowflakeUtil3 } from "@fluxerjs/util";
2449
+ var PartialMessage = class {
2450
+ partial = true;
2451
+ client;
2452
+ id;
2453
+ channelId;
2454
+ guildId;
2455
+ content;
2456
+ authorId;
2457
+ author;
2458
+ createdAt;
2459
+ constructor(client, data) {
2460
+ this.client = client;
2461
+ this.id = data.id;
2462
+ this.channelId = data.channelId;
2463
+ this.guildId = data.guildId ?? null;
2464
+ this.content = data.content ?? null;
2465
+ this.authorId = data.authorId ?? null;
2466
+ this.author = data.author ?? null;
2467
+ this.createdAt = data.createdAt ?? (SnowflakeUtil3.isValid(data.id) ? SnowflakeUtil3.dateFromSnowflake(data.id) : null);
2468
+ }
2469
+ /**
2470
+ * Live text-capable channel from cache, or null if uncached / not text-based.
2471
+ * Same contract as {@link Message.channel}.
2472
+ */
2473
+ get channel() {
2474
+ const channel = this.client.channels.get(this.channelId) ?? null;
2475
+ return channel?.isTextBased() ? channel : null;
2260
2476
  }
2261
2477
  /**
2262
- * Wait for messages matching the filter, then resolve the collected set.
2263
- * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
2478
+ * Fetch this message's channel (cache first). The returned {@link Channel}
2479
+ * has {@link Channel.delete} and {@link Channel.send}.
2264
2480
  * @example
2265
- * const collected = await channel.awaitMessages({ max: 1, time: 15_000 });
2481
+ * const channel = await message.resolveChannel();
2482
+ * await channel.delete();
2266
2483
  */
2267
- awaitMessages(options) {
2268
- return MessageCollector.awaitMessages(this.client, this.id, options);
2484
+ async resolveChannel() {
2485
+ return this.client.channels.resolve(this.channelId);
2269
2486
  }
2270
2487
  /**
2271
- * Delete this channel (or close it if it is a DM).
2272
- * Guild channels require Manage Channels. `silent` / `deleteMessages` are Fluxer query params.
2488
+ * Fetch the full message from the API.
2273
2489
  * @example
2274
- * const channel = await client.channels.fetch(channelId);
2275
- * await channel.delete();
2490
+ * const message = await partial.fetch();
2491
+ * await message.reply('Pong!');
2276
2492
  */
2277
- async delete(options) {
2278
- const params = new URLSearchParams();
2279
- if (options?.silent) params.set("silent", "true");
2280
- if (options?.deleteMessages) params.set("delete_messages", "true");
2281
- const qs2 = params.toString();
2282
- const { silent: _s, deleteMessages: _d, reason: _reason, ...sudo } = options ?? {};
2283
- const body = Object.keys(sudo).length ? toSudoBody(sudo) : void 0;
2284
- await this.client.rest.delete(Routes7.channel(this.id) + (qs2 ? `?${qs2}` : ""), {
2285
- body,
2286
- auth: true,
2287
- ...auditReasonHeaders(_reason)
2288
- });
2289
- this.client.channels.delete(this.id);
2290
- this.client._clearMessageCache(this.id);
2291
- if (this.isGuild() && this.guildId) {
2292
- this.client.guilds.get(this.guildId)?.channels.delete(this.id);
2293
- }
2294
- }
2295
- /** Channel mention (`<#id>`). */
2296
- toString() {
2297
- return `<#${this.id}>`;
2493
+ async fetch() {
2494
+ return this.client.channels.fetchMessage(this.channelId, this.id);
2298
2495
  }
2299
2496
  };
2300
2497
 
2498
+ // src/Domain/User.ts
2499
+ import { Routes as Routes17 } from "@fluxerjs/types";
2500
+ import { SnowflakeUtil as SnowflakeUtil5 } from "@fluxerjs/util";
2501
+
2301
2502
  // src/Domain/Channel/Dm.ts
2302
- import { ChannelType as ChannelType2, Routes as Routes9 } from "@fluxerjs/types";
2503
+ import { ChannelType as ChannelType4, Routes as Routes9 } from "@fluxerjs/types";
2303
2504
 
2304
2505
  // src/Domain/Channel/TextCapable.ts
2305
2506
  import { Routes as Routes8 } from "@fluxerjs/types";
@@ -2391,7 +2592,7 @@ var DMChannel = class extends TextCapable(Channel) {
2391
2592
  * Notes-only; bots usually skip this.
2392
2593
  */
2393
2594
  async purgeMessages() {
2394
- if (this.type !== ChannelType2.DMPersonalNotes) {
2595
+ if (this.type !== ChannelType4.DMPersonalNotes) {
2395
2596
  throw new FluxerError("purgeMessages is only available on personal notes channels", {
2396
2597
  code: ErrorCodes.InvalidChannelType
2397
2598
  });
@@ -2434,6 +2635,12 @@ var DMChannel = class extends TextCapable(Channel) {
2434
2635
  }
2435
2636
  };
2436
2637
 
2638
+ // src/Domain/Channel/Forum.ts
2639
+ import {
2640
+ ChannelType as ChannelType7,
2641
+ Routes as Routes16
2642
+ } from "@fluxerjs/types";
2643
+
2437
2644
  // src/Domain/Channel/Guild.ts
2438
2645
  import { Routes as Routes13 } from "@fluxerjs/types";
2439
2646
  import { PermissionFlags } from "@fluxerjs/util";
@@ -2745,7 +2952,8 @@ var Invite = class _Invite extends Base {
2745
2952
  // src/Domain/Webhook.ts
2746
2953
  import { EmbedBuilder as EmbedBuilder3 } from "@fluxerjs/builders";
2747
2954
  import {
2748
- Routes as Routes11
2955
+ Routes as Routes11,
2956
+ WebhookType
2749
2957
  } from "@fluxerjs/types";
2750
2958
  import { SnowflakeUtil as SnowflakeUtil4 } from "@fluxerjs/util";
2751
2959
  var Webhook = class _Webhook extends Base {
@@ -2765,6 +2973,8 @@ var Webhook = class _Webhook extends Base {
2765
2973
  token;
2766
2974
  /** The user that created this webhook. */
2767
2975
  user;
2976
+ /** Incoming or channel-follower webhook. */
2977
+ type;
2768
2978
  constructor(client, data) {
2769
2979
  super();
2770
2980
  this.client = client;
@@ -2775,6 +2985,7 @@ var Webhook = class _Webhook extends Base {
2775
2985
  this.avatar = data.avatar ?? null;
2776
2986
  this.token = data.token ?? null;
2777
2987
  this.user = client.getOrCreateUser(data.user);
2988
+ this.type = data.type ?? WebhookType.Incoming;
2778
2989
  }
2779
2990
  avatarURL(options) {
2780
2991
  return cdnAvatarURL(this.id, this.avatar, {
@@ -2885,6 +3096,7 @@ var Webhook = class _Webhook extends Base {
2885
3096
  name: options?.name ?? "Webhook",
2886
3097
  avatar: null,
2887
3098
  token,
3099
+ type: WebhookType.Incoming,
2888
3100
  user: {
2889
3101
  id: "",
2890
3102
  username: "webhook",
@@ -3004,6 +3216,23 @@ var PermissionOverwriteManager = class {
3004
3216
  }
3005
3217
  };
3006
3218
 
3219
+ // src/Domain/Channel/ThreadBind.ts
3220
+ var factory;
3221
+ var managers = /* @__PURE__ */ new WeakMap();
3222
+ function bindThreadManager(next) {
3223
+ factory = next;
3224
+ }
3225
+ function threadManagerFor(channel) {
3226
+ const existing = managers.get(channel);
3227
+ if (existing) return existing;
3228
+ if (!factory) {
3229
+ throw new Error("ThreadManager is not initialized");
3230
+ }
3231
+ const created = factory(channel);
3232
+ managers.set(channel, created);
3233
+ return created;
3234
+ }
3235
+
3007
3236
  // src/Domain/Channel/Guild.ts
3008
3237
  var GuildChannel = class extends Channel {
3009
3238
  /** Guild ID this channel belongs to, or null if missing from the payload. */
@@ -3124,6 +3353,93 @@ var TextChannel = class extends TextCapable(GuildChannel) {
3124
3353
  contentWarningLevel;
3125
3354
  /** Custom content warning text. */
3126
3355
  contentWarningText;
3356
+ /** Default auto-archive duration in minutes for new threads. */
3357
+ defaultAutoArchiveDuration;
3358
+ /** Slowmode in seconds copied onto new threads. */
3359
+ defaultThreadRateLimitPerUser;
3360
+ constructor(client, data) {
3361
+ super(client, data);
3362
+ this.topic = data.topic ?? null;
3363
+ this.nsfw = data.nsfw ?? false;
3364
+ this.nsfwOverride = data.nsfw_override ?? null;
3365
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3366
+ this.lastMessageId = data.last_message_id ?? null;
3367
+ this.contentWarningLevel = data.content_warning_level ?? null;
3368
+ this.contentWarningText = data.content_warning_text ?? null;
3369
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3370
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3371
+ }
3372
+ /** Create, list, and search threads in this channel. */
3373
+ get threads() {
3374
+ return threadManagerFor(this);
3375
+ }
3376
+ /**
3377
+ * Set slowmode (seconds between messages). Pass `0` to disable.
3378
+ * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3379
+ */
3380
+ async setSlowmode(seconds) {
3381
+ return this.edit({ rateLimitPerUser: seconds });
3382
+ }
3383
+ applyEditPatch(data) {
3384
+ if ("topic" in data) this.topic = data.topic ?? null;
3385
+ if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3386
+ if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
3387
+ if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3388
+ if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3389
+ if ("content_warning_level" in data) {
3390
+ this.contentWarningLevel = data.content_warning_level ?? null;
3391
+ }
3392
+ if ("content_warning_text" in data) {
3393
+ this.contentWarningText = data.content_warning_text ?? null;
3394
+ }
3395
+ if ("default_auto_archive_duration" in data) {
3396
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3397
+ }
3398
+ if ("default_thread_rate_limit_per_user" in data) {
3399
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3400
+ }
3401
+ }
3402
+ /**
3403
+ * Set the auto-archive and slowmode defaults copied onto new threads.
3404
+ * Sends only those fields. The thread-parent update body does not accept a channel rename.
3405
+ */
3406
+ async editThreadDefaults(options) {
3407
+ const data = await this.client.rest.patch(Routes13.channel(this.id), {
3408
+ body: toThreadParentEditBody(options),
3409
+ auth: true,
3410
+ ...auditReasonHeaders(options.reason)
3411
+ });
3412
+ this._patch(data);
3413
+ return this;
3414
+ }
3415
+ };
3416
+ var AnnouncementChannel = class extends TextChannel {
3417
+ };
3418
+ var CategoryChannel = class extends GuildChannel {
3419
+ };
3420
+ var VoiceChannel = class extends TextCapable(GuildChannel) {
3421
+ /** Channel topic. */
3422
+ topic;
3423
+ /** Whether this channel is marked as NSFW. */
3424
+ nsfw;
3425
+ /** Per-channel NSFW override (`null` inherits). */
3426
+ nsfwOverride;
3427
+ /** Slowmode rate limit in seconds. */
3428
+ rateLimitPerUser;
3429
+ /** ID of the last message sent in this channel. */
3430
+ lastMessageId;
3431
+ /** Content warning level. */
3432
+ contentWarningLevel;
3433
+ /** Custom content warning text. */
3434
+ contentWarningText;
3435
+ /** Voice bitrate. */
3436
+ bitrate;
3437
+ /** Maximum number of users allowed. */
3438
+ userLimit;
3439
+ /** Max active voice connections per user. */
3440
+ voiceConnectionLimit;
3441
+ /** RTC region override for this channel. */
3442
+ rtcRegion;
3127
3443
  constructor(client, data) {
3128
3444
  super(client, data);
3129
3445
  this.topic = data.topic ?? null;
@@ -3133,128 +3449,566 @@ var TextChannel = class extends TextCapable(GuildChannel) {
3133
3449
  this.lastMessageId = data.last_message_id ?? null;
3134
3450
  this.contentWarningLevel = data.content_warning_level ?? null;
3135
3451
  this.contentWarningText = data.content_warning_text ?? null;
3452
+ this.bitrate = data.bitrate ?? null;
3453
+ this.userLimit = data.user_limit ?? null;
3454
+ this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3455
+ this.rtcRegion = data.rtc_region ?? null;
3456
+ }
3457
+ /**
3458
+ * Set slowmode (seconds between messages). Pass `0` to disable.
3459
+ * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3460
+ */
3461
+ async setSlowmode(seconds) {
3462
+ return this.edit({ rateLimitPerUser: seconds });
3463
+ }
3464
+ applyEditPatch(data) {
3465
+ if ("topic" in data) this.topic = data.topic ?? null;
3466
+ if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3467
+ if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
3468
+ if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3469
+ if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3470
+ if ("content_warning_level" in data) {
3471
+ this.contentWarningLevel = data.content_warning_level ?? null;
3472
+ }
3473
+ if ("content_warning_text" in data) {
3474
+ this.contentWarningText = data.content_warning_text ?? null;
3475
+ }
3476
+ if ("bitrate" in data) this.bitrate = data.bitrate ?? null;
3477
+ if ("user_limit" in data) this.userLimit = data.user_limit ?? null;
3478
+ if ("voice_connection_limit" in data) {
3479
+ this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3480
+ }
3481
+ if ("rtc_region" in data) this.rtcRegion = data.rtc_region ?? null;
3482
+ }
3483
+ };
3484
+ var LinkChannel = class extends GuildChannel {
3485
+ /** External URL this channel links to. */
3486
+ url;
3487
+ constructor(client, data) {
3488
+ super(client, data);
3489
+ this.url = data.url ?? null;
3490
+ }
3491
+ applyEditPatch(data) {
3492
+ if ("url" in data) this.url = data.url ?? null;
3493
+ }
3494
+ };
3495
+
3496
+ // src/Domain/Channel/ThreadManager.ts
3497
+ import { ChannelType as ChannelType6, Routes as Routes15 } from "@fluxerjs/types";
3498
+
3499
+ // src/Domain/Channel/ThreadChannel.ts
3500
+ import { ChannelType as ChannelType5, Routes as Routes14 } from "@fluxerjs/types";
3501
+ var ThreadMember = class {
3502
+ /** Thread ID. */
3503
+ id;
3504
+ /** User ID. */
3505
+ userId;
3506
+ /** When the user last joined the thread. */
3507
+ joinedAt;
3508
+ /** Thread member flags bitfield. */
3509
+ flags;
3510
+ /** Whether the current user has muted the thread. */
3511
+ muted;
3512
+ /** ISO-8601 timestamp when the mute expires, if set. */
3513
+ muteEndTime;
3514
+ /** Selected mute duration in seconds, if set. */
3515
+ muteWindow;
3516
+ constructor(data) {
3517
+ this.id = data.id ?? null;
3518
+ this.userId = data.user_id ?? data.member?.user?.id ?? null;
3519
+ this.joinedAt = new Date(data.join_timestamp);
3520
+ this.flags = data.flags;
3521
+ this.muted = data.muted ?? null;
3522
+ this.muteEndTime = data.mute_config?.end_time ?? null;
3523
+ this.muteWindow = data.mute_config?.selected_time_window ?? null;
3524
+ }
3525
+ };
3526
+ function threadEditFields(options) {
3527
+ const source = options;
3528
+ return {
3529
+ name: typeof source.name === "string" ? source.name : void 0,
3530
+ archived: source.archived,
3531
+ autoArchiveDuration: source.autoArchiveDuration,
3532
+ locked: source.locked,
3533
+ rateLimitPerUser: source.rateLimitPerUser,
3534
+ flags: source.flags,
3535
+ appliedTags: source.appliedTags,
3536
+ invitable: source.invitable,
3537
+ reason: source.reason
3538
+ };
3539
+ }
3540
+ function readMetadata(data) {
3541
+ return {
3542
+ archived: data?.archived ?? false,
3543
+ autoArchiveDuration: data?.auto_archive_duration ?? 0,
3544
+ archiveTimestamp: data?.archive_timestamp ?? null,
3545
+ locked: data?.locked ?? false,
3546
+ invitable: data?.invitable ?? null
3547
+ };
3548
+ }
3549
+ var ThreadChannel = class extends TextCapable(GuildChannel) {
3550
+ /** User who created the thread. */
3551
+ ownerId;
3552
+ /** Whether the thread is archived. */
3553
+ archived;
3554
+ /** Minutes of inactivity before the thread archives. */
3555
+ autoArchiveDuration;
3556
+ /** ISO-8601 timestamp when the archive status last changed. */
3557
+ archiveTimestamp;
3558
+ /** Whether only moderators can unarchive the thread. */
3559
+ locked;
3560
+ /** Whether non-moderators can add other non-moderators. Private threads only. */
3561
+ invitable;
3562
+ /** Slowmode in seconds. */
3563
+ rateLimitPerUser;
3564
+ /** ID of the last message sent in this thread. */
3565
+ lastMessageId;
3566
+ /** Messages in the thread, excluding the starter and deleted messages. */
3567
+ messageCount;
3568
+ /** Messages ever sent in the thread. This count is never decremented. */
3569
+ totalMessageSent;
3570
+ /** Approximate member count, capped at 50. */
3571
+ memberCount;
3572
+ /** Tag IDs applied to a forum or media post. */
3573
+ appliedTags;
3574
+ /** Channel flags bitfield. */
3575
+ flags;
3576
+ /** The current user's membership, when the payload included it. */
3577
+ member;
3578
+ /** Add, remove, and list members of this thread. */
3579
+ members;
3580
+ constructor(client, data) {
3581
+ super(client, data);
3582
+ const metadata = readMetadata(data.thread_metadata);
3583
+ this.ownerId = data.owner_id ?? null;
3584
+ this.archived = metadata.archived;
3585
+ this.autoArchiveDuration = metadata.autoArchiveDuration;
3586
+ this.archiveTimestamp = metadata.archiveTimestamp;
3587
+ this.locked = metadata.locked;
3588
+ this.invitable = metadata.invitable;
3589
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3590
+ this.lastMessageId = data.last_message_id ?? null;
3591
+ this.messageCount = data.message_count ?? 0;
3592
+ this.totalMessageSent = data.total_message_sent ?? 0;
3593
+ this.memberCount = data.member_count ?? 0;
3594
+ this.appliedTags = data.applied_tags ?? [];
3595
+ this.flags = data.flags ?? 0;
3596
+ this.member = data.member ? new ThreadMember(data.member) : null;
3597
+ this.members = new ThreadMemberManager(this);
3598
+ }
3599
+ /** @internal */
3600
+ _patch(data) {
3601
+ super._patch(data);
3602
+ if (data.owner_id !== void 0) this.ownerId = data.owner_id ?? null;
3603
+ if (data.thread_metadata) {
3604
+ const metadata = readMetadata(data.thread_metadata);
3605
+ this.archived = metadata.archived;
3606
+ this.autoArchiveDuration = metadata.autoArchiveDuration;
3607
+ this.archiveTimestamp = metadata.archiveTimestamp;
3608
+ this.locked = metadata.locked;
3609
+ this.invitable = metadata.invitable;
3610
+ }
3611
+ if ("rate_limit_per_user" in data && data.rate_limit_per_user !== void 0) {
3612
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3613
+ }
3614
+ if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3615
+ if (data.message_count !== void 0) this.messageCount = data.message_count;
3616
+ if (data.total_message_sent !== void 0) this.totalMessageSent = data.total_message_sent;
3617
+ if (data.member_count !== void 0) this.memberCount = data.member_count;
3618
+ if (data.applied_tags !== void 0) this.appliedTags = data.applied_tags ?? [];
3619
+ if (data.flags !== void 0) this.flags = data.flags;
3620
+ if (data.member !== void 0) this.member = data.member ? new ThreadMember(data.member) : null;
3621
+ }
3622
+ /**
3623
+ * Edit this thread. Requires Manage Threads on public threads, or ownership on private ones.
3624
+ * `appliedTags` is sent for public and announcement threads. `invitable` is sent for private threads.
3625
+ */
3626
+ async edit(options) {
3627
+ const data = await this.client.rest.patch(Routes14.channel(this.id), {
3628
+ body: toThreadEditBody(this.type, threadEditFields(options)),
3629
+ auth: true,
3630
+ ...auditReasonHeaders(options.reason)
3631
+ });
3632
+ this._patch(data);
3633
+ return this;
3634
+ }
3635
+ /** Archive or unarchive this thread. */
3636
+ async setArchived(archived, reason) {
3637
+ return this.edit({ archived, reason });
3638
+ }
3639
+ /** Lock or unlock this thread. Locked threads can only be unarchived by moderators. */
3640
+ async setLocked(locked, reason) {
3641
+ return this.edit({ locked, reason });
3642
+ }
3643
+ /** Join this thread. */
3644
+ async join() {
3645
+ await this.client.rest.put(Routes14.channelThreadMemberMe(this.id), { auth: true });
3646
+ }
3647
+ /** Leave this thread. */
3648
+ async leave() {
3649
+ await this.client.rest.delete(Routes14.channelThreadMemberMe(this.id), { auth: true });
3650
+ }
3651
+ /** Update the current user's notification settings for this thread. */
3652
+ async editSelf(options) {
3653
+ const data = await this.client.rest.patch(
3654
+ Routes14.channelThreadMemberMeSettings(this.id),
3655
+ { body: toThreadMemberSettingsBody(options), auth: true }
3656
+ );
3657
+ this.member = data ? new ThreadMember(data) : null;
3658
+ return this.member;
3659
+ }
3660
+ };
3661
+ var ThreadMemberManager = class {
3662
+ constructor(thread) {
3663
+ this.thread = thread;
3664
+ }
3665
+ /** List members of this thread. */
3666
+ async fetch(options) {
3667
+ const data = await this.thread.client.rest.get(
3668
+ withQuery(Routes14.channelThreadMembers(this.thread.id), {
3669
+ with_member: options?.withMember === void 0 ? void 0 : String(options.withMember),
3670
+ after: options?.after,
3671
+ limit: options?.limit
3672
+ })
3673
+ );
3674
+ return data.map((member) => new ThreadMember(member));
3675
+ }
3676
+ /** Fetch one member of this thread. */
3677
+ async fetchOne(userId, options) {
3678
+ const data = await this.thread.client.rest.get(
3679
+ withQuery(Routes14.channelThreadMember(this.thread.id, userId), {
3680
+ with_member: options?.withMember === void 0 ? void 0 : String(options.withMember)
3681
+ })
3682
+ );
3683
+ return new ThreadMember(data);
3684
+ }
3685
+ /** Add a user to this thread. Private threads only, unless the caller can manage the parent. */
3686
+ async add(userId) {
3687
+ await this.thread.client.rest.put(Routes14.channelThreadMember(this.thread.id, userId), {
3688
+ auth: true
3689
+ });
3690
+ }
3691
+ /** Remove a user from this thread. */
3692
+ async remove(userId) {
3693
+ await this.thread.client.rest.delete(Routes14.channelThreadMember(this.thread.id, userId), {
3694
+ auth: true
3695
+ });
3696
+ }
3697
+ };
3698
+ function isThreadType(type) {
3699
+ return type === ChannelType5.AnnouncementThread || type === ChannelType5.PublicThread || type === ChannelType5.PrivateThread;
3700
+ }
3701
+
3702
+ // src/Domain/Channel/ThreadManager.ts
3703
+ var ThreadManager = class {
3704
+ constructor(channel) {
3705
+ this.channel = channel;
3706
+ }
3707
+ /**
3708
+ * Start a thread in a text or announcement channel.
3709
+ * Forum and media channels must use {@link createPost}.
3710
+ */
3711
+ async create(options) {
3712
+ if (this.channel.type === ChannelType6.GuildForum || this.channel.type === ChannelType6.GuildMedia) {
3713
+ throw new FluxerError("Forum and media channels start posts with createPost", {
3714
+ code: ErrorCodes.InvalidChannelType
3715
+ });
3716
+ }
3717
+ const data = await this.channel.client.rest.post(
3718
+ Routes15.channelThreads(this.channel.id),
3719
+ {
3720
+ body: toStartThreadBody(this.channel.type, options),
3721
+ auth: true,
3722
+ ...auditReasonHeaders(options.reason)
3723
+ }
3724
+ );
3725
+ return cacheThread(this.channel.client, data);
3726
+ }
3727
+ /**
3728
+ * Start a post in a forum or media channel.
3729
+ * The post is a public thread. `message` is its first message.
3730
+ */
3731
+ async createPost(options) {
3732
+ if (this.channel.type !== ChannelType6.GuildForum && this.channel.type !== ChannelType6.GuildMedia) {
3733
+ throw new FluxerError("createPost is for forum and media channels", {
3734
+ code: ErrorCodes.InvalidChannelType
3735
+ });
3736
+ }
3737
+ const prepared = await prepareMessagePostPayload(options.message, {
3738
+ defaultAllowedMentions: this.channel.client.options.defaultAllowedMentions
3739
+ });
3740
+ const body = {
3741
+ name: options.name,
3742
+ type: ChannelType6.PublicThread,
3743
+ message: toForumThreadMessage(prepared.body)
3744
+ };
3745
+ if (options.autoArchiveDuration !== void 0) {
3746
+ body.auto_archive_duration = options.autoArchiveDuration;
3747
+ }
3748
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
3749
+ if (options.appliedTags !== void 0) body.applied_tags = options.appliedTags;
3750
+ const data = await this.channel.client.rest.post(
3751
+ Routes15.channelThreads(this.channel.id),
3752
+ {
3753
+ body,
3754
+ files: prepared.files,
3755
+ auth: true,
3756
+ ...auditReasonHeaders(options.reason)
3757
+ }
3758
+ );
3759
+ const thread = cacheThread(this.channel.client, data);
3760
+ if (data.message) {
3761
+ this.channel.client._addMessageToCache(data.message.channel_id, data.message);
3762
+ }
3763
+ return thread;
3764
+ }
3765
+ /**
3766
+ * List archived threads in this channel.
3767
+ * `before` is an ISO-8601 archive timestamp.
3768
+ */
3769
+ async fetchArchived(options) {
3770
+ const path = options.type === "private" ? Routes15.channelThreadsArchivedPrivate(this.channel.id) : Routes15.channelThreadsArchivedPublic(this.channel.id);
3771
+ const data = await this.channel.client.rest.get(
3772
+ withQuery(path, { before: options.before, limit: options.limit })
3773
+ );
3774
+ return fetchedThreadsFrom(this.channel.client, data);
3136
3775
  }
3137
3776
  /**
3138
- * Set slowmode (seconds between messages). Pass `0` to disable.
3139
- * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3777
+ * List private archived threads in this channel that the current user has joined.
3778
+ * `before` is a thread snowflake.
3140
3779
  */
3141
- async setSlowmode(seconds) {
3142
- return this.edit({ rateLimitPerUser: seconds });
3780
+ async fetchJoinedPrivateArchived(options) {
3781
+ const data = await this.channel.client.rest.get(
3782
+ withQuery(Routes15.channelJoinedArchivedPrivateThreads(this.channel.id), {
3783
+ before: options?.before,
3784
+ limit: options?.limit
3785
+ })
3786
+ );
3787
+ return fetchedThreadsFrom(this.channel.client, data);
3143
3788
  }
3144
- applyEditPatch(data) {
3145
- if ("topic" in data) this.topic = data.topic ?? null;
3146
- if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3147
- if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
3148
- if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3149
- if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3150
- if ("content_warning_level" in data) {
3151
- this.contentWarningLevel = data.content_warning_level ?? null;
3152
- }
3153
- if ("content_warning_text" in data) {
3154
- this.contentWarningText = data.content_warning_text ?? null;
3789
+ /**
3790
+ * Search threads in this channel.
3791
+ * Returns `{ indexing: true }` while the search index is still building.
3792
+ */
3793
+ async search(options) {
3794
+ const data = await this.channel.client.rest.get(
3795
+ withQuery(Routes15.channelThreadSearch(this.channel.id), {
3796
+ name: options?.name,
3797
+ tag: options?.tag,
3798
+ tag_setting: options?.tagSetting,
3799
+ archived: options?.archived === void 0 ? void 0 : String(options.archived),
3800
+ sort_by: options?.sortBy,
3801
+ sort_order: options?.sortOrder,
3802
+ limit: options?.limit,
3803
+ offset: options?.offset,
3804
+ max_id: options?.maxId,
3805
+ min_id: options?.minId
3806
+ })
3807
+ );
3808
+ if (isSearchNotReady(data)) {
3809
+ return { indexing: true, retryAfter: data.retry_after, message: data.message };
3155
3810
  }
3811
+ const page = fetchedThreadsFrom(this.channel.client, data);
3812
+ return {
3813
+ ...page,
3814
+ hasMore: data.has_more,
3815
+ totalResults: data.total_results,
3816
+ firstMessages: (data.first_messages ?? []).map(
3817
+ (message) => new Message(this.channel.client, message)
3818
+ )
3819
+ };
3820
+ }
3821
+ /** Set the auto-archive and slowmode defaults copied onto new threads. */
3822
+ async editDefaults(options) {
3823
+ return this.channel.client.rest.patch(Routes15.channel(this.channel.id), {
3824
+ body: toThreadParentEditBody(options),
3825
+ auth: true,
3826
+ ...auditReasonHeaders(options.reason)
3827
+ });
3156
3828
  }
3157
3829
  };
3158
- var AnnouncementChannel = class extends TextChannel {
3159
- };
3160
- var CategoryChannel = class extends GuildChannel {
3161
- };
3162
- var VoiceChannel = class extends TextCapable(GuildChannel) {
3163
- /** Channel topic. */
3164
- topic;
3165
- /** Whether this channel is marked as NSFW. */
3166
- nsfw;
3167
- /** Per-channel NSFW override (`null` inherits). */
3168
- nsfwOverride;
3169
- /** Slowmode rate limit in seconds. */
3170
- rateLimitPerUser;
3171
- /** ID of the last message sent in this channel. */
3172
- lastMessageId;
3173
- /** Content warning level. */
3174
- contentWarningLevel;
3175
- /** Custom content warning text. */
3176
- contentWarningText;
3177
- /** Voice bitrate. */
3178
- bitrate;
3179
- /** Maximum number of users allowed. */
3180
- userLimit;
3181
- /** Max active voice connections per user. */
3182
- voiceConnectionLimit;
3183
- /** RTC region override for this channel. */
3184
- rtcRegion;
3830
+ function fetchedThreadsFrom(client, data) {
3831
+ return {
3832
+ threads: (data.threads ?? []).map((thread) => cacheThread(client, thread)),
3833
+ members: (data.members ?? []).map((member) => new ThreadMember(member)),
3834
+ hasMore: data.has_more ?? false
3835
+ };
3836
+ }
3837
+ function isSearchNotReady(data) {
3838
+ return "code" in data && data.code === "SEARCH_INDEX_NOT_READY";
3839
+ }
3840
+ async function fetchActiveThreads(client, guildId) {
3841
+ const data = await client.rest.get(Routes15.guildActiveThreads(guildId));
3842
+ return fetchedThreadsFrom(client, data);
3843
+ }
3844
+
3845
+ // src/Domain/Channel/Forum.ts
3846
+ function tagsFrom(data) {
3847
+ return data ?? [];
3848
+ }
3849
+ var ThreadOnlyChannel = class extends GuildChannel {
3850
+ /** Tags that can be applied to posts. */
3851
+ availableTags;
3852
+ /** Default reaction for new posts. */
3853
+ defaultReactionEmoji;
3854
+ /** Default sort order for posts. */
3855
+ defaultSortOrder;
3856
+ /** How posts are filtered when searching by several tags. */
3857
+ defaultTagSetting;
3858
+ /** Default auto-archive duration in minutes for new posts. */
3859
+ defaultAutoArchiveDuration;
3860
+ /** Slowmode in seconds copied onto new posts. */
3861
+ defaultThreadRateLimitPerUser;
3862
+ /** Channel flags bitfield. */
3863
+ flags;
3864
+ /** Create, list, and search posts in this channel. */
3865
+ threads;
3185
3866
  constructor(client, data) {
3186
3867
  super(client, data);
3187
- this.topic = data.topic ?? null;
3188
- this.nsfw = data.nsfw ?? false;
3189
- this.nsfwOverride = data.nsfw_override ?? null;
3190
- this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3191
- this.lastMessageId = data.last_message_id ?? null;
3192
- this.contentWarningLevel = data.content_warning_level ?? null;
3193
- this.contentWarningText = data.content_warning_text ?? null;
3194
- this.bitrate = data.bitrate ?? null;
3195
- this.userLimit = data.user_limit ?? null;
3196
- this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3197
- this.rtcRegion = data.rtc_region ?? null;
3198
- }
3199
- /**
3200
- * Set slowmode (seconds between messages). Pass `0` to disable.
3201
- * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3202
- */
3203
- async setSlowmode(seconds) {
3204
- return this.edit({ rateLimitPerUser: seconds });
3868
+ this.availableTags = tagsFrom(data.available_tags);
3869
+ this.defaultReactionEmoji = data.default_reaction_emoji ?? null;
3870
+ this.defaultSortOrder = data.default_sort_order ?? null;
3871
+ this.defaultTagSetting = data.default_tag_setting ?? null;
3872
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3873
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3874
+ this.flags = data.flags ?? 0;
3875
+ this.threads = new ThreadManager(this);
3205
3876
  }
3206
- applyEditPatch(data) {
3207
- if ("topic" in data) this.topic = data.topic ?? null;
3208
- if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3209
- if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
3210
- if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3211
- if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3212
- if ("content_warning_level" in data) {
3213
- this.contentWarningLevel = data.content_warning_level ?? null;
3877
+ /** @internal */
3878
+ _patch(data) {
3879
+ super._patch(data);
3880
+ if (data.available_tags !== void 0) this.availableTags = tagsFrom(data.available_tags);
3881
+ if ("default_reaction_emoji" in data) {
3882
+ this.defaultReactionEmoji = data.default_reaction_emoji ?? null;
3214
3883
  }
3215
- if ("content_warning_text" in data) {
3216
- this.contentWarningText = data.content_warning_text ?? null;
3884
+ if ("default_sort_order" in data) this.defaultSortOrder = data.default_sort_order ?? null;
3885
+ if ("default_tag_setting" in data) this.defaultTagSetting = data.default_tag_setting ?? null;
3886
+ if ("default_auto_archive_duration" in data) {
3887
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3217
3888
  }
3218
- if ("bitrate" in data) this.bitrate = data.bitrate ?? null;
3219
- if ("user_limit" in data) this.userLimit = data.user_limit ?? null;
3220
- if ("voice_connection_limit" in data) {
3221
- this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3889
+ if ("default_thread_rate_limit_per_user" in data) {
3890
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3222
3891
  }
3223
- if ("rtc_region" in data) this.rtcRegion = data.rtc_region ?? null;
3892
+ if (data.flags !== void 0) this.flags = data.flags;
3893
+ }
3894
+ /**
3895
+ * Edit this channel.
3896
+ * Tag, sort, reaction, and thread-default fields are sent with the usual channel fields.
3897
+ * `defaultForumLayout` is sent only for forum channels.
3898
+ */
3899
+ async edit(options) {
3900
+ const data = await this.client.rest.patch(Routes16.channel(this.id), {
3901
+ body: {
3902
+ ...toChannelEditBody(options),
3903
+ ...forumParentWire(options, this.type === ChannelType7.GuildForum)
3904
+ },
3905
+ auth: true,
3906
+ ...auditReasonHeaders(options.reason)
3907
+ });
3908
+ this._patch(data);
3909
+ return this;
3910
+ }
3911
+ /** Replace the tags that can be applied to posts (max 20). */
3912
+ async setAvailableTags(tags, reason) {
3913
+ return this.edit({ availableTags: tags, reason });
3914
+ }
3915
+ /** Set or clear the default reaction on new posts. */
3916
+ async setDefaultReactionEmoji(emoji, reason) {
3917
+ return this.edit({ defaultReactionEmoji: emoji, reason });
3918
+ }
3919
+ /** Set or clear the default post sort order. */
3920
+ async setDefaultSortOrder(order, reason) {
3921
+ return this.edit({ defaultSortOrder: order, reason });
3922
+ }
3923
+ /** Set or clear how posts match when several tags are selected. */
3924
+ async setDefaultTagSetting(setting, reason) {
3925
+ return this.edit({ defaultTagSetting: setting, reason });
3926
+ }
3927
+ /** Set the auto-archive and slowmode defaults copied onto new posts. */
3928
+ async editThreadDefaults(options) {
3929
+ const data = await this.client.rest.patch(Routes16.channel(this.id), {
3930
+ body: toThreadParentEditBody(options),
3931
+ auth: true,
3932
+ ...auditReasonHeaders(options.reason)
3933
+ });
3934
+ this._patch(data);
3935
+ return this;
3936
+ }
3937
+ /** Create a tag. The response replaces {@link availableTags}. */
3938
+ async createTag(options) {
3939
+ const data = await this.client.rest.post(Routes16.channelTags(this.id), {
3940
+ body: toForumTagBody(options),
3941
+ auth: true,
3942
+ ...auditReasonHeaders(options.reason)
3943
+ });
3944
+ this._patch(data);
3945
+ return this;
3946
+ }
3947
+ /** Replace a tag. The response replaces {@link availableTags}. */
3948
+ async editTag(tagId, options) {
3949
+ const data = await this.client.rest.put(Routes16.channelTag(this.id, tagId), {
3950
+ body: toForumTagBody(options),
3951
+ auth: true,
3952
+ ...auditReasonHeaders(options.reason)
3953
+ });
3954
+ this._patch(data);
3955
+ return this;
3956
+ }
3957
+ /** Delete a tag. The response replaces {@link availableTags}. */
3958
+ async deleteTag(tagId, reason) {
3959
+ const data = await this.client.rest.delete(Routes16.channelTag(this.id, tagId), {
3960
+ auth: true,
3961
+ ...auditReasonHeaders(reason)
3962
+ });
3963
+ this._patch(data);
3964
+ return this;
3224
3965
  }
3225
3966
  };
3226
- var LinkChannel = class extends GuildChannel {
3227
- /** External URL this channel links to. */
3228
- url;
3967
+ var ForumChannel = class extends ThreadOnlyChannel {
3968
+ /** Default layout for posts. */
3969
+ defaultForumLayout;
3970
+ /** Set or clear the default post layout. */
3971
+ async setDefaultForumLayout(layout, reason) {
3972
+ return this.edit({ defaultForumLayout: layout, reason });
3973
+ }
3229
3974
  constructor(client, data) {
3230
3975
  super(client, data);
3231
- this.url = data.url ?? null;
3976
+ this.defaultForumLayout = data.default_forum_layout ?? null;
3232
3977
  }
3233
- applyEditPatch(data) {
3234
- if ("url" in data) this.url = data.url ?? null;
3978
+ /** @internal */
3979
+ _patch(data) {
3980
+ super._patch(data);
3981
+ if ("default_forum_layout" in data) this.defaultForumLayout = data.default_forum_layout ?? null;
3235
3982
  }
3236
3983
  };
3984
+ var MediaChannel = class extends ThreadOnlyChannel {
3985
+ };
3237
3986
 
3238
3987
  // src/Domain/Channel/Factory.ts
3239
- import { ChannelType as ChannelType3 } from "@fluxerjs/types";
3988
+ import { ChannelType as ChannelType8 } from "@fluxerjs/types";
3240
3989
  var GUILD_FACTORIES = {
3241
- [ChannelType3.GuildText]: (c, d) => new TextChannel(c, d),
3242
- [ChannelType3.GuildAnnouncement]: (c, d) => new AnnouncementChannel(c, d),
3243
- [ChannelType3.GuildCategory]: (c, d) => new CategoryChannel(c, d),
3244
- [ChannelType3.GuildVoice]: (c, d) => new VoiceChannel(c, d),
3245
- [ChannelType3.GuildLink]: (c, d) => new LinkChannel(c, d)
3990
+ [ChannelType8.GuildText]: (c, d) => new TextChannel(c, d),
3991
+ [ChannelType8.GuildAnnouncement]: (c, d) => new AnnouncementChannel(c, d),
3992
+ [ChannelType8.GuildCategory]: (c, d) => new CategoryChannel(c, d),
3993
+ [ChannelType8.GuildVoice]: (c, d) => new VoiceChannel(c, d),
3994
+ [ChannelType8.GuildLink]: (c, d) => new LinkChannel(c, d),
3995
+ [ChannelType8.AnnouncementThread]: (c, d) => new ThreadChannel(c, d),
3996
+ [ChannelType8.PublicThread]: (c, d) => new ThreadChannel(c, d),
3997
+ [ChannelType8.PrivateThread]: (c, d) => new ThreadChannel(c, d),
3998
+ [ChannelType8.GuildForum]: (c, d) => new ForumChannel(c, d),
3999
+ [ChannelType8.GuildMedia]: (c, d) => new MediaChannel(c, d)
3246
4000
  };
3247
4001
  var DM_TYPES = /* @__PURE__ */ new Set([
3248
- ChannelType3.DM,
3249
- ChannelType3.GroupDM,
3250
- ChannelType3.DMPersonalNotes
4002
+ ChannelType8.DM,
4003
+ ChannelType8.GroupDM,
4004
+ ChannelType8.DMPersonalNotes
3251
4005
  ]);
3252
4006
  function createDM(client, data) {
3253
4007
  return new DMChannel(client, data);
3254
4008
  }
3255
4009
  function channelFrom(client, data) {
3256
- const factory = GUILD_FACTORIES[data.type ?? 0];
3257
- return factory ? factory(client, data) : new GuildChannel(client, data);
4010
+ const factory2 = GUILD_FACTORIES[data.type ?? 0];
4011
+ return factory2 ? factory2(client, data) : new GuildChannel(client, data);
3258
4012
  }
3259
4013
  function channelFromOrCreate(client, data) {
3260
4014
  return DM_TYPES.has(data.type ?? 0) ? createDM(client, data) : channelFrom(client, data);
@@ -3264,6 +4018,7 @@ function channelFromOrCreate(client, data) {
3264
4018
  Channel.from = channelFrom;
3265
4019
  Channel.fromOrCreate = channelFromOrCreate;
3266
4020
  Channel.createDM = createDM;
4021
+ bindThreadManager((channel) => new ThreadManager(channel));
3267
4022
 
3268
4023
  // src/Domain/User.ts
3269
4024
  var User = class extends Base {
@@ -3363,7 +4118,7 @@ var User = class extends Base {
3363
4118
  * @returns DM channel instance (cached if already open)
3364
4119
  */
3365
4120
  async createDM() {
3366
- const data = await this.client.rest.post(Routes14.userMeChannels(), {
4121
+ const data = await this.client.rest.post(Routes17.userMeChannels(), {
3367
4122
  body: { recipient_id: this.id },
3368
4123
  auth: true
3369
4124
  });
@@ -3580,10 +4335,13 @@ var CacheController = class {
3580
4335
 
3581
4336
  // src/ClientCore/ChannelManager.ts
3582
4337
  import { LimitedCollection } from "@fluxerjs/collection";
3583
- import { Routes as Routes20 } from "@fluxerjs/types";
4338
+ import { Routes as Routes23 } from "@fluxerjs/types";
4339
+
4340
+ // src/Domain/Guild/Cache.ts
4341
+ import { ChannelType as ChannelType9 } from "@fluxerjs/types";
3584
4342
 
3585
4343
  // src/Domain/Guild/GuildEmoji.ts
3586
- import { Routes as Routes15 } from "@fluxerjs/types";
4344
+ import { Routes as Routes18 } from "@fluxerjs/types";
3587
4345
  import { SnowflakeUtil as SnowflakeUtil6 } from "@fluxerjs/util";
3588
4346
  var GuildEmoji = class extends Base {
3589
4347
  client;
@@ -3632,7 +4390,7 @@ var GuildEmoji = class extends Base {
3632
4390
  }
3633
4391
  /** Delete this emoji. Requires Manage Emojis and Stickers permission. */
3634
4392
  async delete(reason) {
3635
- await this.client.rest.delete(Routes15.guildEmoji(this.guildId, this.id), {
4393
+ await this.client.rest.delete(Routes18.guildEmoji(this.guildId, this.id), {
3636
4394
  auth: true,
3637
4395
  ...auditReasonHeaders(reason)
3638
4396
  });
@@ -3645,7 +4403,7 @@ var GuildEmoji = class extends Base {
3645
4403
  */
3646
4404
  async edit(options) {
3647
4405
  const { reason, name } = options;
3648
- const data = await this.client.rest.patch(Routes15.guildEmoji(this.guildId, this.id), {
4406
+ const data = await this.client.rest.patch(Routes18.guildEmoji(this.guildId, this.id), {
3649
4407
  body: { name },
3650
4408
  auth: true,
3651
4409
  ...auditReasonHeaders(reason)
@@ -3656,7 +4414,7 @@ var GuildEmoji = class extends Base {
3656
4414
  };
3657
4415
 
3658
4416
  // src/Domain/Guild/GuildMember.ts
3659
- import { Routes as Routes17 } from "@fluxerjs/types";
4417
+ import { Routes as Routes20 } from "@fluxerjs/types";
3660
4418
  import { PermissionFlags as PermissionFlags3, PermissionsBitField as PermissionsBitField2 } from "@fluxerjs/util";
3661
4419
 
3662
4420
  // src/Helpers/Permissions.ts
@@ -3680,7 +4438,7 @@ function computePermissions(basePermissions, overwrites, memberRoles, memberId,
3680
4438
 
3681
4439
  // src/Domain/Guild/GuildMemberRoleManager.ts
3682
4440
  import { Collection as Collection7 } from "@fluxerjs/collection";
3683
- import { Routes as Routes16 } from "@fluxerjs/types";
4441
+ import { Routes as Routes19 } from "@fluxerjs/types";
3684
4442
  function roleId(roleOrId) {
3685
4443
  return typeof roleOrId === "string" ? roleOrId : roleOrId.id;
3686
4444
  }
@@ -3709,7 +4467,7 @@ var GuildMemberRoleManager = class {
3709
4467
  const id = roleId(roleOrId);
3710
4468
  if (this.ids.includes(id)) return;
3711
4469
  await this.member.client.rest.put(
3712
- Routes16.guildMemberRole(this.member.guild.id, this.member.id, id)
4470
+ Routes19.guildMemberRole(this.member.guild.id, this.member.id, id)
3713
4471
  );
3714
4472
  this.ids.push(id);
3715
4473
  }
@@ -3718,13 +4476,13 @@ var GuildMemberRoleManager = class {
3718
4476
  const idx = this.ids.indexOf(id);
3719
4477
  if (idx === -1) return;
3720
4478
  await this.member.client.rest.delete(
3721
- Routes16.guildMemberRole(this.member.guild.id, this.member.id, id)
4479
+ Routes19.guildMemberRole(this.member.guild.id, this.member.id, id)
3722
4480
  );
3723
4481
  this.ids.splice(idx, 1);
3724
4482
  }
3725
4483
  async set(roleIds) {
3726
4484
  const data = await this.member.client.rest.patch(
3727
- Routes16.guildMember(this.member.guild.id, this.member.id),
4485
+ Routes19.guildMember(this.member.guild.id, this.member.id),
3728
4486
  { body: { roles: roleIds }, auth: true }
3729
4487
  );
3730
4488
  this.ids = data.roles ? [...data.roles] : [];
@@ -3878,7 +4636,7 @@ var GuildMember = class _GuildMember extends Base {
3878
4636
  */
3879
4637
  async edit(options) {
3880
4638
  const isMe = this.client.user?.id === this.id;
3881
- const route = isMe ? Routes17.guildMemberMe(this.guild.id) : Routes17.guildMember(this.guild.id, this.id);
4639
+ const route = isMe ? Routes20.guildMemberMe(this.guild.id) : Routes20.guildMember(this.guild.id, this.id);
3882
4640
  const data = await this.client.rest.patch(route, {
3883
4641
  body: toMemberEditBody(options),
3884
4642
  auth: true,
@@ -3991,7 +4749,7 @@ var GuildMember = class _GuildMember extends Base {
3991
4749
  };
3992
4750
 
3993
4751
  // src/Domain/Guild/GuildSticker.ts
3994
- import { Routes as Routes18 } from "@fluxerjs/types";
4752
+ import { Routes as Routes21 } from "@fluxerjs/types";
3995
4753
  import { SnowflakeUtil as SnowflakeUtil7 } from "@fluxerjs/util";
3996
4754
  var GuildSticker = class extends Base {
3997
4755
  client;
@@ -4042,7 +4800,7 @@ var GuildSticker = class extends Base {
4042
4800
  }
4043
4801
  /** Delete this sticker. Requires Manage Emojis and Stickers permission. */
4044
4802
  async delete(reason) {
4045
- await this.client.rest.delete(Routes18.guildSticker(this.guildId, this.id), {
4803
+ await this.client.rest.delete(Routes21.guildSticker(this.guildId, this.id), {
4046
4804
  auth: true,
4047
4805
  ...auditReasonHeaders(reason)
4048
4806
  });
@@ -4055,7 +4813,7 @@ var GuildSticker = class extends Base {
4055
4813
  */
4056
4814
  async edit(options) {
4057
4815
  const { reason, ...body } = options;
4058
- const data = await this.client.rest.patch(Routes18.guildSticker(this.guildId, this.id), {
4816
+ const data = await this.client.rest.patch(Routes21.guildSticker(this.guildId, this.id), {
4059
4817
  body,
4060
4818
  auth: true,
4061
4819
  ...auditReasonHeaders(reason)
@@ -4068,7 +4826,7 @@ var GuildSticker = class extends Base {
4068
4826
  };
4069
4827
 
4070
4828
  // src/Domain/Guild/Role.ts
4071
- import { Routes as Routes19 } from "@fluxerjs/types";
4829
+ import { Routes as Routes22 } from "@fluxerjs/types";
4072
4830
  import {
4073
4831
  ALL_PERMISSIONS_BIGINT as ALL_PERMISSIONS_BIGINT2,
4074
4832
  PermissionFlags as PermissionFlags4,
@@ -4183,7 +4941,7 @@ var Role = class _Role extends Base {
4183
4941
  */
4184
4942
  async edit(options) {
4185
4943
  const body = toRoleEditBody(options);
4186
- const data = await this.client.rest.patch(Routes19.guildRole(this.guildId, this.id), {
4944
+ const data = await this.client.rest.patch(Routes22.guildRole(this.guildId, this.id), {
4187
4945
  body: Object.keys(body).length ? body : void 0,
4188
4946
  auth: true,
4189
4947
  ...auditReasonHeaders(options.reason)
@@ -4196,7 +4954,7 @@ var Role = class _Role extends Base {
4196
4954
  * @param reason - Audit log reason (`X-Audit-Log-Reason`)
4197
4955
  */
4198
4956
  async delete(reason) {
4199
- await this.client.rest.delete(Routes19.guildRole(this.guildId, this.id), {
4957
+ await this.client.rest.delete(Routes22.guildRole(this.guildId, this.id), {
4200
4958
  auth: true,
4201
4959
  ...auditReasonHeaders(reason)
4202
4960
  });
@@ -4291,11 +5049,30 @@ function syncChannels(guild, channels) {
4291
5049
  const keep = new Set(channels.map((c) => c.id));
4292
5050
  for (const data of channels) cacheChannel(guild, data);
4293
5051
  for (const [id, channel] of [...guild.channels.entries()]) {
4294
- if (keep.has(id)) continue;
5052
+ if (keep.has(id) || channel.isThread()) continue;
4295
5053
  Map.prototype.delete.call(guild.channels, id);
4296
5054
  guild.client.cache.cascadeChannel(channel, "guild");
4297
5055
  }
4298
5056
  }
5057
+ function isThreadChannelType(type) {
5058
+ return type === ChannelType9.AnnouncementThread || type === ChannelType9.PublicThread || type === ChannelType9.PrivateThread;
5059
+ }
5060
+ function syncThreads(guild, threads, alsoKeep = /* @__PURE__ */ new Set()) {
5061
+ const keep = new Set(alsoKeep);
5062
+ for (const data of threads) {
5063
+ if (!isThreadChannelType(data.type)) continue;
5064
+ const withGuild = data.guild_id ? data : { ...data, guild_id: guild.id };
5065
+ cacheThread(guild.client, withGuild);
5066
+ keep.add(data.id);
5067
+ }
5068
+ const seen = /* @__PURE__ */ new Set();
5069
+ for (const channel of [...guild.channels.values(), ...guild.client.channels.values()]) {
5070
+ if (seen.has(channel.id)) continue;
5071
+ seen.add(channel.id);
5072
+ if (!channel.isThread() || channel.guildId !== guild.id || keep.has(channel.id)) continue;
5073
+ guild.client.cache.cascadeChannel(channel);
5074
+ }
5075
+ }
4299
5076
  function mergeMembers(guild, members) {
4300
5077
  for (const m of members) {
4301
5078
  if (!m.user?.id) continue;
@@ -4359,7 +5136,7 @@ var ChannelManager = class extends LimitedCollection {
4359
5136
  const cached = this.get(channelId);
4360
5137
  if (cached && !options?.force) return cached;
4361
5138
  try {
4362
- const data = await this.client.rest.get(Routes20.channel(channelId));
5139
+ const data = await this.client.rest.get(Routes23.channel(channelId));
4363
5140
  const guildId = "guild_id" in data ? data.guild_id : void 0;
4364
5141
  if (guildId) {
4365
5142
  const guild = this.client.guilds.get(guildId);
@@ -4404,7 +5181,7 @@ var ChannelManager = class extends LimitedCollection {
4404
5181
  defaultAllowedMentions: this.client.options.defaultAllowedMentions
4405
5182
  });
4406
5183
  const data = await this.client.rest.post(
4407
- Routes20.channelMessages(channelId),
5184
+ Routes23.channelMessages(channelId),
4408
5185
  postPayload
4409
5186
  );
4410
5187
  this.client._addMessageToCache(channelId, data);
@@ -4414,7 +5191,7 @@ var ChannelManager = class extends LimitedCollection {
4414
5191
 
4415
5192
  // src/ClientCore/ClientEmoji.ts
4416
5193
  import { Collection as Collection8 } from "@fluxerjs/collection";
4417
- import { Routes as Routes21 } from "@fluxerjs/types";
5194
+ import { Routes as Routes24 } from "@fluxerjs/types";
4418
5195
  import { formatEmoji, getUnicodeFromShortcode, parseEmoji } from "@fluxerjs/util";
4419
5196
  async function resolveClientEmoji(client, emoji, guildId) {
4420
5197
  if (typeof emoji === "object" && emoji.id) {
@@ -4433,7 +5210,7 @@ async function resolveClientEmoji(client, emoji, guildId) {
4433
5210
  const unicodeFromShortcode = getUnicodeFromShortcode(parsed.name);
4434
5211
  if (unicodeFromShortcode) return unicodeFromShortcode;
4435
5212
  if (guildId) {
4436
- const emojis = await client.rest.get(Routes21.guildEmojis(guildId));
5213
+ const emojis = await client.rest.get(Routes24.guildEmojis(guildId));
4437
5214
  const found = emojis.find((e) => e.name && e.name.toLowerCase() === parsed.name.toLowerCase());
4438
5215
  if (found) return formatEmoji({ ...parsed, id: found.id, animated: found.animated });
4439
5216
  throw new FluxerError(
@@ -4450,26 +5227,26 @@ async function resolveClientEmoji(client, emoji, guildId) {
4450
5227
  return parsed.name;
4451
5228
  }
4452
5229
  async function fetchInstance(client) {
4453
- const raw = await client.rest.get(Routes21.instanceDiscovery(), {
5230
+ const raw = await client.rest.get(Routes24.instanceDiscovery(), {
4454
5231
  auth: false,
4455
5232
  unversioned: true
4456
5233
  });
4457
5234
  return parseInstanceDiscovery(raw);
4458
5235
  }
4459
5236
  function fetchGatewayInfo(client) {
4460
- return client.rest.get(Routes21.gatewayBot());
5237
+ return client.rest.get(Routes24.gatewayBot());
4461
5238
  }
4462
5239
  function fetchEmojiMetadata(client, emojiId) {
4463
- return client.rest.get(Routes21.emojiMetadata(emojiId), { auth: true });
5240
+ return client.rest.get(Routes24.emojiMetadata(emojiId), { auth: true });
4464
5241
  }
4465
5242
  function fetchStickerMetadata(client, stickerId) {
4466
- return client.rest.get(Routes21.stickerMetadata(stickerId), { auth: true });
5243
+ return client.rest.get(Routes24.stickerMetadata(stickerId), { auth: true });
4467
5244
  }
4468
5245
  function fetchApplication(client) {
4469
- return client.rest.get(Routes21.applicationsMe(), { auth: true });
5246
+ return client.rest.get(Routes24.applicationsMe(), { auth: true });
4470
5247
  }
4471
5248
  async function fetchOAuthApplications(client) {
4472
- const data = await client.rest.get(Routes21.oauth2ApplicationsMe(), { auth: true });
5249
+ const data = await client.rest.get(Routes24.oauth2ApplicationsMe(), { auth: true });
4473
5250
  if (Array.isArray(data)) return data;
4474
5251
  if (data && typeof data === "object" && "applications" in data && Array.isArray(data.applications)) {
4475
5252
  return data.applications;
@@ -4488,14 +5265,14 @@ function assertChannelIdBatch(name, channelIds) {
4488
5265
  }
4489
5266
  function preloadMessages(client, channelIds) {
4490
5267
  assertChannelIdBatch("preloadMessages", channelIds);
4491
- return client.rest.post(Routes21.preloadMessages(), {
5268
+ return client.rest.post(Routes24.preloadMessages(), {
4492
5269
  body: { channels: channelIds },
4493
5270
  auth: true
4494
5271
  });
4495
5272
  }
4496
5273
  function preloadMessagesAlt(client, channelIds) {
4497
5274
  assertChannelIdBatch("preloadMessagesAlt", channelIds);
4498
- return client.rest.post(Routes21.preloadMessagesAlt(), {
5275
+ return client.rest.post(Routes24.preloadMessagesAlt(), {
4499
5276
  body: { channels: channelIds },
4500
5277
  auth: true
4501
5278
  });
@@ -4503,7 +5280,7 @@ function preloadMessagesAlt(client, channelIds) {
4503
5280
  async function bulkFetchMessages(client, requests, options = {}) {
4504
5281
  validateBulkMessageFetchRequests(requests);
4505
5282
  const wire = toBulkFetchWire(requests);
4506
- const data = await client.rest.post(Routes21.channelsMessagesBulk(), {
5283
+ const data = await client.rest.post(Routes24.channelsMessagesBulk(), {
4507
5284
  body: { requests: wire },
4508
5285
  auth: true
4509
5286
  });
@@ -4520,7 +5297,7 @@ async function bulkFetchMessages(client, requests, options = {}) {
4520
5297
  };
4521
5298
  }
4522
5299
  async function searchMessages(client, options = {}) {
4523
- const data = await client.rest.post(Routes21.searchMessages(), {
5300
+ const data = await client.rest.post(Routes24.searchMessages(), {
4524
5301
  body: toMessageSearchBody(options),
4525
5302
  auth: true
4526
5303
  });
@@ -4550,7 +5327,7 @@ import { SnowflakeUtil as SnowflakeUtil9 } from "@fluxerjs/util";
4550
5327
 
4551
5328
  // src/ClientCore/GuildMemberManager.ts
4552
5329
  import { LimitedCollection as LimitedCollection2 } from "@fluxerjs/collection";
4553
- import { Routes as Routes22 } from "@fluxerjs/types";
5330
+ import { Routes as Routes25 } from "@fluxerjs/types";
4554
5331
  var GuildMemberManager = class extends LimitedCollection2 {
4555
5332
  constructor(guild) {
4556
5333
  super({ maxSize: guild.client.cache.limits.members });
@@ -4607,7 +5384,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
4607
5384
  if (options?.limit != null) params.set("limit", String(options.limit));
4608
5385
  if (options?.after) params.set("after", options.after);
4609
5386
  const qs2 = params.toString();
4610
- const url = Routes22.guildMembers(this.guild.id) + (qs2 ? `?${qs2}` : "");
5387
+ const url = Routes25.guildMembers(this.guild.id) + (qs2 ? `?${qs2}` : "");
4611
5388
  const data = await this.guild.client.rest.get(url, { auth: true });
4612
5389
  const members = [];
4613
5390
  for (const m of data) {
@@ -4630,7 +5407,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
4630
5407
  */
4631
5408
  async search(options = {}) {
4632
5409
  const data = await this.guild.client.rest.post(
4633
- Routes22.guildMembersSearch(this.guild.id),
5410
+ Routes25.guildMembersSearch(this.guild.id),
4634
5411
  { body: toMemberSearchBody(options), auth: true }
4635
5412
  );
4636
5413
  const offset = options.offset ?? 0;
@@ -4656,7 +5433,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
4656
5433
  };
4657
5434
 
4658
5435
  // src/Domain/Guild/Admin.ts
4659
- import { Routes as Routes23 } from "@fluxerjs/types";
5436
+ import { Routes as Routes26 } from "@fluxerjs/types";
4660
5437
  function toAuditLogEntryPayload(entry, guildId) {
4661
5438
  return {
4662
5439
  id: entry.id,
@@ -4677,7 +5454,7 @@ function toVanityPayload(data) {
4677
5454
  return { code: data.code ?? null, uses: data.uses };
4678
5455
  }
4679
5456
  async function fetchAuditLogs(guild, options) {
4680
- const url = Routes23.guildAuditLogs(guild.id) + qs({
5457
+ const url = Routes26.guildAuditLogs(guild.id) + qs({
4681
5458
  limit: options?.limit,
4682
5459
  before: options?.before,
4683
5460
  after: options?.after,
@@ -4701,7 +5478,7 @@ async function fetchAuditLogs(guild, options) {
4701
5478
  };
4702
5479
  }
4703
5480
  async function editGuild(guild, options) {
4704
- const data = await guild.client.rest.patch(Routes23.guild(guild.id), {
5481
+ const data = await guild.client.rest.patch(Routes26.guild(guild.id), {
4705
5482
  body: toGuildEditBody(options),
4706
5483
  auth: true
4707
5484
  });
@@ -4709,13 +5486,13 @@ async function editGuild(guild, options) {
4709
5486
  return guild;
4710
5487
  }
4711
5488
  async function fetchVanityURL(guild) {
4712
- const data = await guild.client.rest.get(Routes23.guildVanityUrl(guild.id), {
5489
+ const data = await guild.client.rest.get(Routes26.guildVanityUrl(guild.id), {
4713
5490
  auth: true
4714
5491
  });
4715
5492
  return toVanityPayload(data);
4716
5493
  }
4717
5494
  async function editVanityURL(guild, code) {
4718
- const data = await guild.client.rest.patch(Routes23.guildVanityUrl(guild.id), {
5495
+ const data = await guild.client.rest.patch(Routes26.guildVanityUrl(guild.id), {
4719
5496
  body: { code },
4720
5497
  auth: true
4721
5498
  });
@@ -4723,14 +5500,14 @@ async function editVanityURL(guild, code) {
4723
5500
  return toVanityPayload(data);
4724
5501
  }
4725
5502
  async function fetchDiscoveryStatus(guild) {
4726
- const data = await guild.client.rest.get(Routes23.guildDiscovery(guild.id), {
5503
+ const data = await guild.client.rest.get(Routes26.guildDiscovery(guild.id), {
4727
5504
  auth: true
4728
5505
  });
4729
5506
  return toDiscoveryStatusPayload(data);
4730
5507
  }
4731
5508
  async function applyForDiscovery(guild, options) {
4732
5509
  const data = await guild.client.rest.post(
4733
- Routes23.guildDiscovery(guild.id),
5510
+ Routes26.guildDiscovery(guild.id),
4734
5511
  {
4735
5512
  body: toDiscoveryBody(options),
4736
5513
  auth: true
@@ -4740,7 +5517,7 @@ async function applyForDiscovery(guild, options) {
4740
5517
  }
4741
5518
  async function editDiscoveryApplication(guild, options) {
4742
5519
  const data = await guild.client.rest.patch(
4743
- Routes23.guildDiscovery(guild.id),
5520
+ Routes26.guildDiscovery(guild.id),
4744
5521
  {
4745
5522
  body: toDiscoveryBody(options),
4746
5523
  auth: true
@@ -4749,34 +5526,34 @@ async function editDiscoveryApplication(guild, options) {
4749
5526
  return toDiscoveryApplicationPayload(data);
4750
5527
  }
4751
5528
  async function withdrawDiscoveryApplication(guild) {
4752
- await guild.client.rest.delete(Routes23.guildDiscovery(guild.id), { auth: true });
5529
+ await guild.client.rest.delete(Routes26.guildDiscovery(guild.id), { auth: true });
4753
5530
  }
4754
5531
  async function deleteGuild(guild, options) {
4755
5532
  const body = options ? toSudoBody(options) : {};
4756
- await guild.client.rest.post(Routes23.guildDelete(guild.id), {
5533
+ await guild.client.rest.post(Routes26.guildDelete(guild.id), {
4757
5534
  body,
4758
5535
  auth: true
4759
5536
  });
4760
5537
  guild.client.guilds.delete(guild.id);
4761
5538
  }
4762
5539
  async function transferOwnership(guild, newOwnerId, password) {
4763
- await guild.client.rest.post(Routes23.guildTransferOwnership(guild.id), {
5540
+ await guild.client.rest.post(Routes26.guildTransferOwnership(guild.id), {
4764
5541
  body: { new_owner_id: newOwnerId, ...password != null && { password } },
4765
5542
  auth: true
4766
5543
  });
4767
5544
  }
4768
5545
 
4769
5546
  // src/Domain/Guild/Channels.ts
4770
- import { Routes as Routes24 } from "@fluxerjs/types";
5547
+ import { Routes as Routes27 } from "@fluxerjs/types";
4771
5548
  async function createChannel(guild, options) {
4772
- const created = await guild.client.rest.post(Routes24.guildChannels(guild.id), {
5549
+ const created = await guild.client.rest.post(Routes27.guildChannels(guild.id), {
4773
5550
  body: toChannelCreateBody(options),
4774
5551
  auth: true
4775
5552
  });
4776
5553
  return cacheChannel(guild, created);
4777
5554
  }
4778
5555
  async function fetchChannels(guild) {
4779
- const data = await guild.client.rest.get(Routes24.guildChannels(guild.id));
5556
+ const data = await guild.client.rest.get(Routes27.guildChannels(guild.id));
4780
5557
  const channels = [];
4781
5558
  for (const ch of data) {
4782
5559
  const channel = cacheChannel(guild, ch);
@@ -4785,17 +5562,17 @@ async function fetchChannels(guild) {
4785
5562
  return channels;
4786
5563
  }
4787
5564
  async function setChannelPositions(guild, updates) {
4788
- await guild.client.rest.patch(Routes24.guildChannels(guild.id), {
5565
+ await guild.client.rest.patch(Routes27.guildChannels(guild.id), {
4789
5566
  body: toChannelPositionBody(updates),
4790
5567
  auth: true
4791
5568
  });
4792
5569
  }
4793
5570
  async function fetchWebhooks(guild) {
4794
- const data = await guild.client.rest.get(Routes24.guildWebhooks(guild.id));
5571
+ const data = await guild.client.rest.get(Routes27.guildWebhooks(guild.id));
4795
5572
  return data.map((w) => new Webhook(guild.client, w));
4796
5573
  }
4797
5574
  async function fetchInvites(guild) {
4798
- const data = await guild.client.rest.get(Routes24.guildInvites(guild.id));
5575
+ const data = await guild.client.rest.get(Routes27.guildInvites(guild.id));
4799
5576
  return data.map((invite) => new Invite(guild.client, invite));
4800
5577
  }
4801
5578
  async function fetchInvite(guild, codeOrUrl) {
@@ -4815,14 +5592,14 @@ function resolveGuildOnlineCount(data) {
4815
5592
  }
4816
5593
 
4817
5594
  // src/Domain/Guild/Emojis.ts
4818
- import { Routes as Routes25 } from "@fluxerjs/types";
5595
+ import { Routes as Routes28 } from "@fluxerjs/types";
4819
5596
  async function fetchEmojis(guild) {
4820
- const data = await guild.client.rest.get(Routes25.guildEmojis(guild.id));
5597
+ const data = await guild.client.rest.get(Routes28.guildEmojis(guild.id));
4821
5598
  return data.map((e) => cacheEmoji(guild, e));
4822
5599
  }
4823
5600
  async function fetchEmoji(guild, emojiId) {
4824
5601
  try {
4825
- const data = await guild.client.rest.get(Routes25.guildEmoji(guild.id, emojiId));
5602
+ const data = await guild.client.rest.get(Routes28.guildEmoji(guild.id, emojiId));
4826
5603
  return cacheEmoji(guild, data);
4827
5604
  } catch (err) {
4828
5605
  rethrowMapped(err, {
@@ -4833,7 +5610,7 @@ async function fetchEmoji(guild, emojiId) {
4833
5610
  }
4834
5611
  async function createEmoji(guild, options) {
4835
5612
  const { reason, ...body } = options;
4836
- const data = await guild.client.rest.post(Routes25.guildEmojis(guild.id), {
5613
+ const data = await guild.client.rest.post(Routes28.guildEmojis(guild.id), {
4837
5614
  body,
4838
5615
  auth: true,
4839
5616
  ...auditReasonHeaders(reason)
@@ -4841,7 +5618,7 @@ async function createEmoji(guild, options) {
4841
5618
  return cacheEmoji(guild, data);
4842
5619
  }
4843
5620
  async function cloneEmoji(guild, sourceEmojiId) {
4844
- const data = await guild.client.rest.post(Routes25.guildEmojisClone(guild.id), {
5621
+ const data = await guild.client.rest.post(Routes28.guildEmojisClone(guild.id), {
4845
5622
  body: { source_emoji_id: sourceEmojiId },
4846
5623
  auth: true
4847
5624
  });
@@ -4849,7 +5626,7 @@ async function cloneEmoji(guild, sourceEmojiId) {
4849
5626
  }
4850
5627
  async function createEmojisBulk(guild, emojis) {
4851
5628
  const data = await guild.client.rest.post(
4852
- Routes25.guildEmojisBulk(guild.id),
5629
+ Routes28.guildEmojisBulk(guild.id),
4853
5630
  { body: { emojis }, auth: true }
4854
5631
  );
4855
5632
  return { success: data.success.map((e) => cacheEmoji(guild, e)), failed: data.failed };
@@ -4869,11 +5646,11 @@ var GuildRoleManager = class extends LimitedCollection3 {
4869
5646
  };
4870
5647
 
4871
5648
  // src/Domain/Guild/MemberHttp.ts
4872
- import { Routes as Routes26 } from "@fluxerjs/types";
5649
+ import { Routes as Routes29 } from "@fluxerjs/types";
4873
5650
  async function fetchMember(guild, userId) {
4874
5651
  try {
4875
5652
  const data = await guild.client.rest.get(
4876
- Routes26.guildMember(guild.id, userId)
5653
+ Routes29.guildMember(guild.id, userId)
4877
5654
  );
4878
5655
  return cacheMember(guild, data);
4879
5656
  } catch (err) {
@@ -4888,17 +5665,17 @@ async function fetchMember(guild, userId) {
4888
5665
  }
4889
5666
  async function fetchMe(guild) {
4890
5667
  const data = await guild.client.rest.get(
4891
- Routes26.guildMemberMe(guild.id),
5668
+ Routes29.guildMemberMe(guild.id),
4892
5669
  { auth: true }
4893
5670
  );
4894
5671
  return cacheMember(guild, data);
4895
5672
  }
4896
5673
 
4897
5674
  // src/Domain/Guild/Moderation.ts
4898
- import { Routes as Routes28 } from "@fluxerjs/types";
5675
+ import { Routes as Routes31 } from "@fluxerjs/types";
4899
5676
 
4900
5677
  // src/Domain/Guild/GuildBan.ts
4901
- import { Routes as Routes27 } from "@fluxerjs/types";
5678
+ import { Routes as Routes30 } from "@fluxerjs/types";
4902
5679
  function parseOptionalDate2(value) {
4903
5680
  if (value == null || value === "") return null;
4904
5681
  const date = new Date(value);
@@ -4925,7 +5702,7 @@ var GuildBan = class extends Base {
4925
5702
  * Requires Ban Members permission.
4926
5703
  */
4927
5704
  async unban(reason) {
4928
- await this.client.rest.delete(Routes27.guildBan(this.guildId, this.user.id), {
5705
+ await this.client.rest.delete(Routes30.guildBan(this.guildId, this.user.id), {
4929
5706
  auth: true,
4930
5707
  ...auditReasonHeaders(reason)
4931
5708
  });
@@ -4935,35 +5712,35 @@ var GuildBan = class extends Base {
4935
5712
  // src/Domain/Guild/Moderation.ts
4936
5713
  async function ban(guild, userId, options) {
4937
5714
  const body = options ? toGuildBanBody(options) : {};
4938
- await guild.client.rest.put(Routes28.guildBan(guild.id, userId), {
5715
+ await guild.client.rest.put(Routes31.guildBan(guild.id, userId), {
4939
5716
  body: Object.keys(body).length ? body : void 0,
4940
5717
  auth: true,
4941
5718
  ...auditReasonHeaders(options?.reason)
4942
5719
  });
4943
5720
  }
4944
5721
  async function fetchBans(guild) {
4945
- const data = await guild.client.rest.get(Routes28.guildBans(guild.id));
5722
+ const data = await guild.client.rest.get(Routes31.guildBans(guild.id));
4946
5723
  return data.map((b) => new GuildBan(guild.client, { ...b, guild_id: guild.id }, guild.id));
4947
5724
  }
4948
5725
  async function unban(guild, userId, reason) {
4949
- await guild.client.rest.delete(Routes28.guildBan(guild.id, userId), {
5726
+ await guild.client.rest.delete(Routes31.guildBan(guild.id, userId), {
4950
5727
  auth: true,
4951
5728
  ...auditReasonHeaders(reason)
4952
5729
  });
4953
5730
  }
4954
5731
  async function kick(guild, userId, reason) {
4955
- await guild.client.rest.delete(Routes28.guildMember(guild.id, userId), {
5732
+ await guild.client.rest.delete(Routes31.guildMember(guild.id, userId), {
4956
5733
  auth: true,
4957
5734
  ...auditReasonHeaders(reason)
4958
5735
  });
4959
5736
  }
4960
5737
 
4961
5738
  // src/Domain/Guild/Roles.ts
4962
- import { Routes as Routes29 } from "@fluxerjs/types";
5739
+ import { Routes as Routes32 } from "@fluxerjs/types";
4963
5740
  import { parseRoleMention } from "@fluxerjs/util";
4964
5741
  async function createRole(guild, options = {}) {
4965
5742
  const body = toRoleCreateBody(options);
4966
- const data = await guild.client.rest.post(Routes29.guildRoles(guild.id), {
5743
+ const data = await guild.client.rest.post(Routes32.guildRoles(guild.id), {
4967
5744
  body: Object.keys(body).length ? body : void 0,
4968
5745
  auth: true,
4969
5746
  ...auditReasonHeaders(options.reason)
@@ -4971,12 +5748,12 @@ async function createRole(guild, options = {}) {
4971
5748
  return cacheRole(guild, data);
4972
5749
  }
4973
5750
  async function fetchRoles(guild) {
4974
- const data = await guild.client.rest.get(Routes29.guildRoles(guild.id));
5751
+ const data = await guild.client.rest.get(Routes32.guildRoles(guild.id));
4975
5752
  return data.map((r) => cacheRole(guild, r));
4976
5753
  }
4977
5754
  async function fetchRole(guild, roleId2) {
4978
5755
  try {
4979
- const data = await guild.client.rest.get(Routes29.guildRole(guild.id, roleId2));
5756
+ const data = await guild.client.rest.get(Routes32.guildRole(guild.id, roleId2));
4980
5757
  return cacheRole(guild, data);
4981
5758
  } catch (err) {
4982
5759
  rethrowMapped(err, {
@@ -4993,7 +5770,7 @@ async function resolveRoleId(guild, arg) {
4993
5770
  const needle = trimmed.toLowerCase();
4994
5771
  const cached = guild.roles.find((r) => r.name?.toLowerCase() === needle);
4995
5772
  if (cached) return cached.id;
4996
- const roles = await guild.client.rest.get(Routes29.guildRoles(guild.id));
5773
+ const roles = await guild.client.rest.get(Routes32.guildRoles(guild.id));
4997
5774
  const role = roles.find((r) => r.name?.toLowerCase() === needle);
4998
5775
  if (!role) return null;
4999
5776
  cacheRole(guild, role);
@@ -5002,7 +5779,7 @@ async function resolveRoleId(guild, arg) {
5002
5779
  async function setRolePositions(guild, updates) {
5003
5780
  return replaceRoles(
5004
5781
  guild,
5005
- await guild.client.rest.patch(Routes29.guildRoles(guild.id), {
5782
+ await guild.client.rest.patch(Routes32.guildRoles(guild.id), {
5006
5783
  body: updates,
5007
5784
  auth: true
5008
5785
  })
@@ -5011,7 +5788,7 @@ async function setRolePositions(guild, updates) {
5011
5788
  async function setRoleHoistPositions(guild, updates) {
5012
5789
  return replaceRoles(
5013
5790
  guild,
5014
- await guild.client.rest.patch(Routes29.guildRolesHoistPositions(guild.id), {
5791
+ await guild.client.rest.patch(Routes32.guildRolesHoistPositions(guild.id), {
5015
5792
  body: updates.map((u) => ({
5016
5793
  id: u.id,
5017
5794
  ...u.hoistPosition !== void 0 ? { hoist_position: u.hoistPosition } : {}
@@ -5023,17 +5800,17 @@ async function setRoleHoistPositions(guild, updates) {
5023
5800
  async function resetRoleHoistPositions(guild) {
5024
5801
  return replaceRoles(
5025
5802
  guild,
5026
- await guild.client.rest.delete(Routes29.guildRolesHoistPositions(guild.id), {
5803
+ await guild.client.rest.delete(Routes32.guildRolesHoistPositions(guild.id), {
5027
5804
  auth: true
5028
5805
  })
5029
5806
  );
5030
5807
  }
5031
5808
 
5032
5809
  // src/Domain/Guild/Stickers.ts
5033
- import { Routes as Routes30 } from "@fluxerjs/types";
5810
+ import { Routes as Routes33 } from "@fluxerjs/types";
5034
5811
  async function createSticker(guild, options) {
5035
5812
  const { reason, ...body } = options;
5036
- const data = await guild.client.rest.post(Routes30.guildStickers(guild.id), {
5813
+ const data = await guild.client.rest.post(Routes33.guildStickers(guild.id), {
5037
5814
  body,
5038
5815
  auth: true,
5039
5816
  ...auditReasonHeaders(reason)
@@ -5041,7 +5818,7 @@ async function createSticker(guild, options) {
5041
5818
  return cacheSticker(guild, data);
5042
5819
  }
5043
5820
  async function cloneSticker(guild, sourceStickerId) {
5044
- const data = await guild.client.rest.post(Routes30.guildStickersClone(guild.id), {
5821
+ const data = await guild.client.rest.post(Routes33.guildStickersClone(guild.id), {
5045
5822
  body: { source_sticker_id: sourceStickerId },
5046
5823
  auth: true
5047
5824
  });
@@ -5049,17 +5826,17 @@ async function cloneSticker(guild, sourceStickerId) {
5049
5826
  }
5050
5827
  async function createStickersBulk(guild, stickers) {
5051
5828
  const data = await guild.client.rest.post(
5052
- Routes30.guildStickersBulk(guild.id),
5829
+ Routes33.guildStickersBulk(guild.id),
5053
5830
  { body: { stickers }, auth: true }
5054
5831
  );
5055
5832
  return { success: data.success.map((s) => cacheSticker(guild, s)), failed: data.failed };
5056
5833
  }
5057
5834
  async function fetchStickers(guild) {
5058
- const data = await guild.client.rest.get(Routes30.guildStickers(guild.id));
5835
+ const data = await guild.client.rest.get(Routes33.guildStickers(guild.id));
5059
5836
  return data.map((s) => cacheSticker(guild, s));
5060
5837
  }
5061
5838
  async function fetchSticker(guild, stickerId) {
5062
- const data = await guild.client.rest.get(Routes30.guildSticker(guild.id, stickerId));
5839
+ const data = await guild.client.rest.get(Routes33.guildSticker(guild.id, stickerId));
5063
5840
  return cacheSticker(guild, data);
5064
5841
  }
5065
5842
 
@@ -5291,7 +6068,7 @@ var Guild = class extends Base {
5291
6068
  });
5292
6069
  }
5293
6070
  /**
5294
- * Create a channel. `type`: 0=text, 2=voice, 4=category, 998=link (set `url`).
6071
+ * Create a channel. `type`: 0=text, 2=voice, 4=category, 5=announcement, 15=forum, 16=media, 998=link (set `url`).
5295
6072
  * Requires Manage Channels.
5296
6073
  */
5297
6074
  createChannel(options) {
@@ -5301,6 +6078,10 @@ var Guild = class extends Base {
5301
6078
  fetchChannels() {
5302
6079
  return fetchChannels(this);
5303
6080
  }
6081
+ /** Fetch active threads in this guild. */
6082
+ fetchActiveThreads() {
6083
+ return fetchActiveThreads(this.client, this.id);
6084
+ }
5304
6085
  /** Update channel positions (reordering). */
5305
6086
  setChannelPositions(updates) {
5306
6087
  return setChannelPositions(this, updates);
@@ -5531,6 +6312,13 @@ function upsertGuildFromSnapshot(client, guildData, resources = {}) {
5531
6312
  client.guilds.set(guild.id, guild);
5532
6313
  if (resources.roles !== void 0) syncRoles(guild, resources.roles);
5533
6314
  if (resources.channels !== void 0) syncChannels(guild, resources.channels);
6315
+ if (resources.threads !== void 0) {
6316
+ syncThreads(
6317
+ guild,
6318
+ resources.threads,
6319
+ new Set((resources.channels ?? []).map((channel) => channel.id))
6320
+ );
6321
+ }
5534
6322
  if (resources.members !== void 0) mergeMembers(guild, resources.members);
5535
6323
  if (resources.emojis !== void 0) syncEmojis(guild, resources.emojis);
5536
6324
  if (resources.stickers !== void 0) syncStickers(guild, resources.stickers);
@@ -5545,7 +6333,9 @@ function applyGuildSnapshotFromGateway(client, raw) {
5545
6333
  channels: g.channels,
5546
6334
  members: g.members,
5547
6335
  emojis: g.emojis,
5548
- stickers: g.stickers
6336
+ stickers: g.stickers,
6337
+ // A channel list without `threads` means this session has no viewable threads.
6338
+ threads: g.channels !== void 0 ? g.threads ?? [] : g.threads
5549
6339
  });
5550
6340
  if (g.voice_states?.length) {
5551
6341
  client.emit(Events.VoiceStatesSync, {
@@ -5557,7 +6347,7 @@ function applyGuildSnapshotFromGateway(client, raw) {
5557
6347
  }
5558
6348
 
5559
6349
  // src/ClientCore/ClientUser.ts
5560
- import { GatewayOpcodes, Routes as Routes31 } from "@fluxerjs/types";
6350
+ import { GatewayOpcodes, Routes as Routes34 } from "@fluxerjs/types";
5561
6351
  var ClientUser = class extends User {
5562
6352
  /** Broadcast presence (gateway opcode 3) on all shards. */
5563
6353
  setPresence(presence) {
@@ -5567,13 +6357,13 @@ var ClientUser = class extends User {
5567
6357
  }
5568
6358
  /** GET /users/@me — refresh the logged-in user from REST and patch this instance. */
5569
6359
  async fetch() {
5570
- const data = await this.client.rest.get(Routes31.currentUser(), { auth: true });
6360
+ const data = await this.client.rest.get(Routes34.currentUser(), { auth: true });
5571
6361
  this._patch(data);
5572
6362
  return this;
5573
6363
  }
5574
6364
  /** GET /users/@me/guilds — returns camelCase partial guilds. */
5575
6365
  async fetchGuilds(options) {
5576
- const path = Routes31.currentUserGuilds() + (options?.withCounts ? "?with_counts=true" : "");
6366
+ const path = Routes34.currentUserGuilds() + (options?.withCounts ? "?with_counts=true" : "");
5577
6367
  const data = await this.client.rest.get(path, { auth: true });
5578
6368
  return data.map((g) => ({
5579
6369
  id: g.id,
@@ -5597,7 +6387,7 @@ var ClientUser = class extends User {
5597
6387
  */
5598
6388
  async leaveGuild(guildId, options) {
5599
6389
  const body = options ? toSudoBody(options) : void 0;
5600
- await this.client.rest.delete(Routes31.leaveGuild(guildId), {
6390
+ await this.client.rest.delete(Routes34.leaveGuild(guildId), {
5601
6391
  body: body && Object.keys(body).length ? body : void 0,
5602
6392
  auth: true
5603
6393
  });
@@ -5605,7 +6395,7 @@ var ClientUser = class extends User {
5605
6395
  /** Delete every message authored by the caller across a guild (sudo). */
5606
6396
  async bulkDeleteMyMessagesInGuild(guildId, options) {
5607
6397
  const body = options ? toSudoBody(options) : void 0;
5608
- await this.client.rest.post(Routes31.guildBulkDeleteMine(guildId), {
6398
+ await this.client.rest.post(Routes34.guildBulkDeleteMine(guildId), {
5609
6399
  body: body && Object.keys(body).length ? body : void 0,
5610
6400
  auth: true
5611
6401
  });
@@ -5640,6 +6430,7 @@ var channelHandlers = {
5640
6430
  if (!ch) return;
5641
6431
  indexChannel(client, ch);
5642
6432
  client.emit(Events.ChannelCreate, ch);
6433
+ if (ch.isThread()) client.emit(Events.ThreadCreate, ch);
5643
6434
  },
5644
6435
  CHANNEL_UPDATE(client, d) {
5645
6436
  const data = d;
@@ -5652,12 +6443,14 @@ var channelHandlers = {
5652
6443
  existing._patch(data);
5653
6444
  indexChannel(client, existing);
5654
6445
  client.emit(Events.ChannelUpdate, oldCh, existing);
6446
+ if (existing.isThread()) client.emit(Events.ThreadUpdate, oldCh, existing);
5655
6447
  return;
5656
6448
  }
5657
6449
  const newCh = Channel.from(client, data);
5658
6450
  if (!newCh) return;
5659
6451
  indexChannel(client, newCh);
5660
6452
  client.emit(Events.ChannelUpdate, existing ?? newCh, newCh);
6453
+ if (newCh.isThread()) client.emit(Events.ThreadUpdate, existing ?? newCh, newCh);
5661
6454
  },
5662
6455
  CHANNEL_UPDATE_BULK(client, d) {
5663
6456
  const data = d;
@@ -5679,7 +6472,11 @@ var channelHandlers = {
5679
6472
  }
5680
6473
  if (!channel) return;
5681
6474
  client.channels.delete(id);
6475
+ if (channel.isGuild() && channel.guildId) {
6476
+ client.guilds.get(channel.guildId)?.channels.delete(id);
6477
+ }
5682
6478
  client.emit(Events.ChannelDelete, channel);
6479
+ if (channel.isThread()) client.emit(Events.ThreadDelete, channel);
5683
6480
  },
5684
6481
  CHANNEL_PINS_UPDATE(client, d) {
5685
6482
  const data = d;
@@ -5869,6 +6666,10 @@ var guildHandlers = {
5869
6666
  }
5870
6667
  client._onGuildReceived(guild.id);
5871
6668
  },
6669
+ /** Same snapshot as Guild Create, including `threads`. Cache only: this is not a join. */
6670
+ GUILD_SYNC(client, d) {
6671
+ applyGuildSnapshotFromGateway(client, d);
6672
+ },
5872
6673
  GUILD_UPDATE(client, d) {
5873
6674
  const guildData = normalizeGuildUpdatePayload(d);
5874
6675
  if (!guildData) return;
@@ -5918,7 +6719,7 @@ var guildHandlers = {
5918
6719
 
5919
6720
  // src/ClientCore/EventHandlers/Invites.ts
5920
6721
  import {
5921
- ChannelType as ChannelType4,
6722
+ ChannelType as ChannelType10,
5922
6723
  InviteType as InviteType2
5923
6724
  } from "@fluxerjs/types";
5924
6725
  function normalizeInviteCreate(client, payload) {
@@ -5943,11 +6744,11 @@ function normalizeInviteCreate(client, payload) {
5943
6744
  const guildId = str(guildObj?.id) ?? str(raw.guild_id) ?? "0";
5944
6745
  const channelId = str(channelObj?.id) ?? str(raw.channel_id) ?? "0";
5945
6746
  const cachedGuild = guildId !== "0" ? client.guilds.get(guildId) : null;
5946
- const cachedChannel = channelId !== "0" ? client.channels.get(channelId) : null;
6747
+ const cachedChannel2 = channelId !== "0" ? client.channels.get(channelId) : null;
5947
6748
  const channel = {
5948
6749
  id: channelId,
5949
- type: num(channelObj?.type) ?? cachedChannel?.type ?? ChannelType4.GuildText,
5950
- name: str(channelObj?.name) ?? cachedChannel?.name ?? null,
6750
+ type: num(channelObj?.type) ?? cachedChannel2?.type ?? ChannelType10.GuildText,
6751
+ name: str(channelObj?.name) ?? cachedChannel2?.name ?? null,
5951
6752
  icon: channelObj?.icon ?? null
5952
6753
  };
5953
6754
  if (type === InviteType2.GroupDM) return { ...shared, type, channel };
@@ -6351,6 +7152,107 @@ var passthroughHandlers = {
6351
7152
  WEBAUTHN_CREDENTIALS_UPDATE: pass(Events.WebAuthnCredentialsUpdate)
6352
7153
  };
6353
7154
 
7155
+ // src/ClientCore/EventHandlers/Threads.ts
7156
+ function cachedChannel(client, id) {
7157
+ const direct = client.channels.get(id);
7158
+ if (direct) return direct;
7159
+ for (const guild of client.guilds.values()) {
7160
+ const nested = guild.channels.get(id);
7161
+ if (nested) return nested;
7162
+ }
7163
+ return null;
7164
+ }
7165
+ var threadHandlers = {
7166
+ THREAD_CREATE(client, d) {
7167
+ channelHandlers.CHANNEL_CREATE(client, d);
7168
+ },
7169
+ THREAD_UPDATE(client, d) {
7170
+ channelHandlers.CHANNEL_UPDATE(client, d);
7171
+ },
7172
+ THREAD_DELETE(client, d) {
7173
+ const data = d;
7174
+ const existing = data.id ? cachedChannel(client, data.id) : null;
7175
+ if (existing?.isThread()) {
7176
+ channelHandlers.CHANNEL_DELETE(client, data);
7177
+ return;
7178
+ }
7179
+ if (!data.id || !isThreadType(data.type)) return;
7180
+ const thread = Channel.from(client, {
7181
+ id: data.id,
7182
+ type: data.type,
7183
+ guild_id: data.guild_id,
7184
+ parent_id: data.parent_id
7185
+ });
7186
+ if (!thread.isThread()) return;
7187
+ client.emit(Events.ChannelDelete, thread);
7188
+ client.emit(Events.ThreadDelete, thread);
7189
+ },
7190
+ THREAD_LIST_SYNC(client, d) {
7191
+ const data = d;
7192
+ const { threads } = fetchedThreadsFrom(client, {
7193
+ threads: data.threads ?? [],
7194
+ members: data.members ?? []
7195
+ });
7196
+ const payload = {
7197
+ guildId: data.guild_id,
7198
+ channelIds: data.channel_ids ?? [],
7199
+ threads
7200
+ };
7201
+ client.emit(Events.ThreadListSync, payload);
7202
+ },
7203
+ THREAD_MEMBER_UPDATE(client, d) {
7204
+ const data = d;
7205
+ const member = new ThreadMember(data);
7206
+ const thread = member.id ? client.channels.get(member.id) : void 0;
7207
+ if (thread?.isThread() && member.userId && member.userId === client.user?.id) {
7208
+ thread.member = member;
7209
+ }
7210
+ client.emit(Events.ThreadMemberUpdate, member);
7211
+ },
7212
+ THREAD_MEMBERS_UPDATE(client, d) {
7213
+ const data = d;
7214
+ const thread = client.channels.get(data.id);
7215
+ if (thread?.isThread()) thread.memberCount = data.member_count;
7216
+ const payload = {
7217
+ id: data.id,
7218
+ guildId: data.guild_id,
7219
+ memberCount: data.member_count,
7220
+ addedMembers: (data.added_members ?? []).map((member) => new ThreadMember(member)),
7221
+ removedMemberIds: data.removed_member_ids ?? []
7222
+ };
7223
+ client.emit(Events.ThreadMembersUpdate, payload);
7224
+ },
7225
+ THREAD_MEMBER_LIST_UPDATE(client, d) {
7226
+ const data = d;
7227
+ const guild = data.guild_id ? client.guilds.get(data.guild_id) : void 0;
7228
+ const payload = {
7229
+ guildId: data.guild_id,
7230
+ threadId: data.thread_id,
7231
+ members: (data.members ?? []).map((entry) => ({
7232
+ userId: entry.user_id,
7233
+ joinTimestamp: entry.join_timestamp,
7234
+ flags: entry.flags,
7235
+ member: guild && entry.member?.user?.id ? cacheMember(guild, entry.member) : null,
7236
+ presence: entry.presence ? { status: entry.presence.status ?? null } : null
7237
+ }))
7238
+ };
7239
+ client.emit(Events.ThreadMemberListUpdate, payload);
7240
+ },
7241
+ FORUM_UNREADS(client, d) {
7242
+ const data = d;
7243
+ const payload = {
7244
+ guildId: data.guild_id,
7245
+ channelId: data.channel_id,
7246
+ threads: (data.threads ?? []).map((entry) => ({
7247
+ threadId: entry.thread_id,
7248
+ count: entry.count ?? null,
7249
+ missing: entry.missing === true
7250
+ }))
7251
+ };
7252
+ client.emit(Events.ForumUnreads, payload);
7253
+ }
7254
+ };
7255
+
6354
7256
  // src/ClientCore/EventHandlers/index.ts
6355
7257
  var eventHandlers = buildRegistry(
6356
7258
  messageHandlers,
@@ -6359,7 +7261,8 @@ var eventHandlers = buildRegistry(
6359
7261
  memberHandlers,
6360
7262
  inviteHandlers,
6361
7263
  guildResourceHandlers,
6362
- passthroughHandlers
7264
+ passthroughHandlers,
7265
+ threadHandlers
6363
7266
  );
6364
7267
 
6365
7268
  // src/ClientCore/GatewayDispatch.ts
@@ -6585,7 +7488,7 @@ async function connectClientGateway(client, token, signal) {
6585
7488
 
6586
7489
  // src/ClientCore/GuildManager.ts
6587
7490
  import { LimitedCollection as LimitedCollection5 } from "@fluxerjs/collection";
6588
- import { Routes as Routes32 } from "@fluxerjs/types";
7491
+ import { Routes as Routes35 } from "@fluxerjs/types";
6589
7492
  var GuildManager = class extends LimitedCollection5 {
6590
7493
  constructor(client) {
6591
7494
  super({
@@ -6624,7 +7527,7 @@ var GuildManager = class extends LimitedCollection5 {
6624
7527
  const cached = this.get(guildId);
6625
7528
  if (cached && !options?.force) return cached;
6626
7529
  try {
6627
- const data = await this.client.rest.get(Routes32.guild(guildId));
7530
+ const data = await this.client.rest.get(Routes35.guild(guildId));
6628
7531
  if (cached) {
6629
7532
  cached._patch(data);
6630
7533
  return cached;
@@ -6712,7 +7615,7 @@ var MessageCache = class {
6712
7615
  // src/ClientCore/UserManager.ts
6713
7616
  import { LimitedCollection as LimitedCollection6 } from "@fluxerjs/collection";
6714
7617
  import {
6715
- Routes as Routes33
7618
+ Routes as Routes36
6716
7619
  } from "@fluxerjs/types";
6717
7620
  var soft = (p) => p.catch(() => null);
6718
7621
  var UserManager = class extends LimitedCollection6 {
@@ -6737,7 +7640,7 @@ var UserManager = class extends LimitedCollection6 {
6737
7640
  async fetch(userId, options) {
6738
7641
  const cached = this.get(userId);
6739
7642
  if (cached && !options?.force) return cached;
6740
- const data = await this.client.rest.get(Routes33.user(userId));
7643
+ const data = await this.client.rest.get(Routes36.user(userId));
6741
7644
  return this.client.getOrCreateUser(data);
6742
7645
  }
6743
7646
  /** Return a cached user, otherwise {@link fetch}. */
@@ -6755,10 +7658,10 @@ var UserManager = class extends LimitedCollection6 {
6755
7658
  async fetchWithProfile(userId, options) {
6756
7659
  const guildId = options?.guildId ?? void 0;
6757
7660
  const [userData, globalProfileRaw, serverProfileRaw, memberData] = await Promise.all([
6758
- this.client.rest.get(Routes33.user(userId)),
6759
- soft(this.client.rest.get(Routes33.userProfile(userId))),
6760
- guildId ? soft(this.client.rest.get(Routes33.userProfile(userId, guildId))) : null,
6761
- guildId ? soft(this.client.rest.get(Routes33.guildMember(guildId, userId))) : null
7661
+ this.client.rest.get(Routes36.user(userId)),
7662
+ soft(this.client.rest.get(Routes36.userProfile(userId))),
7663
+ guildId ? soft(this.client.rest.get(Routes36.userProfile(userId, guildId))) : null,
7664
+ guildId ? soft(this.client.rest.get(Routes36.guildMember(guildId, userId))) : null
6762
7665
  ]);
6763
7666
  const user = this.client.getOrCreateUser(userData);
6764
7667
  let member = null;
@@ -7137,6 +8040,72 @@ var Client = class _Client extends EventEmitter3 {
7137
8040
  if (options.nonce !== void 0) data.nonce = options.nonce;
7138
8041
  this._sendToAllShards({ op: GatewayOpcodes2.RequestChannelMemberCounts, d: data });
7139
8042
  }
8043
+ /**
8044
+ * Request unread counts for posts in one forum or media channel (opcode 28).
8045
+ * Listen for `forumUnreads`. The gateway keeps at most 40 posts and ignores a channel the session cannot view.
8046
+ */
8047
+ requestForumUnreads(options) {
8048
+ if (!options.guildId || !options.channelId) {
8049
+ throw new FluxerError("requestForumUnreads requires guildId and channelId", {
8050
+ code: ErrorCodes.InvalidGatewayRequest
8051
+ });
8052
+ }
8053
+ const threads = [];
8054
+ const seen = /* @__PURE__ */ new Set();
8055
+ for (const thread of options.threads) {
8056
+ if (!thread.threadId || seen.has(thread.threadId)) continue;
8057
+ seen.add(thread.threadId);
8058
+ const entry = { thread_id: thread.threadId };
8059
+ if (thread.ackMessageId !== void 0) entry.ack_message_id = thread.ackMessageId;
8060
+ threads.push(entry);
8061
+ }
8062
+ if (!threads.length) {
8063
+ throw new FluxerError("requestForumUnreads requires at least one thread", {
8064
+ code: ErrorCodes.InvalidGatewayRequest
8065
+ });
8066
+ }
8067
+ if (threads.length > 40) {
8068
+ throw new FluxerError("requestForumUnreads accepts at most 40 threads", {
8069
+ code: ErrorCodes.InvalidGatewayRequest
8070
+ });
8071
+ }
8072
+ const data = {
8073
+ guild_id: options.guildId,
8074
+ channel_id: options.channelId,
8075
+ threads
8076
+ };
8077
+ this._sendToAllShards({ op: GatewayOpcodes2.RequestForumUnreads, d: data });
8078
+ }
8079
+ /**
8080
+ * Subscribe to thread traffic in a guild (opcode 14).
8081
+ * `threads: true` receives every thread event in the guild.
8082
+ * `threadIds` (at most 10) subscribes to those member lists. Each one arrives as `threadMemberListUpdate`.
8083
+ */
8084
+ subscribeThreads(options) {
8085
+ if (!options.guildId) {
8086
+ throw new FluxerError("subscribeThreads requires guildId", {
8087
+ code: ErrorCodes.InvalidGatewayRequest
8088
+ });
8089
+ }
8090
+ if (options.threads === void 0 && options.threadIds === void 0) {
8091
+ throw new FluxerError("subscribeThreads requires threads or threadIds", {
8092
+ code: ErrorCodes.InvalidGatewayRequest
8093
+ });
8094
+ }
8095
+ const subscription = {};
8096
+ if (options.threads !== void 0) subscription.threads = options.threads;
8097
+ if (options.threadIds !== void 0) {
8098
+ const threadIds = [...new Set(options.threadIds.filter(Boolean))];
8099
+ if (threadIds.length > 10) {
8100
+ throw new FluxerError("subscribeThreads accepts at most 10 threadIds", {
8101
+ code: ErrorCodes.InvalidGatewayRequest
8102
+ });
8103
+ }
8104
+ subscription.thread_member_lists = threadIds;
8105
+ }
8106
+ const data = { subscriptions: { [options.guildId]: subscription } };
8107
+ this._sendToAllShards({ op: GatewayOpcodes2.LazyRequest, d: data });
8108
+ }
7140
8109
  /**
7141
8110
  * Broadcast a gateway payload to all shards.
7142
8111
  * @param payload - Gateway send payload
@@ -7240,7 +8209,7 @@ var Client = class _Client extends EventEmitter3 {
7240
8209
  * @see {@link Routes}
7241
8210
  */
7242
8211
  static get Routes() {
7243
- return Routes34;
8212
+ return Routes37;
7244
8213
  }
7245
8214
  };
7246
8215
  export {