seyfert 0.1.0 → 1.0.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 (198) hide show
  1. package/README.md +19 -30
  2. package/lib/api/CDN.d.ts +0 -8
  3. package/lib/api/CDN.js +7 -13
  4. package/lib/api/Router.d.ts +2 -2
  5. package/lib/api/Router.js +1 -1
  6. package/lib/api/Routes/applications.d.ts +1 -1
  7. package/lib/api/Routes/channels.d.ts +1 -1
  8. package/lib/api/Routes/gateway.d.ts +1 -1
  9. package/lib/api/Routes/guilds.d.ts +1 -1
  10. package/lib/api/Routes/interactions.d.ts +1 -1
  11. package/lib/api/Routes/invites.d.ts +1 -1
  12. package/lib/api/Routes/stage-instances.d.ts +1 -1
  13. package/lib/api/Routes/stickers.d.ts +1 -1
  14. package/lib/api/Routes/users.d.ts +1 -1
  15. package/lib/api/Routes/voice.d.ts +1 -1
  16. package/lib/api/Routes/webhooks.d.ts +1 -1
  17. package/lib/api/api.d.ts +44 -0
  18. package/lib/api/api.js +354 -0
  19. package/lib/api/bucket.d.ts +19 -0
  20. package/lib/api/bucket.js +71 -0
  21. package/lib/api/index.d.ts +1 -1
  22. package/lib/api/index.js +1 -1
  23. package/lib/api/shared.d.ts +33 -5
  24. package/lib/api/shared.js +2 -7
  25. package/lib/api/utils/constants.d.ts +1 -30
  26. package/lib/api/utils/constants.js +2 -41
  27. package/lib/api/utils/types.d.ts +1 -320
  28. package/lib/api/utils/utils.d.ts +0 -38
  29. package/lib/api/utils/utils.js +1 -139
  30. package/lib/builders/ActionRow.js +1 -1
  31. package/lib/builders/Attachment.d.ts +14 -6
  32. package/lib/builders/Attachment.js +30 -7
  33. package/lib/builders/Button.d.ts +5 -14
  34. package/lib/builders/Button.js +0 -11
  35. package/lib/builders/{MessageEmbed.d.ts → Embed.d.ts} +15 -15
  36. package/lib/builders/{MessageEmbed.js → Embed.js} +16 -16
  37. package/lib/builders/Modal.js +1 -1
  38. package/lib/builders/SelectMenu.d.ts +14 -15
  39. package/lib/builders/SelectMenu.js +19 -18
  40. package/lib/builders/index.d.ts +1 -1
  41. package/lib/builders/index.js +1 -1
  42. package/lib/builders/types.d.ts +2 -2
  43. package/lib/cache/adapters/default.d.ts +1 -0
  44. package/lib/cache/adapters/default.js +3 -2
  45. package/lib/cache/adapters/redis.d.ts +3 -3
  46. package/lib/cache/adapters/redis.js +14 -5
  47. package/lib/cache/adapters/types.d.ts +1 -0
  48. package/lib/cache/adapters/workeradapter.d.ts +10 -1
  49. package/lib/cache/adapters/workeradapter.js +8 -3
  50. package/lib/cache/index.d.ts +18 -5
  51. package/lib/cache/index.js +23 -9
  52. package/lib/cache/resources/channels.d.ts +6 -2
  53. package/lib/cache/resources/channels.js +12 -6
  54. package/lib/cache/resources/default/base.d.ts +17 -16
  55. package/lib/cache/resources/default/base.js +25 -24
  56. package/lib/cache/resources/default/guild-based.d.ts +22 -19
  57. package/lib/cache/resources/default/guild-based.js +32 -31
  58. package/lib/cache/resources/default/guild-related.d.ts +22 -19
  59. package/lib/cache/resources/default/guild-related.js +37 -43
  60. package/lib/cache/resources/emojis.d.ts +4 -2
  61. package/lib/cache/resources/emojis.js +8 -6
  62. package/lib/cache/resources/guilds.d.ts +4 -2
  63. package/lib/cache/resources/guilds.js +15 -8
  64. package/lib/cache/resources/members.d.ts +4 -2
  65. package/lib/cache/resources/members.js +16 -13
  66. package/lib/cache/resources/overwrites.d.ts +25 -0
  67. package/lib/cache/resources/overwrites.js +39 -0
  68. package/lib/cache/resources/presence.js +3 -4
  69. package/lib/cache/resources/roles.d.ts +4 -2
  70. package/lib/cache/resources/roles.js +8 -6
  71. package/lib/cache/resources/stickers.d.ts +4 -2
  72. package/lib/cache/resources/stickers.js +8 -6
  73. package/lib/cache/resources/threads.d.ts +4 -2
  74. package/lib/cache/resources/threads.js +8 -6
  75. package/lib/cache/resources/users.d.ts +4 -2
  76. package/lib/cache/resources/users.js +8 -6
  77. package/lib/cache/resources/voice-states.d.ts +3 -3
  78. package/lib/cache/resources/voice-states.js +6 -7
  79. package/lib/client/base.d.ts +48 -16
  80. package/lib/client/base.js +19 -15
  81. package/lib/client/client.d.ts +15 -4
  82. package/lib/client/client.js +26 -28
  83. package/lib/client/httpclient.d.ts +3 -5
  84. package/lib/client/httpclient.js +29 -16
  85. package/lib/client/{oninteraction.d.ts → oninteractioncreate.d.ts} +1 -1
  86. package/lib/client/{oninteraction.js → oninteractioncreate.js} +34 -23
  87. package/lib/client/onmessagecreate.d.ts +3 -0
  88. package/lib/client/onmessagecreate.js +337 -0
  89. package/lib/client/workerclient.d.ts +19 -2
  90. package/lib/client/workerclient.js +156 -46
  91. package/lib/collection.d.ts +1 -1
  92. package/lib/collection.js +9 -6
  93. package/lib/commands/applications/chat.d.ts +32 -25
  94. package/lib/commands/applications/chat.js +51 -34
  95. package/lib/commands/applications/chatcontext.d.ts +34 -16
  96. package/lib/commands/applications/chatcontext.js +99 -20
  97. package/lib/commands/applications/menu.d.ts +9 -8
  98. package/lib/commands/applications/menu.js +14 -5
  99. package/lib/commands/applications/menucontext.d.ts +27 -10
  100. package/lib/commands/applications/menucontext.js +51 -7
  101. package/lib/commands/applications/options.d.ts +13 -13
  102. package/lib/commands/applications/shared.d.ts +7 -2
  103. package/lib/commands/decorators.d.ts +14 -14
  104. package/lib/commands/decorators.js +9 -5
  105. package/lib/commands/handler.d.ts +2 -1
  106. package/lib/commands/handler.js +60 -14
  107. package/lib/commands/index.d.ts +1 -1
  108. package/lib/commands/index.js +2 -1
  109. package/lib/commands/optionresolver.d.ts +6 -5
  110. package/lib/commands/optionresolver.js +10 -6
  111. package/lib/common/bot/watcher.d.ts +3 -3
  112. package/lib/common/bot/watcher.js +3 -1
  113. package/lib/common/index.d.ts +1 -1
  114. package/lib/common/index.js +2 -1
  115. package/lib/common/it/logger.d.ts +11 -0
  116. package/lib/common/it/logger.js +51 -2
  117. package/lib/common/it/utils.d.ts +3 -13
  118. package/lib/common/it/utils.js +9 -30
  119. package/lib/common/shorters/channels.d.ts +55 -5
  120. package/lib/common/shorters/channels.js +59 -0
  121. package/lib/common/shorters/guilds.d.ts +5 -2
  122. package/lib/common/shorters/guilds.js +18 -0
  123. package/lib/common/shorters/messages.js +0 -2
  124. package/lib/common/shorters/overwrites.d.ts +29 -0
  125. package/lib/common/shorters/overwrites.js +63 -0
  126. package/lib/common/shorters/roles.js +3 -3
  127. package/lib/common/shorters/webhook.d.ts +2 -2
  128. package/lib/common/types/util.d.ts +3 -2
  129. package/lib/common/types/write.d.ts +3 -7
  130. package/lib/components/handler.d.ts +11 -17
  131. package/lib/components/handler.js +45 -93
  132. package/lib/components/index.d.ts +0 -1
  133. package/lib/components/index.js +0 -1
  134. package/lib/components/listener.d.ts +2 -2
  135. package/lib/components/listener.js +2 -3
  136. package/lib/events/event.d.ts +2 -2
  137. package/lib/events/handler.d.ts +3 -2
  138. package/lib/events/handler.js +14 -6
  139. package/lib/events/hooks/dispatch.d.ts +2 -1
  140. package/lib/events/hooks/dispatch.js +5 -1
  141. package/lib/events/hooks/thread.d.ts +63 -63
  142. package/lib/index.d.ts +8 -5
  143. package/lib/index.js +20 -10
  144. package/lib/langs/handler.d.ts +6 -4
  145. package/lib/langs/handler.js +10 -8
  146. package/lib/langs/router.d.ts +8 -9
  147. package/lib/langs/router.js +5 -5
  148. package/lib/structures/ClientUser.d.ts +1 -16
  149. package/lib/structures/ClientUser.js +0 -31
  150. package/lib/structures/Guild.d.ts +1 -1
  151. package/lib/structures/GuildMember.d.ts +12 -0
  152. package/lib/structures/GuildMember.js +14 -0
  153. package/lib/structures/GuildRole.d.ts +4 -2
  154. package/lib/structures/GuildRole.js +4 -1
  155. package/lib/structures/GuildTemplate.js +1 -1
  156. package/lib/structures/Interaction.d.ts +2 -0
  157. package/lib/structures/Interaction.js +12 -13
  158. package/lib/structures/Message.d.ts +7 -2
  159. package/lib/structures/Message.js +6 -3
  160. package/lib/structures/Sticker.d.ts +1 -1
  161. package/lib/structures/Sticker.js +1 -1
  162. package/lib/structures/User.d.ts +5 -0
  163. package/lib/structures/User.js +3 -0
  164. package/lib/structures/Webhook.d.ts +1 -1
  165. package/lib/structures/Webhook.js +1 -1
  166. package/lib/structures/channels.d.ts +45 -6
  167. package/lib/structures/channels.js +23 -7
  168. package/lib/structures/extra/BitField.d.ts +9 -6
  169. package/lib/structures/extra/BitField.js +27 -3
  170. package/lib/structures/extra/Permissions.d.ts +6 -1
  171. package/lib/structures/extra/Permissions.js +7 -0
  172. package/lib/websocket/constants/index.js +1 -3
  173. package/lib/websocket/discord/basesocket.js +0 -1
  174. package/lib/websocket/discord/shared.d.ts +2 -0
  175. package/lib/websocket/discord/worker.d.ts +23 -7
  176. package/lib/websocket/discord/workermanager.d.ts +32 -5
  177. package/lib/websocket/discord/workermanager.js +98 -29
  178. package/package.json +23 -21
  179. package/lib/api/REST.d.ts +0 -127
  180. package/lib/api/REST.js +0 -424
  181. package/lib/api/errors/DiscordAPIError.d.ts +0 -51
  182. package/lib/api/errors/DiscordAPIError.js +0 -81
  183. package/lib/api/errors/HTTPError.d.ts +0 -20
  184. package/lib/api/errors/HTTPError.js +0 -28
  185. package/lib/api/errors/RateLimitError.d.ts +0 -19
  186. package/lib/api/errors/RateLimitError.js +0 -37
  187. package/lib/api/handlers/BurstHandler.d.ts +0 -51
  188. package/lib/api/handlers/BurstHandler.js +0 -124
  189. package/lib/api/handlers/SequentialHandler.d.ts +0 -81
  190. package/lib/api/handlers/SequentialHandler.js +0 -365
  191. package/lib/api/handlers/Shared.d.ts +0 -14
  192. package/lib/api/handlers/Shared.js +0 -125
  193. package/lib/api/interfaces/Handler.d.ts +0 -21
  194. package/lib/api/interfaces/Handler.js +0 -2
  195. package/lib/websocket/discord/handlemessage.d.ts +0 -0
  196. package/lib/websocket/discord/handlemessage.js +0 -1
  197. package/lib/websocket/discord/memberUpdate.d.ts +0 -16
  198. package/lib/websocket/discord/memberUpdate.js +0 -47
