utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. /** @typedef {import("webpack").LoaderContext<any>} LoaderContext */
  7. /**
  8. * @returns {boolean}
  9. */
  10. function trueFn() {
  11. return true;
  12. }
  13. /**
  14. * @param {Compilation} compilation
  15. * @param {string | number} id
  16. * @returns {null | Module}
  17. */
  18. function findModuleById(compilation, id) {
  19. const {
  20. modules,
  21. chunkGraph
  22. } = compilation;
  23. for (const module of modules) {
  24. const moduleId = typeof chunkGraph !== "undefined" ? chunkGraph.getModuleId(module) : module.id;
  25. if (moduleId === id) {
  26. return module;
  27. }
  28. }
  29. return null;
  30. }
  31. /**
  32. * @param {LoaderContext} loaderContext
  33. * @param {string | Buffer} code
  34. * @param {string} filename
  35. * @returns {object}
  36. */
  37. function evalModuleCode(loaderContext, code, filename) {
  38. // @ts-ignore
  39. const module = new NativeModule(filename, loaderContext);
  40. // @ts-ignore
  41. module.paths = NativeModule._nodeModulePaths(loaderContext.context); // eslint-disable-line no-underscore-dangle
  42. module.filename = filename;
  43. // @ts-ignore
  44. module._compile(code, filename); // eslint-disable-line no-underscore-dangle
  45. return module.exports;
  46. }
  47. /**
  48. * @param {string} a
  49. * @param {string} b
  50. * @returns {0 | 1 | -1}
  51. */
  52. function compareIds(a, b) {
  53. if (typeof a !== typeof b) {
  54. return typeof a < typeof b ? -1 : 1;
  55. }
  56. if (a < b) {
  57. return -1;
  58. }
  59. if (a > b) {
  60. return 1;
  61. }
  62. return 0;
  63. }
  64. /**
  65. * @param {Module} a
  66. * @param {Module} b
  67. * @returns {0 | 1 | -1}
  68. */
  69. function compareModulesByIdentifier(a, b) {
  70. return compareIds(a.identifier(), b.identifier());
  71. }
  72. const MODULE_TYPE = "css/mini-extract";
  73. const AUTO_PUBLIC_PATH = "__mini_css_extract_plugin_public_path_auto__";
  74. const ABSOLUTE_PUBLIC_PATH = "webpack:///mini-css-extract-plugin/";
  75. const BASE_URI = "webpack://";
  76. const SINGLE_DOT_PATH_SEGMENT = "__mini_css_extract_plugin_single_dot_path_segment__";
  77. /**
  78. * @param {string} str
  79. * @returns {boolean}
  80. */
  81. function isAbsolutePath(str) {
  82. return path.posix.isAbsolute(str) || path.win32.isAbsolute(str);
  83. }
  84. const RELATIVE_PATH_REGEXP = /^\.\.?[/\\]/;
  85. /**
  86. * @param {string} str
  87. * @returns {boolean}
  88. */
  89. function isRelativePath(str) {
  90. return RELATIVE_PATH_REGEXP.test(str);
  91. }
  92. // TODO simplify for the next major release
  93. /**
  94. * @param {LoaderContext} loaderContext
  95. * @param {string} request
  96. * @returns {string}
  97. */
  98. function stringifyRequest(loaderContext, request) {
  99. if (typeof loaderContext.utils !== "undefined" && typeof loaderContext.utils.contextify === "function") {
  100. return JSON.stringify(loaderContext.utils.contextify(loaderContext.context || loaderContext.rootContext, request));
  101. }
  102. const splitted = request.split("!");
  103. const {
  104. context
  105. } = loaderContext;
  106. return JSON.stringify(splitted.map(part => {
  107. // First, separate singlePath from query, because the query might contain paths again
  108. const splittedPart = part.match(/^(.*?)(\?.*)/);
  109. const query = splittedPart ? splittedPart[2] : "";
  110. let singlePath = splittedPart ? splittedPart[1] : part;
  111. if (isAbsolutePath(singlePath) && context) {
  112. singlePath = path.relative(context, singlePath);
  113. if (isAbsolutePath(singlePath)) {
  114. // If singlePath still matches an absolute path, singlePath was on a different drive than context.
  115. // In this case, we leave the path platform-specific without replacing any separators.
  116. // @see https://github.com/webpack/loader-utils/pull/14
  117. return singlePath + query;
  118. }
  119. if (isRelativePath(singlePath) === false) {
  120. // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
  121. singlePath = `./${singlePath}`;
  122. }
  123. }
  124. return singlePath.replace(/\\/g, "/") + query;
  125. }).join("!"));
  126. }
  127. /**
  128. * @param {string} filename
  129. * @param {string} outputPath
  130. * @param {boolean} enforceRelative
  131. * @returns {string}
  132. */
  133. function getUndoPath(filename, outputPath, enforceRelative) {
  134. let depth = -1;
  135. let append = "";
  136. // eslint-disable-next-line no-param-reassign
  137. outputPath = outputPath.replace(/[\\/]$/, "");
  138. for (const part of filename.split(/[/\\]+/)) {
  139. if (part === "..") {
  140. if (depth > -1) {
  141. // eslint-disable-next-line no-plusplus
  142. depth--;
  143. } else {
  144. const i = outputPath.lastIndexOf("/");
  145. const j = outputPath.lastIndexOf("\\");
  146. const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j);
  147. if (pos < 0) {
  148. return `${outputPath}/`;
  149. }
  150. append = `${outputPath.slice(pos + 1)}/${append}`;
  151. // eslint-disable-next-line no-param-reassign
  152. outputPath = outputPath.slice(0, pos);
  153. }
  154. } else if (part !== ".") {
  155. // eslint-disable-next-line no-plusplus
  156. depth++;
  157. }
  158. }
  159. return depth > 0 ? `${"../".repeat(depth)}${append}` : enforceRelative ? `./${append}` : append;
  160. }
  161. /**
  162. *
  163. * @param {string | function} value
  164. * @returns {string}
  165. */
  166. function stringifyLocal(value) {
  167. return typeof value === "function" ? value.toString() : JSON.stringify(value);
  168. }
  169. /**
  170. * @param {string} str string
  171. * @returns {string} string
  172. */
  173. const toSimpleString = str => {
  174. if (`${+str}` === str) {
  175. return str;
  176. }
  177. return JSON.stringify(str);
  178. };
  179. /**
  180. * @param {string} str string
  181. * @returns {string} quoted meta
  182. */
  183. const quoteMeta = str => str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
  184. /**
  185. * @param {Array<string>} items items
  186. * @returns {string} common prefix
  187. */
  188. const getCommonPrefix = items => {
  189. let prefix = items[0];
  190. for (let i = 1; i < items.length; i++) {
  191. const item = items[i];
  192. for (let p = 0; p < prefix.length; p++) {
  193. if (item[p] !== prefix[p]) {
  194. prefix = prefix.slice(0, p);
  195. break;
  196. }
  197. }
  198. }
  199. return prefix;
  200. };
  201. /**
  202. * @param {Array<string>} items items
  203. * @returns {string} common suffix
  204. */
  205. const getCommonSuffix = items => {
  206. let suffix = items[0];
  207. for (let i = 1; i < items.length; i++) {
  208. const item = items[i];
  209. for (let p = item.length - 1, s = suffix.length - 1; s >= 0; p--, s--) {
  210. if (item[p] !== suffix[s]) {
  211. suffix = suffix.slice(s + 1);
  212. break;
  213. }
  214. }
  215. }
  216. return suffix;
  217. };
  218. /**
  219. * @param {Set<string>} itemsSet items set
  220. * @param {(str: string) => string | false} getKey get key function
  221. * @param {(str: Array<string>) => boolean} condition condition
  222. * @returns {Array<Array<string>>} list of common items
  223. */
  224. const popCommonItems = (itemsSet, getKey, condition) => {
  225. /** @type {Map<string, Array<string>>} */
  226. const map = new Map();
  227. for (const item of itemsSet) {
  228. const key = getKey(item);
  229. if (key) {
  230. let list = map.get(key);
  231. if (list === undefined) {
  232. /** @type {Array<string>} */
  233. list = [];
  234. map.set(key, list);
  235. }
  236. list.push(item);
  237. }
  238. }
  239. /** @type {Array<Array<string>>} */
  240. const result = [];
  241. for (const list of map.values()) {
  242. if (condition(list)) {
  243. for (const item of list) {
  244. itemsSet.delete(item);
  245. }
  246. result.push(list);
  247. }
  248. }
  249. return result;
  250. };
  251. /**
  252. * @param {Array<string>} itemsArr array of items
  253. * @returns {string} regexp
  254. */
  255. const itemsToRegexp = itemsArr => {
  256. if (itemsArr.length === 1) {
  257. return quoteMeta(itemsArr[0]);
  258. }
  259. /** @type {Array<string>} */
  260. const finishedItems = [];
  261. // merge single char items: (a|b|c|d|ef) => ([abcd]|ef)
  262. let countOfSingleCharItems = 0;
  263. for (const item of itemsArr) {
  264. if (item.length === 1) {
  265. // eslint-disable-next-line no-plusplus
  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.concat(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 {function(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|(function(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. trueFn,
  371. findModuleById,
  372. evalModuleCode,
  373. compareModulesByIdentifier,
  374. MODULE_TYPE,
  375. AUTO_PUBLIC_PATH,
  376. ABSOLUTE_PUBLIC_PATH,
  377. BASE_URI,
  378. SINGLE_DOT_PATH_SEGMENT,
  379. stringifyRequest,
  380. stringifyLocal,
  381. getUndoPath,
  382. compileBooleanMatcher
  383. };