@discordjs/rest 2.1.1-dev.1699877033-8d04cbc20 → 2.1.1-dev.1699963438-4b88306dc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,14 +1,380 @@
1
- import { R as ResponseLike, a as RawFile, I as InternalRequest, b as RateLimitData, c as RestEventsMap, H as HashData, d as IHandler, e as RESTOptions, f as RouteLike, g as RequestData } from './types-c3e7077b.js';
2
- export { A as APIRequest, m as HandlerRequestData, j as InvalidRequestWarningData, i as RateLimitQueueFilter, k as RequestHeaders, l as RequestMethod, h as RestEvents, n as RouteData } from './types-c3e7077b.js';
3
1
  import * as url from 'url';
4
2
  import { Snowflake } from 'discord-api-types/v10';
5
- import * as undici from 'undici';
6
- import { Dispatcher } from 'undici';
3
+ import { Readable } from 'node:stream';
4
+ import { ReadableStream } from 'node:stream/web';
7
5
  import { Collection } from '@discordjs/collection';
6
+ import { Awaitable } from '@discordjs/util';
7
+ import * as undici from 'undici';
8
+ import { RequestInit, Dispatcher, Response, BodyInit, Agent } from 'undici';
8
9
  import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';
9
- import 'node:stream';
10
- import 'node:stream/web';
11
- import '@discordjs/util';
10
+
11
+ interface IHandler {
12
+ /**
13
+ * The unique id of the handler
14
+ */
15
+ readonly id: string;
16
+ /**
17
+ * If the bucket is currently inactive (no pending requests)
18
+ */
19
+ get inactive(): boolean;
20
+ /**
21
+ * Queues a request to be sent
22
+ *
23
+ * @param routeId - The generalized api route with literal ids for major parameters
24
+ * @param url - The url to do the request on
25
+ * @param options - All the information needed to make a request
26
+ * @param requestData - Extra data from the user's request needed for errors and additional processing
27
+ */
28
+ queueRequest(routeId: RouteData, url: string, options: RequestInit, requestData: HandlerRequestData): Promise<ResponseLike>;
29
+ }
30
+
31
+ interface RestEvents {
32
+ handlerSweep: [sweptHandlers: Collection<string, IHandler>];
33
+ hashSweep: [sweptHashes: Collection<string, HashData>];
34
+ invalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];
35
+ rateLimited: [rateLimitInfo: RateLimitData];
36
+ response: [request: APIRequest, response: ResponseLike];
37
+ restDebug: [info: string];
38
+ }
39
+ type RestEventsMap = {
40
+ [K in keyof RestEvents]: RestEvents[K];
41
+ };
42
+ /**
43
+ * Options to be passed when creating the REST instance
44
+ */
45
+ interface RESTOptions {
46
+ /**
47
+ * The agent to set globally
48
+ */
49
+ agent: Dispatcher | null;
50
+ /**
51
+ * The base api path, without version
52
+ *
53
+ * @defaultValue `'https://discord.com/api'`
54
+ */
55
+ api: string;
56
+ /**
57
+ * The authorization prefix to use for requests, useful if you want to use
58
+ * bearer tokens
59
+ *
60
+ * @defaultValue `'Bot'`
61
+ */
62
+ authPrefix: 'Bearer' | 'Bot';
63
+ /**
64
+ * The cdn path
65
+ *
66
+ * @defaultValue `'https://cdn.discordapp.com'`
67
+ */
68
+ cdn: string;
69
+ /**
70
+ * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)
71
+ *
72
+ * @defaultValue `50`
73
+ */
74
+ globalRequestsPerSecond: number;
75
+ /**
76
+ * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)
77
+ *
78
+ * @defaultValue `3_600_000`
79
+ */
80
+ handlerSweepInterval: number;
81
+ /**
82
+ * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)
83
+ *
84
+ * @defaultValue `86_400_000`
85
+ */
86
+ hashLifetime: number;
87
+ /**
88
+ * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)
89
+ *
90
+ * @defaultValue `14_400_000`
91
+ */
92
+ hashSweepInterval: number;
93
+ /**
94
+ * Additional headers to send for all API requests
95
+ *
96
+ * @defaultValue `{}`
97
+ */
98
+ headers: Record<string, string>;
99
+ /**
100
+ * The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).
101
+ * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.
102
+ *
103
+ * @defaultValue `0`
104
+ */
105
+ invalidRequestWarningInterval: number;
106
+ /**
107
+ * The method called to perform the actual HTTP request given a url and web `fetch` options
108
+ * For example, to use global fetch, simply provide `makeRequest: fetch`
109
+ */
110
+ makeRequest(url: string, init: RequestInit): Promise<ResponseLike>;
111
+ /**
112
+ * The extra offset to add to rate limits in milliseconds
113
+ *
114
+ * @defaultValue `50`
115
+ */
116
+ offset: number;
117
+ /**
118
+ * Determines how rate limiting and pre-emptive throttling should be handled.
119
+ * When an array of strings, each element is treated as a prefix for the request route
120
+ * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)
121
+ * for which to throw {@link RateLimitError}s. All other request routes will be queued normally
122
+ *
123
+ * @defaultValue `null`
124
+ */
125
+ rejectOnRateLimit: RateLimitQueueFilter | string[] | null;
126
+ /**
127
+ * The number of retries for errors with the 500 code, or errors
128
+ * that timeout
129
+ *
130
+ * @defaultValue `3`
131
+ */
132
+ retries: number;
133
+ /**
134
+ * The time to wait in milliseconds before a request is aborted
135
+ *
136
+ * @defaultValue `15_000`
137
+ */
138
+ timeout: number;
139
+ /**
140
+ * Extra information to add to the user agent
141
+ *
142
+ * @defaultValue DefaultUserAgentAppendix
143
+ */
144
+ userAgentAppendix: string;
145
+ /**
146
+ * The version of the API to use
147
+ *
148
+ * @defaultValue `'10'`
149
+ */
150
+ version: string;
151
+ }
152
+ /**
153
+ * Data emitted on `RESTEvents.RateLimited`
154
+ */
155
+ interface RateLimitData {
156
+ /**
157
+ * Whether the rate limit that was reached was the global limit
158
+ */
159
+ global: boolean;
160
+ /**
161
+ * The bucket hash for this request
162
+ */
163
+ hash: string;
164
+ /**
165
+ * The amount of requests we can perform before locking requests
166
+ */
167
+ limit: number;
168
+ /**
169
+ * The major parameter of the route
170
+ *
171
+ * For example, in `/channels/x`, this will be `x`.
172
+ * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.
173
+ */
174
+ majorParameter: string;
175
+ /**
176
+ * The HTTP method being performed
177
+ */
178
+ method: string;
179
+ /**
180
+ * The time, in milliseconds, that will need to pass before this specific request can be retried
181
+ */
182
+ retryAfter: number;
183
+ /**
184
+ * The route being hit in this request
185
+ */
186
+ route: string;
187
+ /**
188
+ * The time, in milliseconds, that will need to pass before the sublimit lock for the route resets, and requests that fall under a sublimit
189
+ * can be retried
190
+ *
191
+ * This is only present on certain sublimits, and `0` otherwise
192
+ */
193
+ sublimitTimeout: number;
194
+ /**
195
+ * The time, in milliseconds, until the route's request-lock is reset
196
+ */
197
+ timeToReset: number;
198
+ /**
199
+ * The full URL for this request
200
+ */
201
+ url: string;
202
+ }
203
+ /**
204
+ * A function that determines whether the rate limit hit should throw an Error
205
+ */
206
+ type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Awaitable<boolean>;
207
+ interface APIRequest {
208
+ /**
209
+ * The data that was used to form the body of this request
210
+ */
211
+ data: HandlerRequestData;
212
+ /**
213
+ * The HTTP method used in this request
214
+ */
215
+ method: string;
216
+ /**
217
+ * Additional HTTP options for this request
218
+ */
219
+ options: RequestInit;
220
+ /**
221
+ * The full path used to make the request
222
+ */
223
+ path: RouteLike;
224
+ /**
225
+ * The number of times this request has been attempted
226
+ */
227
+ retries: number;
228
+ /**
229
+ * The API route identifying the ratelimit for this request
230
+ */
231
+ route: string;
232
+ }
233
+ interface ResponseLike extends Pick<Response, 'arrayBuffer' | 'bodyUsed' | 'headers' | 'json' | 'ok' | 'status' | 'statusText' | 'text'> {
234
+ body: Readable | ReadableStream | null;
235
+ }
236
+ interface InvalidRequestWarningData {
237
+ /**
238
+ * Number of invalid requests that have been made in the window
239
+ */
240
+ count: number;
241
+ /**
242
+ * Time in milliseconds remaining before the count resets
243
+ */
244
+ remainingTime: number;
245
+ }
246
+ /**
247
+ * Represents a file to be added to the request
248
+ */
249
+ interface RawFile {
250
+ /**
251
+ * Content-Type of the file
252
+ */
253
+ contentType?: string;
254
+ /**
255
+ * The actual data for the file
256
+ */
257
+ data: Buffer | Uint8Array | boolean | number | string;
258
+ /**
259
+ * An explicit key to use for key of the formdata field for this file.
260
+ * When not provided, the index of the file in the files array is used in the form `files[${index}]`.
261
+ * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)
262
+ */
263
+ key?: string;
264
+ /**
265
+ * The name of the file
266
+ */
267
+ name: string;
268
+ }
269
+ /**
270
+ * Represents possible data to be given to an endpoint
271
+ */
272
+ interface RequestData {
273
+ /**
274
+ * Whether to append JSON data to form data instead of `payload_json` when sending files
275
+ */
276
+ appendToFormData?: boolean;
277
+ /**
278
+ * If this request needs the `Authorization` header
279
+ *
280
+ * @defaultValue `true`
281
+ */
282
+ auth?: boolean;
283
+ /**
284
+ * The authorization prefix to use for this request, useful if you use this with bearer tokens
285
+ *
286
+ * @defaultValue `'Bot'`
287
+ */
288
+ authPrefix?: 'Bearer' | 'Bot';
289
+ /**
290
+ * The body to send to this request.
291
+ * If providing as BodyInit, set `passThroughBody: true`
292
+ */
293
+ body?: BodyInit | unknown;
294
+ /**
295
+ * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.
296
+ */
297
+ dispatcher?: Agent;
298
+ /**
299
+ * Files to be attached to this request
300
+ */
301
+ files?: RawFile[] | undefined;
302
+ /**
303
+ * Additional headers to add to this request
304
+ */
305
+ headers?: Record<string, string>;
306
+ /**
307
+ * Whether to pass-through the body property directly to `fetch()`.
308
+ * <warn>This only applies when files is NOT present</warn>
309
+ */
310
+ passThroughBody?: boolean;
311
+ /**
312
+ * Query string parameters to append to the called endpoint
313
+ */
314
+ query?: URLSearchParams;
315
+ /**
316
+ * Reason to show in the audit logs
317
+ */
318
+ reason?: string | undefined;
319
+ /**
320
+ * The signal to abort the queue entry or the REST call, where applicable
321
+ */
322
+ signal?: AbortSignal | undefined;
323
+ /**
324
+ * If this request should be versioned
325
+ *
326
+ * @defaultValue `true`
327
+ */
328
+ versioned?: boolean;
329
+ }
330
+ /**
331
+ * Possible headers for an API call
332
+ */
333
+ interface RequestHeaders {
334
+ Authorization?: string;
335
+ 'User-Agent': string;
336
+ 'X-Audit-Log-Reason'?: string;
337
+ }
338
+ /**
339
+ * Possible API methods to be used when doing requests
340
+ */
341
+ declare enum RequestMethod {
342
+ Delete = "DELETE",
343
+ Get = "GET",
344
+ Patch = "PATCH",
345
+ Post = "POST",
346
+ Put = "PUT"
347
+ }
348
+ type RouteLike = `/${string}`;
349
+ /**
350
+ * Internal request options
351
+ *
352
+ * @internal
353
+ */
354
+ interface InternalRequest extends RequestData {
355
+ fullRoute: RouteLike;
356
+ method: RequestMethod;
357
+ }
358
+ type HandlerRequestData = Pick<InternalRequest, 'auth' | 'body' | 'files' | 'signal'>;
359
+ /**
360
+ * Parsed route data for an endpoint
361
+ *
362
+ * @internal
363
+ */
364
+ interface RouteData {
365
+ bucketRoute: string;
366
+ majorParameter: string;
367
+ original: RouteLike;
368
+ }
369
+ /**
370
+ * Represents a hash and its associated fields
371
+ *
372
+ * @internal
373
+ */
374
+ interface HashData {
375
+ lastAccess: number;
376
+ value: string;
377
+ }
12
378
 
