postcss-url-parser.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
  7. var _utils = require("../utils");
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. const isUrlFunc = /url/i;
  10. const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
  11. const needParseDeclaration = /(?:url|(?:-webkit-)?image-set)\(/i;
  12. function getNodeFromUrlFunc(node) {
  13. return node.nodes && node.nodes[0];
  14. }
  15. function getWebpackIgnoreCommentValue(index, nodes, inBetween) {
  16. if (index === 0 && typeof inBetween !== "undefined") {
  17. return inBetween;
  18. }
  19. let prevValueNode = nodes[index - 1];
  20. if (!prevValueNode) {
  21. // eslint-disable-next-line consistent-return
  22. return;
  23. }
  24. if (prevValueNode.type === "space") {
  25. if (!nodes[index - 2]) {
  26. // eslint-disable-next-line consistent-return
  27. return;
  28. }
  29. prevValueNode = nodes[index - 2];
  30. }
  31. if (prevValueNode.type !== "comment") {
  32. // eslint-disable-next-line consistent-return
  33. return;
  34. }
  35. const matched = prevValueNode.value.match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
  36. return matched && matched[2] === "true";
  37. }
  38. function shouldHandleURL(url, declaration, result) {
  39. if (url.length === 0) {
  40. result.warn(`Unable to find uri in '${declaration.toString()}'`, {
  41. node: declaration
  42. });
  43. return false;
  44. }
  45. if (!(0, _utils.isUrlRequestable)(url)) {
  46. return false;
  47. }
  48. return true;
  49. }
  50. function parseDeclaration(declaration, key, result) {
  51. if (!needParseDeclaration.test(declaration[key])) {
  52. return;
  53. }
  54. const parsed = (0, _postcssValueParser.default)(declaration.raws && declaration.raws.value && declaration.raws.value.raw ? declaration.raws.value.raw : declaration[key]);
  55. let inBetween;
  56. if (declaration.raws && declaration.raws.between) {
  57. const lastCommentIndex = declaration.raws.between.lastIndexOf("/*");
  58. const matched = declaration.raws.between.slice(lastCommentIndex).match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
  59. if (matched) {
  60. inBetween = matched[2] === "true";
  61. }
  62. }
  63. let isIgnoreOnDeclaration = false;
  64. const prevNode = declaration.prev();
  65. if (prevNode && prevNode.type === "comment") {
  66. const matched = prevNode.text.match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
  67. if (matched) {
  68. isIgnoreOnDeclaration = matched[2] === "true";
  69. }
  70. }
  71. let needIgnore;
  72. const parsedURLs = [];
  73. parsed.walk((valueNode, index, valueNodes) => {
  74. if (valueNode.type !== "function") {
  75. return;
  76. }
  77. if (isUrlFunc.test(valueNode.value)) {
  78. needIgnore = getWebpackIgnoreCommentValue(index, valueNodes, inBetween);
  79. if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
  80. if (needIgnore) {
  81. // eslint-disable-next-line no-undefined
  82. needIgnore = undefined;
  83. }
  84. return;
  85. }
  86. const {
  87. nodes
  88. } = valueNode;
  89. const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
  90. let url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
  91. url = (0, _utils.normalizeUrl)(url, isStringValue); // Do not traverse inside `url`
  92. if (!shouldHandleURL(url, declaration, result)) {
  93. // eslint-disable-next-line consistent-return
  94. return false;
  95. }
  96. const queryParts = url.split("!");
  97. let prefix;
  98. if (queryParts.length > 1) {
  99. url = queryParts.pop();
  100. prefix = queryParts.join("!");
  101. }
  102. parsedURLs.push({
  103. declaration,
  104. parsed,
  105. node: getNodeFromUrlFunc(valueNode),
  106. prefix,
  107. url,
  108. needQuotes: false
  109. }); // eslint-disable-next-line consistent-return
  110. return false;
  111. } else if (isImageSetFunc.test(valueNode.value)) {
  112. for (const [innerIndex, nNode] of valueNode.nodes.entries()) {
  113. const {
  114. type,
  115. value
  116. } = nNode;
  117. if (type === "function" && isUrlFunc.test(value)) {
  118. needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
  119. if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
  120. if (needIgnore) {
  121. // eslint-disable-next-line no-undefined
  122. needIgnore = undefined;
  123. } // eslint-disable-next-line no-continue
  124. continue;
  125. }
  126. const {
  127. nodes
  128. } = nNode;
  129. const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
  130. let url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
  131. url = (0, _utils.normalizeUrl)(url, isStringValue); // Do not traverse inside `url`
  132. if (!shouldHandleURL(url, declaration, result)) {
  133. // eslint-disable-next-line consistent-return
  134. return false;
  135. }
  136. const queryParts = url.split("!");
  137. let prefix;
  138. if (queryParts.length > 1) {
  139. url = queryParts.pop();
  140. prefix = queryParts.join("!");
  141. }
  142. parsedURLs.push({
  143. declaration,
  144. parsed,
  145. node: getNodeFromUrlFunc(nNode),
  146. prefix,
  147. url,
  148. needQuotes: false
  149. });
  150. } else if (type === "string") {
  151. needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
  152. if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
  153. if (needIgnore) {
  154. // eslint-disable-next-line no-undefined
  155. needIgnore = undefined;
  156. } // eslint-disable-next-line no-continue
  157. continue;
  158. }
  159. let url = (0, _utils.normalizeUrl)(value, true); // Do not traverse inside `url`
  160. if (!shouldHandleURL(url, declaration, result)) {
  161. // eslint-disable-next-line consistent-return
  162. return false;
  163. }
  164. const queryParts = url.split("!");
  165. let prefix;
  166. if (queryParts.length > 1) {
  167. url = queryParts.pop();
  168. prefix = queryParts.join("!");
  169. }
  170. parsedURLs.push({
  171. declaration,
  172. parsed,
  173. node: nNode,
  174. prefix,
  175. url,
  176. needQuotes: true
  177. });
  178. }
  179. } // Do not traverse inside `image-set`
  180. // eslint-disable-next-line consistent-return
  181. return false;
  182. }
  183. }); // eslint-disable-next-line consistent-return
  184. return parsedURLs;
  185. }
  186. const plugin = (options = {}) => {
  187. return {
  188. postcssPlugin: "postcss-url-parser",
  189. prepare(result) {
  190. const parsedDeclarations = [];
  191. return {
  192. Declaration(declaration) {
  193. const parsedURL = parseDeclaration(declaration, "value", result);
  194. if (!parsedURL) {
  195. return;
  196. }
  197. parsedDeclarations.push(...parsedURL);
  198. },
  199. async OnceExit() {
  200. if (parsedDeclarations.length === 0) {
  201. return;
  202. }
  203. const resolvedDeclarations = await Promise.all(parsedDeclarations.map(async parsedDeclaration => {
  204. const {
  205. url
  206. } = parsedDeclaration;
  207. if (options.filter) {
  208. const needKeep = await options.filter(url);
  209. if (!needKeep) {
  210. return;
  211. }
  212. }
  213. const splittedUrl = url.split(/(\?)?#/);
  214. const [pathname, query, hashOrQuery] = splittedUrl;
  215. let hash = query ? "?" : "";
  216. hash += hashOrQuery ? `#${hashOrQuery}` : "";
  217. const request = (0, _utils.requestify)(pathname, options.rootContext);
  218. const {
  219. resolver,
  220. context
  221. } = options;
  222. const resolvedUrl = await (0, _utils.resolveRequests)(resolver, context, [...new Set([request, url])]);
  223. if (!resolvedUrl) {
  224. return;
  225. } // eslint-disable-next-line consistent-return
  226. return { ...parsedDeclaration,
  227. url: resolvedUrl,
  228. hash
  229. };
  230. }));
  231. const urlToNameMap = new Map();
  232. const urlToReplacementMap = new Map();
  233. let hasUrlImportHelper = false;
  234. for (let index = 0; index <= resolvedDeclarations.length - 1; index++) {
  235. const item = resolvedDeclarations[index];
  236. if (!item) {
  237. // eslint-disable-next-line no-continue
  238. continue;
  239. }
  240. if (!hasUrlImportHelper) {
  241. options.imports.push({
  242. importName: "___CSS_LOADER_GET_URL_IMPORT___",
  243. url: options.urlHandler(require.resolve("../runtime/getUrl.js")),
  244. index: -1
  245. });
  246. hasUrlImportHelper = true;
  247. }
  248. const {
  249. url,
  250. prefix
  251. } = item;
  252. const newUrl = prefix ? `${prefix}!${url}` : url;
  253. let importName = urlToNameMap.get(newUrl);
  254. if (!importName) {
  255. importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`;
  256. urlToNameMap.set(newUrl, importName);
  257. options.imports.push({
  258. importName,
  259. url: options.urlHandler(newUrl),
  260. index
  261. });
  262. }
  263. const {
  264. hash,
  265. needQuotes
  266. } = item;
  267. const replacementKey = JSON.stringify({
  268. newUrl,
  269. hash,
  270. needQuotes
  271. });
  272. let replacementName = urlToReplacementMap.get(replacementKey);
  273. if (!replacementName) {
  274. replacementName = `___CSS_LOADER_URL_REPLACEMENT_${urlToReplacementMap.size}___`;
  275. urlToReplacementMap.set(replacementKey, replacementName);
  276. options.replacements.push({
  277. replacementName,
  278. importName,
  279. hash,
  280. needQuotes
  281. });
  282. } // eslint-disable-next-line no-param-reassign
  283. item.node.type = "word"; // eslint-disable-next-line no-param-reassign
  284. item.node.value = replacementName; // eslint-disable-next-line no-param-reassign
  285. item.declaration.value = item.parsed.toString();
  286. }
  287. }
  288. };
  289. }
  290. };
  291. };
  292. plugin.postcss = true;
  293. var _default = plugin;
  294. exports.default = _default;