utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. "use strict";
  2. const NativeModule = require("module");
  3. const path = require("path");
  4. /** @typedef {import("webpack").Compilation} Compilation */
  5. /** @typedef {import("webpack").Module} Module */
  6. // eslint-disable-next-line jsdoc/reject-any-type
  7. /** @typedef {import("webpack").LoaderContext<any>} LoaderContext */
  8. /**
  9. * @returns {boolean} always returns true
  10. */
  11. function trueFn() {
  12. return true;
  13. }
  14. /**
  15. * @param {Compilation} compilation compilation
  16. * @param {string | number} id module id
  17. * @returns {null | Module} the found module
  18. */
  19. function findModuleById(compilation, id) {
  20. const {
  21. modules,
  22. chunkGraph
  23. } = compilation;
  24. for (const module of modules) {
  25. const moduleId = typeof chunkGraph !== "undefined" ? chunkGraph.getModuleId(module) : module.id;
  26. if (moduleId === id) {
  27. return module;
  28. }
  29. }
  30. return null;
  31. }
  32. /* eslint-disable jsdoc/reject-any-type */
  33. /**
  34. * @param {LoaderContext} loaderContext loader context
  35. * @param {string | Buffer} code code
  36. * @param {string} filename filename
  37. * @returns {Record<string, any>} exports of a module
  38. */
  39. function evalModuleCode(loaderContext, code, filename) {
  40. // @ts-expect-error
  41. const module = new NativeModule(filename, loaderContext);
  42. // @ts-expect-error
  43. module.paths = NativeModule._nodeModulePaths(loaderContext.context);
  44. module.filename = filename;
  45. // @ts-expect-error
  46. module._compile(code, filename);
  47. return module.exports;
  48. }
  49. /* eslint-enable jsdoc/reject-any-type */
  50. /**
  51. * @param {string} a a
  52. * @param {string} b b
  53. * @returns {0 | 1 | -1} result of comparing
  54. */
  55. function compareIds(a, b) {
  56. if (typeof a !== typeof b) {
  57. return typeof a < typeof b ? -1 : 1;
  58. }
  59. if (a < b) {
  60. return -1;
  61. }
  62. if (a > b) {
  63. return 1;
  64. }
  65. return 0;
  66. }
  67. /**
  68. * @param {Module} a a
  69. * @param {Module} b b
  70. * @returns {0 | 1 | -1} result of comparing
  71. */
  72. function compareModulesByIdentifier(a, b) {
  73. return compareIds(a.identifier(), b.identifier());
  74. }
  75. const MODULE_TYPE = "css/mini-extract";
  76. const AUTO_PUBLIC_PATH = "__mini_css_extract_plugin_public_path_auto__";
  77. const ABSOLUTE_PUBLIC_PATH = "webpack:///mini-css-extract-plugin/";
  78. const BASE_URI = "webpack://";
  79. const SINGLE_DOT_PATH_SEGMENT = "__mini_css_extract_plugin_single_dot_path_segment__";
  80. /**
  81. * @param {string} str path
  82. * @returns {boolean} true when path is absolute, otherwise false
  83. */
  84. function isAbsolutePath(str) {
  85. return path.posix.isAbsolute(str) || path.win32.isAbsolute(str);
  86. }
  87. const RELATIVE_PATH_REGEXP = /^\.\.?[/\\]/;
  88. /**
  89. * @param {string} str string
  90. * @returns {boolean} true when path is relative, otherwise false
  91. */
  92. function isRelativePath(str) {
  93. return RELATIVE_PATH_REGEXP.test(str);
  94. }
  95. // TODO simplify for the next major release
  96. /**
  97. * @param {LoaderContext} loaderContext the loader context
  98. * @param {string} request a request
  99. * @returns {string} a stringified request
  100. */
  101. function stringifyRequest(loaderContext, request) {
  102. if (typeof loaderContext.utils !== "undefined" && typeof loaderContext.utils.contextify === "function") {
  103. return JSON.stringify(loaderContext.utils.contextify(loaderContext.context || loaderContext.rootContext, request));
  104. }
  105. const splitted = request.split("!");
  106. const {
  107. context
  108. } = loaderContext;
  109. return JSON.stringify(splitted.map(part => {
  110. // First, separate singlePath from query, because the query might contain paths again
  111. const splittedPart = part.match(/^(.*?)(\?.*)/);
  112. const query = splittedPart ? splittedPart[2] : "";
  113. let singlePath = splittedPart ? splittedPart[1] : part;
  114. if (isAbsolutePath(singlePath) && context) {
  115. singlePath = path.relative(context, singlePath);
  116. if (isAbsolutePath(singlePath)) {
  117. // If singlePath still matches an absolute path, singlePath was on a different drive than context.
  118. // In this case, we leave the path platform-specific without replacing any separators.
  119. // @see https://github.com/webpack/loader-utils/pull/14
  120. return singlePath + query;
  121. }
  122. if (isRelativePath(singlePath) === false) {
  123. // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
  124. singlePath = `./${singlePath}`;
  125. }
  126. }
  127. return singlePath.replace(/\\/g, "/") + query;
  128. }).join("!"));
  129. }
  130. /**
  131. * @param {string} filename filename
  132. * @param {string} outputPath output path
  133. * @param {boolean} enforceRelative true when need to enforce relative path, otherwise false
  134. * @returns {string} undo path
  135. */
  136. function getUndoPath(filename, outputPath, enforceRelative) {
  137. let depth = -1;
  138. let append = "";
  139. outputPath = outputPath.replace(/[\\/]$/, "");
  140. for (const part of filename.split(/[/\\]+/)) {
  141. if (part === "..") {
  142. if (depth > -1) {
  143. depth--;
  144. } else {
  145. const i = outputPath.lastIndexOf("/");
  146. const j = outputPath.lastIndexOf("\\");
  147. const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j);
  148. if (pos < 0) {
  149. return `${outputPath}/`;
  150. }
  151. append = `${outputPath.slice(pos + 1)}/${append}`;
  152. outputPath = outputPath.slice(0, pos);
  153. }
  154. } else if (part !== ".") {
  155. depth++;
  156. }
  157. }
  158. return depth > 0 ? `${"../".repeat(depth)}${append}` : enforceRelative ? `./${append}` : append;
  159. }
  160. /* eslint-disable jsdoc/reject-function-type */
  161. /**
  162. * @param {string | Function} value local
  163. * @returns {string} stringified local
  164. */
  165. function stringifyLocal(value) {
  166. return typeof value === "function" ? value.toString() : JSON.stringify(value);
  167. }
  168. /* eslint-enable jsdoc/reject-function-type */
  169. /**
  170. * @param {string} str string
  171. * @returns {string} string
  172. */
  173. const toSimpleString = str => {
  174. // eslint-disable-next-line no-implicit-coercion
  175. if (`${+str}` === str) {
  176. return str;
  177. }
  178. return JSON.stringify(str);
  179. };
  180. /**
  181. * @param {string} str string
  182. * @returns {string} quoted meta
  183. */
  184. const quoteMeta = str => str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
  185. /**
  186. * @param {string[]} items items
  187. * @returns {string} common prefix
  188. */
  189. const getCommonPrefix = items => {
  190. let [prefix] = items;
  191. for (let i = 1; i < items.length; i++) {
  192. const item = items[i];
  193. for (let prefixIndex = 0; prefixIndex < prefix.length; prefixIndex++) {
  194. if (item[prefixIndex] !== prefix[prefixIndex]) {
  195. prefix = prefix.slice(0, prefixIndex);
  196. break;
  197. }
  198. }
  199. }
  200. return prefix;
  201. };
  202. /**
  203. * @param {string[]} items items
  204. * @returns {string} common suffix
  205. */
  206. const getCommonSuffix = items => {
  207. let [suffix] = items;
  208. for (let i = 1; i < items.length; i++) {
  209. const item = items[i];
  210. for (let itemIndex = item.length - 1, suffixIndex = suffix.length - 1; suffixIndex >= 0; itemIndex--, suffixIndex--) {
  211. if (item[itemIndex] !== suffix[suffixIndex]) {
  212. suffix = suffix.slice(suffixIndex + 1);
  213. break;
  214. }
  215. }
  216. }
  217. return suffix;
  218. };
  219. /**
  220. * @param {Set<string>} itemsSet items set
  221. * @param {(str: string) => string | false} getKey get key function
  222. * @param {(str: string[]) => boolean} condition condition
  223. * @returns {string[][]} list of common items
  224. */
  225. const popCommonItems = (itemsSet, getKey, condition) => {
  226. /** @type {Map<string, string[]>} */
  227. const map = new Map();
  228. for (const item of itemsSet) {
  229. const key = getKey(item);
  230. if (key) {
  231. let list = map.get(key);
  232. if (list === undefined) {
  233. /** @type {string[]} */
  234. list = [];
  235. map.set(key, list);
  236. }
  237. list.push(item);
  238. }
  239. }
  240. /** @type {string[][]} */
  241. const result = [];
  242. for (const list of map.values()) {
  243. if (condition(list)) {
  244. for (const item of list) {
  245. itemsSet.delete(item);
  246. }
  247. result.push(list);
  248. }
  249. }
  250. return result;
  251. };
  252. /**
  253. * @param {string[]} itemsArr array of items
  254. * @returns {string} regexp
  255. */
  256. const itemsToRegexp = itemsArr => {
  257. if (itemsArr.length === 1) {
  258. return quoteMeta(itemsArr[0]);
  259. }
  260. /** @type {string[]} */
  261. const finishedItems = [];
  262. // merge single char items: (a|b|c|d|ef) => ([abcd]|ef)
  263. let countOfSingleCharItems = 0;
  264. for (const item of itemsArr) {
  265. if (item.length === 1) {
  266. countOfSingleCharItems++;
  267. }
  268. }
  269. // special case for only single char items
  270. if (countOfSingleCharItems === itemsArr.length) {
  271. return `[${quoteMeta(itemsArr.sort().join(""))}]`;
  272. }
  273. const items = new Set(itemsArr.sort());
  274. if (countOfSingleCharItems > 2) {
  275. let singleCharItems = "";
  276. for (const item of items) {
  277. if (item.length === 1) {
  278. singleCharItems += item;
  279. items.delete(item);
  280. }
  281. }
  282. finishedItems.push(`[${quoteMeta(singleCharItems)}]`);
  283. }
  284. // special case for 2 items with common prefix/suffix
  285. if (finishedItems.length === 0 && items.size === 2) {
  286. const prefix = getCommonPrefix(itemsArr);
  287. const suffix = getCommonSuffix(itemsArr.map(item => item.slice(prefix.length)));
  288. if (prefix.length > 0 || suffix.length > 0) {
  289. return `${quoteMeta(prefix)}${itemsToRegexp(itemsArr.map(i => i.slice(prefix.length, -suffix.length || undefined)))}${quoteMeta(suffix)}`;
  290. }
  291. }
  292. // special case for 2 items with common suffix
  293. if (finishedItems.length === 0 && items.size === 2) {
  294. /** @type {Iterator<string>} */
  295. const it = items[Symbol.iterator]();
  296. const a = it.next().value;
  297. const b = it.next().value;
  298. if (a.length > 0 && b.length > 0 && a.slice(-1) === b.slice(-1)) {
  299. return `${itemsToRegexp([a.slice(0, -1), b.slice(0, -1)])}${quoteMeta(a.slice(-1))}`;
  300. }
  301. }
  302. // find common prefix: (a1|a2|a3|a4|b5) => (a(1|2|3|4)|b5)
  303. const prefixed = popCommonItems(items, item => item.length >= 1 ? item[0] : false, list => {
  304. if (list.length >= 3) return true;
  305. if (list.length <= 1) return false;
  306. return list[0][1] === list[1][1];
  307. });
  308. for (const prefixedItems of prefixed) {
  309. const prefix = getCommonPrefix(prefixedItems);
  310. finishedItems.push(`${quoteMeta(prefix)}${itemsToRegexp(prefixedItems.map(i => i.slice(prefix.length)))}`);
  311. }
  312. // find common suffix: (a1|b1|c1|d1|e2) => ((a|b|c|d)1|e2)
  313. const suffixed = popCommonItems(items, item => item.length >= 1 ? item.slice(-1) : false, list => {
  314. if (list.length >= 3) return true;
  315. if (list.length <= 1) return false;
  316. return list[0].slice(-2) === list[1].slice(-2);
  317. });
  318. for (const suffixedItems of suffixed) {
  319. const suffix = getCommonSuffix(suffixedItems);
  320. finishedItems.push(`${itemsToRegexp(suffixedItems.map(i => i.slice(0, -suffix.length)))}${quoteMeta(suffix)}`);
  321. }
  322. // TODO further optimize regexp, i. e.
  323. // use ranges: (1|2|3|4|a) => [1-4a]
  324. const conditional = [...finishedItems, ...Array.from(items, quoteMeta)];
  325. if (conditional.length === 1) return conditional[0];
  326. return `(${conditional.join("|")})`;
  327. };
  328. /**
  329. * @param {string[]} positiveItems positive items
  330. * @param {string[]} negativeItems negative items
  331. * @returns {(val: string) => string} a template function to determine the value at runtime
  332. */
  333. const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => {
  334. if (positiveItems.length === 0) {
  335. return () => "false";
  336. }
  337. if (negativeItems.length === 0) {
  338. return () => "true";
  339. }
  340. if (positiveItems.length === 1) {
  341. return value => `${toSimpleString(positiveItems[0])} == ${value}`;
  342. }
  343. if (negativeItems.length === 1) {
  344. return value => `${toSimpleString(negativeItems[0])} != ${value}`;
  345. }
  346. const positiveRegexp = itemsToRegexp(positiveItems);
  347. const negativeRegexp = itemsToRegexp(negativeItems);
  348. if (positiveRegexp.length <= negativeRegexp.length) {
  349. return value => `/^${positiveRegexp}$/.test(${value})`;
  350. }
  351. return value => `!/^${negativeRegexp}$/.test(${value})`;
  352. };
  353. // TODO simplify in the next major release and use it from webpack
  354. /**
  355. * @param {Record<string | number, boolean>} map value map
  356. * @returns {boolean | ((value: string) => string)} true/false, when unconditionally true/false, or a template function to determine the value at runtime
  357. */
  358. const compileBooleanMatcher = map => {
  359. const positiveItems = Object.keys(map).filter(i => map[i]);
  360. const negativeItems = Object.keys(map).filter(i => !map[i]);
  361. if (positiveItems.length === 0) {
  362. return false;
  363. }
  364. if (negativeItems.length === 0) {
  365. return true;
  366. }
  367. return compileBooleanMatcherFromLists(positiveItems, negativeItems);
  368. };
  369. module.exports = {
  370. ABSOLUTE_PUBLIC_PATH,
  371. AUTO_PUBLIC_PATH,
  372. BASE_URI,
  373. MODULE_TYPE,
  374. SINGLE_DOT_PATH_SEGMENT,
  375. compareModulesByIdentifier,
  376. compileBooleanMatcher,
  377. evalModuleCode,
  378. findModuleById,
  379. getUndoPath,
  380. stringifyLocal,
  381. stringifyRequest,
  382. trueFn
  383. };