mini-interactions 0.0.0-stage → 0.15.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 (152) hide show
  1. package/LICENSE +21 -0
  2. package/MIGRATION.md +126 -0
  3. package/README.md +253 -2
  4. package/dist/bot.d.ts +58 -0
  5. package/dist/bot.js +217 -0
  6. package/dist/builders/ActionRowBuilder.d.ts +22 -0
  7. package/dist/builders/ActionRowBuilder.js +33 -0
  8. package/dist/builders/AutomodRuleBuilder.d.ts +45 -0
  9. package/dist/builders/AutomodRuleBuilder.js +151 -0
  10. package/dist/builders/ButtonBuilder.d.ts +53 -0
  11. package/dist/builders/ButtonBuilder.js +124 -0
  12. package/dist/builders/ChannelSelectMenuBuilder.d.ts +53 -0
  13. package/dist/builders/ChannelSelectMenuBuilder.js +105 -0
  14. package/dist/builders/CheckboxBuilder.d.ts +20 -0
  15. package/dist/builders/CheckboxBuilder.js +20 -0
  16. package/dist/builders/CheckboxGroupBuilder.d.ts +25 -0
  17. package/dist/builders/CheckboxGroupBuilder.js +48 -0
  18. package/dist/builders/EmbedBuilder.d.ts +33 -0
  19. package/dist/builders/EmbedBuilder.js +103 -0
  20. package/dist/builders/FileUploadBuilder.d.ts +17 -0
  21. package/dist/builders/FileUploadBuilder.js +22 -0
  22. package/dist/builders/LabelBuilder.d.ts +16 -0
  23. package/dist/builders/LabelBuilder.js +21 -0
  24. package/dist/builders/MiniContainerBuilder.d.ts +131 -0
  25. package/dist/builders/MiniContainerBuilder.js +347 -0
  26. package/dist/builders/ModalBuilder.d.ts +16 -0
  27. package/dist/builders/ModalBuilder.js +36 -0
  28. package/dist/builders/ModalChannelSelectMenuBuilder.d.ts +29 -0
  29. package/dist/builders/ModalChannelSelectMenuBuilder.js +25 -0
  30. package/dist/builders/ModalMentionableSelectMenuBuilder.d.ts +53 -0
  31. package/dist/builders/ModalMentionableSelectMenuBuilder.js +87 -0
  32. package/dist/builders/ModalRoleSelectMenuBuilder.d.ts +27 -0
  33. package/dist/builders/ModalRoleSelectMenuBuilder.js +24 -0
  34. package/dist/builders/ModalStringSelectMenuBuilder.d.ts +62 -0
  35. package/dist/builders/ModalStringSelectMenuBuilder.js +120 -0
  36. package/dist/builders/ModalUserSelectMenuBuilder.d.ts +53 -0
  37. package/dist/builders/ModalUserSelectMenuBuilder.js +96 -0
  38. package/dist/builders/RadioBuilder.d.ts +22 -0
  39. package/dist/builders/RadioBuilder.js +36 -0
  40. package/dist/builders/RoleSelectMenuBuilder.d.ts +47 -0
  41. package/dist/builders/RoleSelectMenuBuilder.js +92 -0
  42. package/dist/builders/StringSelectMenuBuilder.d.ts +52 -0
  43. package/dist/builders/StringSelectMenuBuilder.js +104 -0
  44. package/dist/builders/StringSelectMenuOptionBuilder.d.ts +46 -0
  45. package/dist/builders/StringSelectMenuOptionBuilder.js +106 -0
  46. package/dist/builders/TextInputBuilder.d.ts +23 -0
  47. package/dist/builders/TextInputBuilder.js +26 -0
  48. package/dist/builders/index.d.ts +44 -0
  49. package/dist/builders/index.js +22 -0
  50. package/dist/builders/shared.d.ts +8 -0
  51. package/dist/builders/shared.js +11 -0
  52. package/dist/commands/CommandBuilder.d.ts +278 -0
  53. package/dist/commands/CommandBuilder.js +687 -0
  54. package/dist/commands/ContextMenuCommandBuilder.d.ts +94 -0
  55. package/dist/commands/ContextMenuCommandBuilder.js +145 -0
  56. package/dist/core/http/DiscordRestClient.d.ts +400 -0
  57. package/dist/core/http/DiscordRestClient.js +988 -0
  58. package/dist/core/interactions/InteractionContext.d.ts +33 -0
  59. package/dist/core/interactions/InteractionContext.js +61 -0
  60. package/dist/core/interactions/InteractionVerifier.d.ts +8 -0
  61. package/dist/core/interactions/InteractionVerifier.js +9 -0
  62. package/dist/core/messages/DiscordSentMessage.d.ts +32 -0
  63. package/dist/core/messages/DiscordSentMessage.js +64 -0
  64. package/dist/core/messages/message-payloads.d.ts +94 -0
  65. package/dist/core/messages/message-payloads.js +99 -0
  66. package/dist/core/webhooks/DiscordWebhook.d.ts +14 -0
  67. package/dist/core/webhooks/DiscordWebhook.js +69 -0
  68. package/dist/database/MiniDataBuilder.d.ts +61 -0
  69. package/dist/database/MiniDataBuilder.js +98 -0
  70. package/dist/database/MiniDatabase.d.ts +67 -0
  71. package/dist/database/MiniDatabase.js +222 -0
  72. package/dist/database/MiniDatabaseBuilder.d.ts +58 -0
  73. package/dist/database/MiniDatabaseBuilder.js +84 -0
  74. package/dist/database/index.d.ts +5 -0
  75. package/dist/database/index.js +3 -0
  76. package/dist/identity/ApplicationIdentityProfile.d.ts +188 -0
  77. package/dist/identity/ApplicationIdentityProfile.js +207 -0
  78. package/dist/index.d.ts +54 -0
  79. package/dist/index.js +34 -0
  80. package/dist/lobby/Lobby.d.ts +150 -0
  81. package/dist/lobby/Lobby.js +90 -0
  82. package/dist/node/MiniInteraction.d.ts +199 -0
  83. package/dist/node/MiniInteraction.js +861 -0
  84. package/dist/node/index.d.ts +2 -0
  85. package/dist/node/index.js +1 -0
  86. package/dist/oauth2/DiscordOAuth.d.ts +49 -0
  87. package/dist/oauth2/DiscordOAuth.js +113 -0
  88. package/dist/oauth2/OAuth2Builder.d.ts +296 -0
  89. package/dist/oauth2/OAuth2Builder.js +435 -0
  90. package/dist/oauth2/OAuth2Scopes.d.ts +285 -0
  91. package/dist/oauth2/OAuth2Scopes.js +438 -0
  92. package/dist/oauth2/OAuthTokenStorage.d.ts +37 -0
  93. package/dist/oauth2/OAuthTokenStorage.js +109 -0
  94. package/dist/oauth2/index.d.ts +8 -0
  95. package/dist/oauth2/index.js +4 -0
  96. package/dist/router/AutocompleteContext.d.ts +36 -0
  97. package/dist/router/AutocompleteContext.js +82 -0
  98. package/dist/router/InteractionRouter.d.ts +82 -0
  99. package/dist/router/InteractionRouter.js +225 -0
  100. package/dist/types/ButtonStyle.d.ts +16 -0
  101. package/dist/types/ButtonStyle.js +17 -0
  102. package/dist/types/ChannelType.d.ts +2 -0
  103. package/dist/types/ChannelType.js +2 -0
  104. package/dist/types/Commands.d.ts +35 -0
  105. package/dist/types/Commands.js +1 -0
  106. package/dist/types/ComponentTypes.d.ts +19 -0
  107. package/dist/types/ComponentTypes.js +1 -0
  108. package/dist/types/InteractionFlags.d.ts +5 -0
  109. package/dist/types/InteractionFlags.js +6 -0
  110. package/dist/types/PermissionFlags.d.ts +56 -0
  111. package/dist/types/PermissionFlags.js +5 -0
  112. package/dist/types/RoleConnectionMetadata.d.ts +14 -0
  113. package/dist/types/RoleConnectionMetadata.js +1 -0
  114. package/dist/types/RoleConnectionMetadataTypes.d.ts +11 -0
  115. package/dist/types/RoleConnectionMetadataTypes.js +12 -0
  116. package/dist/types/SeparatorSpacingSize.d.ts +2 -0
  117. package/dist/types/SeparatorSpacingSize.js +2 -0
  118. package/dist/types/checkbox.d.ts +16 -0
  119. package/dist/types/checkbox.js +12 -0
  120. package/dist/types/discord.d.ts +2 -0
  121. package/dist/types/discord.js +1 -0
  122. package/dist/types/radio.d.ts +12 -0
  123. package/dist/types/radio.js +10 -0
  124. package/dist/types/validation.d.ts +14 -0
  125. package/dist/types/validation.js +40 -0
  126. package/dist/utils/CommandInteractionOptions.d.ts +66 -0
  127. package/dist/utils/CommandInteractionOptions.js +364 -0
  128. package/dist/utils/ContextMenuInteraction.d.ts +76 -0
  129. package/dist/utils/ContextMenuInteraction.js +152 -0
  130. package/dist/utils/MessageComponentInteraction.d.ts +148 -0
  131. package/dist/utils/MessageComponentInteraction.js +259 -0
  132. package/dist/utils/ModalSubmitInteraction.d.ts +86 -0
  133. package/dist/utils/ModalSubmitInteraction.js +267 -0
  134. package/dist/utils/cdn.d.ts +30 -0
  135. package/dist/utils/cdn.js +60 -0
  136. package/dist/utils/formatting.d.ts +76 -0
  137. package/dist/utils/formatting.js +132 -0
  138. package/dist/utils/interactionMessageHelpers.d.ts +40 -0
  139. package/dist/utils/interactionMessageHelpers.js +118 -0
  140. package/dist/utils/localization.d.ts +25 -0
  141. package/dist/utils/localization.js +38 -0
  142. package/dist/utils/snowflake.d.ts +19 -0
  143. package/dist/utils/snowflake.js +32 -0
  144. package/dist/webhooks/WebhookEvent.d.ts +229 -0
  145. package/dist/webhooks/WebhookEvent.js +59 -0
  146. package/dist/webhooks/WebhookEventRouter.d.ts +123 -0
  147. package/dist/webhooks/WebhookEventRouter.js +160 -0
  148. package/dist/webhooks/WebhookEventVerifier.d.ts +33 -0
  149. package/dist/webhooks/WebhookEventVerifier.js +37 -0
  150. package/dist/webhooks/index.d.ts +6 -0
  151. package/dist/webhooks/index.js +3 -0
  152. package/package.json +90 -4
