micup.ts 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +93 -38
  2. package/README.tr.md +137 -0
  3. package/dist/bot/client.d.ts +79 -0
  4. package/dist/bot/client.js +299 -0
  5. package/dist/events/background.d.ts +7 -0
  6. package/dist/events/background.js +23 -0
  7. package/dist/events/catalog.d.ts +243 -0
  8. package/dist/events/catalog.js +1 -0
  9. package/dist/events/guild-tag.d.ts +9 -0
  10. package/dist/events/guild-tag.js +38 -0
  11. package/dist/events/mux.d.ts +20 -5
  12. package/dist/events/names.d.ts +1 -0
  13. package/dist/events/names.js +71 -0
  14. package/dist/events/safe.d.ts +9 -0
  15. package/dist/events/safe.js +27 -0
  16. package/dist/gateway/compression.d.ts +9 -0
  17. package/dist/gateway/compression.js +119 -0
  18. package/dist/gateway/connection.js +42 -17
  19. package/dist/gateway/protocol.d.ts +4 -1
  20. package/dist/gateway/protocol.js +9 -3
  21. package/dist/gateway/subscription.d.ts +10 -0
  22. package/dist/gateway/subscription.js +26 -0
  23. package/dist/index.d.ts +48 -4
  24. package/dist/index.js +19 -3
  25. package/dist/model/components.d.ts +82 -0
  26. package/dist/model/components.js +74 -0
  27. package/dist/model/constants.d.ts +330 -0
  28. package/dist/model/constants.js +330 -0
  29. package/dist/model/embed.d.ts +59 -0
  30. package/dist/model/embed.js +40 -0
  31. package/dist/model/entities.d.ts +125 -0
  32. package/dist/model/entities.js +12 -0
  33. package/dist/model/format.d.ts +32 -0
  34. package/dist/model/format.js +61 -0
  35. package/dist/model/guild.d.ts +114 -1
  36. package/dist/model/helpers.d.ts +88 -0
  37. package/dist/model/helpers.js +185 -0
  38. package/dist/model/interaction.d.ts +1 -1
  39. package/dist/model/locale.d.ts +15 -0
  40. package/dist/model/locale.js +55 -0
  41. package/dist/model/media.d.ts +23 -0
  42. package/dist/model/media.js +65 -0
  43. package/dist/model/permissions.d.ts +5 -0
  44. package/dist/model/permissions.js +31 -0
  45. package/dist/rest/attachments.d.ts +26 -0
  46. package/dist/rest/attachments.js +82 -0
  47. package/dist/rest/channels.d.ts +87 -3
  48. package/dist/rest/channels.js +181 -2
  49. package/dist/rest/commands.d.ts +1 -0
  50. package/dist/rest/commands.js +17 -0
  51. package/dist/rest/discovery.d.ts +35 -0
  52. package/dist/rest/discovery.js +33 -0
  53. package/dist/rest/errors.d.ts +38 -0
  54. package/dist/rest/errors.js +46 -0
  55. package/dist/rest/expressions.d.ts +65 -0
  56. package/dist/rest/expressions.js +89 -0
  57. package/dist/rest/guilds.d.ts +102 -1
  58. package/dist/rest/guilds.js +127 -0
  59. package/dist/rest/identity.d.ts +1 -0
  60. package/dist/rest/identity.js +15 -0
  61. package/dist/rest/interactions.d.ts +1 -1
  62. package/dist/rest/messages.d.ts +54 -30
  63. package/dist/rest/messages.js +32 -12
  64. package/dist/rest/rooms.d.ts +142 -0
  65. package/dist/rest/rooms.js +133 -0
  66. package/dist/rest/sounds.d.ts +44 -0
  67. package/dist/rest/sounds.js +89 -0
  68. package/dist/rest/transport.d.ts +8 -2
  69. package/dist/rest/transport.js +38 -5
  70. package/dist/rest/users.d.ts +65 -0
  71. package/dist/rest/users.js +63 -0
  72. package/dist/rest/webhooks.d.ts +56 -0
  73. package/dist/rest/webhooks.js +94 -0
  74. package/dist/session/inventory.d.ts +22 -0
  75. package/dist/session/inventory.js +159 -0
  76. package/dist/session/session.d.ts +21 -2
  77. package/dist/session/session.js +61 -4
  78. package/dist/session/voice.d.ts +1 -0
  79. package/dist/session/voice.js +25 -17
  80. package/dist/shard/manager.d.ts +38 -1
  81. package/dist/shard/manager.js +87 -0
  82. package/dist/state/cache.d.ts +6 -1
  83. package/dist/state/cache.js +45 -1
  84. package/docs/README.md +13 -0
  85. package/docs/commands-and-interactions.md +120 -0
  86. package/docs/errors-and-limits.md +79 -0
  87. package/docs/gateway-and-sharding.md +102 -0
  88. package/docs/getting-started.md +79 -0
  89. package/docs/migrating.md +44 -0
  90. package/docs/rest-reference.md +101 -0
  91. package/docs/voice.md +95 -0
  92. package/package.json +25 -7
  93. package/dist/rest/client.d.ts +0 -48
  94. package/dist/rest/client.js +0 -151
