isStandardSyntaxUrl.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import hasLessInterpolation from './hasLessInterpolation.mjs';
  2. import hasPsvInterpolation from './hasPsvInterpolation.mjs';
  3. import hasScssInterpolation from './hasScssInterpolation.mjs';
  4. import hasTplInterpolation from './hasTplInterpolation.mjs';
  5. const IS_LESS_VARIABLE_IN_URL = /^@@?[\w-]+$/;
  6. const IS_SCSS_VARIABLE_IN_URL = /^[$\s\w+\-,./*'"@#?]+$/;
  7. /**
  8. * Check whether a URL is standard
  9. *
  10. * @param {string} url
  11. * @returns {boolean}
  12. */
  13. export default function isStandardSyntaxUrl(url) {
  14. if (url.length === 0) {
  15. return true;
  16. }
  17. // Sass interpolation works anywhere
  18. if (hasScssInterpolation(url) || hasTplInterpolation(url) || hasPsvInterpolation(url)) {
  19. return false;
  20. }
  21. // Inside `'` and `"` work only LESS interpolation
  22. if ((url.startsWith(`'`) && url.endsWith(`'`)) || (url.startsWith(`"`) && url.endsWith(`"`))) {
  23. if (hasLessInterpolation(url)) {
  24. return false;
  25. }
  26. return true;
  27. }
  28. // Less variable works only at the beginning
  29. // Check is less variable, allow use '@url/some/path'
  30. // https://github.com/less/less.js/blob/3.x/lib/less/parser/parser.js#L547
  31. if (url.startsWith('@') && IS_LESS_VARIABLE_IN_URL.test(url)) {
  32. return false;
  33. }
  34. // In url without quotes scss variable can be everywhere
  35. // But in this case it is allowed to use only specific characters
  36. // Also forbidden "/" at the end of url
  37. if (url.includes('$') && IS_SCSS_VARIABLE_IN_URL.test(url) && !url.endsWith('/')) {
  38. return false;
  39. }
  40. return true;
  41. }