micup.ts 0.0.0-stage → 1.0.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 (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/dist/events/mux.d.ts +82 -0
  4. package/dist/events/mux.js +23 -0
  5. package/dist/events/router.d.ts +11 -0
  6. package/dist/events/router.js +54 -0
  7. package/dist/gateway/connection.d.ts +30 -0
  8. package/dist/gateway/connection.js +272 -0
  9. package/dist/gateway/protocol.d.ts +40 -0
  10. package/dist/gateway/protocol.js +59 -0
  11. package/dist/index.d.ts +29 -0
  12. package/dist/index.js +12 -0
  13. package/dist/model/guild.d.ts +69 -0
  14. package/dist/model/guild.js +1 -0
  15. package/dist/model/interaction.d.ts +137 -0
  16. package/dist/model/interaction.js +18 -0
  17. package/dist/model/permissions.d.ts +47 -0
  18. package/dist/model/permissions.js +81 -0
  19. package/dist/model/presence.d.ts +16 -0
  20. package/dist/model/presence.js +30 -0
  21. package/dist/rest/channels.d.ts +82 -0
  22. package/dist/rest/channels.js +68 -0
  23. package/dist/rest/client.d.ts +48 -0
  24. package/dist/rest/client.js +151 -0
  25. package/dist/rest/commands.d.ts +18 -0
  26. package/dist/rest/commands.js +94 -0
  27. package/dist/rest/errors.d.ts +24 -0
  28. package/dist/rest/errors.js +26 -0
  29. package/dist/rest/guilds.d.ts +76 -0
  30. package/dist/rest/guilds.js +90 -0
  31. package/dist/rest/interactions.d.ts +30 -0
  32. package/dist/rest/interactions.js +79 -0
  33. package/dist/rest/messages.d.ts +65 -0
  34. package/dist/rest/messages.js +38 -0
  35. package/dist/rest/transport.d.ts +16 -0
  36. package/dist/rest/transport.js +154 -0
  37. package/dist/session/requests.d.ts +39 -0
  38. package/dist/session/requests.js +144 -0
  39. package/dist/session/session.d.ts +63 -0
  40. package/dist/session/session.js +193 -0
  41. package/dist/session/voice.d.ts +41 -0
  42. package/dist/session/voice.js +168 -0
  43. package/dist/shard/manager.d.ts +20 -0
  44. package/dist/shard/manager.js +93 -0
  45. package/dist/state/cache.d.ts +15 -0
  46. package/dist/state/cache.js +257 -0
  47. package/package.json +39 -4
@@ -0,0 +1,38 @@
1
+ export function snowflake(id, label) {
2
+ if (typeof id !== 'string' || !/^\d+$/.test(id))
3
+ throw new TypeError(label + ' must be a numeric string');
4
+ return id;
5
+ }
6
+ export function messagesPath(channelId, messageId) {
7
+ const base = '/channels/' + snowflake(channelId, 'Channel ID') + '/messages';
8
+ return messageId === undefined ? base : base + '/' + snowflake(messageId, 'Message ID');
9
+ }
10
+ export function messageBody({ files = [], ...message }, reply) {
11
+ const body = { ...message, ...(reply && { message_reference: reply }) };
12
+ if (files.length === 0)
13
+ return body;
14
+ const form = new FormData();
15
+ const attachments = [...(body.attachments ?? []), ...files.map(({ name, data, description }, index) => {
16
+ if (!name || /[/\\\r\n\u0000]/.test(name) || !(data instanceof Blob)) {
17
+ throw new TypeError('Micup attachments require a filename and a Blob');
18
+ }
19
+ return { id: index, filename: name, description };
20
+ })];
21
+ if (attachments.length > 10)
22
+ throw new RangeError('Micup messages support up to 10 attachments');
23
+ form.append('payload_json', JSON.stringify({ ...body, attachments }));
24
+ files.forEach(({ name, data }, index) => form.append('files[' + index + ']', data, name));
25
+ return form;
26
+ }
27
+ export function messageQuery({ before, after, around, limit }) {
28
+ const entries = Object.entries({ before, after, around }).filter((entry) => entry[1] !== undefined);
29
+ if (entries.length > 1)
30
+ throw new TypeError('Only one message cursor can be used at a time');
31
+ const query = new URLSearchParams(entries.map(([name, value]) => [name, snowflake(value, name)]));
32
+ if (limit !== undefined) {
33
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
34
+ throw new RangeError('Message limit must be between 1 and 100');
35
+ query.set('limit', String(limit));
36
+ }
37
+ return query;
38
+ }
@@ -0,0 +1,16 @@
1
+ export type RestMethod = 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
2
+ export interface MicupRequestOptions {
3
+ signal?: AbortSignal;
4
+ }
5
+ export interface RestRequestOptions extends MicupRequestOptions {
6
+ body?: unknown;
7
+ query?: URLSearchParams;
8
+ reason?: string;
9
+ }
10
+ export declare class RestTransport {
11
+ #private;
12
+ private readonly token;
13
+ private readonly attempts;
14
+ constructor(api: string, token: string, attempts?: number);
15
+ request<T>(method: RestMethod, path: string, { body, signal, query, reason }?: RestRequestOptions): Promise<T>;
16
+ }
@@ -0,0 +1,154 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { MicupAPIError, retryDelay } from './errors.js';
3
+ const majorParameters = new Set(['channels', 'guilds', 'webhooks']);
4
+ const maxRetryDelay = 30_000;
5
+ const repeatable = new Set(['GET', 'HEAD', 'PUT', 'DELETE']);
6
+ const snowflake = /^\d+$/;
7
+ function routeKey(method, path) {
8
+ const parts = path.split('/');
9
+ return method + ' ' + parts.map((part, index) => {
10
+ if (parts[index - 1] === 'reactions')
11
+ return '{emoji}';
12
+ if (parts[index - 2] === 'webhooks' && snowflake.test(parts[index - 1]))
13
+ return '{token}';
14
+ return snowflake.test(part) && !majorParameters.has(parts[index - 1]) ? '{id}' : part;
15
+ }).join('/');
16
+ }
17
+ class RateLimits {
18
+ #reset = new Map();
19
+ #global = 0;
20
+ async wait(route, signal) {
21
+ while (true) {
22
+ signal?.throwIfAborted();
23
+ const wait = Math.max(this.#global, this.#reset.get(route) ?? 0) - performance.now();
24
+ if (wait <= 0) {
25
+ this.#reset.delete(route);
26
+ return;
27
+ }
28
+ await delay(Math.ceil(wait), undefined, { signal });
29
+ }
30
+ }
31
+ block(route, wait, global = false) {
32
+ if (!wait)
33
+ return;
34
+ const now = performance.now();
35
+ if (global) {
36
+ this.#global = Math.max(this.#global, now + wait);
37
+ return;
38
+ }
39
+ this.#reset.set(route, Math.max(this.#reset.get(route) ?? 0, now + wait));
40
+ if (this.#reset.size > 4096) {
41
+ for (const [key, until] of this.#reset) {
42
+ if (until <= now)
43
+ this.#reset.delete(key);
44
+ }
45
+ }
46
+ }
47
+ }
48
+ async function readJson(response, limit) {
49
+ if (!response.body)
50
+ return undefined;
51
+ if (Number(response.headers.get('content-length')) > limit) {
52
+ await response.body.cancel();
53
+ throw new RangeError('Micup API response exceeds its size limit');
54
+ }
55
+ const reader = response.body.getReader();
56
+ const chunks = [];
57
+ let size = 0;
58
+ try {
59
+ while (true) {
60
+ const next = await reader.read();
61
+ if (next.done)
62
+ break;
63
+ size += next.value.length;
64
+ if (size > limit) {
65
+ await reader.cancel();
66
+ throw new RangeError('Micup API response exceeds its size limit');
67
+ }
68
+ chunks.push(next.value);
69
+ }
70
+ }
71
+ finally {
72
+ reader.releaseLock();
73
+ }
74
+ return size ? JSON.parse(Buffer.concat(chunks, size).toString('utf8')) : undefined;
75
+ }
76
+ export class RestTransport {
77
+ token;
78
+ attempts;
79
+ #limits = new RateLimits();
80
+ #api;
81
+ constructor(api, token, attempts = 5) {
82
+ this.token = token;
83
+ this.attempts = attempts;
84
+ this.#api = new URL(api + '/');
85
+ if (!Number.isSafeInteger(attempts) || attempts < 1 || attempts > 5) {
86
+ throw new RangeError('Micup REST attempts must be between 1 and 5');
87
+ }
88
+ }
89
+ async request(method, path, { body, signal, query, reason } = {}) {
90
+ if (!path.startsWith('/') || path.startsWith('//') || /[\\?#\u0000-\u0020]/.test(path)) {
91
+ throw new TypeError('Micup REST path must be relative to the versioned API');
92
+ }
93
+ const target = new URL('.' + path, this.#api);
94
+ if (target.origin !== this.#api.origin || !target.pathname.startsWith(this.#api.pathname)) {
95
+ throw new TypeError('Micup REST path must be relative to the versioned API');
96
+ }
97
+ if (query?.size)
98
+ target.search = query.toString();
99
+ const headers = new Headers({ Authorization: 'Bot ' + this.token, 'User-Agent': 'micup.ts' });
100
+ if (reason !== undefined) {
101
+ if (typeof reason !== 'string' || !reason.trim() || reason.length > 512 || /[\r\n]/.test(reason)) {
102
+ throw new TypeError('Invalid Micup audit log reason');
103
+ }
104
+ headers.set('X-Audit-Log-Reason', encodeURIComponent(reason.trim()));
105
+ }
106
+ const multipart = body instanceof FormData;
107
+ if (body !== undefined && !multipart)
108
+ headers.set('Content-Type', 'application/json');
109
+ const payload = multipart ? body : JSON.stringify(body);
110
+ const route = routeKey(method, target.pathname.slice(this.#api.pathname.length - 1));
111
+ let last;
112
+ for (let attempt = 0; attempt < this.attempts; attempt++) {
113
+ await this.#limits.wait(route, signal);
114
+ const backoff = 500 * 2 ** attempt;
115
+ const remaining = attempt + 1 < this.attempts;
116
+ let response;
117
+ try {
118
+ response = await fetch(target.href, { method, headers, body: payload, signal, redirect: 'error' });
119
+ }
120
+ catch {
121
+ signal?.throwIfAborted();
122
+ last = new Error('Micup API connection failed');
123
+ if (!remaining || !repeatable.has(method))
124
+ throw last;
125
+ await delay(backoff, undefined, { signal });
126
+ continue;
127
+ }
128
+ if (response.headers.get('x-ratelimit-remaining') === '0') {
129
+ this.#limits.block(route, retryDelay(response.headers.get('x-ratelimit-reset-after')));
130
+ }
131
+ if (response.ok)
132
+ return await readJson(response, 2 * 1024 * 1024);
133
+ const errorBody = await readJson(response, 64 * 1024).catch(() => undefined);
134
+ signal?.throwIfAborted();
135
+ const error = new MicupAPIError(response, errorBody);
136
+ last = error;
137
+ let wait = 0;
138
+ if (response.status === 429) {
139
+ wait = Math.max(error.retryAfterMs, 1);
140
+ this.#limits.block(route, wait, error.global);
141
+ }
142
+ else if (response.status === 423) {
143
+ wait = Math.max(error.retryAfterMs, 1000);
144
+ }
145
+ else if (response.status >= 500 && repeatable.has(method)) {
146
+ wait = Math.max(error.retryAfterMs, backoff);
147
+ }
148
+ if (!remaining || wait === 0 || wait > maxRetryDelay)
149
+ throw error;
150
+ await delay(wait, undefined, { signal });
151
+ }
152
+ throw last;
153
+ }
154
+ }
@@ -0,0 +1,39 @@
1
+ import { type GatewayDispatch } from '../gateway/protocol.js';
2
+ import type { MicupMember } from '../model/guild.js';
3
+ export interface GuildCount {
4
+ guild_id: string;
5
+ member_count: number;
6
+ online_count: number;
7
+ }
8
+ export interface ChannelMemberCount {
9
+ guild_id?: string;
10
+ channel_id: string;
11
+ member_count: number;
12
+ online_count: number;
13
+ }
14
+ export interface GuildMembersRequest {
15
+ query?: string;
16
+ limit?: number;
17
+ userIds?: readonly string[];
18
+ presences?: boolean;
19
+ signal?: AbortSignal;
20
+ }
21
+ export declare class GatewayRequestError extends Error {
22
+ readonly opcode: number;
23
+ readonly retryAfter: number;
24
+ constructor(opcode: number, retryAfter: number);
25
+ }
26
+ type Send = (opcode: number, data: unknown, options?: {
27
+ signal?: AbortSignal;
28
+ }) => Promise<void>;
29
+ export declare class SessionRequests {
30
+ #private;
31
+ private readonly send;
32
+ constructor(send: Send);
33
+ guildCounts(ids: readonly string[], signal?: AbortSignal): Promise<GuildCount[]>;
34
+ channelCounts(guildId: string, ids: readonly string[], signal?: AbortSignal): Promise<ChannelMemberCount[]>;
35
+ members(guildId: string, { query, limit, userIds, presences, signal }?: GuildMembersRequest): Promise<MicupMember[]>;
36
+ receive(event: GatewayDispatch): void;
37
+ invalidate(): void;
38
+ }
39
+ export {};
@@ -0,0 +1,144 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { GatewayOpcode } from '../gateway/protocol.js';
3
+ import { snowflake } from '../rest/messages.js';
4
+ export class GatewayRequestError extends Error {
5
+ opcode;
6
+ retryAfter;
7
+ constructor(opcode, retryAfter) {
8
+ super('Micup rate-limited the Gateway request');
9
+ this.opcode = opcode;
10
+ this.retryAfter = retryAfter;
11
+ this.name = 'GatewayRequestError';
12
+ }
13
+ }
14
+ function unique(ids, max, label) {
15
+ const values = [...new Set(ids.map((id) => snowflake(id, label)))];
16
+ if (!values.length || values.length > max)
17
+ throw new RangeError(label + ' list accepts 1 to ' + max + ' IDs');
18
+ return values;
19
+ }
20
+ class Slots {
21
+ capacity;
22
+ #waiters = new Set();
23
+ #active = 0;
24
+ constructor(capacity) {
25
+ this.capacity = capacity;
26
+ }
27
+ async acquire(signal) {
28
+ while (this.#active >= this.capacity) {
29
+ signal.throwIfAborted();
30
+ await new Promise((resolve, reject) => {
31
+ const wake = () => {
32
+ signal.removeEventListener('abort', abort);
33
+ this.#waiters.delete(wake);
34
+ resolve();
35
+ };
36
+ const abort = () => {
37
+ this.#waiters.delete(wake);
38
+ reject(signal.reason);
39
+ };
40
+ this.#waiters.add(wake);
41
+ signal.addEventListener('abort', abort, { once: true });
42
+ });
43
+ }
44
+ signal.throwIfAborted();
45
+ this.#active++;
46
+ return () => {
47
+ this.#active--;
48
+ this.#waiters.values().next().value?.();
49
+ };
50
+ }
51
+ }
52
+ export class SessionRequests {
53
+ send;
54
+ #pending = new Map();
55
+ #members = new Slots(2);
56
+ #counts = new Slots(8);
57
+ #epoch = new AbortController();
58
+ constructor(send) {
59
+ this.send = send;
60
+ }
61
+ guildCounts(ids, signal) {
62
+ return this.#request(GatewayOpcode.RequestGuildCounts, 'GUILD_COUNTS_UPDATE', { guild_ids: unique(ids, 100, 'Guild ID') }, this.#counts, signal, (value, resolve) => {
63
+ const counts = value.counts;
64
+ if (Array.isArray(counts))
65
+ resolve(counts);
66
+ });
67
+ }
68
+ channelCounts(guildId, ids, signal) {
69
+ return this.#request(GatewayOpcode.RequestChannelMemberCounts, 'CHANNEL_MEMBER_COUNTS_UPDATE', { guild_id: snowflake(guildId, 'Guild ID'), channel_ids: unique(ids, 25, 'Channel ID') }, this.#counts, signal, (value, resolve) => {
70
+ const counts = value.counts;
71
+ if (Array.isArray(counts))
72
+ resolve(counts);
73
+ });
74
+ }
75
+ members(guildId, { query = '', limit = 0, userIds, presences, signal } = {}) {
76
+ snowflake(guildId, 'Guild ID');
77
+ if (!Number.isSafeInteger(limit) || limit < 0 || limit > 100 || (userIds?.length && query)) {
78
+ throw new TypeError('Invalid Micup member request');
79
+ }
80
+ const body = {
81
+ guild_id: guildId, query, limit, presences: presences ?? false,
82
+ ...(userIds?.length ? { user_ids: unique(userIds, 100, 'User ID') } : {}),
83
+ };
84
+ const chunks = new Map();
85
+ return this.#request(GatewayOpcode.RequestGuildMembers, 'GUILD_MEMBERS_CHUNK', body, this.#members, signal, (value, resolve, reject) => {
86
+ const chunk = value;
87
+ if (chunk.guild_id !== guildId)
88
+ return;
89
+ if (!Number.isSafeInteger(chunk.chunk_count) || chunk.chunk_count < 1 || chunk.chunk_count > 16_384 ||
90
+ !Number.isSafeInteger(chunk.chunk_index) || chunk.chunk_index < 0 || chunk.chunk_index >= chunk.chunk_count ||
91
+ !Array.isArray(chunk.members)) {
92
+ reject(new Error('Micup returned an invalid member chunk'));
93
+ return;
94
+ }
95
+ chunks.set(chunk.chunk_index, chunk.members);
96
+ if (chunks.size === chunk.chunk_count) {
97
+ resolve([...chunks].sort(([a], [b]) => a - b).flatMap(([, members]) => members));
98
+ }
99
+ });
100
+ }
101
+ receive(event) {
102
+ const data = event.data;
103
+ const nonce = data?.nonce ?? data?.meta?.nonce;
104
+ if (!nonce)
105
+ return;
106
+ const pending = this.#pending.get(nonce);
107
+ if (!pending)
108
+ return;
109
+ if (event.name === 'RATE_LIMITED') {
110
+ pending.reject(new GatewayRequestError(pending.opcode, data?.retry_after ?? 0));
111
+ }
112
+ else if (event.name === pending.name) {
113
+ pending.accept(data);
114
+ }
115
+ }
116
+ invalidate() {
117
+ this.#epoch.abort(new Error('Micup Gateway session ended'));
118
+ this.#epoch = new AbortController();
119
+ }
120
+ async #request(opcode, name, body, slots, caller, accept) {
121
+ const signals = [this.#epoch.signal, AbortSignal.timeout(12_000)];
122
+ if (caller)
123
+ signals.push(caller);
124
+ const signal = AbortSignal.any(signals);
125
+ const release = await slots.acquire(signal);
126
+ const nonce = randomBytes(12).toString('hex');
127
+ let pending;
128
+ const result = new Promise((resolve, reject) => {
129
+ pending = { opcode, name, accept: (data) => accept(data, resolve, reject), reject };
130
+ });
131
+ const abort = () => pending.reject(signal.reason);
132
+ this.#pending.set(nonce, pending);
133
+ signal.addEventListener('abort', abort, { once: true });
134
+ try {
135
+ const [, reply] = await Promise.all([this.send(opcode, { ...body, nonce }, { signal }), result]);
136
+ return reply;
137
+ }
138
+ finally {
139
+ this.#pending.delete(nonce);
140
+ signal.removeEventListener('abort', abort);
141
+ release();
142
+ }
143
+ }
144
+ }
@@ -0,0 +1,63 @@
1
+ import { type GatewayDispatch } from '../gateway/protocol.js';
2
+ import { type VoiceJoinOptions, type VoiceServerUpdate, type VoiceSessionOptions } from './voice.js';
3
+ import { GatewayState } from '../state/cache.js';
4
+ import type { MicupMember } from '../model/guild.js';
5
+ import { type CustomStatus, type Presence, type PresenceStatus } from '../model/presence.js';
6
+ import { type ChannelMemberCount, type GuildCount, type GuildMembersRequest } from './requests.js';
7
+ export interface GatewaySessionConfig {
8
+ readonly endpoint: string;
9
+ readonly token: string;
10
+ readonly botId?: string;
11
+ readonly shardId?: number;
12
+ readonly shardCount?: number;
13
+ }
14
+ export interface GatewaySessionOptions extends VoiceSessionOptions {
15
+ readonly handler: (event: GatewayDispatch, signal: AbortSignal) => void | Promise<void>;
16
+ readonly ignoredEvents?: readonly string[];
17
+ readonly flags?: number;
18
+ readonly presence?: Presence;
19
+ readonly minBackoffMs?: number;
20
+ readonly maxBackoffMs?: number;
21
+ readonly onReady?: (resumed: boolean) => void;
22
+ readonly onDisconnect?: (error: unknown) => void;
23
+ readonly onGatewayError?: (data: unknown) => void;
24
+ readonly beforeIdentify?: (signal: AbortSignal) => Promise<void>;
25
+ }
26
+ export declare class GatewaySession {
27
+ #private;
28
+ readonly state: GatewayState;
29
+ constructor(config: GatewaySessionConfig, options: GatewaySessionOptions);
30
+ get ready(): boolean;
31
+ get shardId(): number;
32
+ get sessionId(): string | undefined;
33
+ get latency(): number | undefined;
34
+ send(opcode: number, data: unknown, { signal }?: {
35
+ signal?: AbortSignal;
36
+ }): Promise<void>;
37
+ get presence(): Presence;
38
+ updatePresence(presence: Presence, { signal }?: {
39
+ signal?: AbortSignal;
40
+ }): Promise<void>;
41
+ setStatus(status: PresenceStatus, options?: {
42
+ signal?: AbortSignal;
43
+ }): Promise<void>;
44
+ setCustomStatus(custom_status: CustomStatus | null, options?: {
45
+ signal?: AbortSignal;
46
+ }): Promise<void>;
47
+ requestGuildCounts(ids: readonly string[], { signal }?: {
48
+ signal?: AbortSignal;
49
+ }): Promise<GuildCount[]>;
50
+ requestChannelMemberCounts(guildId: string, ids: readonly string[], { signal }?: {
51
+ signal?: AbortSignal;
52
+ }): Promise<ChannelMemberCount[]>;
53
+ requestGuildMembers(guildId: string, request?: GuildMembersRequest): Promise<MicupMember[]>;
54
+ joinVoice(guildId: string, channelId: string, options?: VoiceJoinOptions): Promise<VoiceServerUpdate>;
55
+ voice(guildId: string): VoiceServerUpdate | undefined;
56
+ leaveVoice(guildId: string, connectionId: string, { signal }?: {
57
+ signal?: AbortSignal;
58
+ }): Promise<void>;
59
+ updateVoiceState(guildId: string, options: VoiceJoinOptions): Promise<void>;
60
+ run({ signal }?: {
61
+ signal?: AbortSignal;
62
+ }): Promise<void>;
63
+ }
@@ -0,0 +1,193 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { GatewayConnection } from '../gateway/connection.js';
3
+ import { GatewayCloseError, gatewayEndpoint } from '../gateway/protocol.js';
4
+ import { SessionVoice } from './voice.js';
5
+ import { Permission, hasPermissions } from '../model/permissions.js';
6
+ import { GatewayState } from '../state/cache.js';
7
+ import { GatewayOpcode } from '../gateway/protocol.js';
8
+ import { activePresence, normalizePresence } from '../model/presence.js';
9
+ import { SessionRequests } from './requests.js';
10
+ export class GatewaySession {
11
+ #resume = { sequence: null };
12
+ #endpoint;
13
+ #token;
14
+ #shard;
15
+ #options;
16
+ #ignoredEvents;
17
+ #flags;
18
+ #voice;
19
+ state = new GatewayState();
20
+ #botId;
21
+ #presence;
22
+ #requests;
23
+ #minBackoff;
24
+ #maxBackoff;
25
+ #running = false;
26
+ #ready = false;
27
+ #connection;
28
+ constructor(config, options) {
29
+ this.#endpoint = gatewayEndpoint(config.endpoint);
30
+ if (!/^[\x21-\x7E]+$/.test(config.token ?? ''))
31
+ throw new TypeError('Gateway token is required');
32
+ this.#token = config.token;
33
+ this.#botId = config.botId;
34
+ const id = config.shardId ?? 0;
35
+ const count = config.shardCount ?? 1;
36
+ if (!Number.isSafeInteger(id) || !Number.isSafeInteger(count) || id < 0 || id >= count) {
37
+ throw new RangeError('Invalid Micup shard configuration');
38
+ }
39
+ this.#shard = [id, count];
40
+ if (typeof options?.handler !== 'function')
41
+ throw new TypeError('A Gateway event handler is required');
42
+ this.#options = { ...options };
43
+ this.#voice = new SessionVoice(config.botId, this.send.bind(this), this.#options);
44
+ this.#requests = new SessionRequests(this.send.bind(this));
45
+ this.#presence = options.presence && normalizePresence(options.presence);
46
+ this.#ignoredEvents = [...(options.ignoredEvents ?? [])];
47
+ if (this.#ignoredEvents.length > 256 || this.#ignoredEvents.some((name) => !/^[A-Z][A-Z_0-9]*$/.test(name))) {
48
+ throw new TypeError('Invalid Micup ignored Gateway events');
49
+ }
50
+ this.#flags = options.flags ?? 0;
51
+ if (!Number.isSafeInteger(this.#flags) || this.#flags < 0)
52
+ throw new RangeError('Invalid Micup session flags');
53
+ this.#minBackoff = options.minBackoffMs ?? 1000;
54
+ this.#maxBackoff = options.maxBackoffMs ?? 15_000;
55
+ if (!Number.isSafeInteger(this.#minBackoff) || !Number.isSafeInteger(this.#maxBackoff) ||
56
+ this.#minBackoff < 1 || this.#maxBackoff < this.#minBackoff || this.#maxBackoff > 2_147_483_647) {
57
+ throw new RangeError('Invalid Micup reconnect backoff');
58
+ }
59
+ }
60
+ get ready() {
61
+ return this.#ready;
62
+ }
63
+ get shardId() {
64
+ return this.#shard[0];
65
+ }
66
+ get sessionId() {
67
+ return this.#resume.sessionId;
68
+ }
69
+ get latency() {
70
+ return this.#connection?.latency;
71
+ }
72
+ async send(opcode, data, { signal } = {}) {
73
+ if (!this.#ready || !this.#connection)
74
+ throw new Error('Micup Gateway is disconnected');
75
+ await this.#connection.send(opcode, data, signal);
76
+ }
77
+ get presence() {
78
+ return structuredClone(activePresence(this.#presence ?? { status: 'online', custom_status: null }));
79
+ }
80
+ async updatePresence(presence, { signal } = {}) {
81
+ signal?.throwIfAborted();
82
+ this.#presence = normalizePresence(presence);
83
+ if (this.ready)
84
+ await this.send(GatewayOpcode.PresenceUpdate, this.#presence, { signal });
85
+ }
86
+ setStatus(status, options) {
87
+ return this.updatePresence({ ...this.presence, status }, options);
88
+ }
89
+ setCustomStatus(custom_status, options) {
90
+ return this.updatePresence({ ...this.presence, custom_status }, options);
91
+ }
92
+ requestGuildCounts(ids, { signal } = {}) {
93
+ return this.#requests.guildCounts(ids, signal);
94
+ }
95
+ requestChannelMemberCounts(guildId, ids, { signal } = {}) {
96
+ return this.#requests.channelCounts(guildId, ids, signal);
97
+ }
98
+ requestGuildMembers(guildId, request) {
99
+ return this.#requests.members(guildId, request);
100
+ }
101
+ async joinVoice(guildId, channelId, options) {
102
+ const permission = this.#botId && this.state.permissions(guildId, this.#botId, channelId);
103
+ if (typeof permission === 'bigint' && !hasPermissions(permission, Permission.ViewChannel | Permission.Connect)) {
104
+ throw new Error('The bot needs View Channel and Connect permissions for this voice channel');
105
+ }
106
+ return this.#voice.join(guildId, channelId, options);
107
+ }
108
+ voice(guildId) {
109
+ return this.#voice.grant(guildId);
110
+ }
111
+ leaveVoice(guildId, connectionId, { signal } = {}) {
112
+ return this.#voice.leave(guildId, connectionId, signal);
113
+ }
114
+ updateVoiceState(guildId, options) {
115
+ return this.#voice.update(guildId, options);
116
+ }
117
+ async run({ signal = new AbortController().signal } = {}) {
118
+ if (this.#running)
119
+ throw new Error('Micup Gateway session is already running');
120
+ this.#running = true;
121
+ let backoff = this.#minBackoff;
122
+ try {
123
+ while (!signal.aborted) {
124
+ try {
125
+ await GatewayConnection.run({
126
+ endpoint: this.#endpoint,
127
+ token: this.#token,
128
+ shard: this.#shard,
129
+ flags: this.#flags,
130
+ presence: () => this.#presence && activePresence(this.#presence),
131
+ ignoredEvents: this.#ignoredEvents,
132
+ resume: this.#resume,
133
+ beforeIdentify: this.#options.beforeIdentify,
134
+ dispatch: async (event, lifetime) => {
135
+ if (event.name === 'READY') {
136
+ this.#botId = event.data?.user?.id ?? this.#botId;
137
+ }
138
+ this.state.apply(event);
139
+ await this.#options.handler(event, lifetime);
140
+ },
141
+ receive: (event) => {
142
+ this.#voice.receive(event);
143
+ this.#requests.receive(event);
144
+ },
145
+ onGatewayError: (data) => {
146
+ this.#voice.refuse(data);
147
+ this.#options.onGatewayError?.(data);
148
+ },
149
+ onInvalidate: () => {
150
+ this.#ready = false;
151
+ this.#voice.invalidate();
152
+ this.#requests.invalidate();
153
+ this.state.clear();
154
+ },
155
+ onReady: (resumed) => {
156
+ this.#ready = true;
157
+ backoff = this.#minBackoff;
158
+ this.#options.onReady?.(resumed);
159
+ },
160
+ }, signal, (connection) => { this.#connection = connection; });
161
+ }
162
+ catch (error) {
163
+ this.#ready = false;
164
+ this.#connection = undefined;
165
+ if (signal.aborted)
166
+ return;
167
+ if (error instanceof GatewayCloseError && error.resetsSession) {
168
+ this.#voice.invalidate();
169
+ this.#requests.invalidate();
170
+ this.state.clear();
171
+ this.#resume.sessionId = undefined;
172
+ this.#resume.sequence = null;
173
+ }
174
+ this.#options.onDisconnect?.(error);
175
+ if (error instanceof GatewayCloseError && error.fatal)
176
+ throw error;
177
+ await delay(backoff, undefined, { signal }).catch((cause) => {
178
+ if (!signal.aborted)
179
+ throw cause;
180
+ });
181
+ backoff = Math.min(this.#maxBackoff, backoff * 2);
182
+ }
183
+ }
184
+ }
185
+ finally {
186
+ this.#ready = false;
187
+ this.#connection = undefined;
188
+ this.#running = false;
189
+ this.#requests.invalidate();
190
+ this.#voice.invalidate();
191
+ }
192
+ }
193
+ }