browser-geturl.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. import { arrayify } from "@ethersproject/bytes";
  3. import type { GetUrlResponse, Options } from "./types";
  4. export { GetUrlResponse, Options };
  5. export async function getUrl(href: string, options?: Options): Promise<GetUrlResponse> {
  6. if (options == null) { options = { }; }
  7. const request: RequestInit = {
  8. method: (options.method || "GET"),
  9. headers: (options.headers || { }),
  10. body: (options.body || undefined),
  11. };
  12. if (options.skipFetchSetup !== true) {
  13. request.mode = <RequestMode>"cors"; // no-cors, cors, *same-origin
  14. request.cache = <RequestCache>"no-cache"; // *default, no-cache, reload, force-cache, only-if-cached
  15. request.credentials = <RequestCredentials>"same-origin"; // include, *same-origin, omit
  16. request.redirect = <RequestRedirect>"follow"; // manual, *follow, error
  17. request.referrer = "client"; // no-referrer, *client
  18. };
  19. if (options.fetchOptions != null) {
  20. const opts = options.fetchOptions;
  21. if (opts.mode) { request.mode = <RequestMode>(opts.mode); }
  22. if (opts.cache) { request.cache = <RequestCache>(opts.cache); }
  23. if (opts.credentials) { request.credentials = <RequestCredentials>(opts.credentials); }
  24. if (opts.redirect) { request.redirect = <RequestRedirect>(opts.redirect); }
  25. if (opts.referrer) { request.referrer = opts.referrer; }
  26. }
  27. const response = await fetch(href, request);
  28. const body = await response.arrayBuffer();
  29. const headers: { [ name: string ]: string } = { };
  30. if (response.headers.forEach) {
  31. response.headers.forEach((value, key) => {
  32. headers[key.toLowerCase()] = value;
  33. });
  34. } else {
  35. (<() => Array<string>>((<any>(response.headers)).keys))().forEach((key) => {
  36. headers[key.toLowerCase()] = response.headers.get(key);
  37. });
  38. }
  39. return {
  40. headers: headers,
  41. statusCode: response.status,
  42. statusMessage: response.statusText,
  43. body: arrayify(new Uint8Array(body)),
  44. }
  45. }