@@ -0,0 +1,2 @@
1
+ export { MiniInteraction, LegacyMiniInteractionAdapter, } from "./MiniInteraction.js";
2
+ export type { MiniInteractionOptions, CloudflareEnv, CloudflareExecutionContext, } from "./MiniInteraction.js";
@@ -0,0 +1 @@
1
+ export { MiniInteraction, LegacyMiniInteractionAdapter, } from "./MiniInteraction.js";
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Discord OAuth utilities for handling the OAuth2 flow.
3
+ * Simplifies Discord authentication for mini-interaction apps.
4
+ */
5
+ export interface OAuthConfig {
6
+ appId: string;
7
+ appSecret: string;
8
+ redirectUri: string;
9
+ }
10
+ export interface OAuthTokens {
11
+ access_token: string;
12
+ refresh_token: string;
13
+ expires_at: number;
14
+ token_type: string;
15
+ scope: string;
16
+ }
17
+ export interface DiscordUser {
18
+ id: string;
19
+ username: string;
20
+ discriminator: string;
21
+ avatar: string | null;
22
+ email?: string;
23
+ verified?: boolean;
24
+ locale?: string;
25
+ mfa_enabled?: boolean;
26
+ }
27
+ /**
28
+ * Generates an OAuth authorization URL for Discord.
29
+ */
30
+ export declare function generateOAuthUrl(config: OAuthConfig, scopes?: string[]): {
31
+ url: string;
32
+ state: string;
33
+ };
34
+ /**
35
+ * Exchanges an OAuth code for access tokens.
36
+ */
37
+ export declare function getOAuthTokens(code: string, config: OAuthConfig): Promise<OAuthTokens>;
38
+ /**
39
+ * Refreshes an expired access token.
40
+ */
41
+ export declare function refreshAccessToken(refreshToken: string, config: OAuthConfig): Promise<OAuthTokens>;
42
+ /**
43
+ * Gets the current user's Discord profile.
44
+ */
45
+ export declare function getDiscordUser(accessToken: string): Promise<DiscordUser>;
46
+ /**
47
+ * Ensures the access token is valid, refreshing if necessary.
48
+ */
49
+ export declare function ensureValidToken(tokens: OAuthTokens, config: OAuthConfig): Promise<OAuthTokens>;
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Discord OAuth utilities for handling the OAuth2 flow.
3
+ * Simplifies Discord authentication for mini-interaction apps.
4
+ */
5
+ /**
6
+ * Generates an OAuth authorization URL for Discord.
7
+ */
8
+ export function generateOAuthUrl(config, scopes = ["identify", "email"]) {
9
+ const state = crypto.randomUUID();
10
+ const url = new URL("https://discord.com/api/oauth2/authorize");
11
+ url.searchParams.set("client_id", config.appId);
12
+ url.searchParams.set("redirect_uri", config.redirectUri);
13
+ url.searchParams.set("response_type", "code");
14
+ url.searchParams.set("state", state);
15
+ url.searchParams.set("scope", scopes.join(" "));
16
+ url.searchParams.set("prompt", "consent");
17
+ return { url: url.toString(), state };
18
+ }
19
+ /**
20
+ * Exchanges an OAuth code for access tokens.
21
+ */
22
+ export async function getOAuthTokens(code, config) {
23
+ const url = "https://discord.com/api/v10/oauth2/token";
24
+ const body = new URLSearchParams({
25
+ client_id: config.appId,
26
+ client_secret: config.appSecret,
27
+ grant_type: "authorization_code",
28
+ code,
29
+ redirect_uri: config.redirectUri,
30
+ });
31
+ const response = await fetch(url, {
32
+ method: "POST",
33
+ body,
34
+ headers: {
35
+ "Content-Type": "application/x-www-form-urlencoded",
36
+ },
37
+ });
38
+ if (!response.ok) {
39
+ throw new Error(`Failed to get OAuth tokens: [${response.status}] ${response.statusText}`);
40
+ }
41
+ const data = (await response.json());
42
+ return {
43
+ access_token: data.access_token,
44
+ refresh_token: data.refresh_token,
45
+ expires_at: Date.now() + data.expires_in * 1000,
46
+ token_type: data.token_type,
47
+ scope: data.scope,
48
+ };
49
+ }
50
+ /**
51
+ * Refreshes an expired access token.
52
+ */
53
+ export async function refreshAccessToken(refreshToken, config) {
54
+ const url = "https://discord.com/api/v10/oauth2/token";
55
+ const body = new URLSearchParams({
56
+ client_id: config.appId,
57
+ client_secret: config.appSecret,
58
+ grant_type: "refresh_token",
59
+ refresh_token: refreshToken,
60
+ });
61
+ const response = await fetch(url, {
62
+ method: "POST",
63
+ body,
64
+ headers: {
65
+ "Content-Type": "application/x-www-form-urlencoded",
66
+ },
67
+ });
68
+ if (!response.ok) {
69
+ throw new Error(`Failed to refresh access token: [${response.status}] ${response.statusText}`);
70
+ }
71
+ const data = (await response.json());
72
+ return {
73
+ access_token: data.access_token,
74
+ refresh_token: data.refresh_token,
75
+ expires_at: Date.now() + data.expires_in * 1000,
76
+ token_type: data.token_type,
77
+ scope: data.scope,
78
+ };
79
+ }
80
+ /**
81
+ * Gets the current user's Discord profile.
82
+ */
83
+ export async function getDiscordUser(accessToken) {
84
+ const url = "https://discord.com/api/v10/oauth2/@me";
85
+ const response = await fetch(url, {
86
+ headers: {
87
+ Authorization: `Bearer ${accessToken}`,
88
+ },
89
+ });
90
+ if (!response.ok) {
91
+ throw new Error(`Failed to get Discord user: [${response.status}] ${response.statusText}`);
92
+ }
93
+ const data = (await response.json());
94
+ return {
95
+ id: data.user.id,
96
+ username: data.user.username,
97
+ discriminator: data.user.discriminator,
98
+ avatar: data.user.avatar,
99
+ email: data.user.email,
100
+ verified: data.user.verified,
101
+ locale: data.user.locale,
102
+ mfa_enabled: data.user.mfa_enabled,
103
+ };
104
+ }
105
+ /**
106
+ * Ensures the access token is valid, refreshing if necessary.
107
+ */
108
+ export async function ensureValidToken(tokens, config) {
109
+ if (Date.now() > tokens.expires_at) {
110
+ return refreshAccessToken(tokens.refresh_token, config);
111
+ }
112
+ return tokens;
113
+ }
@@ -0,0 +1,296 @@
1
+ import type { APIApplication, APIGuild, APIUser, APIWebhook } from "discord-api-types/v10";
2
+ import { OAuth2Scope } from "./OAuth2Scopes.js";
3
+ import type { OAuth2ScopeCategory } from "./OAuth2Scopes.js";
4
+ /**
5
+ * A fluent builder for Discord's OAuth2 flows, plus typed clients for the token
6
+ * endpoints.
7
+ *
8
+ * ```ts
9
+ * const oauth = new OAuth2Builder({
10
+ * clientId: process.env.DISCORD_CLIENT_ID!,
11
+ * clientSecret: process.env.DISCORD_CLIENT_SECRET!,
12
+ * redirectUri: "https://example.com/api/discord-oauth-callback",
13
+ * }).addScopes(...OAuth2ScopePresets.SignIn);
14
+ *
15
+ * const { url, state } = oauth.build(); // send the user here
16
+ * const tokens = await oauth.exchangeCode(code); // in the callback
17
+ * ```
18
+ *
19
+ * Everything here is Fetch-API only — no Node built-ins — so the same instance
20
+ * works in a Vercel function, a Cloudflare Worker or a long-lived server.
21
+ *
22
+ * @see {@link https://docs.discord.com/developers/topics/oauth2}
23
+ */
24
+ export declare class OAuth2Builder {
25
+ private readonly clientId;
26
+ private readonly clientSecret;
27
+ private readonly fetchImpl;
28
+ private scopes;
29
+ private redirectUri;
30
+ private state;
31
+ private responseType;
32
+ private prompt;
33
+ private permissions;
34
+ private guildId;
35
+ private disableGuildSelect;
36
+ private integrationType;
37
+ private teamApplication;
38
+ constructor(options: OAuth2BuilderOptions);
39
+ /**
40
+ * Starts from the Social SDK's `GetDefaultCommunicationScopes`, i.e. the set
41
+ * **Linked Channels** requires: `openid sdk.social_layer`.
42
+ *
43
+ * ```ts
44
+ * OAuth2Builder.communication({ clientId, clientSecret, redirectUri })
45
+ * ```
46
+ */
47
+ static communication(options: OAuth2BuilderOptions): OAuth2Builder;
48
+ /**
49
+ * Starts from the Social SDK's `GetDefaultPresenceScopes`
50
+ * (`openid sdk.social_layer_presence`) — account linking, friends and rich
51
+ * presence, but no messaging or Linked Channels.
52
+ */
53
+ static presence(options: OAuth2BuilderOptions): OAuth2Builder;
54
+ /**
55
+ * Starts from the plain user-install sign-in set (`identify email`), the
56
+ * usual starting point for a dashboard that reads `/users/@me`.
57
+ */
58
+ static signIn(options: OAuth2BuilderOptions): OAuth2Builder;
59
+ /**
60
+ * A bot-invite URL: no `response_type`, no `redirect_uri` — Discord adds the
61
+ * bot to the selected server and redirects nowhere.
62
+ *
63
+ * Pass `permissions` for the bot's permission integer and `guildId` to
64
+ * preselect a server, optionally locking the picker with
65
+ * `disableGuildSelect`.
66
+ */
67
+ static bot(options: OAuth2BuilderOptions & {
68
+ permissions?: string | number | bigint;
69
+ guildId?: string;
70
+ disableGuildSelect?: boolean;
71
+ integrationType?: OAuth2IntegrationType;
72
+ }): OAuth2Builder;
73
+ /** Replaces the requested scopes. Duplicates and blanks are dropped; order is preserved. */
74
+ setScopes(scopes: Iterable<string>): this;
75
+ /** Appends scopes, ignoring ones already requested. */
76
+ addScopes(...scopes: (OAuth2Scope | string)[]): this;
77
+ /** Removes scopes; names that are not currently requested are ignored. */
78
+ removeScopes(...scopes: string[]): this;
79
+ /** The scopes requested so far, in request order. */
80
+ getScopes(): string[];
81
+ /** Where Discord sends the user after they approve. */
82
+ setRedirectUri(redirectUri: string | null | undefined): this;
83
+ /**
84
+ * Pins the CSRF `state`. Discord returns it untouched on the redirect and you
85
+ * **must** compare it against the value bound to the user's session.
86
+ *
87
+ * When unset, {@link build} generates a cryptographically random one.
88
+ */
89
+ setState(state: string | null | undefined): this;
90
+ /**
91
+ * `code` (authorization code grant, the default) or `token` (implicit grant,
92
+ * for browser-only clients that cannot keep a secret).
93
+ *
94
+ * Pass `undefined` for the bot flow, which has no response type at all.
95
+ */
96
+ setResponseType(responseType: OAuth2ResponseType | undefined): this;
97
+ /**
98
+ * `consent` forces the approval screen even for an existing authorization;
99
+ * `none` skips it. Passthrough scopes (`bot`, `webhook.incoming`) always ask.
100
+ */
101
+ setPrompt(prompt: OAuth2Prompt): this;
102
+ /** Bot permissions as an integer; bigints are serialised exactly. */
103
+ setPermissions(permissions: string | number | bigint): this;
104
+ /** Preselects a server in the bot-invite picker. */
105
+ setGuildId(guildId: string | null | undefined): this;
106
+ /** Locks the bot-invite picker to {@link setGuildId}'s server. */
107
+ setDisableGuildSelect(disableGuildSelect?: boolean): this;
108
+ /**
109
+ * Where the app installs: `0` for a server, `1` for the user's account.
110
+ *
111
+ * Only meaningful when the scopes include `applications.commands`, and the app
112
+ * must be configured in the Developer Portal to support the context.
113
+ */
114
+ setIntegrationType(integrationType: OAuth2IntegrationType | null | undefined): this;
115
+ /**
116
+ * Marks the application as team-owned, which restricts the client credentials
117
+ * grant to `identify` and `applications.commands.update`.
118
+ */
119
+ setTeamApplication(teamApplication?: boolean): this;
120
+ /**
121
+ * Builds the authorization URL. Generates a `state` when none was set, and
122
+ * validates the scope/grant combination first — see {@link OAuth2BuilderError}.
123
+ */
124
+ build(): OAuth2AuthorizationUrl;
125
+ /** The authorization URL from {@link build}, for callers that ignore the rest. */
126
+ toURL(): string;
127
+ /**
128
+ * The requested scopes grouped for a consent screen, with the copy from
129
+ * `OAuth2ScopeMetadata`.
130
+ *
131
+ * ```ts
132
+ * oauth.describeScopes();
133
+ * // [{ category: "identity", scopes: [{ scope: "identify", description: "…" }] }]
134
+ * ```
135
+ */
136
+ describeScopes(): OAuth2ConsentGroup[];
137
+ /**
138
+ * Exchanges the `code` from the redirect for tokens — the authorization code
139
+ * grant. Needs `clientSecret` and the same `redirect_uri` used in the
140
+ * authorization request.
141
+ *
142
+ * On a `webhook.incoming` flow the response also carries `webhook`; store its
143
+ * `id` and `token` immediately, they are the only copy you get.
144
+ */
145
+ exchangeCode(code: string, options?: OAuth2RequestOptions): Promise<OAuth2TokenResponse>;
146
+ /**
147
+ * Exchanges a refresh token for a fresh access token. Discord may rotate the
148
+ * refresh token, so always persist the one in the response.
149
+ */
150
+ refresh(refreshToken: string, options?: OAuth2RequestOptions): Promise<OAuth2TokenResponse>;
151
+ /**
152
+ * Requests an application-level Bearer token with no user context, for testing
153
+ * or for the `applications.commands.update` route.
154
+ *
155
+ * Team-owned applications may only ask for `identify` and
156
+ * `applications.commands.update`; mark the client with
157
+ * {@link setTeamApplication} to have that enforced locally instead of by a
158
+ * confusing API error.
159
+ */
160
+ clientCredentials(scopes?: Iterable<string>, options?: OAuth2RequestOptions): Promise<OAuth2TokenResponse>;
161
+ /**
162
+ * Revokes an access **or** refresh token.
163
+ *
164
+ * Revocation is authorization-wide: every token issued from the same
165
+ * authorization dies, whichever token you pass and whatever hint you give.
166
+ * For a Social SDK game this is what triggers `APPLICATION_DEAUTHORIZED`.
167
+ */
168
+ revokeToken(token: string, tokenTypeHint?: OAuth2TokenType, options?: OAuth2RequestOptions): Promise<void>;
169
+ /**
170
+ * Reads what the current Bearer token is actually allowed to do
171
+ * (`GET /oauth2/@me`) — the only reliable way to learn the granted scopes,
172
+ * since users may decline individual ones.
173
+ */
174
+ getAuthorizationInfo(accessToken: string): Promise<OAuth2AuthorizationInfo>;
175
+ /** Resolves the current user from a Bearer token. Requires the `identify` scope. */
176
+ getUser(accessToken: string): Promise<APIUser | undefined>;
177
+ private validate;
178
+ private requireClientSecret;
179
+ private tokenRequest;
180
+ private formRequest;
181
+ private basicAuthHeader;
182
+ private request;
183
+ }
184
+ /** Options accepted by every {@link OAuth2Builder} constructor shorthand. */
185
+ export type OAuth2BuilderOptions = {
186
+ /** Application client ID. */
187
+ clientId: string;
188
+ /**
189
+ * Application client secret. Required for the code, refresh and client
190
+ * credentials grants, and for revocation; omit only for the implicit grant.
191
+ */
192
+ clientSecret?: string;
193
+ /** Must match a redirect registered in the Developer Portal, character for character. */
194
+ redirectUri?: string;
195
+ /** Scopes to start with. */
196
+ scopes?: Iterable<string>;
197
+ /** Custom fetch, for tests or a proxied runtime. */
198
+ fetch?: typeof fetch;
199
+ };
200
+ /** Per-call overrides, mostly for tests. */
201
+ export type OAuth2RequestOptions = {
202
+ /**
203
+ * Send `client_id`/`client_secret` in the form body instead of using HTTP
204
+ * Basic authentication. Discord accepts either.
205
+ */
206
+ clientCredentialsInBody?: boolean;
207
+ };
208
+ /** The response type requesting a code, or a token straight from the browser. */
209
+ export type OAuth2ResponseType = "code" | "token";
210
+ /** Whether the approval screen is shown again. */
211
+ export type OAuth2Prompt = "consent" | "none";
212
+ /** `0` installs to a server, `1` to the user's account. */
213
+ export type OAuth2IntegrationType = 0 | 1;
214
+ /** Which kind of token a revocation request is about. */
215
+ export type OAuth2TokenType = "access_token" | "refresh_token";
216
+ /** One requested scope, ready to render. */
217
+ export type OAuth2ConsentEntry = {
218
+ scope: string;
219
+ /** `undefined` when the scope is not one Discord documents. */
220
+ description: string | undefined;
221
+ /** Whether Discord must approve the app for this scope first. */
222
+ restricted: boolean;
223
+ };
224
+ /** Requested scopes for one consent-screen section. */
225
+ export type OAuth2ConsentGroup = {
226
+ category: OAuth2ScopeCategory;
227
+ scopes: OAuth2ConsentEntry[];
228
+ };
229
+ /** The pieces of an authorization request, ready to hand to the user. */
230
+ export type OAuth2AuthorizationUrl = {
231
+ /** The full authorization URL. */
232
+ url: string;
233
+ /** The CSRF nonce, echoed back on the redirect — verify it before using the code. */
234
+ state: string;
235
+ /** Scopes requested, in order. */
236
+ scopes: string[];
237
+ /** `code`, `token`, or `undefined` for the bot flow. */
238
+ responseType: OAuth2ResponseType | undefined;
239
+ /** `true` when at least one scope needs Discord's approval first. */
240
+ requiresApproval: boolean;
241
+ /** Consent-screen copy for each requested scope. */
242
+ consent: OAuth2ConsentEntry[];
243
+ };
244
+ /**
245
+ * A token response. `refresh_token` is absent on the client credentials grant,
246
+ * and `webhook`/`guild` only appear on the `webhook.incoming` and extended bot
247
+ * flows respectively.
248
+ */
249
+ export type OAuth2TokenResponse = {
250
+ access_token: string;
251
+ token_type: string;
252
+ expires_in: number;
253
+ scope: string;
254
+ /** Absent for client credentials, which never issue a refresh token. */
255
+ refresh_token?: string;
256
+ /** Present on the `webhook.incoming` flow; store `id` and `token` immediately. */
257
+ webhook?: APIWebhook;
258
+ /** Present on an extended bot authorization: the server the bot was added to. */
259
+ guild?: OAuth2AuthorizedGuild;
260
+ };
261
+ /** The server a bot was added to, echoed on an extended bot authorization. */
262
+ export type OAuth2AuthorizedGuild = Pick<APIGuild, "id" | "name"> & Partial<APIGuild>;
263
+ /** `GET /oauth2/@me` — what the current Bearer token may actually do. */
264
+ export type OAuth2AuthorizationInfo = {
265
+ application: APIApplication;
266
+ scopes: OAuth2Scope[];
267
+ /** ISO8601 timestamp of when the access token expires. */
268
+ expires: string;
269
+ /** Only present when the `identify` scope was granted. */
270
+ user?: APIUser;
271
+ };
272
+ /** Machine-readable reasons the builder refuses to produce a URL. */
273
+ export type OAuth2BuilderErrorCode = "missing_scope" | "missing_redirect_uri" | "implicit_grant_unsupported_scope" | "missing_client_secret" | "team_scopes_restricted" | "missing_crypto";
274
+ /**
275
+ * Thrown when an authorization request is contradictory — a combination Discord
276
+ * would reject, caught before the user ever sees a broken consent screen.
277
+ */
278
+ export declare class OAuth2BuilderError extends Error {
279
+ readonly code: OAuth2BuilderErrorCode;
280
+ constructor(message: string, code: OAuth2BuilderErrorCode);
281
+ }
282
+ /**
283
+ * Thrown when Discord rejects a token or revocation request. The request bodies
284
+ * are form-encoded but the error payload is JSON, so `error` and
285
+ * `errorDescription` are parsed out of `body` when possible.
286
+ */
287
+ export declare class OAuth2RequestError extends Error {
288
+ readonly status: number;
289
+ readonly body: string;
290
+ readonly url: string;
291
+ /** Discord's `error` code, e.g. `invalid_grant` or `invalid_client`. */
292
+ readonly error: string | undefined;
293
+ /** Discord's human-readable `error_description`, when present. */
294
+ readonly errorDescription: string | undefined;
295
+ constructor(status: number, body: string, url: string);
296
+ }