postcss-url-parser.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _util = require("util");
  7. var _postcss = _interopRequireDefault(require("postcss"));
  8. var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
  9. var _utils = require("../utils");
  10. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11. const pluginName = 'postcss-url-parser';
  12. const isUrlFunc = /url/i;
  13. const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
  14. const needParseDecl = /(?:url|(?:-webkit-)?image-set)\(/i;
  15. function getNodeFromUrlFunc(node) {
  16. return node.nodes && node.nodes[0];
  17. }
  18. function shouldHandleRule(rule, decl, result) {
  19. // https://www.w3.org/TR/css-syntax-3/#typedef-url-token
  20. if (rule.url.replace(/^[\s]+|[\s]+$/g, '').length === 0) {
  21. result.warn(`Unable to find uri in '${decl.toString()}'`, {
  22. node: decl
  23. });
  24. return false;
  25. }
  26. if (!(0, _utils.isUrlRequestable)(rule.url)) {
  27. return false;
  28. }
  29. return true;
  30. }
  31. function walkCss(css, result, options, callback) {
  32. const accumulator = [];
  33. css.walkDecls(decl => {
  34. if (!needParseDecl.test(decl.value)) {
  35. return;
  36. }
  37. const parsed = (0, _postcssValueParser.default)(decl.value);
  38. parsed.walk(node => {
  39. if (node.type !== 'function') {
  40. return;
  41. }
  42. if (isUrlFunc.test(node.value)) {
  43. const {
  44. nodes
  45. } = node;
  46. const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
  47. const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
  48. const rule = {
  49. node: getNodeFromUrlFunc(node),
  50. url,
  51. needQuotes: false,
  52. isStringValue
  53. };
  54. if (shouldHandleRule(rule, decl, result)) {
  55. accumulator.push({
  56. decl,
  57. rule,
  58. parsed
  59. });
  60. } // Do not traverse inside `url`
  61. // eslint-disable-next-line consistent-return
  62. return false;
  63. } else if (isImageSetFunc.test(node.value)) {
  64. for (const nNode of node.nodes) {
  65. const {
  66. type,
  67. value
  68. } = nNode;
  69. if (type === 'function' && isUrlFunc.test(value)) {
  70. const {
  71. nodes
  72. } = nNode;
  73. const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
  74. const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
  75. const rule = {
  76. node: getNodeFromUrlFunc(nNode),
  77. url,
  78. needQuotes: false,
  79. isStringValue
  80. };
  81. if (shouldHandleRule(rule, decl, result)) {
  82. accumulator.push({
  83. decl,
  84. rule,
  85. parsed
  86. });
  87. }
  88. } else if (type === 'string') {
  89. const rule = {
  90. node: nNode,
  91. url: value,
  92. needQuotes: true,
  93. isStringValue: true
  94. };
  95. if (shouldHandleRule(rule, decl, result)) {
  96. accumulator.push({
  97. decl,
  98. rule,
  99. parsed
  100. });
  101. }
  102. }
  103. } // Do not traverse inside `image-set`
  104. // eslint-disable-next-line consistent-return
  105. return false;
  106. }
  107. });
  108. });
  109. callback(null, accumulator);
  110. }
  111. const asyncWalkCss = (0, _util.promisify)(walkCss);
  112. var _default = _postcss.default.plugin(pluginName, options => async (css, result) => {
  113. const parsedResults = await asyncWalkCss(css, result, options);
  114. if (parsedResults.length === 0) {
  115. return Promise.resolve();
  116. }
  117. const tasks = [];
  118. const imports = new Map();
  119. const replacements = new Map();
  120. let hasUrlImportHelper = false;
  121. for (const parsedResult of parsedResults) {
  122. const {
  123. url,
  124. isStringValue
  125. } = parsedResult.rule;
  126. let normalizedUrl = url;
  127. let prefix = '';
  128. const queryParts = normalizedUrl.split('!');
  129. if (queryParts.length > 1) {
  130. normalizedUrl = queryParts.pop();
  131. prefix = queryParts.join('!');
  132. }
  133. normalizedUrl = (0, _utils.normalizeUrl)(normalizedUrl, isStringValue);
  134. if (!options.filter(normalizedUrl)) {
  135. // eslint-disable-next-line no-continue
  136. continue;
  137. }
  138. if (!hasUrlImportHelper) {
  139. options.imports.push({
  140. importName: '___CSS_LOADER_GET_URL_IMPORT___',
  141. url: options.urlHandler(require.resolve('../runtime/getUrl.js')),
  142. index: -1
  143. });
  144. hasUrlImportHelper = true;
  145. }
  146. const splittedUrl = normalizedUrl.split(/(\?)?#/);
  147. const [pathname, query, hashOrQuery] = splittedUrl;
  148. let hash = query ? '?' : '';
  149. hash += hashOrQuery ? `#${hashOrQuery}` : '';
  150. const request = (0, _utils.requestify)(pathname, options.rootContext);
  151. tasks.push((async () => {
  152. const {
  153. resolver,
  154. context
  155. } = options;
  156. const resolvedUrl = await (0, _utils.resolveRequests)(resolver, context, [...new Set([request, normalizedUrl])]);
  157. return {
  158. url: resolvedUrl,
  159. prefix,
  160. hash,
  161. parsedResult
  162. };
  163. })());
  164. }
  165. const results = await Promise.all(tasks);
  166. for (let index = 0; index <= results.length - 1; index++) {
  167. const {
  168. url,
  169. prefix,
  170. hash,
  171. parsedResult: {
  172. decl,
  173. rule,
  174. parsed
  175. }
  176. } = results[index];
  177. const newUrl = prefix ? `${prefix}!${url}` : url;
  178. const importKey = newUrl;
  179. let importName = imports.get(importKey);
  180. if (!importName) {
  181. importName = `___CSS_LOADER_URL_IMPORT_${imports.size}___`;
  182. imports.set(importKey, importName);
  183. options.imports.push({
  184. importName,
  185. url: options.urlHandler(newUrl),
  186. index
  187. });
  188. }
  189. const {
  190. needQuotes
  191. } = rule;
  192. const replacementKey = JSON.stringify({
  193. newUrl,
  194. hash,
  195. needQuotes
  196. });
  197. let replacementName = replacements.get(replacementKey);
  198. if (!replacementName) {
  199. replacementName = `___CSS_LOADER_URL_REPLACEMENT_${replacements.size}___`;
  200. replacements.set(replacementKey, replacementName);
  201. options.replacements.push({
  202. replacementName,
  203. importName,
  204. hash,
  205. needQuotes
  206. });
  207. } // eslint-disable-next-line no-param-reassign
  208. rule.node.type = 'word'; // eslint-disable-next-line no-param-reassign
  209. rule.node.value = replacementName; // eslint-disable-next-line no-param-reassign
  210. decl.value = parsed.toString();
  211. }
  212. return Promise.resolve();
  213. });
  214. exports.default = _default;