@discordjs/rest 0.5.0-dev.1651147752-679dcda → 0.5.0-dev.1652400670-aed687b

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.mjs CHANGED
@@ -86,11 +86,9 @@ var require_package = __commonJS({
86
86
  "@discordjs/collection": "workspace:^",
87
87
  "@sapphire/async-queue": "^1.3.1",
88
88
  "@sapphire/snowflake": "^3.2.1",
89
- "@types/node-fetch": "^2.6.1",
90
89
  "discord-api-types": "^0.29.0",
91
- "form-data": "^4.0.0",
92
- "node-fetch": "^2.6.7",
93
- tslib: "^2.3.1"
90
+ tslib: "^2.3.1",
91
+ undici: "^5.2.0"
94
92
  },
95
93
  devDependencies: {
96
94
  "@babel/core": "^7.17.9",
@@ -108,7 +106,6 @@ var require_package = __commonJS({
108
106
  "eslint-config-prettier": "^8.5.0",
109
107
  "eslint-plugin-import": "^2.26.0",
110
108
  jest: "^27.5.1",
111
- nock: "^13.2.4",
112
109
  prettier: "^2.6.2",
113
110
  tsup: "^5.12.5",
114
111
  typedoc: "^0.22.15",
@@ -126,10 +123,13 @@ var require_package = __commonJS({
126
123
 
127
124
  // src/lib/utils/constants.ts
128
125
  import { APIVersion } from "discord-api-types/v10";
126
+ import { getGlobalDispatcher } from "undici";
129
127
  var Package = require_package();
130
128
  var DefaultUserAgent = `DiscordBot (${Package.homepage}, ${Package.version})`;
131
129
  var DefaultRestOptions = {
132
- agent: {},
130
+ get agent() {
131
+ return getGlobalDispatcher();
132
+ },
133
133
  api: "https://discord.com/api",
134
134
  authPrefix: "Bot",
135
135
  cdn: "https://cdn.discordapp.com",
@@ -150,7 +150,6 @@ var RESTEvents = /* @__PURE__ */ ((RESTEvents2) => {
150
150
  RESTEvents2["Debug"] = "restDebug";
151
151
  RESTEvents2["InvalidRequestWarning"] = "invalidRequestWarning";
152
152
  RESTEvents2["RateLimited"] = "rateLimited";
153
- RESTEvents2["Request"] = "request";
154
153
  RESTEvents2["Response"] = "response";
155
154
  RESTEvents2["HashSweep"] = "hashSweep";
156
155
  RESTEvents2["HandlerSweep"] = "handlerSweep";
@@ -294,8 +293,8 @@ __name(DiscordAPIError, "DiscordAPIError");
294
293
 
295
294
  // src/lib/errors/HTTPError.ts
296
295
  var HTTPError = class extends Error {
297
- constructor(message, name, status, method, url, bodyData) {
298
- super(message);
296
+ constructor(name, status, method, url, bodyData) {
297
+ super();
299
298
  this.name = name;
300
299
  this.status = status;
301
300
  this.method = method;
@@ -334,19 +333,31 @@ var RateLimitError = class extends Error {
334
333
  __name(RateLimitError, "RateLimitError");
335
334
 
336
335
  // src/lib/RequestManager.ts
336
+ import { Blob as Blob2 } from "node:buffer";
337
337
  import { EventEmitter } from "node:events";
338
- import { Agent as httpAgent } from "node:http";
339
- import { Agent as httpsAgent } from "node:https";
340
338
  import Collection from "@discordjs/collection";
341
339
  import { DiscordSnowflake } from "@sapphire/snowflake";
342
- import FormData from "form-data";
340
+ import { FormData as FormData2 } from "undici";
343
341
 
344
342
  // src/lib/handlers/SequentialHandler.ts
345
343
  import { setTimeout as sleep } from "node:timers/promises";
346
344
  import { AsyncQueue } from "@sapphire/async-queue";
347
- import fetch from "node-fetch";
345
+ import { request } from "undici";
348
346
 
349
347
  // src/lib/utils/utils.ts
348
+ import { Blob } from "node:buffer";
349
+ import { URLSearchParams } from "node:url";
350
+ import { types } from "node:util";
351
+ import { FormData } from "undici";
352
+ function parseHeader(header) {
353
+ if (header === void 0) {
354
+ return header;
355
+ } else if (typeof header === "string") {
356
+ return header;
357
+ }
358
+ return header.join(";");
359
+ }
360
+ __name(parseHeader, "parseHeader");
350
361
  function serializeSearchParam(value) {
351
362
  switch (typeof value) {
352
363
  case "string":
@@ -382,17 +393,18 @@ function makeURLSearchParams(options) {
382
393
  }
383
394
  __name(makeURLSearchParams, "makeURLSearchParams");
384
395
  function parseResponse(res) {
385
- if (res.headers.get("Content-Type")?.startsWith("application/json")) {
386
- return res.json();
396
+ const header = parseHeader(res.headers["content-type"]);
397
+ if (header?.startsWith("application/json")) {
398
+ return res.body.json();
387
399
  }
388
- return res.arrayBuffer();
400
+ return res.body.arrayBuffer();
389
401
  }
390
402
  __name(parseResponse, "parseResponse");
391
403
  function hasSublimit(bucketRoute, body, method) {
392
404
  if (bucketRoute === "/channels/:id") {
393
405
  if (typeof body !== "object" || body === null)
394
406
  return false;
395
- if (method !== "patch" /* Patch */)
407
+ if (method !== "PATCH" /* Patch */)
396
408
  return false;
397
409
  const castedBody = body;
398
410
  return ["name", "topic"].some((key) => Reflect.has(castedBody, key));
@@ -400,6 +412,43 @@ function hasSublimit(bucketRoute, body, method) {
400
412
  return true;
401
413
  }
402
414
  __name(hasSublimit, "hasSublimit");
415
+ async function resolveBody(body) {
416
+ if (body == null) {
417
+ return null;
418
+ } else if (typeof body === "string") {
419
+ return body;
420
+ } else if (types.isUint8Array(body)) {
421
+ return body;
422
+ } else if (types.isArrayBuffer(body)) {
423
+ return new Uint8Array(body);
424
+ } else if (body instanceof URLSearchParams) {
425
+ return body.toString();
426
+ } else if (body instanceof DataView) {
427
+ return new Uint8Array(body.buffer);
428
+ } else if (body instanceof Blob) {
429
+ return new Uint8Array(await body.arrayBuffer());
430
+ } else if (body instanceof FormData) {
431
+ return body;
432
+ } else if (body[Symbol.iterator]) {
433
+ const chunks = [...body];
434
+ const length = chunks.reduce((a, b) => a + b.length, 0);
435
+ const uint8 = new Uint8Array(length);
436
+ let lengthUsed = 0;
437
+ return chunks.reduce((a, b) => {
438
+ a.set(b, lengthUsed);
439
+ lengthUsed += b.length;
440
+ return a;
441
+ }, uint8);
442
+ } else if (body[Symbol.asyncIterator]) {
443
+ const chunks = [];
444
+ for await (const chunk of body) {
445
+ chunks.push(chunk);
446
+ }
447
+ return Buffer.concat(chunks);
448
+ }
449
+ throw new TypeError(`Unable to resolve body.`);
450
+ }
451
+ __name(resolveBody, "resolveBody");
403
452
 
404
453
  // src/lib/handlers/SequentialHandler.ts
405
454
  var invalidCount = 0;
@@ -526,21 +575,11 @@ var SequentialHandler = class {
526
575
  }
527
576
  this.manager.globalRemaining--;
528
577
  const method = options.method ?? "get";
529
- if (this.manager.listenerCount("request" /* Request */)) {
530
- this.manager.emit("request" /* Request */, {
531
- method,
532
- path: routeId.original,
533
- route: routeId.bucketRoute,
534
- options,
535
- data: requestData,
536
- retries
537
- });
538
- }
539
578
  const controller = new AbortController();
540
579
  const timeout = setTimeout(() => controller.abort(), this.manager.options.timeout).unref();
541
580
  let res;
542
581
  try {
543
- res = await fetch(url, { ...options, signal: controller.signal });
582
+ res = await request(url, { ...options, signal: controller.signal });
544
583
  } catch (error) {
545
584
  if (error instanceof Error && error.name === "AbortError" && retries !== this.manager.options.retries) {
546
585
  return await this.runRequest(routeId, url, options, requestData, ++retries);
@@ -557,14 +596,15 @@ var SequentialHandler = class {
557
596
  options,
558
597
  data: requestData,
559
598
  retries
560
- }, res.clone());
599
+ }, { ...res });
561
600
  }
601
+ const status = res.statusCode;
562
602
  let retryAfter = 0;
563
- const limit = res.headers.get("X-RateLimit-Limit");
564
- const remaining = res.headers.get("X-RateLimit-Remaining");
565
- const reset = res.headers.get("X-RateLimit-Reset-After");
566
- const hash = res.headers.get("X-RateLimit-Bucket");
567
- const retry = res.headers.get("Retry-After");
603
+ const limit = parseHeader(res.headers["x-ratelimit-limit"]);
604
+ const remaining = parseHeader(res.headers["x-ratelimit-remaining"]);
605
+ const reset = parseHeader(res.headers["x-ratelimit-reset-after"]);
606
+ const hash = parseHeader(res.headers["x-ratelimit-bucket"]);
607
+ const retry = parseHeader(res.headers["retry-after"]);
568
608
  this.limit = limit ? Number(limit) : Infinity;
569
609
  this.remaining = remaining ? Number(remaining) : 1;
570
610
  this.reset = reset ? Number(reset) * 1e3 + Date.now() + this.manager.options.offset : Date.now();
@@ -581,14 +621,14 @@ var SequentialHandler = class {
581
621
  }
582
622
  let sublimitTimeout = null;
583
623
  if (retryAfter > 0) {
584
- if (res.headers.get("X-RateLimit-Global")) {
624
+ if (res.headers["x-ratelimit-global"] !== void 0) {
585
625
  this.manager.globalRemaining = 0;
586
626
  this.manager.globalReset = Date.now() + retryAfter;
587
627
  } else if (!this.localLimited) {
588
628
  sublimitTimeout = retryAfter;
589
629
  }
590
630
  }
591
- if (res.status === 401 || res.status === 403 || res.status === 429) {
631
+ if (status === 401 || status === 403 || status === 429) {
592
632
  if (!invalidCountResetTime || invalidCountResetTime < Date.now()) {
593
633
  invalidCountResetTime = Date.now() + 1e3 * 60 * 10;
594
634
  invalidCount = 0;
@@ -602,9 +642,9 @@ var SequentialHandler = class {
602
642
  });
603
643
  }
604
644
  }
605
- if (res.ok) {
645
+ if (status === 200) {
606
646
  return parseResponse(res);
607
- } else if (res.status === 429) {
647
+ } else if (status === 429) {
608
648
  const isGlobal = this.globalLimited;
609
649
  let limit2;
610
650
  let timeout2;
@@ -656,18 +696,18 @@ var SequentialHandler = class {
656
696
  }
657
697
  }
658
698
  return this.runRequest(routeId, url, options, requestData, retries);
659
- } else if (res.status >= 500 && res.status < 600) {
699
+ } else if (status >= 500 && status < 600) {
660
700
  if (retries !== this.manager.options.retries) {
661
701
  return this.runRequest(routeId, url, options, requestData, ++retries);
662
702
  }
663
- throw new HTTPError(res.statusText, res.constructor.name, res.status, method, url, requestData);
703
+ throw new HTTPError(res.constructor.name, status, method, url, requestData);
664
704
  } else {
665
- if (res.status >= 400 && res.status < 500) {
666
- if (res.status === 401 && requestData.auth) {
705
+ if (status >= 400 && status < 500) {
706
+ if (status === 401 && requestData.auth) {
667
707
  this.manager.setToken(null);
668
708
  }
669
709
  const data = await parseResponse(res);
670
- throw new DiscordAPIError(data, "code" in data ? data.code : data.error, res.status, method, url, requestData);
710
+ throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
671
711
  }
672
712
  return null;
673
713
  }
@@ -681,17 +721,18 @@ _shiftSublimit = new WeakMap();
681
721
 
682
722
  // src/lib/RequestManager.ts
683
723
  var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => {
684
- RequestMethod2["Delete"] = "delete";
685
- RequestMethod2["Get"] = "get";
686
- RequestMethod2["Patch"] = "patch";
687
- RequestMethod2["Post"] = "post";
688
- RequestMethod2["Put"] = "put";
724
+ RequestMethod2["Delete"] = "DELETE";
725
+ RequestMethod2["Get"] = "GET";
726
+ RequestMethod2["Patch"] = "PATCH";
727
+ RequestMethod2["Post"] = "POST";
728
+ RequestMethod2["Put"] = "PUT";
689
729
  return RequestMethod2;
690
730
  })(RequestMethod || {});
691
731
  var _token;
692
732
  var _RequestManager = class extends EventEmitter {
693
733
  constructor(options) {
694
734
  super();
735
+ __publicField(this, "agent", null);
695
736
  __publicField(this, "globalRemaining");
696
737
  __publicField(this, "globalDelay", null);
697
738
  __publicField(this, "globalReset", -1);
@@ -700,11 +741,11 @@ var _RequestManager = class extends EventEmitter {
700
741
  __privateAdd(this, _token, null);
701
742
  __publicField(this, "hashTimer");
702
743
  __publicField(this, "handlerTimer");
703
- __publicField(this, "agent", null);
704
744
  __publicField(this, "options");
705
745
  this.options = { ...DefaultRestOptions, ...options };
706
746
  this.options.offset = Math.max(0, this.options.offset);
707
747
  this.globalRemaining = this.options.globalRequestsPerSecond;
748
+ this.agent = options.agent ?? null;
708
749
  this.setupSweepers();
709
750
  }
710
751
  setupSweepers() {
@@ -747,22 +788,26 @@ var _RequestManager = class extends EventEmitter {
747
788
  }, this.options.handlerSweepInterval).unref();
748
789
  }
749
790
  }
791
+ setAgent(agent) {
792
+ this.agent = agent;
793
+ return this;
794
+ }
750
795
  setToken(token) {
751
796
  __privateSet(this, _token, token);
752
797
  return this;
753
798
  }
754
- async queueRequest(request) {
755
- const routeId = _RequestManager.generateRouteData(request.fullRoute, request.method);
756
- const hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {
757
- value: `Global(${request.method}:${routeId.bucketRoute})`,
799
+ async queueRequest(request2) {
800
+ const routeId = _RequestManager.generateRouteData(request2.fullRoute, request2.method);
801
+ const hash = this.hashes.get(`${request2.method}:${routeId.bucketRoute}`) ?? {
802
+ value: `Global(${request2.method}:${routeId.bucketRoute})`,
758
803
  lastAccess: -1
759
804
  };
760
805
  const handler = this.handlers.get(`${hash.value}:${routeId.majorParameter}`) ?? this.createHandler(hash.value, routeId.majorParameter);
761
- const { url, fetchOptions } = this.resolveRequest(request);
806
+ const { url, fetchOptions } = await this.resolveRequest(request2);
762
807
  return handler.queueRequest(routeId, url, fetchOptions, {
763
- body: request.body,
764
- files: request.files,
765
- auth: request.auth !== false
808
+ body: request2.body,
809
+ files: request2.files,
810
+ auth: request2.auth !== false
766
811
  });
767
812
  }
768
813
  createHandler(hash, majorParameter) {
@@ -770,12 +815,11 @@ var _RequestManager = class extends EventEmitter {
770
815
  this.handlers.set(queue.id, queue);
771
816
  return queue;
772
817
  }
773
- resolveRequest(request) {
818
+ async resolveRequest(request2) {
774
819
  const { options } = this;
775
- this.agent ??= options.api.startsWith("https") ? new httpsAgent({ ...options.agent, keepAlive: true }) : new httpAgent({ ...options.agent, keepAlive: true });
776
820
  let query = "";
777
- if (request.query) {
778
- const resolvedQuery = request.query.toString();
821
+ if (request2.query) {
822
+ const resolvedQuery = request2.query.toString();
779
823
  if (resolvedQuery !== "") {
780
824
  query = `?${resolvedQuery}`;
781
825
  }
@@ -784,48 +828,55 @@ var _RequestManager = class extends EventEmitter {
784
828
  ...this.options.headers,
785
829
  "User-Agent": `${DefaultUserAgent} ${options.userAgentAppendix}`.trim()
786
830
  };
787
- if (request.auth !== false) {
831
+ if (request2.auth !== false) {
788
832
  if (!__privateGet(this, _token)) {
789
833
  throw new Error("Expected token to be set for this request, but none was present");
790
834
  }
791
- headers.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${__privateGet(this, _token)}`;
835
+ headers.Authorization = `${request2.authPrefix ?? this.options.authPrefix} ${__privateGet(this, _token)}`;
792
836
  }
793
- if (request.reason?.length) {
794
- headers["X-Audit-Log-Reason"] = encodeURIComponent(request.reason);
837
+ if (request2.reason?.length) {
838
+ headers["X-Audit-Log-Reason"] = encodeURIComponent(request2.reason);
795
839
  }
796
- const url = `${options.api}${request.versioned === false ? "" : `/v${options.version}`}${request.fullRoute}${query}`;
840
+ const url = `${options.api}${request2.versioned === false ? "" : `/v${options.version}`}${request2.fullRoute}${query}`;
797
841
  let finalBody;
798
842
  let additionalHeaders = {};
799
- if (request.files?.length) {
800
- const formData = new FormData();
801
- for (const [index, file] of request.files.entries()) {
802
- formData.append(file.key ?? `files[${index}]`, file.data, file.name);
843
+ if (request2.files?.length) {
844
+ const formData = new FormData2();
845
+ for (const [index, file] of request2.files.entries()) {
846
+ const fileKey = file.key ?? `files[${index}]`;
847
+ if (Buffer.isBuffer(file.data) || typeof file.data === "string") {
848
+ formData.append(fileKey, new Blob2([file.data]), file.name);
849
+ } else {
850
+ formData.append(fileKey, new Blob2([`${file.data}`]), file.name);
851
+ }
803
852
  }
804
- if (request.body != null) {
805
- if (request.appendToFormData) {
806
- for (const [key, value] of Object.entries(request.body)) {
853
+ if (request2.body != null) {
854
+ if (request2.appendToFormData) {
855
+ for (const [key, value] of Object.entries(request2.body)) {
807
856
  formData.append(key, value);
808
857
  }
809
858
  } else {
810
- formData.append("payload_json", JSON.stringify(request.body));
859
+ formData.append("payload_json", JSON.stringify(request2.body));
811
860
  }
812
861
  }
813
862
  finalBody = formData;
814
- additionalHeaders = formData.getHeaders();
815
- } else if (request.body != null) {
816
- if (request.passThroughBody) {
817
- finalBody = request.body;
863
+ } else if (request2.body != null) {
864
+ if (request2.passThroughBody) {
865
+ finalBody = request2.body;
818
866
  } else {
819
- finalBody = JSON.stringify(request.body);
867
+ finalBody = JSON.stringify(request2.body);
820
868
  additionalHeaders = { "Content-Type": "application/json" };
821
869
  }
822
870
  }
871
+ finalBody = await resolveBody(finalBody);
823
872
  const fetchOptions = {
824
- agent: this.agent,
825
- body: finalBody,
826
- headers: { ...request.headers ?? {}, ...additionalHeaders, ...headers },
827
- method: request.method
873
+ headers: { ...request2.headers ?? {}, ...additionalHeaders, ...headers },
874
+ method: request2.method.toUpperCase()
828
875
  };
876
+ if (finalBody !== void 0) {
877
+ fetchOptions.body = finalBody;
878
+ }
879
+ fetchOptions.dispatcher = request2.dispatcher ?? this.agent ?? void 0;
829
880
  return { url, fetchOptions };
830
881
  }
831
882
  clearHashSweeper() {
@@ -839,7 +890,7 @@ var _RequestManager = class extends EventEmitter {
839
890
  const majorId = majorIdMatch?.[1] ?? "global";
840
891
  const baseRoute = endpoint.replace(/\d{16,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction");
841
892
  let exceptions = "";
842
- if (method === "delete" /* Delete */ && baseRoute === "/channels/:id/messages/:id") {
893
+ if (method === "DELETE" /* Delete */ && baseRoute === "/channels/:id/messages/:id") {
843
894
  const id = /\d{16,19}$/.exec(endpoint)[0];
844
895
  const timestamp = DiscordSnowflake.timestampFrom(id);
845
896
  if (Date.now() - timestamp > 1e3 * 60 * 60 * 24 * 14) {
@@ -867,32 +918,39 @@ var REST = class extends EventEmitter2 {
867
918
  this.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn);
868
919
  this.requestManager = new RequestManager(options).on("restDebug" /* Debug */, this.emit.bind(this, "restDebug" /* Debug */)).on("rateLimited" /* RateLimited */, this.emit.bind(this, "rateLimited" /* RateLimited */)).on("invalidRequestWarning" /* InvalidRequestWarning */, this.emit.bind(this, "invalidRequestWarning" /* InvalidRequestWarning */)).on("hashSweep" /* HashSweep */, this.emit.bind(this, "hashSweep" /* HashSweep */));
869
920
  this.on("newListener", (name, listener) => {
870
- if (name === "request" /* Request */ || name === "response" /* Response */)
921
+ if (name === "response" /* Response */)
871
922
  this.requestManager.on(name, listener);
872
923
  });
873
924
  this.on("removeListener", (name, listener) => {
874
- if (name === "request" /* Request */ || name === "response" /* Response */)
925
+ if (name === "response" /* Response */)
875
926
  this.requestManager.off(name, listener);
876
927
  });
877
928
  }
929
+ getAgent() {
930
+ return this.requestManager.agent;
931
+ }
932
+ setAgent(agent) {
933
+ this.requestManager.setAgent(agent);
934
+ return this;
935
+ }
878
936
  setToken(token) {
879
937
  this.requestManager.setToken(token);
880
938
  return this;
881
939
  }
882
940
  get(fullRoute, options = {}) {
883
- return this.request({ ...options, fullRoute, method: "get" /* Get */ });
941
+ return this.request({ ...options, fullRoute, method: "GET" /* Get */ });
884
942
  }
885
943
  delete(fullRoute, options = {}) {
886
- return this.request({ ...options, fullRoute, method: "delete" /* Delete */ });
944
+ return this.request({ ...options, fullRoute, method: "DELETE" /* Delete */ });
887
945
  }
888
946
  post(fullRoute, options = {}) {
889
- return this.request({ ...options, fullRoute, method: "post" /* Post */ });
947
+ return this.request({ ...options, fullRoute, method: "POST" /* Post */ });
890
948
  }
891
949
  put(fullRoute, options = {}) {
892
- return this.request({ ...options, fullRoute, method: "put" /* Put */ });
950
+ return this.request({ ...options, fullRoute, method: "PUT" /* Put */ });
893
951
  }
894
952
  patch(fullRoute, options = {}) {
895
- return this.request({ ...options, fullRoute, method: "patch" /* Patch */ });
953
+ return this.request({ ...options, fullRoute, method: "PATCH" /* Patch */ });
896
954
  }
897
955
  request(options) {
898
956
  return this.requestManager.queueRequest(options);