response.mjs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // src/response.ts
  2. var responseCache = Symbol("responseCache");
  3. var getResponseCache = Symbol("getResponseCache");
  4. var cacheKey = Symbol("cache");
  5. var GlobalResponse = global.Response;
  6. var Response = class _Response {
  7. #body;
  8. #init;
  9. [getResponseCache]() {
  10. delete this[cacheKey];
  11. return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
  12. }
  13. constructor(body, init) {
  14. let headers;
  15. this.#body = body;
  16. if (init instanceof _Response) {
  17. const cachedGlobalResponse = init[responseCache];
  18. if (cachedGlobalResponse) {
  19. this.#init = cachedGlobalResponse;
  20. this[getResponseCache]();
  21. return;
  22. } else {
  23. this.#init = init.#init;
  24. headers = new Headers(init.#init.headers);
  25. }
  26. } else {
  27. this.#init = init;
  28. }
  29. if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
  30. ;
  31. this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
  32. }
  33. }
  34. get headers() {
  35. const cache = this[cacheKey];
  36. if (cache) {
  37. if (!(cache[2] instanceof Headers)) {
  38. cache[2] = new Headers(
  39. cache[2] || { "content-type": "text/plain; charset=UTF-8" }
  40. );
  41. }
  42. return cache[2];
  43. }
  44. return this[getResponseCache]().headers;
  45. }
  46. get status() {
  47. return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
  48. }
  49. get ok() {
  50. const status = this.status;
  51. return status >= 200 && status < 300;
  52. }
  53. };
  54. ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
  55. Object.defineProperty(Response.prototype, k, {
  56. get() {
  57. return this[getResponseCache]()[k];
  58. }
  59. });
  60. });
  61. ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
  62. Object.defineProperty(Response.prototype, k, {
  63. value: function() {
  64. return this[getResponseCache]()[k]();
  65. }
  66. });
  67. });
  68. Object.setPrototypeOf(Response, GlobalResponse);
  69. Object.setPrototypeOf(Response.prototype, GlobalResponse.prototype);
  70. export {
  71. GlobalResponse,
  72. Response,
  73. cacheKey
  74. };