getSchemeFromUrl.js 939 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. const { URL } = require('url');
  3. /**
  4. * Get unit from value node
  5. *
  6. * Returns `null` if the unit is not found.
  7. *
  8. * @param {string} urlString
  9. */
  10. module.exports = function getSchemeFromUrl(urlString) {
  11. let protocol = null;
  12. try {
  13. protocol = new URL(urlString).protocol;
  14. } catch {
  15. return null;
  16. }
  17. if (protocol === null || typeof protocol === 'undefined') {
  18. return null;
  19. }
  20. const scheme = protocol.slice(0, -1); // strip trailing `:`
  21. // The URL spec does not require a scheme to be followed by `//`, but checking
  22. // for it allows this rule to differentiate <scheme>:<hostname> urls from
  23. // <hostname>:<port> urls. `data:` scheme urls are an exception to this rule.
  24. const slashIndex = protocol.length;
  25. const expectedSlashes = urlString.slice(slashIndex, slashIndex + 2);
  26. const isSchemeLessUrl = expectedSlashes !== '//' && scheme !== 'data';
  27. if (isSchemeLessUrl) {
  28. return null;
  29. }
  30. return scheme;
  31. };