13
379
  declare const DefaultUserAgent: `DiscordBot (https://discord.js.org, ${string})`;
14
380
  /**
@@ -519,9 +885,9 @@ declare function parseResponse(res: ResponseLike): Promise<unknown>;
519
885
  declare function calculateUserDefaultAvatarIndex(userId: Snowflake): number;
520
886
 
521
887
  /**
522
- * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version
888
+ * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest#readme | @discordjs/rest} version
523
889
  * that you are currently using.
524
890
  */
525
891
  declare const version: string;
526
892
 
527
- export { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, BaseImageURLOptions, BurstHandlerMajorIdKey, CDN, DEPRECATION_WARNING_PREFIX, DefaultRestOptions, DefaultUserAgent, DefaultUserAgentAppendix, DiscordAPIError, DiscordErrorData, HTTPError, HashData, ImageExtension, ImageSize, ImageURLOptions, InternalRequest, MakeURLOptions, OAuthErrorData, OverwrittenMimeTypes, REST, RESTEvents, RESTOptions, RateLimitData, RateLimitError, RawFile, RequestBody, RequestData, ResponseLike, RestEventsMap, RouteLike, StickerExtension, calculateUserDefaultAvatarIndex, makeURLSearchParams, parseResponse, version };
893
+ export { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, APIRequest, BaseImageURLOptions, BurstHandlerMajorIdKey, CDN, DEPRECATION_WARNING_PREFIX, DefaultRestOptions, DefaultUserAgent, DefaultUserAgentAppendix, DiscordAPIError, DiscordErrorData, HTTPError, HandlerRequestData, HashData, ImageExtension, ImageSize, ImageURLOptions, InternalRequest, InvalidRequestWarningData, MakeURLOptions, OAuthErrorData, OverwrittenMimeTypes, REST, RESTEvents, RESTOptions, RateLimitData, RateLimitError, RateLimitQueueFilter, RawFile, RequestBody, RequestData, RequestHeaders, RequestMethod, ResponseLike, RestEvents, RestEventsMap, RouteData, RouteLike, StickerExtension, calculateUserDefaultAvatarIndex, makeURLSearchParams, parseResponse, version };