minurl.shared.js 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. /**
  2. * Checks if a value has the shape of a WHATWG URL object.
  3. *
  4. * Using a symbol or instanceof would not be able to recognize URL objects
  5. * coming from other implementations (e.g. in Electron), so instead we are
  6. * checking some well known properties for a lack of a better test.
  7. *
  8. * We use `href` and `protocol` as they are the only properties that are
  9. * easy to retrieve and calculate due to the lazy nature of the getters.
  10. *
  11. * We check for auth attribute to distinguish legacy url instance with
  12. * WHATWG URL instance.
  13. *
  14. * @param {unknown} fileUrlOrPath
  15. * File path or URL.
  16. * @returns {fileUrlOrPath is URL}
  17. * Whether it’s a URL.
  18. */
  19. // From: <https://github.com/nodejs/node/blob/6a3403c/lib/internal/url.js#L720>
  20. export function isUrl(fileUrlOrPath) {
  21. return Boolean(
  22. fileUrlOrPath !== null &&
  23. typeof fileUrlOrPath === 'object' &&
  24. 'href' in fileUrlOrPath &&
  25. fileUrlOrPath.href &&
  26. 'protocol' in fileUrlOrPath &&
  27. fileUrlOrPath.protocol &&
  28. // @ts-expect-error: indexing is fine.
  29. fileUrlOrPath.auth === undefined
  30. )
  31. }