geturl-browser.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { assert, makeError } from "./errors.js";
  2. export function createGetUrl(options) {
  3. async function getUrl(req, _signal) {
  4. assert(_signal == null || !_signal.cancelled, "request cancelled before sending", "CANCELLED");
  5. const protocol = req.url.split(":")[0].toLowerCase();
  6. assert(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", {
  7. info: { protocol },
  8. operation: "request"
  9. });
  10. assert(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", {
  11. operation: "request"
  12. });
  13. let error = null;
  14. const controller = new AbortController();
  15. const timer = setTimeout(() => {
  16. error = makeError("request timeout", "TIMEOUT");
  17. controller.abort();
  18. }, req.timeout);
  19. if (_signal) {
  20. _signal.addListener(() => {
  21. error = makeError("request cancelled", "CANCELLED");
  22. controller.abort();
  23. });
  24. }
  25. const init = {
  26. method: req.method,
  27. headers: new Headers(Array.from(req)),
  28. body: req.body || undefined,
  29. signal: controller.signal
  30. };
  31. let resp;
  32. try {
  33. resp = await fetch(req.url, init);
  34. }
  35. catch (_error) {
  36. clearTimeout(timer);
  37. if (error) {
  38. throw error;
  39. }
  40. throw _error;
  41. }
  42. clearTimeout(timer);
  43. const headers = {};
  44. resp.headers.forEach((value, key) => {
  45. headers[key.toLowerCase()] = value;
  46. });
  47. const respBody = await resp.arrayBuffer();
  48. const body = (respBody == null) ? null : new Uint8Array(respBody);
  49. return {
  50. statusCode: resp.status,
  51. statusMessage: resp.statusText,
  52. headers, body
  53. };
  54. }
  55. return getUrl;
  56. }
  57. // @TODO: remove in v7; provided for backwards compat
  58. const defaultGetUrl = createGetUrl({});
  59. export async function getUrl(req, _signal) {
  60. return defaultGetUrl(req, _signal);
  61. }
  62. //# sourceMappingURL=geturl-browser.js.map