@@ -0,0 +1,26 @@
1
+ import type { MicupRequestOptions, RestTransport } from './transport.js';
2
+ export interface AttachmentUpload {
3
+ name: string;
4
+ data: Blob;
5
+ contentType?: string;
6
+ description?: string;
7
+ }
8
+ export interface UploadedAttachment {
9
+ filename: string;
10
+ upload_filename: string;
11
+ file_size: number;
12
+ content_type: string;
13
+ description?: string;
14
+ title?: string;
15
+ flags?: number;
16
+ }
17
+ export interface RefreshedAttachmentURL {
18
+ original: string;
19
+ refreshed: string;
20
+ }
21
+ export declare class MicupAttachments {
22
+ private readonly rest;
23
+ constructor(rest: RestTransport);
24
+ upload(channelId: string, upload: AttachmentUpload, { signal }?: MicupRequestOptions): Promise<UploadedAttachment>;
25
+ refresh(urls: readonly string[], options?: MicupRequestOptions): Promise<RefreshedAttachmentURL[]>;
26
+ }
@@ -0,0 +1,82 @@
1
+ import { assertFileName, snowflake } from './messages.js';
2
+ function uploadURL(address) {
3
+ if (!address || !URL.canParse(address))
4
+ throw new Error('Micup returned an invalid upload URL');
5
+ const url = new URL(address);
6
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash) {
7
+ throw new Error('Micup returned an invalid upload URL');
8
+ }
9
+ return url;
10
+ }
11
+ async function put(url, data, signal, contentType) {
12
+ const headers = new Headers({ 'User-Agent': 'micup.ts' });
13
+ if (contentType)
14
+ headers.set('Content-Type', contentType);
15
+ let response;
16
+ try {
17
+ response = await fetch(url.href, { method: 'PUT', body: data, headers, signal, redirect: 'error' });
18
+ }
19
+ catch {
20
+ signal?.throwIfAborted();
21
+ throw new Error('Micup attachment upload failed');
22
+ }
23
+ await response.body?.cancel();
24
+ if (!response.ok)
25
+ throw new Error('Micup attachment upload returned HTTP ' + response.status);
26
+ }
27
+ export class MicupAttachments {
28
+ rest;
29
+ constructor(rest) {
30
+ this.rest = rest;
31
+ }
32
+ async upload(channelId, upload, { signal } = {}) {
33
+ const path = '/channels/' + snowflake(channelId, 'Channel ID') + '/attachments';
34
+ assertFileName(upload.name);
35
+ if (!(upload.data instanceof Blob) || upload.data.size <= 0)
36
+ throw new TypeError('An attachment needs a nonempty Blob');
37
+ const { name, data, description } = upload;
38
+ const type = (upload.contentType ?? data.type) || 'application/octet-stream';
39
+ const plan = await this.rest.request('POST', path, {
40
+ signal,
41
+ body: { attachments: [{ id: 0, filename: name, file_size: data.size, content_type: type }] },
42
+ });
43
+ const item = plan?.attachments?.[0];
44
+ if (plan?.attachments?.length !== 1 || typeof item?.upload_filename !== 'string' || !item.upload_filename) {
45
+ throw new Error('Micup returned an invalid upload plan');
46
+ }
47
+ const contentType = item.content_type || type;
48
+ if (item.upload_mode === 'singlepart') {
49
+ await put(uploadURL(item.upload_url), data, signal, contentType);
50
+ }
51
+ else if (item.upload_mode === 'multipart') {
52
+ const size = item.part_size;
53
+ if (!size || !Number.isSafeInteger(size) || size < 1 || !item.upload_id ||
54
+ !Array.isArray(item.parts) || item.parts.length !== Math.ceil(data.size / size)) {
55
+ throw new Error('Micup returned an invalid multipart upload plan');
56
+ }
57
+ const urls = [...item.parts].sort((a, b) => a.part_number - b.part_number).map((part, index) => {
58
+ if (part.part_number !== index + 1)
59
+ throw new Error('Micup returned an invalid multipart upload plan');
60
+ return uploadURL(part.upload_url);
61
+ });
62
+ for (const [index, url] of urls.entries()) {
63
+ await put(url, data.slice(index * size, (index + 1) * size), signal);
64
+ }
65
+ await this.rest.request('POST', path + '/complete', {
66
+ signal, body: { uploads: [{ upload_filename: item.upload_filename, upload_id: item.upload_id }] },
67
+ });
68
+ }
69
+ else {
70
+ throw new Error('Unsupported Micup upload mode');
71
+ }
72
+ return { filename: name, upload_filename: item.upload_filename, file_size: data.size, content_type: contentType, description };
73
+ }
74
+ async refresh(urls, options) {
75
+ if (!urls.length || urls.length > 50)
76
+ throw new RangeError('An attachment refresh takes 1 to 50 URLs');
77
+ const result = await this.rest.request('POST', '/attachments/refresh-urls', {
78
+ ...options, body: { attachment_urls: urls }, idempotent: true,
79
+ });
80
+ return result.refreshed_urls;
81
+ }
82
+ }
@@ -1,6 +1,7 @@
1
- import type { MicupChannel, PermissionOverwrite } from '../model/guild.js';
2
- import type { MicupMessage, MicupUser } from './client.js';
3
- import { type AuditOptions } from './guilds.js';
1
+ import type { MicupChannel, MicupMember, PermissionOverwrite, ThreadMember } from '../model/guild.js';
2
+ import type { MicupMessage, MicupUser } from '../model/entities.js';
3
+ import { type AuditOptions, type SudoProof } from './guilds.js';
4
+ import { type MessageInput } from './messages.js';
4
5
  import type { MicupRequestOptions, RestTransport } from './transport.js';
