micup.ts 0.0.0-stage → 1.1.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.
Files changed (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +134 -2
  3. package/README.tr.md +137 -0
  4. package/dist/bot/client.d.ts +79 -0
  5. package/dist/bot/client.js +299 -0
  6. package/dist/events/background.d.ts +7 -0
  7. package/dist/events/background.js +23 -0
  8. package/dist/events/catalog.d.ts +243 -0
  9. package/dist/events/catalog.js +1 -0
  10. package/dist/events/guild-tag.d.ts +9 -0
  11. package/dist/events/guild-tag.js +38 -0
  12. package/dist/events/mux.d.ts +97 -0
  13. package/dist/events/mux.js +23 -0
  14. package/dist/events/names.d.ts +1 -0
  15. package/dist/events/names.js +71 -0
  16. package/dist/events/router.d.ts +11 -0
  17. package/dist/events/router.js +54 -0
  18. package/dist/events/safe.d.ts +9 -0
  19. package/dist/events/safe.js +27 -0
  20. package/dist/gateway/compression.d.ts +9 -0
  21. package/dist/gateway/compression.js +119 -0
  22. package/dist/gateway/connection.d.ts +30 -0
  23. package/dist/gateway/connection.js +297 -0
  24. package/dist/gateway/protocol.d.ts +43 -0
  25. package/dist/gateway/protocol.js +65 -0
  26. package/dist/gateway/subscription.d.ts +10 -0
  27. package/dist/gateway/subscription.js +26 -0
  28. package/dist/index.d.ts +73 -0
  29. package/dist/index.js +28 -0
  30. package/dist/model/components.d.ts +82 -0
  31. package/dist/model/components.js +74 -0
  32. package/dist/model/constants.d.ts +330 -0
  33. package/dist/model/constants.js +330 -0
  34. package/dist/model/embed.d.ts +59 -0
  35. package/dist/model/embed.js +40 -0
  36. package/dist/model/entities.d.ts +125 -0
  37. package/dist/model/entities.js +12 -0
  38. package/dist/model/format.d.ts +32 -0
  39. package/dist/model/format.js +61 -0
  40. package/dist/model/guild.d.ts +182 -0
  41. package/dist/model/guild.js +1 -0
  42. package/dist/model/helpers.d.ts +88 -0
  43. package/dist/model/helpers.js +185 -0
  44. package/dist/model/interaction.d.ts +137 -0
  45. package/dist/model/interaction.js +18 -0
  46. package/dist/model/locale.d.ts +15 -0
  47. package/dist/model/locale.js +55 -0
  48. package/dist/model/media.d.ts +23 -0
  49. package/dist/model/media.js +65 -0
  50. package/dist/model/permissions.d.ts +52 -0
  51. package/dist/model/permissions.js +112 -0
  52. package/dist/model/presence.d.ts +16 -0
  53. package/dist/model/presence.js +30 -0
  54. package/dist/rest/attachments.d.ts +26 -0
  55. package/dist/rest/attachments.js +82 -0
  56. package/dist/rest/channels.d.ts +166 -0
  57. package/dist/rest/channels.js +247 -0
  58. package/dist/rest/commands.d.ts +19 -0
  59. package/dist/rest/commands.js +111 -0
  60. package/dist/rest/discovery.d.ts +35 -0
  61. package/dist/rest/discovery.js +33 -0
  62. package/dist/rest/errors.d.ts +62 -0
  63. package/dist/rest/errors.js +72 -0
  64. package/dist/rest/expressions.d.ts +65 -0
  65. package/dist/rest/expressions.js +89 -0
  66. package/dist/rest/guilds.d.ts +177 -0
  67. package/dist/rest/guilds.js +217 -0
  68. package/dist/rest/identity.d.ts +1 -0
  69. package/dist/rest/identity.js +15 -0
  70. package/dist/rest/interactions.d.ts +30 -0
  71. package/dist/rest/interactions.js +79 -0
  72. package/dist/rest/messages.d.ts +89 -0
  73. package/dist/rest/messages.js +58 -0
  74. package/dist/rest/rooms.d.ts +142 -0
  75. package/dist/rest/rooms.js +133 -0
  76. package/dist/rest/sounds.d.ts +44 -0
  77. package/dist/rest/sounds.js +89 -0
  78. package/dist/rest/transport.d.ts +22 -0
  79. package/dist/rest/transport.js +187 -0
  80. package/dist/rest/users.d.ts +65 -0
  81. package/dist/rest/users.js +63 -0
  82. package/dist/rest/webhooks.d.ts +56 -0
  83. package/dist/rest/webhooks.js +94 -0
  84. package/dist/session/inventory.d.ts +22 -0
  85. package/dist/session/inventory.js +159 -0
  86. package/dist/session/requests.d.ts +39 -0
  87. package/dist/session/requests.js +144 -0
  88. package/dist/session/session.d.ts +82 -0
  89. package/dist/session/session.js +250 -0
  90. package/dist/session/voice.d.ts +42 -0
  91. package/dist/session/voice.js +176 -0
  92. package/dist/shard/manager.d.ts +57 -0
  93. package/dist/shard/manager.js +180 -0
  94. package/dist/state/cache.d.ts +20 -0
  95. package/dist/state/cache.js +301 -0
  96. package/docs/README.md +13 -0
  97. package/docs/commands-and-interactions.md +120 -0
  98. package/docs/errors-and-limits.md +79 -0
  99. package/docs/gateway-and-sharding.md +102 -0
  100. package/docs/getting-started.md +79 -0
  101. package/docs/migrating.md +44 -0
  102. package/docs/rest-reference.md +101 -0
  103. package/docs/voice.md +95 -0
  104. package/package.json +57 -4
@@ -0,0 +1,299 @@
1
+ import { GatewaySession } from '../session/session.js';
2
+ import { ShardManager } from '../shard/manager.js';
3
+ import { MicupAPIError } from '../rest/errors.js';
4
+ import { RestTransport } from '../rest/transport.js';
5
+ import { tokenId } from '../rest/identity.js';
6
+ import { MessageFlag } from '../model/entities.js';
7
+ import { messageBody, messageQuery, messagesPath, snowflake } from '../rest/messages.js';
8
+ import { MicupCommands } from '../rest/commands.js';
9
+ import { MicupInteractions } from '../rest/interactions.js';
10
+ import { MicupGuilds } from '../rest/guilds.js';
11
+ import { MicupChannels } from '../rest/channels.js';
12
+ import { MicupAttachments } from '../rest/attachments.js';
13
+ import { MicupWebhooks } from '../rest/webhooks.js';
14
+ import { MicupUsers } from '../rest/users.js';
15
+ import { MicupExpressions } from '../rest/expressions.js';
16
+ import { MicupSounds } from '../rest/sounds.js';
17
+ import { MicupDiscovery } from '../rest/discovery.js';
18
+ import { MicupVoiceRooms } from '../rest/rooms.js';
19
+ import { discoverPublicBase, MicupMedia } from '../model/media.js';
20
+ const defaultOrigin = 'https://micup.gg';
21
+ const connection = Symbol('Micup connection');
22
+ export class MicupClient {
23
+ #token;
24
+ #rest;
25
+ #gateway;
26
+ #botId;
27
+ #self;
28
+ #application;
29
+ #commands;
30
+ interactions;
31
+ guilds;
32
+ channels;
33
+ attachments;
34
+ webhooks;
35
+ users;
36
+ expressions;
37
+ sounds;
38
+ discovery;
39
+ rooms;
40
+ media;
41
+ inviteBase;
42
+ #origin;
43
+ constructor(key, token, api, endpoints, maxAttempts, logger) {
44
+ if (key !== connection) {
45
+ throw new TypeError('Use MicupClient.connect() to create a client');
46
+ }
47
+ this.#token = token;
48
+ this.#rest = new RestTransport(api, token, maxAttempts, logger);
49
+ this.interactions = new MicupInteractions(this.#rest);
50
+ this.guilds = new MicupGuilds(this.#rest);
51
+ this.channels = new MicupChannels(this.#rest);
52
+ this.attachments = new MicupAttachments(this.#rest);
53
+ this.webhooks = new MicupWebhooks(this.#rest);
54
+ this.users = new MicupUsers(this.#rest);
55
+ this.expressions = new MicupExpressions(this.#rest);
56
+ this.sounds = new MicupSounds(this.#rest);
57
+ this.discovery = new MicupDiscovery(this.#rest);
58
+ this.rooms = new MicupVoiceRooms(this.#rest);
59
+ this.#gateway = endpoints.gateway;
60
+ this.#origin = new URL(api).origin;
61
+ this.media = new MicupMedia(endpoints.media ?? '');
62
+ this.inviteBase = discoverPublicBase(endpoints.invite);
63
+ }
64
+ static async connect({ token, origin = defaultOrigin, maxRestAttempts, logger }, { signal } = {}) {
65
+ if (typeof token !== 'string' || !/^[\x21-\x7E]+$/.test(token)) {
66
+ throw new TypeError('A valid Micup bot token is required');
67
+ }
68
+ const url = new URL(origin);
69
+ if (url.protocol !== 'https:' || url.username || url.password ||
70
+ url.pathname !== '/' || url.search || url.hash) {
71
+ throw new TypeError('Micup origin must be an HTTPS origin');
72
+ }
73
+ const response = await fetch(new URL('/.well-known/fluxer', url), {
74
+ redirect: 'error',
75
+ signal,
76
+ });
77
+ if (!response.ok) {
78
+ await response.body?.cancel();
79
+ throw new MicupAPIError(response);
80
+ }
81
+ const discovery = await response.json();
82
+ const endpoint = discovery?.endpoints?.api_public;
83
+ if (typeof endpoint !== 'string') {
84
+ throw new Error('Micup discovery returned no API endpoint');
85
+ }
86
+ const api = new URL(endpoint);
87
+ if (api.origin !== url.origin || api.username || api.password || api.search || api.hash) {
88
+ throw new Error('Micup discovery returned an invalid API endpoint');
89
+ }
90
+ const gateway = discovery.endpoints?.gateway;
91
+ if (gateway !== undefined) {
92
+ if (typeof gateway !== 'string')
93
+ throw new Error('Micup discovery returned an invalid Gateway endpoint');
94
+ const endpoint = new URL(gateway);
95
+ if (endpoint.protocol !== 'wss:' || endpoint.host !== url.host || endpoint.username ||
96
+ endpoint.password || endpoint.hash) {
97
+ throw new Error('Micup discovery returned an invalid Gateway endpoint');
98
+ }
99
+ }
100
+ const client = new MicupClient(connection, token, `${api.href.replace(/\/+$/, '')}/v1`, { ...discovery.endpoints, gateway }, maxRestAttempts, logger);
101
+ const user = await client.getCurrentUser({ signal });
102
+ if (user?.bot !== true) {
103
+ throw new Error('The credential must belong to a Micup bot');
104
+ }
105
+ client.#botId = user.id;
106
+ client.#self = user;
107
+ return client;
108
+ }
109
+ get self() {
110
+ if (!this.#self)
111
+ throw new Error('Micup did not return the bot user');
112
+ return this.#self;
113
+ }
114
+ get tokenId() {
115
+ return tokenId(this.#token);
116
+ }
117
+ application(options) {
118
+ if (!this.#application) {
119
+ this.#application = this.users.application(options);
120
+ this.#application.catch(() => { this.#application = undefined; });
121
+ }
122
+ return this.#application;
123
+ }
124
+ async applicationId(options) {
125
+ try {
126
+ return (await this.application(options)).id;
127
+ }
128
+ catch (error) {
129
+ options?.signal?.throwIfAborted();
130
+ if (!this.#botId)
131
+ throw error;
132
+ return this.#botId;
133
+ }
134
+ }
135
+ get commands() {
136
+ if (!this.#botId)
137
+ throw new Error('Micup did not return the bot ID');
138
+ return this.#commands ??= new MicupCommands(this.#rest, this.#botId);
139
+ }
140
+ newSession(options, shard = {}) {
141
+ if (!this.#gateway)
142
+ throw new Error('Micup discovery returned no Gateway endpoint');
143
+ return new GatewaySession({ ...shard, endpoint: this.#gateway, token: this.#token, botId: this.#botId, lookupChannel: this.channels.get.bind(this.channels), lookupMembers: this.guilds.members.bind(this.guilds) }, options);
144
+ }
145
+ newShardManager(options) {
146
+ if (!this.#gateway)
147
+ throw new Error('Micup discovery returned no Gateway endpoint');
148
+ return new ShardManager({ endpoint: this.#gateway, token: this.#token, botId: this.#botId, lookupChannel: this.channels.get.bind(this.channels), lookupMembers: this.guilds.members.bind(this.guilds) }, options);
149
+ }
150
+ gateway(options, runOptions) {
151
+ return this.newSession(options).runOnce(runOptions);
152
+ }
153
+ async recommendedShards(options) {
154
+ let count = 0;
155
+ for await (const guild of this.users.iterateGuilds(options)) {
156
+ if (guild.id)
157
+ count++;
158
+ }
159
+ let recommended = 0;
160
+ try {
161
+ const info = await this.request('GET', '/gateway/bot', options);
162
+ if (Number.isSafeInteger(info?.shards))
163
+ recommended = info.shards;
164
+ }
165
+ catch {
166
+ options?.signal?.throwIfAborted();
167
+ }
168
+ return Math.max(1, Math.ceil(count / 2000), recommended);
169
+ }
170
+ botInviteURL({ scopes = ['bot'], permissions, guildId } = {}) {
171
+ if (!this.#botId)
172
+ throw new Error('Micup did not return the bot ID');
173
+ if (!scopes.length || scopes.some((scope) => !scope || /\s/.test(scope)))
174
+ throw new TypeError('OAuth scopes must be nonempty words');
175
+ if (permissions !== undefined && (typeof permissions !== 'bigint' || permissions < 0n))
176
+ throw new TypeError('Invalid OAuth permissions');
177
+ const url = new URL('/oauth2/authorize', this.#origin);
178
+ url.searchParams.set('client_id', this.#botId);
179
+ url.searchParams.set('scope', scopes.join(' '));
180
+ if (permissions)
181
+ url.searchParams.set('permissions', String(permissions));
182
+ if (guildId !== undefined)
183
+ url.searchParams.set('guild_id', snowflake(guildId, 'Guild ID'));
184
+ return url.href;
185
+ }
186
+ getCurrentUser({ signal } = {}) {
187
+ return this.request('GET', '/users/@me', { signal });
188
+ }
189
+ sendMessage(channelId, content, { replyTo, signal } = {}) {
190
+ const path = messagesPath(channelId);
191
+ const input = typeof content === 'string' ? { content } : content;
192
+ if (!input?.content?.trim() && !input?.embeds?.length && !input?.components?.length &&
193
+ !input?.files?.length && !input?.attachments?.length && !input?.uploads?.length && !input?.sticker_ids?.length) {
194
+ throw new TypeError('Message content, embeds, components or attachments are required');
195
+ }
196
+ const reply = replyTo === undefined ? undefined : { message_id: snowflake(replyTo, 'Reply message ID'), channel_id: channelId };
197
+ return this.request('POST', path, { body: messageBody(input, reply), signal, idempotent: Boolean(input.nonce && input.enforce_nonce) });
198
+ }
199
+ getMessage(channelId, messageId, options) {
200
+ return this.request('GET', messagesPath(channelId, messageId), options);
201
+ }
202
+ listMessages(channelId, options = {}) {
203
+ return this.request('GET', messagesPath(channelId), { query: messageQuery(options), signal: options.signal });
204
+ }
205
+ async *iterateMessages(channelId, options = {}) {
206
+ if (options.before !== undefined && options.after !== undefined)
207
+ throw new TypeError('Only one message cursor can be used');
208
+ let cursor = options.after ?? options.before;
209
+ const forward = options.after !== undefined;
210
+ while (true) {
211
+ const page = await this.listMessages(channelId, {
212
+ ...(forward ? { after: cursor } : { before: cursor }), limit: 100, signal: options.signal,
213
+ });
214
+ if (!page.length)
215
+ return;
216
+ page.sort((a, b) => {
217
+ const x = BigInt(a.id);
218
+ const y = BigInt(b.id);
219
+ if (x === y)
220
+ return 0;
221
+ return (x < y) === forward ? -1 : 1;
222
+ });
223
+ for (const message of page) {
224
+ if (cursor === undefined || (forward ? BigInt(message.id) > BigInt(cursor) : BigInt(message.id) < BigInt(cursor))) {
225
+ yield message;
226
+ }
227
+ }
228
+ const next = page.at(-1).id;
229
+ if (page.length < 100 || next === cursor || (cursor !== undefined && (forward ? BigInt(next) <= BigInt(cursor) : BigInt(next) >= BigInt(cursor))))
230
+ return;
231
+ cursor = next;
232
+ }
233
+ }
234
+ editMessage(channelId, messageId, edit, options) {
235
+ return this.request('PATCH', messagesPath(channelId, messageId), { ...options, body: messageBody(edit) });
236
+ }
237
+ async suppressEmbeds(channelId, messageId, suppress = true, options) {
238
+ const current = await this.getMessage(channelId, messageId, options);
239
+ const settable = MessageFlag.SuppressEmbeds | MessageFlag.SuppressNotifications | MessageFlag.VoiceMessage;
240
+ const kept = (current.flags ?? 0) & settable & ~MessageFlag.SuppressEmbeds;
241
+ return this.editMessage(channelId, messageId, { flags: suppress ? kept | MessageFlag.SuppressEmbeds : kept }, options);
242
+ }
243
+ deleteMessage(channelId, messageId, options) {
244
+ return this.request('DELETE', messagesPath(channelId, messageId), options);
245
+ }
246
+ triggerTyping(channelId, options) {
247
+ return this.request('POST', '/channels/' + snowflake(channelId, 'Channel ID') + '/typing', options);
248
+ }
249
+ async sendDM(userId, message, options) {
250
+ const channel = await this.users.createDM(userId, options);
251
+ return this.sendMessage(channel.id, message, options);
252
+ }
253
+ forwardMessage(channelId, forward, { signal, nonce, flags } = {}) {
254
+ if ((forward.attachment_ids?.length ?? 0) > 10 || (forward.embed_indices?.length ?? 0) > 10 ||
255
+ forward.embed_indices?.some((index) => !Number.isSafeInteger(index) || index < 0)) {
256
+ throw new RangeError('Invalid Micup forward attachment or embed selection');
257
+ }
258
+ const reference = {
259
+ type: 1,
260
+ channel_id: snowflake(forward.channel_id, 'Source channel ID'),
261
+ message_id: snowflake(forward.message_id, 'Source message ID'),
262
+ guild_id: forward.guild_id === undefined ? undefined : snowflake(forward.guild_id, 'Source guild ID'),
263
+ attachment_ids: forward.attachment_ids?.map((id) => snowflake(id, 'Attachment ID')),
264
+ embed_indices: forward.embed_indices,
265
+ };
266
+ return this.request('POST', messagesPath(channelId), {
267
+ body: { message_reference: reference, nonce, flags }, signal, idempotent: Boolean(nonce),
268
+ });
269
+ }
270
+ crosspostMessage(channelId, messageId, options) {
271
+ return this.request('POST', messagesPath(channelId, messageId) + '/crosspost', options);
272
+ }
273
+ bulkDeleteMessages(channelId, messageIds, options) {
274
+ const ids = [...new Set(messageIds.map((id) => snowflake(id, 'Message ID')))];
275
+ if (!ids.length || ids.length > 100)
276
+ throw new RangeError('Bulk deletion takes 1 to 100 unique message IDs');
277
+ return this.request('POST', messagesPath(channelId) + '/bulk-delete', { ...options, body: { message_ids: ids } });
278
+ }
279
+ deleteAttachment(channelId, messageId, attachmentId, options) {
280
+ return this.request('DELETE', messagesPath(channelId, messageId) + '/attachments/' + snowflake(attachmentId, 'Attachment ID'), options);
281
+ }
282
+ searchMessages(search, options) {
283
+ if (search.context_guild_id === undefined && search.context_channel_id === undefined) {
284
+ throw new TypeError('A Micup message search needs a guild ID or a channel ID');
285
+ }
286
+ if (search.context_guild_id !== undefined)
287
+ snowflake(search.context_guild_id, 'Guild ID');
288
+ if (search.context_channel_id !== undefined)
289
+ snowflake(search.context_channel_id, 'Channel ID');
290
+ if (search.page !== undefined && (!Number.isSafeInteger(search.page) || search.page < 1 || search.page > 400) ||
291
+ search.hits_per_page !== undefined && (!Number.isSafeInteger(search.hits_per_page) || search.hits_per_page < 1 || search.hits_per_page > 25)) {
292
+ throw new RangeError('Micup search takes 1 to 25 hits per page and up to 400 pages');
293
+ }
294
+ return this.request('POST', '/search/messages', { ...options, body: search, idempotent: true });
295
+ }
296
+ request(method, path, options) {
297
+ return this.#rest.request(method, path, options);
298
+ }
299
+ }
@@ -0,0 +1,7 @@
1
+ export interface BackgroundOptions {
2
+ signal?: AbortSignal;
3
+ timeoutMs?: number;
4
+ name?: string;
5
+ onError?: (error: unknown, name: string) => void;
6
+ }
7
+ export declare function background(task: (signal: AbortSignal) => void | Promise<void>, options?: BackgroundOptions): Promise<void>;
@@ -0,0 +1,23 @@
1
+ export function background(task, options = {}) {
2
+ const { signal: parent, timeoutMs, name = 'background task', onError = (error, label) => console.error(label + ' failed', error) } = options;
3
+ if (timeoutMs !== undefined && (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647)) {
4
+ throw new RangeError('Background task timeout must be a positive timer duration');
5
+ }
6
+ const signals = [parent, timeoutMs === undefined ? undefined : AbortSignal.timeout(timeoutMs)].filter((value) => value !== undefined);
7
+ const signal = signals.length ? AbortSignal.any(signals) : new AbortController().signal;
8
+ return new Promise((resolve) => {
9
+ setImmediate(() => {
10
+ void Promise.resolve()
11
+ .then(() => task(signal))
12
+ .catch((error) => {
13
+ if (parent?.aborted)
14
+ return;
15
+ try {
16
+ onError(error, name);
17
+ }
18
+ catch { }
19
+ })
20
+ .finally(resolve);
21
+ });
22
+ });
23
+ }
@@ -0,0 +1,243 @@
1
+ import type { MicupUser } from '../model/entities.js';
2
+ import type { Emoji } from '../model/format.js';
3
+ import type { MicupMember, MicupVoiceState, ThreadMember } from '../model/guild.js';
4
+ import type { Presence } from '../model/presence.js';
5
+ import type { MicupInvite } from '../rest/channels.js';
6
+ import type { MicupSoundboardSound } from '../rest/sounds.js';
7
+ import type { ChannelMemberCount, GuildCount } from '../session/requests.js';
8
+ export interface PresenceUpdate extends Presence {
9
+ user: MicupUser;
10
+ guild_id?: string;
11
+ }
12
+ export interface MessageReaction {
13
+ user_id: string;
14
+ channel_id: string;
15
+ message_id: string;
16
+ guild_id?: string;
17
+ emoji: Emoji;
18
+ member?: MicupMember;
19
+ burst?: boolean;
20
+ type?: number;
21
+ session_id?: string;
22
+ }
23
+ type ThreadMemberPresence = ThreadMember & {
24
+ presence?: PresenceUpdate;
25
+ };
26
+ type MemberWithPresence = MicupMember & {
27
+ presence?: PresenceUpdate;
28
+ };
29
+ type GuildBan = {
30
+ guild_id: string;
31
+ user: MicupUser;
32
+ };
33
+ type MemberListGroup = {
34
+ id: string;
35
+ count: number;
36
+ };
37
+ type MemberListItem = {
38
+ group?: MemberListGroup;
39
+ member?: MemberWithPresence;
40
+ };
41
+ type ReactionTarget = Pick<MessageReaction, 'channel_id' | 'message_id' | 'guild_id'>;
42
+ type Call = {
43
+ channel_id: string;
44
+ message_id?: string;
45
+ region?: string | null;
46
+ ringing?: string[];
47
+ voice_states?: MicupVoiceState[];
48
+ recipients?: string[];
49
+ created_at?: number;
50
+ };
51
+ type Relationship = {
52
+ id: string;
53
+ type: number;
54
+ user?: MicupUser;
55
+ since?: string;
56
+ nickname?: string | null;
57
+ };
58
+ type Recipient = {
59
+ channel_id: string;
60
+ user: MicupUser;
61
+ };
62
+ type SessionStatus = {
63
+ session_id: string;
64
+ status: string;
65
+ afk: boolean;
66
+ mobile: boolean;
67
+ };
68
+ export interface AdditionalGatewayEvents {
69
+ RATE_LIMITED: {
70
+ opcode: number;
71
+ retry_after: number;
72
+ meta?: {
73
+ guild_id?: string;
74
+ nonce?: string;
75
+ };
76
+ };
77
+ SESSIONS_REPLACE: SessionStatus[];
78
+ GATEWAY_ROLLOUT_UPDATE: {
79
+ game_activity_enabled: boolean;
80
+ game_activity_epoch: number;
81
+ listening_activity: boolean;
82
+ };
83
+ GUILD_AUDIT_LOG_ENTRY_CREATE: {
84
+ id: string;
85
+ guild_id: string;
86
+ user_id?: string;
87
+ target_id?: string;
88
+ action_type: number;
89
+ reason?: string;
90
+ changes?: {
91
+ key: string;
92
+ old_value?: unknown;
93
+ new_value?: unknown;
94
+ }[];
95
+ options?: Record<string, string | number | boolean>;
96
+ };
97
+ GUILD_BAN_ADD: GuildBan;
98
+ GUILD_BAN_REMOVE: GuildBan;
99
+ CHANNEL_PINS_UPDATE: {
100
+ guild_id?: string;
101
+ channel_id: string;
102
+ last_pin_timestamp?: string | null;
103
+ };
104
+ MESSAGE_DELETE_BULK: {
105
+ ids: string[];
106
+ channel_id: string;
107
+ guild_id?: string;
108
+ };
109
+ MESSAGE_REACTION_ADD: MessageReaction;
110
+ MESSAGE_REACTION_REMOVE: MessageReaction;
111
+ MESSAGE_REACTION_REMOVE_ALL: ReactionTarget;
112
+ MESSAGE_REACTION_REMOVE_EMOJI: ReactionTarget & {
113
+ emoji: Emoji;
114
+ };
115
+ MESSAGE_REACTION_ADD_MANY: ReactionTarget & {
116
+ reactions: Pick<MessageReaction, 'user_id' | 'emoji' | 'member'>[];
117
+ };
118
+ PRESENCE_UPDATE: PresenceUpdate;
119
+ TYPING_START: {
120
+ channel_id: string;
121
+ user_id: string;
122
+ timestamp: number;
123
+ guild_id?: string;
124
+ member?: MicupMember;
125
+ };
126
+ INVITE_CREATE: MicupInvite;
127
+ INVITE_DELETE: {
128
+ code: string;
129
+ guild_id?: string;
130
+ channel_id: string;
131
+ };
132
+ WEBHOOKS_UPDATE: {
133
+ guild_id: string;
134
+ channel_id: string;
135
+ };
136
+ APPLICATION_COMMANDS_UPDATE: {
137
+ application_id: string;
138
+ guild_id?: string;
139
+ scope_id?: string;
140
+ version: string;
141
+ };
142
+ GUILD_EMOJIS_UPDATE: {
143
+ guild_id: string;
144
+ emojis: Emoji[];
145
+ };
146
+ GUILD_STICKERS_UPDATE: {
147
+ guild_id: string;
148
+ stickers: {
149
+ id: string;
150
+ name: string;
151
+ description?: string;
152
+ tags?: string;
153
+ format_type?: number;
154
+ }[];
155
+ };
156
+ GUILD_SOUNDBOARD_SOUNDS_UPDATE: {
157
+ guild_id: string;
158
+ operation: 'create' | 'update' | 'delete';
159
+ sound_id: string;
160
+ version: number;
161
+ sound?: MicupSoundboardSound;
162
+ };
163
+ GUILD_SOUNDBOARD_SOUND_PLAY: {
164
+ guild_id: string;
165
+ channel_id: string;
166
+ actor_id: string;
167
+ session_id: string;
168
+ sound_id: string;
169
+ event_id: string;
170
+ asset_version: string;
171
+ volume: number;
172
+ server_time: number;
173
+ recipient_connection_id: string;
174
+ recipient_soundboard_epoch?: number;
175
+ };
176
+ GUILD_MEMBER_LIST_UPDATE: {
177
+ guild_id: string;
178
+ id: string;
179
+ channel_id?: string;
180
+ member_count: number;
181
+ online_count: number;
182
+ groups?: MemberListGroup[];
183
+ ops?: {
184
+ op: string;
185
+ range?: number[];
186
+ items?: MemberListItem[];
187
+ }[];
188
+ };
189
+ GUILD_COUNTS_UPDATE: {
190
+ counts: GuildCount[];
191
+ nonce?: string;
192
+ };
193
+ CHANNEL_RECIPIENT_ADD: Recipient;
194
+ CHANNEL_RECIPIENT_REMOVE: Recipient;
195
+ CHANNEL_MEMBER_COUNTS_UPDATE: {
196
+ counts: ChannelMemberCount[];
197
+ nonce?: string;
198
+ };
199
+ PRESENCE_UPDATE_BULK: {
200
+ guild_id: string;
201
+ presences: PresenceUpdate[];
202
+ };
203
+ PASSIVE_UPDATES: {
204
+ guild_id: string;
205
+ channels?: Record<string, string>;
206
+ voice_states?: MicupVoiceState[];
207
+ };
208
+ THREAD_MEMBER_UPDATE: ThreadMember;
209
+ THREAD_MEMBERS_UPDATE: {
210
+ id: string;
211
+ guild_id: string;
212
+ member_count: number;
213
+ added_members?: ThreadMemberPresence[];
214
+ removed_member_ids?: string[];
215
+ };
216
+ THREAD_MEMBER_LIST_UPDATE: {
217
+ guild_id: string;
218
+ thread_id: string;
219
+ members: ThreadMemberPresence[];
220
+ };
221
+ CALL_CREATE: Call;
222
+ CALL_UPDATE: Call;
223
+ CALL_DELETE: {
224
+ channel_id: string;
225
+ unavailable?: boolean;
226
+ };
227
+ ENTRANCE_SOUND_PLAY: {
228
+ user_id: string;
229
+ channel_id: string;
230
+ guild_id?: string;
231
+ sound_id: string;
232
+ hash?: string;
233
+ url: string;
234
+ duration_ms?: number;
235
+ content_type?: string;
236
+ };
237
+ RELATIONSHIP_ADD: Relationship;
238
+ RELATIONSHIP_UPDATE: Relationship;
239
+ RELATIONSHIP_REMOVE: {
240
+ id: string;
241
+ };
242
+ }
243
+ export type { ThreadMember } from '../model/guild.js';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import type { EventMux } from './mux.js';
2
+ export interface GuildTagChange {
3
+ userId: string;
4
+ guildId?: string;
5
+ previous?: string;
6
+ current?: string;
7
+ cleared: boolean;
8
+ }
9
+ export declare function onGuildTagChange(events: EventMux, listener: (change: GuildTagChange, signal: AbortSignal) => void | Promise<void>): () => void;
@@ -0,0 +1,38 @@
1
+ export function onGuildTagChange(events, listener) {
2
+ const tags = new Map();
3
+ const remember = (user) => {
4
+ if (!user?.id)
5
+ return undefined;
6
+ const previous = tags.get(user.id);
7
+ if (user.tag_guild_id)
8
+ tags.set(user.id, user.tag_guild_id);
9
+ else
10
+ tags.delete(user.id);
11
+ return previous;
12
+ };
13
+ const notify = async (user, signal, guildId) => {
14
+ if (!user?.id || !Object.hasOwn(user, 'tag_guild_id'))
15
+ return;
16
+ const previous = remember(user);
17
+ const current = user.tag_guild_id || undefined;
18
+ if (previous === current)
19
+ return;
20
+ await listener({ userId: user.id, guildId, previous, current, cleared: !current }, signal);
21
+ };
22
+ const registrations = [
23
+ events.on('GUILD_MEMBER_ADD', (member, event, signal) => notify(member.user, signal, member.guild_id)),
24
+ events.on('GUILD_MEMBER_UPDATE', (member, event, signal) => notify(member.user, signal, member.guild_id)),
25
+ events.on('USER_UPDATE', (user, event, signal) => notify(user, signal)),
26
+ events.on('GUILD_MEMBERS_CHUNK', ({ members }) => {
27
+ for (const member of members) {
28
+ if (member.user && Object.hasOwn(member.user, 'tag_guild_id'))
29
+ remember(member.user);
30
+ }
31
+ }),
32
+ ];
33
+ return () => {
34
+ for (const unregister of registrations)
35
+ unregister();
36
+ tags.clear();
37
+ };
38
+ }