@@ -1,365 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SequentialHandler = void 0;
4
- const async_queue_1 = require("@sapphire/async-queue");
5
- const utils_js_1 = require("../utils/utils.js");
6
- const Shared_js_1 = require("./Shared.js");
7
- var QueueType;
8
- (function (QueueType) {
9
- QueueType[QueueType["Standard"] = 0] = "Standard";
10
- QueueType[QueueType["Sublimit"] = 1] = "Sublimit";
11
- })(QueueType || (QueueType = {}));
12
- /**
13
- * The structure used to handle sequential requests for a given bucket
14
- */
15
- class SequentialHandler {
16
- manager;
17
- hash;
18
- majorParameter;
19
- /**
20
- * {@inheritDoc IHandler.id}
21
- */
22
- id;
23
- /**
24
- * The time this rate limit bucket will reset
25
- */
26
- reset = -1;
27
- /**
28
- * The remaining requests that can be made before we are rate limited
29
- */
30
- remaining = 1;
31
- /**
32
- * The total number of requests that can be made before we are rate limited
33
- */
34
- limit = Number.POSITIVE_INFINITY;
35
- /**
36
- * The interface used to sequence async requests sequentially
37
- */
38
- #asyncQueue = new async_queue_1.AsyncQueue();
39
- /**
40
- * The interface used to sequence sublimited async requests sequentially
41
- */
42
- #sublimitedQueue = null;
43
- /**
44
- * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed
45
- */
46
- #sublimitPromise = null;
47
- /**
48
- * Whether the sublimit queue needs to be shifted in the finally block
49
- */
50
- #shiftSublimit = false;
51
- /**
52
- * @param manager - The request manager
53
- * @param hash - The hash that this RequestHandler handles
54
- * @param majorParameter - The major parameter for this handler
55
- */
56
- constructor(manager, hash, majorParameter) {
57
- this.manager = manager;
58
- this.hash = hash;
59
- this.majorParameter = majorParameter;
60
- this.id = `${hash}:${majorParameter}`;
61
- }
62
- /**
63
- * {@inheritDoc IHandler.inactive}
64
- */
65
- get inactive() {
66
- return (this.#asyncQueue.remaining === 0 &&
67
- (this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) &&
68
- !this.limited);
69
- }
70
- /**
71
- * If the rate limit bucket is currently limited by the global limit
72
- */
73
- get globalLimited() {
74
- return this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset;
75
- }
76
- /**
77
- * If the rate limit bucket is currently limited by its limit
78
- */
79
- get localLimited() {
80
- return this.remaining <= 0 && Date.now() < this.reset;
81
- }
82
- /**
83
- * If the rate limit bucket is currently limited
84
- */
85
- get limited() {
86
- return this.globalLimited || this.localLimited;
87
- }
88
- /**
89
- * The time until queued requests can continue
90
- */
91
- get timeToReset() {
92
- return this.reset + this.manager.options.offset - Date.now();
93
- }
94
- /**
95
- * Emits a debug message
96
- *
97
- * @param message - The message to debug
98
- */
99
- debug(message) {
100
- this.manager.debugger?.info(`#${this.id} ${message}`);
101
- }
102
- /**
103
- * Delay all requests for the specified amount of time, handling global rate limits
104
- *
105
- * @param time - The amount of time to delay all requests for
106
- */
107
- async globalDelayFor(time) {
108
- await (0, utils_js_1.sleep)(time);
109
- this.manager.globalDelay = null;
110
- }
111
- /**
112
- * {@inheritDoc IHandler.queueRequest}
113
- */
114
- async queueRequest(routeId, url, options, requestData) {
115
- let queue = this.#asyncQueue;
116
- let queueType = QueueType.Standard;
117
- // Separate sublimited requests when already sublimited
118
- if (this.#sublimitedQueue && (0, utils_js_1.hasSublimit)(routeId.bucketRoute, requestData.body, options.method)) {
119
- queue = this.#sublimitedQueue;
120
- queueType = QueueType.Sublimit;
121
- }
122
- // Wait for any previous requests to be completed before this one is run
123
- await queue.wait({ signal: requestData.signal });
124
- // This set handles retroactively sublimiting requests
125
- if (queueType === QueueType.Standard) {
126
- if (this.#sublimitedQueue && (0, utils_js_1.hasSublimit)(routeId.bucketRoute, requestData.body, options.method)) {
127
- /**
128
- * Remove the request from the standard queue, it should never be possible to get here while processing the
129
- * sublimit queue so there is no need to worry about shifting the wrong request
130
- */
131
- queue = this.#sublimitedQueue;
132
- const wait = queue.wait();
133
- this.#asyncQueue.shift();
134
- await wait;
135
- }
136
- else if (this.#sublimitPromise) {
137
- // Stall requests while the sublimit queue gets processed
138
- await this.#sublimitPromise.promise;
139
- }
140
- }
141
- try {
142
- // Make the request, and return the results
143
- return this.runRequest(routeId, url, options, requestData);
144
- }
145
- finally {
146
- // Allow the next request to fire
147
- queue.shift();
148
- if (this.#shiftSublimit) {
149
- this.#shiftSublimit = false;
150
- this.#sublimitedQueue?.shift();
151
- }
152
- // If this request is the last request in a sublimit
153
- if (this.#sublimitedQueue?.remaining === 0) {
154
- this.#sublimitPromise?.resolve();
155
- this.#sublimitedQueue = null;
156
- }
157
- }
158
- }
159
- /**
160
- * The method that actually makes the request to the api, and updates info about the bucket accordingly
161
- *
162
- * @param routeId - The generalized api route with literal ids for major parameters
163
- * @param url - The fully resolved url to make the request to
164
- * @param options - The fetch options needed to make the request
165
- * @param requestData - Extra data from the user's request needed for errors and additional processing
166
- * @param retries - The number of retries this request has already attempted (recursion)
167
- */
168
- async runRequest(routeId, url, options, requestData, retries = 0) {
169
- /*
170
- * After calculations have been done, pre-emptively stop further requests
171
- * Potentially loop until this task can run if e.g. the global rate limit is hit twice
172
- */
173
- while (this.limited) {
174
- const isGlobal = this.globalLimited;
175
- let limit;
176
- let timeout;
177
- let delay;
178
- if (isGlobal) {
179
- // Set RateLimitData based on the global limit
180
- limit = this.manager.options.globalRequestsPerSecond;
181
- timeout = this.manager.globalReset + this.manager.options.offset - Date.now();
182
- // If this is the first task to reach the global timeout, set the global delay
183
- if (!this.manager.globalDelay) {
184
- // The global delay function clears the global delay state when it is resolved
185
- this.manager.globalDelay = this.globalDelayFor(timeout);
186
- }
187
- delay = this.manager.globalDelay;
188
- }
189
- else {
190
- // Set RateLimitData based on the route-specific limit
191
- limit = this.limit;
192
- timeout = this.timeToReset;
193
- delay = (0, utils_js_1.sleep)(timeout);
194
- }
195
- const rateLimitData = {
196
- global: isGlobal,
197
- method: options.method ?? 'get',
198
- url,
199
- route: routeId.bucketRoute,
200
- majorParameter: this.majorParameter,
201
- hash: this.hash,
202
- limit,
203
- timeToReset: timeout,
204
- retryAfter: timeout,
205
- sublimitTimeout: 0,
206
- scope: 'user',
207
- };
208
- // Let library users know they have hit a rate limit
209
- this.manager.debugger?.info(rateLimitData);
210
- // Determine whether a RateLimitError should be thrown
211
- await (0, utils_js_1.onRateLimit)(this.manager, rateLimitData);
212
- // When not erroring, emit debug for what is happening
213
- if (isGlobal) {
214
- this.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`);
215
- }
216
- else {
217
- this.debug(`Waiting ${timeout}ms for rate limit to pass`);
218
- }
219
- // Wait the remaining time left before the rate limit resets
220
- await delay;
221
- }
222
- // As the request goes out, update the global usage information
223
- if (!this.manager.globalReset || this.manager.globalReset < Date.now()) {
224
- this.manager.globalReset = Date.now() + 1_000;
225
- this.manager.globalRemaining = this.manager.options.globalRequestsPerSecond;
226
- }
227
- this.manager.globalRemaining--;
228
- const method = options.method ?? 'get';
229
- const res = await (0, Shared_js_1.makeNetworkRequest)(this.manager, routeId, url, options, requestData, retries);
230
- // Retry requested
231
- if (res === null) {
232
- // eslint-disable-next-line no-param-reassign
233
- return this.runRequest(routeId, url, options, requestData, ++retries);
234
- }
235
- const status = res.status;
236
- let retryAfter = 0;
237
- const limit = res.headers.get('X-RateLimit-Limit');
238
- const remaining = res.headers.get('X-RateLimit-Remaining');
239
- const reset = res.headers.get('X-RateLimit-Reset-After');
240
- const hash = res.headers.get('X-RateLimit-Bucket');
241
- const retry = res.headers.get('Retry-After');
242
- const scope = (res.headers.get('X-RateLimit-Scope') ?? 'user');
243
- // Update the total number of requests that can be made before the rate limit resets
244
- this.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY;
245
- // Update the number of remaining requests that can be made before the rate limit resets
246
- this.remaining = remaining ? Number(remaining) : 1;
247
- // Update the time when this rate limit resets (reset-after is in seconds)
248
- this.reset = reset ? Number(reset) * 1_000 + Date.now() + this.manager.options.offset : Date.now();
249
- // Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)
250
- if (retry)
251
- retryAfter = Number(retry) * 1_000 + this.manager.options.offset;
252
- // Handle buckets via the hash header retroactively
253
- if (hash && hash !== this.hash) {
254
- // Let library users know when rate limit buckets have been updated
255
- this.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\n'));
256
- // This queue will eventually be eliminated via attrition
257
- this.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { value: hash, lastAccess: Date.now() });
258
- }
259
- else if (hash) {
260
- // Handle the case where hash value doesn't change
261
- // Fetch the hash data from the manager
262
- const hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`);
263
- // When fetched, update the last access of the hash
264
- if (hashData) {
265
- hashData.lastAccess = Date.now();
266
- }
267
- }
268
- // Handle retryAfter, which means we have actually hit a rate limit
269
- let sublimitTimeout = null;
270
- if (retryAfter > 0) {
271
- if (res.headers.has('X-RateLimit-Global')) {
272
- this.manager.globalRemaining = 0;
273
- this.manager.globalReset = Date.now() + retryAfter;
274
- }
275
- else if (!this.localLimited) {
276
- /*
277
- * This is a sublimit (e.g. 2 channel name changes/10 minutes) since the headers don't indicate a
278
- * route-wide rate limit. Don't update remaining or reset to avoid rate limiting the whole
279
- * endpoint, just set a reset time on the request itself to avoid retrying too soon.
280
- */
281
- sublimitTimeout = retryAfter;
282
- }
283
- }
284
- // Count the invalid requests
285
- if (status === 401 || status === 403 || status === 429) {
286
- (0, Shared_js_1.incrementInvalidCount)(this.manager);
287
- }
288
- if (res.ok) {
289
- return res;
290
- }
291
- if (status === 429) {
292
- // A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited
293
- const isGlobal = this.globalLimited;
294
- let limit;
295
- let timeout;
296
- if (isGlobal) {
297
- // Set RateLimitData based on the global limit
298
- limit = this.manager.options.globalRequestsPerSecond;
299
- timeout = this.manager.globalReset + this.manager.options.offset - Date.now();
300
- }
301
- else {
302
- // Set RateLimitData based on the route-specific limit
303
- limit = this.limit;
304
- timeout = this.timeToReset;
305
- }
306
- await (0, utils_js_1.onRateLimit)(this.manager, {
307
- global: isGlobal,
308
- method,
309
- url,
310
- route: routeId.bucketRoute,
311
- majorParameter: this.majorParameter,
312
- hash: this.hash,
313
- limit,
314
- timeToReset: timeout,
315
- retryAfter,
316
- sublimitTimeout: sublimitTimeout ?? 0,
317
- scope,
318
- });
319
- this.debug([
320
- 'Encountered unexpected 429 rate limit',
321
- ` Global : ${isGlobal.toString()}`,
322
- ` Method : ${method}`,
323
- ` URL : ${url}`,
324
- ` Bucket : ${routeId.bucketRoute}`,
325
- ` Major parameter: ${routeId.majorParameter}`,
326
- ` Hash : ${this.hash}`,
327
- ` Limit : ${limit}`,
328
- ` Retry After : ${retryAfter}ms`,
329
- ` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,
330
- ` Scope : ${scope}`,
331
- ].join('\n'));
332
- // If caused by a sublimit, wait it out here so other requests on the route can be handled
333
- if (sublimitTimeout) {
334
- // Normally the sublimit queue will not exist, however, if a sublimit is hit while in the sublimit queue, it will
335
- const firstSublimit = !this.#sublimitedQueue;
336
- if (firstSublimit) {
337
- this.#sublimitedQueue = new async_queue_1.AsyncQueue();
338
- void this.#sublimitedQueue.wait();
339
- this.#asyncQueue.shift();
340
- }
341
- this.#sublimitPromise?.resolve();
342
- this.#sublimitPromise = null;
343
- await (0, utils_js_1.sleep)(sublimitTimeout);
344
- let resolve;
345
- // eslint-disable-next-line promise/param-names, no-promise-executor-return
346
- const promise = new Promise(res => (resolve = res));
347
- this.#sublimitPromise = { promise, resolve: resolve };
348
- if (firstSublimit) {
349
- // Re-queue this request so it can be shifted by the finally
350
- await this.#asyncQueue.wait();
351
- this.#shiftSublimit = true;
352
- }
353
- }
354
- // Since this is not a server side issue, the next request should pass, so we don't bump the retries counter
355
- return this.runRequest(routeId, url, options, requestData, retries);
356
- }
357
- const handled = await (0, Shared_js_1.handleErrors)(this.manager, res, method, url, requestData, retries);
358
- if (handled === null) {
359
- // eslint-disable-next-line no-param-reassign
360
- return this.runRequest(routeId, url, options, requestData, ++retries);
361
- }
362
- return handled;
363
- }
364
- }
365
- exports.SequentialHandler = SequentialHandler;
@@ -1,14 +0,0 @@
1
- import type { REST } from '../REST.js';
2
- import type { HandlerRequestData, ResponseLike } from '../utils/types.js';
3
- /**
4
- * Handles 5xx and 4xx errors (not 429's) conventionally. 429's should be handled before calling this function
5
- *
6
- * @param manager - The manager that holds options and emits informational events
7
- * @param res - The response received from {@link makeNetworkRequest}
8
- * @param method - The method used to make the request
9
- * @param url - The fully resolved url to make the request to
10
- * @param requestData - Extra data from the user's request needed for errors and additional processing
11
- * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)
12
- * @returns The response if the status code is not handled or null to request a retry
13
- */
14
- export declare function handleErrors(manager: REST, res: ResponseLike, method: string, url: string, requestData: HandlerRequestData, retries: number): Promise<ResponseLike | null>;
@@ -1,125 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.handleErrors = exports.makeNetworkRequest = exports.incrementInvalidCount = void 0;
4
- const DiscordAPIError_js_1 = require("../errors/DiscordAPIError.js");
5
- const HTTPError_js_1 = require("../errors/HTTPError.js");
6
- const constants_js_1 = require("../utils/constants.js");
7
- const utils_js_1 = require("../utils/utils.js");
8
- /**
9
- * Invalid request limiting is done on a per-IP basis, not a per-token basis.
10
- * The best we can do is track invalid counts process-wide (on the theory that
11
- * users could have multiple bots run from one process) rather than per-bot.
12
- * Therefore, store these at file scope here rather than in the client's
13
- * RESTManager object.
14
- */
15
- let invalidCount = 0;
16
- let invalidCountResetTime = null;
17
- /**
18
- * Increment the invalid request count and emit warning if necessary
19
- *
20
- * @internal
21
- */
22
- function incrementInvalidCount(manager) {
23
- if (!invalidCountResetTime || invalidCountResetTime < Date.now()) {
24
- invalidCountResetTime = Date.now() + 1_000 * 60 * 10;
25
- invalidCount = 0;
26
- }
27
- invalidCount++;
28
- const emitInvalid = manager.options.invalidRequestWarningInterval > 0 &&
29
- invalidCount % manager.options.invalidRequestWarningInterval === 0;
30
- if (emitInvalid) {
31
- // Let library users know periodically about invalid requests
32
- manager.debugger?.info({
33
- count: invalidCount,
34
- remainingTime: invalidCountResetTime - Date.now(),
35
- });
36
- }
37
- }
38
- exports.incrementInvalidCount = incrementInvalidCount;
39
- /**
40
- * Performs the actual network request for a request handler
41
- *
42
- * @param manager - The manager that holds options and emits informational events
43
- * @param routeId - The generalized api route with literal ids for major parameters
44
- * @param url - The fully resolved url to make the request to
45
- * @param options - The fetch options needed to make the request
46
- * @param requestData - Extra data from the user's request needed for errors and additional processing
47
- * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)
48
- * @returns The respond from the network or `null` when the request should be retried
49
- * @internal
50
- */
51
- async function makeNetworkRequest(manager, routeId, url, options, requestData, retries) {
52
- const controller = new AbortController();
53
- const timeout = setTimeout(() => controller.abort(), manager.options.timeout);
54
- if (requestData.signal) {
55
- // If the user signal was aborted, abort the controller, else abort the local signal.
56
- // The reason why we don't re-use the user's signal, is because users may use the same signal for multiple
57
- // requests, and we do not want to cause unexpected side-effects.
58
- if (requestData.signal.aborted)
59
- controller.abort();
60
- else
61
- requestData.signal.addEventListener('abort', () => controller.abort());
62
- }
63
- let res;
64
- try {
65
- res = await manager.options.makeRequest(url, { ...options, signal: controller.signal });
66
- }
67
- catch (error) {
68
- if (!(error instanceof Error))
69
- throw error;
70
- // Retry the specified number of times if needed
71
- if ((0, utils_js_1.shouldRetry)(error) && retries !== manager.options.retries) {
72
- // Retry is handled by the handler upon receiving null
73
- return null;
74
- }
75
- throw error;
76
- }
77
- finally {
78
- clearTimeout(timeout);
79
- }
80
- manager.debugger?.info(constants_js_1.RESTEvents.Response, {
81
- method: options.method ?? 'get',
82
- path: routeId.original,
83
- route: routeId.bucketRoute,
84
- options,
85
- data: requestData,
86
- retries,
87
- }, res instanceof Response ? res.clone() : { ...res });
88
- return res;
89
- }
90
- exports.makeNetworkRequest = makeNetworkRequest;
91
- /**
92
- * Handles 5xx and 4xx errors (not 429's) conventionally. 429's should be handled before calling this function
93
- *
94
- * @param manager - The manager that holds options and emits informational events
95
- * @param res - The response received from {@link makeNetworkRequest}
96
- * @param method - The method used to make the request
97
- * @param url - The fully resolved url to make the request to
98
- * @param requestData - Extra data from the user's request needed for errors and additional processing
99
- * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)
100
- * @returns The response if the status code is not handled or null to request a retry
101
- */
102
- async function handleErrors(manager, res, method, url, requestData, retries) {
103
- const status = res.status;
104
- if (status >= 500 && status < 600) {
105
- // Retry the specified number of times for possible server side issues
106
- if (retries !== manager.options.retries) {
107
- return null;
108
- }
109
- // We are out of retries, throw an error
110
- throw new HTTPError_js_1.HTTPError(status, res.statusText, method, url, requestData);
111
- }
112
- // Handle possible malformed requests
113
- if (status >= 400 && status < 500) {
114
- // If we receive this status code, it means the token we had is no longer valid.
115
- if (status === 401 && requestData.auth) {
116
- manager.setToken(null);
117
- }
118
- // The request will not succeed for some reason, parse the error returned from the api
119
- const data = (await (0, utils_js_1.parseResponse)(res));
120
- // throw the API error
121
- throw new DiscordAPIError_js_1.DiscordAPIError(data, 'code' in data ? data.code : data.error, status, method, url, requestData);
122
- }
123
- return res;
124
- }
125
- exports.handleErrors = handleErrors;
@@ -1,21 +0,0 @@
1
- import type { RequestInit } from 'undici-types';
2
- import type { HandlerRequestData, ResponseLike, RouteData } from '../utils/types.js';
3
- export interface IHandler {
4
- /**
5
- * The unique id of the handler
6
- */
7
- readonly id: string;
8
- /**
9
- * If the bucket is currently inactive (no pending requests)
10
- */
11
- get inactive(): boolean;
12
- /**
13
- * Queues a request to be sent
14
- *
15
- * @param routeId - The generalized api route with literal ids for major parameters
16
- * @param url - The url to do the request on
17
- * @param options - All the information needed to make a request
18
- * @param requestData - Extra data from the user's request needed for errors and additional processing
19
- */
20
- queueRequest(routeId: RouteData, url: string, options: RequestInit, requestData: HandlerRequestData): Promise<ResponseLike>;
21
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
File without changes
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,16 +0,0 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
- /// <reference types="node" />
5
- /// <reference types="node" />
6
- import type { APIUser, GatewayGuildMemberUpdateDispatchData } from 'discord-api-types/v10';
7
- export declare class MemberUpdateHandler {
8
- guildMemberUpdate: Map<string, {
9
- timeout: NodeJS.Timeout;
10
- member: GatewayGuildMemberUpdateDispatchData;
11
- }>;
12
- check(member: GatewayGuildMemberUpdateDispatchData): boolean;
13
- setMember(member: GatewayGuildMemberUpdateDispatchData): void;
14
- membersEquals(old: GatewayGuildMemberUpdateDispatchData, member: GatewayGuildMemberUpdateDispatchData): boolean;
15
- usersEqual(old: APIUser, user: APIUser): boolean;
16
- }
@@ -1,47 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MemberUpdateHandler = void 0;
4
- class MemberUpdateHandler {
5
- guildMemberUpdate = new Map();
6
- check(member) {
7
- if (!this.guildMemberUpdate.has(member.user.id)) {
8
- this.setMember(member);
9
- return true;
10
- }
11
- const data = this.guildMemberUpdate.get(member.user.id);
12
- if (this.usersEqual(data.member.user, member.user)) {
13
- return this.membersEquals(data.member, member);
14
- }
15
- clearTimeout(data.timeout);
16
- this.setMember(member);
17
- return true;
18
- }
19
- setMember(member) {
20
- this.guildMemberUpdate.set(member.user.id, {
21
- member,
22
- timeout: setTimeout(() => {
23
- this.guildMemberUpdate.delete(member.user.id);
24
- }, 1.5e3),
25
- });
26
- }
27
- membersEquals(old, member) {
28
- return (old.joined_at === member.joined_at &&
29
- old.nick === member.nick &&
30
- old.avatar === member.avatar &&
31
- old.pending === member.pending &&
32
- old.communication_disabled_until === member.communication_disabled_until &&
33
- old.flags === member.flags &&
34
- (old.roles === member.roles ||
35
- (old.roles.length === member.roles.length && old.roles.every((role, i) => role === member.roles[i]))));
36
- }
37
- usersEqual(old, user) {
38
- return (old.username === user.username &&
39
- old.discriminator === user.discriminator &&
40
- old.global_name === user.global_name &&
41
- old.avatar === user.avatar &&
42
- old.public_flags === user.public_flags &&
43
- old.banner === user.banner &&
44
- old.accent_color === user.accent_color);
45
- }
46
- }
47
- exports.MemberUpdateHandler = MemberUpdateHandler;