5
6
  export interface ChannelEdit {
6
7
  name?: string;
@@ -17,6 +18,20 @@ export interface ChannelEdit {
17
18
  rate_limit_per_user?: number;
18
19
  nsfw?: boolean;
19
20
  }
21
+ export interface CrosspostSource {
22
+ guild: {
23
+ id: string;
24
+ name: string;
25
+ icon: string | null;
26
+ banner: string | null;
27
+ description: string | null;
28
+ features: string[];
29
+ badge_ids: string[];
30
+ approximate_member_count: number | null;
31
+ approximate_presence_count: number | null;
32
+ discoverable: boolean;
33
+ };
34
+ }
20
35
  export interface ThreadStart {
21
36
  name: string;
22
37
  type?: 10 | 11 | 12;
@@ -44,6 +59,29 @@ export interface MicupInvite {
44
59
  max_uses?: number;
45
60
  expires_at?: string | null;
46
61
  }
62
+ export interface ForumTag {
63
+ name: string;
64
+ emoji_id?: string | null;
65
+ emoji_name?: string | null;
66
+ moderated?: boolean;
67
+ }
68
+ export interface ForumPostInput extends Omit<ThreadStart, 'type' | 'invitable'> {
69
+ message: MessageInput;
70
+ applied_tags?: readonly string[];
71
+ }
72
+ export interface ForumPost extends MicupChannel {
73
+ message?: MicupMessage;
74
+ }
75
+ export interface ArchivedThreadOptions extends MicupRequestOptions {
76
+ before?: string;
77
+ limit?: number;
78
+ kind?: 'public' | 'private' | 'joined';
79
+ }
80
+ export interface ReactionUsersPage {
81
+ items: MicupUser[];
82
+ has_more: boolean;
83
+ next_after?: string | null;
84
+ }
47
85
  export declare class MicupChannels {
48
86
  private readonly rest;
49
87
  constructor(rest: RestTransport);
@@ -64,6 +102,13 @@ export declare class MicupChannels {
64
102
  }[];
65
103
  has_more: boolean;
66
104
  }>;
105
+ iteratePins(id: string, { signal }?: MicupRequestOptions): AsyncGenerator<{
106
+ message: MicupMessage;
107
+ pinned_at: string;
108
+ }>;
109
+ iterateThreadMembers(threadId: string, { withMember, signal }?: MicupRequestOptions & {
110
+ withMember?: boolean;
111
+ }): AsyncGenerator<ThreadMember>;
67
112
  addReaction(id: string, messageId: string, emoji: string, options?: MicupRequestOptions): Promise<void>;
68
113
  removeReaction(id: string, messageId: string, emoji: string, options?: MicupRequestOptions): Promise<void>;
69
114
  startThread(id: string, body: ThreadStart, options?: AuditOptions & {
@@ -72,6 +117,45 @@ export declare class MicupChannels {
72
117
  activeThreads(guildId: string, options?: MicupRequestOptions): Promise<ThreadList>;
73
118
  joinThread(threadId: string, options?: MicupRequestOptions): Promise<void>;
74
119
  leaveThread(threadId: string, options?: MicupRequestOptions): Promise<void>;
120
+ createForumPost(channelId: string, { message, applied_tags, ...input }: ForumPostInput, options?: AuditOptions): Promise<ForumPost>;
121
+ archivedThreads(id: string, { before, limit, kind, signal }?: ArchivedThreadOptions): Promise<ThreadList>;
122
+ searchThreads(id: string, query: URLSearchParams, options?: MicupRequestOptions): Promise<ThreadList>;
123
+ addThreadMember(threadId: string, userId: string, options?: MicupRequestOptions): Promise<void>;
124
+ removeThreadMember(threadId: string, userId: string, options?: MicupRequestOptions): Promise<void>;
125
+ createForumTag(channelId: string, tag: ForumTag, options?: AuditOptions): Promise<MicupChannel>;
126
+ editForumTag(channelId: string, tagId: string, tag: ForumTag, options?: AuditOptions): Promise<MicupChannel>;
127
+ deleteForumTag(channelId: string, tagId: string, options?: AuditOptions): Promise<MicupChannel>;
128
+ reactionUsers(id: string, messageId: string, emoji: string, query?: URLSearchParams, options?: MicupRequestOptions): Promise<ReactionUsersPage>;
129
+ iterateReactionUsers(id: string, messageId: string, emoji: string, options?: MicupRequestOptions): AsyncGenerator<MicupUser>;
130
+ deleteReaction(id: string, messageId: string, { emoji, userId }?: {
131
+ emoji?: string;
132
+ userId?: string;
133
+ }, options?: MicupRequestOptions): Promise<void>;
134
+ addRecipient(channelId: string, userId: string, options?: MicupRequestOptions): Promise<void>;
135
+ removeRecipient(channelId: string, userId: string, { silent, signal }?: MicupRequestOptions & {
136
+ silent?: boolean;
137
+ }): Promise<void>;
138
+ deleteOwnMessages(channelId: string, { signal, ...proof }?: MicupRequestOptions & SudoProof): Promise<void>;
139
+ crosspostSource(channelId: string, messageId: string, options?: MicupRequestOptions): Promise<CrosspostSource>;
140
+ archiveThread(threadId: string, archived?: boolean, options?: AuditOptions): Promise<MicupChannel>;
141
+ lockThread(threadId: string, locked?: boolean, options?: AuditOptions): Promise<MicupChannel>;
142
+ follow(announcementId: string, targetId: string, options?: AuditOptions): Promise<{
143
+ channel_id: string;
144
+ webhook_id: string;
145
+ }>;
146
+ followerStats(announcementId: string, options?: MicupRequestOptions): Promise<{
147
+ channel_count: number;
148
+ guild_count: number;
149
+ }>;
150
+ forumPostData(channelId: string, threadIds: readonly string[], options?: MicupRequestOptions): Promise<Record<string, {
151
+ owner?: MicupMember | null;
152
+ first_message?: MicupMessage | null;
153
+ }>>;
154
+ threadMembers(threadId: string, query?: URLSearchParams, options?: MicupRequestOptions): Promise<ThreadMember[]>;
155
+ threadMember(threadId: string, userId: string, withMember?: boolean, options?: MicupRequestOptions): Promise<ThreadMember>;
156
+ guildInvites(guildId: string, options?: MicupRequestOptions): Promise<MicupInvite[]>;
157
+ getInvite(code: string, options?: MicupRequestOptions): Promise<MicupInvite>;
158
+ deleteInvite(code: string, options?: AuditOptions): Promise<void>;
75
159
  invites(channelId: string, options?: MicupRequestOptions): Promise<MicupInvite[]>;
76
160
  createInvite(channelId: string, body?: {
77
161
  max_uses?: number;
@@ -1,5 +1,23 @@
1
1
  import { guildPath } from './guilds.js';
2
- import { messagesPath, snowflake } from './messages.js';
2
+ import { messageBody, messagesPath, snowflake } from './messages.js';
3
+ function threadStart(input) {
4
+ if (!input.name || [...input.name].length > 100)
5
+ throw new TypeError('Thread names must contain 1 to 100 characters');
6
+ if (input.auto_archive_duration !== undefined && ![60, 1440, 4320, 10080].includes(input.auto_archive_duration)) {
7
+ throw new RangeError('Invalid Micup auto archive duration');
8
+ }
9
+ return input;
10
+ }
11
+ function forumTag(tag) {
12
+ if (!tag.name || [...tag.name].length > 50 || tag.emoji_id && tag.emoji_name)
13
+ throw new TypeError('Invalid Micup forum tag');
14
+ return tag;
15
+ }
16
+ function invitePath(code) {
17
+ if (!code || code === '.' || code === '..')
18
+ throw new TypeError('A Micup invite code is required');
19
+ return '/invites/' + encodeURIComponent(code);
20
+ }
3
21
  function channelPath(channelId) {
4
22
  return '/channels/' + snowflake(channelId, 'Channel ID');
5
23
  }
@@ -40,6 +58,46 @@ export class MicupChannels {
40
58
  pins(id, query, options) {
41
59
  return this.rest.request('GET', messagesPath(id) + '/pins', { ...options, query });
42
60
  }
61
+ async *iteratePins(id, { signal } = {}) {
62
+ const seen = new Set();
63
+ let before;
64
+ while (true) {
65
+ const query = new URLSearchParams({ limit: '50' });
66
+ if (before !== undefined)
67
+ query.set('before', before);
68
+ const page = await this.pins(id, query, { signal });
69
+ let fresh = 0;
70
+ for (const pin of page.items) {
71
+ if (seen.has(pin.message.id))
72
+ continue;
73
+ seen.add(pin.message.id);
74
+ fresh++;
75
+ yield pin;
76
+ }
77
+ if (!page.has_more || fresh === 0)
78
+ return;
79
+ before = page.items.at(-1).pinned_at;
80
+ }
81
+ }
82
+ async *iterateThreadMembers(threadId, { withMember = false, signal } = {}) {
83
+ let after;
84
+ while (true) {
85
+ const query = new URLSearchParams({ limit: '100' });
86
+ if (withMember)
87
+ query.set('with_member', 'true');
88
+ if (after !== undefined)
89
+ query.set('after', snowflake(after, 'Thread member cursor'));
90
+ const page = await this.threadMembers(threadId, query, { signal });
91
+ let next = after;
92
+ for (const member of page) {
93
+ yield member;
94
+ next = member.user_id ?? next;
95
+ }
96
+ if (page.length < 100 || next === after)
97
+ return;
98
+ after = next;
99
+ }
100
+ }
43
101
  addReaction(id, messageId, emoji, options) {
44
102
  return this.rest.request('PUT', reactionPath(id, messageId, emoji) + '/@me', options);
45
103
  }
@@ -47,8 +105,13 @@ export class MicupChannels {
47
105
  return this.rest.request('DELETE', reactionPath(id, messageId, emoji) + '/@me', options);
48
106
  }
49
107
  startThread(id, body, options = {}) {
108
+ threadStart(body);
109
+ if (options.messageId !== undefined && (body.type !== undefined || body.invitable !== undefined)) {
110
+ throw new TypeError('A thread from a message takes only a name, archive duration and slowmode');
111
+ }
50
112
  const base = options.messageId === undefined ? channelPath(id) : messagesPath(id, options.messageId);
51
- return this.rest.request('POST', base + '/threads', { ...options, body });
113
+ const payload = options.messageId === undefined ? { ...body, type: body.type ?? 11 } : body;
114
+ return this.rest.request('POST', base + '/threads', { ...options, body: payload });
52
115
  }
53
116
  activeThreads(guildId, options) {
54
117
  return this.rest.request('GET', guildPath(guildId) + '/threads/active', options);
@@ -59,6 +122,122 @@ export class MicupChannels {
59
122
  leaveThread(threadId, options) {
60
123
  return this.rest.request('DELETE', channelPath(threadId) + '/thread-members/@me', options);
61
124
  }
125
+ createForumPost(channelId, { message, applied_tags, ...input }, options) {
126
+ threadStart(input);
127
+ if ((applied_tags?.length ?? 0) > 5 || message.nonce || message.enforce_nonce || message.tts) {
128
+ throw new TypeError('Invalid forum post tags or message options');
129
+ }
130
+ if (!message.content && !message.embeds?.length && !message.files?.length && !message.uploads?.length && !message.sticker_ids?.length) {
131
+ throw new TypeError('A forum post requires content, an embed, an attachment or a sticker');
132
+ }
133
+ const first = messageBody(message);
134
+ const post = { ...input, applied_tags };
135
+ if (first instanceof FormData) {
136
+ first.set('payload_json', JSON.stringify({ ...post, message: JSON.parse(String(first.get('payload_json'))) }));
137
+ return this.rest.request('POST', channelPath(channelId) + '/threads', { ...options, body: first });
138
+ }
139
+ return this.rest.request('POST', channelPath(channelId) + '/threads', { ...options, body: { ...post, message: first } });
140
+ }
141
+ archivedThreads(id, { before, limit, kind = 'public', signal } = {}) {
142
+ const suffix = kind === 'joined' ? '/users/@me/threads/archived/private' : '/threads/archived/' + kind;
143
+ const query = new URLSearchParams();
144
+ if (before)
145
+ query.set('before', before);
146
+ if (limit !== undefined) {
147
+ if (!Number.isInteger(limit) || limit < 2 || limit > 100)
148
+ throw new RangeError('Archived threads take 2 to 100 entries per page');
149
+ query.set('limit', String(limit));
150
+ }
151
+ return this.rest.request('GET', channelPath(id) + suffix, { query, signal });
152
+ }
153
+ searchThreads(id, query, options) {
154
+ return this.rest.request('GET', channelPath(id) + '/threads/search', { ...options, query });
155
+ }
156
+ addThreadMember(threadId, userId, options) {
157
+ return this.rest.request('PUT', channelPath(threadId) + '/thread-members/' + snowflake(userId, 'User ID'), options);
158
+ }
159
+ removeThreadMember(threadId, userId, options) {
160
+ return this.rest.request('DELETE', channelPath(threadId) + '/thread-members/' + snowflake(userId, 'User ID'), options);
161
+ }
162
+ createForumTag(channelId, tag, options) {
163
+ return this.rest.request('POST', channelPath(channelId) + '/tags', { ...options, body: forumTag(tag) });
164
+ }
165
+ editForumTag(channelId, tagId, tag, options) {
166
+ const path = channelPath(channelId) + '/tags/' + snowflake(tagId, 'Tag ID');
167
+ return this.rest.request('PUT', path, { ...options, body: forumTag(tag) });
168
+ }
169
+ deleteForumTag(channelId, tagId, options) {
170
+ return this.rest.request('DELETE', channelPath(channelId) + '/tags/' + snowflake(tagId, 'Tag ID'), options);
171
+ }
172
+ reactionUsers(id, messageId, emoji, query, options) {
173
+ return this.rest.request('GET', reactionPath(id, messageId, emoji) + '/users', { ...options, query });
174
+ }
175
+ async *iterateReactionUsers(id, messageId, emoji, options) {
176
+ const query = new URLSearchParams({ limit: '100' });
177
+ while (true) {
178
+ const page = await this.reactionUsers(id, messageId, emoji, query, options);
179
+ yield* page.items;
180
+ if (!page.has_more || !page.next_after || page.next_after === query.get('after'))
181
+ return;
182
+ query.set('after', page.next_after);
183
+ }
184
+ }
185
+ deleteReaction(id, messageId, { emoji, userId } = {}, options) {
186
+ if (userId !== undefined && emoji === undefined)
187
+ throw new TypeError('A user reaction needs an emoji');
188
+ const path = emoji === undefined ? messagesPath(id, messageId) + '/reactions' : reactionPath(id, messageId, emoji);
189
+ return this.rest.request('DELETE', path + (userId === undefined ? '' : '/' + snowflake(userId, 'User ID')), options);
190
+ }
191
+ addRecipient(channelId, userId, options) {
192
+ return this.rest.request('PUT', channelPath(channelId) + '/recipients/' + snowflake(userId, 'User ID'), options);
193
+ }
194
+ removeRecipient(channelId, userId, { silent, signal } = {}) {
195
+ const query = silent === undefined ? undefined : new URLSearchParams({ silent: String(silent) });
196
+ return this.rest.request('DELETE', channelPath(channelId) + '/recipients/' + snowflake(userId, 'User ID'), { query, signal });
197
+ }
198
+ deleteOwnMessages(channelId, { signal, ...proof } = {}) {
199
+ return this.rest.request('POST', messagesPath(channelId) + '/bulk-delete-mine', { signal, body: proof });
200
+ }
201
+ crosspostSource(channelId, messageId, options) {
202
+ return this.rest.request('GET', messagesPath(channelId, messageId) + '/crosspost-source', options);
203
+ }
204
+ archiveThread(threadId, archived = true, options) {
205
+ return this.edit(threadId, { archived }, options);
206
+ }
207
+ lockThread(threadId, locked = true, options) {
208
+ return this.edit(threadId, { locked }, options);
209
+ }
210
+ follow(announcementId, targetId, options) {
211
+ return this.rest.request('POST', channelPath(announcementId) + '/followers', {
212
+ ...options, body: { webhook_channel_id: snowflake(targetId, 'Target channel ID') },
213
+ });
214
+ }
215
+ followerStats(announcementId, options) {
216
+ return this.rest.request('GET', channelPath(announcementId) + '/follower-stats', options);
217
+ }
218
+ async forumPostData(channelId, threadIds, options) {
219
+ const ids = [...new Set(threadIds.map((id) => snowflake(id, 'Thread ID')))];
220
+ if (!ids.length || ids.length > 100)
221
+ throw new RangeError('Forum post data accepts 1 to 100 thread IDs');
222
+ const result = await this.rest.request('POST', channelPath(channelId) + '/post-data', { ...options, body: { thread_ids: ids }, idempotent: true });
223
+ return result.threads;
224
+ }
225
+ threadMembers(threadId, query, options) {
226
+ return this.rest.request('GET', channelPath(threadId) + '/thread-members', { ...options, query });
227
+ }
228
+ threadMember(threadId, userId, withMember = false, options) {
229
+ const query = withMember ? new URLSearchParams({ with_member: 'true' }) : undefined;
230
+ return this.rest.request('GET', channelPath(threadId) + '/thread-members/' + snowflake(userId, 'User ID'), { ...options, query });
231
+ }
232
+ guildInvites(guildId, options) {
233
+ return this.rest.request('GET', guildPath(guildId) + '/invites', options);
234
+ }
235
+ getInvite(code, options) {
236
+ return this.rest.request('GET', invitePath(code), options);
237
+ }
238
+ deleteInvite(code, options) {
239
+ return this.rest.request('DELETE', invitePath(code), options);
240
+ }
62
241
  invites(channelId, options) {
63
242
  return this.rest.request('GET', channelPath(channelId) + '/invites', options);
64
243
  }
@@ -14,5 +14,6 @@ export declare class MicupCommands {
14
14
  create(command: CommandDefinition, scope?: CommandScope): Promise<MicupCommand>;
15
15
  edit(id: string, command: Partial<CommandDefinition>, scope?: CommandScope): Promise<MicupCommand>;
16
16
  delete(id: string, scope?: CommandScope): Promise<void>;
17
+ clear(scope?: CommandScope): Promise<void>;
17
18
  set(commands: readonly CommandDefinition[], scope?: CommandScope): Promise<MicupCommand[]>;
18
19
  }
@@ -1,7 +1,14 @@
1
1
  import { CommandType } from '../model/interaction.js';
2
+ import { isLocaleTag } from '../model/locale.js';
2
3
  import { snowflake } from './messages.js';
3
4
  const chatName = /^[-_\p{Ll}\p{Lo}\p{N}]{1,32}$/u;
4
5
  const lengthWithin = (value, limit) => Boolean(value && [...value].length <= limit);
6
+ function validateLocalizations(values, validate) {
7
+ for (const [locale, text] of Object.entries(values ?? {})) {
8
+ if (!isLocaleTag(locale) || !validate(text))
9
+ throw new TypeError('Invalid command localization: ' + locale);
10
+ }
11
+ }
5
12
  function validateOptions(options, depth, group = false) {
6
13
  if (options.length > 25)
7
14
  throw new RangeError('A command can contain at most 25 options per level');
@@ -14,6 +21,8 @@ function validateOptions(options, depth, group = false) {
14
21
  throw new TypeError('Invalid or duplicate Micup command option: ' + option.name);
15
22
  }
16
23
  names.add(option.name);
24
+ validateLocalizations(option.name_localizations, (name) => chatName.test(name));
25
+ validateLocalizations(option.description_localizations, (text) => lengthWithin(text, 100));
17
26
  if (!Number.isInteger(option.type) || option.type < 1 || option.type > 11 ||
18
27
  (nested && !structural) || (group && option.type !== 1)) {
19
28
  throw new TypeError('Invalid Micup option structure');
@@ -37,6 +46,7 @@ function validateOptions(options, depth, group = false) {
37
46
  ? typeof choice.value === 'string' && lengthWithin(choice.value, 100)
38
47
  : typeof choice.value === 'number' && Number.isFinite(choice.value) &&
39
48
  (option.type !== 4 || Number.isSafeInteger(choice.value));
49
+ validateLocalizations(choice.name_localizations, (text) => lengthWithin(text, 100));
40
50
  if (!lengthWithin(choice.name, 100) || !validValue)
41
51
  throw new TypeError('Invalid Micup command choice');
42
52
  }
@@ -51,12 +61,16 @@ function commandBody(command) {
51
61
  if (type === CommandType.ChatInput) {
52
62
  if (!chatName.test(name) || !lengthWithin(description, 100))
53
63
  throw new TypeError('Invalid Micup command name or description');
64
+ validateLocalizations(name_localizations, (text) => chatName.test(text));
65
+ validateLocalizations(description_localizations, (text) => lengthWithin(text, 100));
54
66
  validateOptions(options ?? [], 0);
55
67
  }
56
68
  else if ((type !== CommandType.User && type !== CommandType.Message) ||
57
69
  !lengthWithin(name, 32) || description || options?.length) {
58
70
  throw new TypeError('Invalid Micup context menu command');
59
71
  }
72
+ if (type !== CommandType.ChatInput)
73
+ validateLocalizations(name_localizations, (text) => lengthWithin(text, 32));
60
74
  return { type, name, description, options, name_localizations, description_localizations, default_member_permissions, dm_permission };
61
75
  }
62
76
  export class MicupCommands {
@@ -86,6 +100,9 @@ export class MicupCommands {
86
100
  delete(id, scope = {}) {
87
101
  return this.rest.request('DELETE', this.#path(scope, id), scope);
88
102
  }
103
+ clear(scope = {}) {
104
+ return this.rest.request('DELETE', this.#path(scope), scope);
105
+ }
89
106
  set(commands, scope = {}) {
90
107
  if (commands.length > 100)
91
108
  throw new RangeError('Micup accepts up to 100 commands per scope');
@@ -0,0 +1,35 @@
1
+ import type { MicupRequestOptions, RestTransport } from './transport.js';
2
+ export type DiscoveryApplicationStatus = 'pending' | 'approved' | 'rejected' | 'removed';
3
+ export interface DiscoveryApplication {
4
+ guild_id: string;
5
+ status: DiscoveryApplicationStatus | string;
6
+ description: string;
7
+ category_type: number;
8
+ primary_language: string | null;
9
+ custom_tags: string[];
10
+ applied_at: string;
11
+ reviewed_at: string | null;
12
+ review_reason: string | null;
13
+ removed_at: string | null;
14
+ removal_reason: string | null;
15
+ }
16
+ export interface DiscoveryStatus {
17
+ application: DiscoveryApplication | null;
18
+ eligible: boolean;
19
+ min_member_count: number;
20
+ }
21
+ export interface DiscoveryApplicationInput {
22
+ description: string;
23
+ category_type: number;
24
+ primary_language?: string;
25
+ custom_tags?: readonly string[];
26
+ }
27
+ export type DiscoveryApplicationEdit = Partial<DiscoveryApplicationInput>;
28
+ export declare class MicupDiscovery {
29
+ private readonly rest;
30
+ constructor(rest: RestTransport);
31
+ status(guildId: string, options?: MicupRequestOptions): Promise<DiscoveryStatus>;
32
+ apply(guildId: string, application: DiscoveryApplicationInput, options?: MicupRequestOptions): Promise<DiscoveryApplication>;
33
+ edit(guildId: string, edit: DiscoveryApplicationEdit, options?: MicupRequestOptions): Promise<DiscoveryApplication>;
34
+ withdraw(guildId: string, options?: MicupRequestOptions): Promise<void>;
35
+ }
@@ -0,0 +1,33 @@
1
+ import { guildPath } from './guilds.js';
2
+ function check({ description, category_type, custom_tags }) {
3
+ if (description !== undefined && (typeof description !== 'string' || [...description].length < 10 || [...description].length > 300)) {
4
+ throw new RangeError('A discovery description takes 10 to 300 characters');
5
+ }
6
+ if (category_type !== undefined && !Number.isSafeInteger(category_type))
7
+ throw new TypeError('A discovery category is an integer');
8
+ if (custom_tags !== undefined && custom_tags.length > 10)
9
+ throw new RangeError('A discovery listing takes up to 10 custom tags');
10
+ }
11
+ export class MicupDiscovery {
12
+ rest;
13
+ constructor(rest) {
14
+ this.rest = rest;
15
+ }
16
+ status(guildId, options) {
17
+ return this.rest.request('GET', guildPath(guildId) + '/discovery', options);
18
+ }
19
+ apply(guildId, application, options) {
20
+ if (application.description === undefined || application.category_type === undefined) {
21
+ throw new TypeError('A discovery application needs a description and a category');
22
+ }
23
+ check(application);
24
+ return this.rest.request('POST', guildPath(guildId) + '/discovery', { ...options, body: application });
25
+ }
26
+ edit(guildId, edit, options) {
27
+ check(edit);
28
+ return this.rest.request('PATCH', guildPath(guildId) + '/discovery', { ...options, body: edit });
29
+ }
30
+ withdraw(guildId, options) {
31
+ return this.rest.request('DELETE', guildPath(guildId) + '/discovery', options);
32
+ }
33
+ }
@@ -11,6 +11,40 @@ interface APIErrorBody {
11
11
  global?: unknown;
12
12
  }
13
13
  export declare function retryDelay(value: unknown): number;
14
+ export declare const MicupErrorCode: Readonly<{
15
+ readonly InvalidFormBody: 'INVALID_FORM_BODY';
16
+ readonly RateLimited: 'RATE_LIMITED';
17
+ readonly NewDMRateLimited: 'NEW_DM_RATE_LIMITED';
18
+ readonly SlowmodeRateLimited: 'SLOWMODE_RATE_LIMITED';
19
+ readonly ResourceLocked: 'RESOURCE_LOCKED';
20
+ readonly Unauthorized: 'UNAUTHORIZED';
21
+ readonly MissingAccess: 'MISSING_ACCESS';
22
+ readonly MissingPermissions: 'MISSING_PERMISSIONS';
23
+ readonly TwoFactorRequired: 'TWO_FACTOR_REQUIRED';
24
+ readonly CommunicationDisabled: 'COMMUNICATION_DISABLED';
25
+ readonly ContentBlocked: 'CONTENT_BLOCKED';
26
+ readonly SpamBlocked: 'SPAM_BLOCKED';
27
+ readonly CannotSendEmptyMessage: 'CANNOT_SEND_EMPTY_MESSAGE';
28
+ readonly UnknownChannel: 'UNKNOWN_CHANNEL';
29
+ readonly UnknownGuild: 'UNKNOWN_GUILD';
30
+ readonly UnknownMember: 'UNKNOWN_MEMBER';
31
+ readonly UnknownMessage: 'UNKNOWN_MESSAGE';
32
+ readonly UnknownRole: 'UNKNOWN_ROLE';
33
+ readonly UnknownUser: 'UNKNOWN_USER';
34
+ readonly UnknownInvite: 'UNKNOWN_INVITE';
35
+ readonly UnknownEmoji: 'UNKNOWN_EMOJI';
36
+ readonly UnknownSticker: 'UNKNOWN_STICKER';
37
+ readonly UnknownWebhook: 'UNKNOWN_WEBHOOK';
38
+ readonly ThreadArchived: 'THREAD_ARCHIVED';
39
+ readonly ThreadLocked: 'THREAD_LOCKED';
40
+ readonly MaxActiveThreads: 'MAX_ACTIVE_THREADS';
41
+ readonly NsfwAgeRestricted: 'NSFW_CONTENT_AGE_RESTRICTED';
42
+ readonly FeatureTemporarilyDisabled: 'FEATURE_TEMPORARILY_DISABLED';
43
+ readonly VoiceRoomNotActive: 'VOICE_ROOM_NOT_ACTIVE';
44
+ readonly RoomTournamentConflict: 'ROOM_TOURNAMENT_CONFLICT';
45
+ readonly UnknownRoomTournament: 'UNKNOWN_ROOM_TOURNAMENT';
46
+ readonly SudoModeRequired: 'SUDO_MODE_REQUIRED';
47
+ }>;
14
48
  export declare class MicupAPIError extends Error {
15
49
  readonly status: number;
16
50
  readonly code?: string;
@@ -20,5 +54,9 @@ export declare class MicupAPIError extends Error {
20
54
  readonly global: boolean;
21
55
  readonly errors: readonly MicupFieldError[];
22
56
  constructor(response: Response, body?: APIErrorBody);
57
+ get notFound(): boolean;
58
+ get forbidden(): boolean;
59
+ get rateLimited(): boolean;
60
+ hasFieldCode(code: string): boolean;
23
61
  }
24
62
  export {};