utils.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.WEBPACK_IGNORE_COMMENT_REGEXP = void 0;
  6. exports.camelCase = camelCase;
  7. exports.combineRequests = combineRequests;
  8. exports.defaultGetLocalIdent = defaultGetLocalIdent;
  9. exports.getExportCode = getExportCode;
  10. exports.getFilter = getFilter;
  11. exports.getImportCode = getImportCode;
  12. exports.getModuleCode = getModuleCode;
  13. exports.getModulesOptions = getModulesOptions;
  14. exports.getModulesPlugins = getModulesPlugins;
  15. exports.getPreRequester = getPreRequester;
  16. exports.isDataUrl = isDataUrl;
  17. exports.isURLRequestable = isURLRequestable;
  18. exports.normalizeOptions = normalizeOptions;
  19. exports.normalizeSourceMap = normalizeSourceMap;
  20. exports.normalizeUrl = normalizeUrl;
  21. exports.requestify = requestify;
  22. exports.resolveRequests = resolveRequests;
  23. exports.shouldUseIcssPlugin = shouldUseIcssPlugin;
  24. exports.shouldUseImportPlugin = shouldUseImportPlugin;
  25. exports.shouldUseModulesPlugins = shouldUseModulesPlugins;
  26. exports.shouldUseURLPlugin = shouldUseURLPlugin;
  27. exports.sort = sort;
  28. exports.stringifyRequest = stringifyRequest;
  29. var _url = require("url");
  30. var _path = _interopRequireDefault(require("path"));
  31. var _postcssModulesValues = _interopRequireDefault(require("postcss-modules-values"));
  32. var _postcssModulesLocalByDefault = _interopRequireDefault(require("postcss-modules-local-by-default"));
  33. var _postcssModulesExtractImports = _interopRequireDefault(require("postcss-modules-extract-imports"));
  34. var _postcssModulesScope = _interopRequireDefault(require("postcss-modules-scope"));
  35. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36. /*
  37. MIT License http://www.opensource.org/licenses/mit-license.php
  38. Author Tobias Koppers @sokra
  39. */
  40. const WEBPACK_IGNORE_COMMENT_REGEXP = /webpackIgnore:(\s+)?(true|false)/;
  41. exports.WEBPACK_IGNORE_COMMENT_REGEXP = WEBPACK_IGNORE_COMMENT_REGEXP;
  42. const matchRelativePath = /^\.\.?[/\\]/;
  43. function isAbsolutePath(str) {
  44. return _path.default.posix.isAbsolute(str) || _path.default.win32.isAbsolute(str);
  45. }
  46. function isRelativePath(str) {
  47. return matchRelativePath.test(str);
  48. } // TODO simplify for the next major release
  49. function stringifyRequest(loaderContext, request) {
  50. if (typeof loaderContext.utils !== "undefined" && typeof loaderContext.utils.contextify === "function") {
  51. return JSON.stringify(loaderContext.utils.contextify(loaderContext.context || loaderContext.rootContext, request));
  52. }
  53. const splitted = request.split("!");
  54. const {
  55. context
  56. } = loaderContext;
  57. return JSON.stringify(splitted.map(part => {
  58. // First, separate singlePath from query, because the query might contain paths again
  59. const splittedPart = part.match(/^(.*?)(\?.*)/);
  60. const query = splittedPart ? splittedPart[2] : "";
  61. let singlePath = splittedPart ? splittedPart[1] : part;
  62. if (isAbsolutePath(singlePath) && context) {
  63. singlePath = _path.default.relative(context, singlePath);
  64. if (isAbsolutePath(singlePath)) {
  65. // If singlePath still matches an absolute path, singlePath was on a different drive than context.
  66. // In this case, we leave the path platform-specific without replacing any separators.
  67. // @see https://github.com/webpack/loader-utils/pull/14
  68. return singlePath + query;
  69. }
  70. if (isRelativePath(singlePath) === false) {
  71. // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
  72. singlePath = `./${singlePath}`;
  73. }
  74. }
  75. return singlePath.replace(/\\/g, "/") + query;
  76. }).join("!"));
  77. } // We can't use path.win32.isAbsolute because it also matches paths starting with a forward slash
  78. const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
  79. const IS_MODULE_REQUEST = /^[^?]*~/;
  80. function urlToRequest(url, root) {
  81. let request;
  82. if (IS_NATIVE_WIN32_PATH.test(url)) {
  83. // absolute windows path, keep it
  84. request = url;
  85. } else if (typeof root !== "undefined" && /^\//.test(url)) {
  86. request = root + url;
  87. } else if (/^\.\.?\//.test(url)) {
  88. // A relative url stays
  89. request = url;
  90. } else {
  91. // every other url is threaded like a relative url
  92. request = `./${url}`;
  93. } // A `~` makes the url an module
  94. if (IS_MODULE_REQUEST.test(request)) {
  95. request = request.replace(IS_MODULE_REQUEST, "");
  96. }
  97. return request;
  98. } // eslint-disable-next-line no-useless-escape
  99. const regexSingleEscape = /[ -,.\/:-@[\]\^`{-~]/;
  100. const regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  101. const preserveCamelCase = string => {
  102. let result = string;
  103. let isLastCharLower = false;
  104. let isLastCharUpper = false;
  105. let isLastLastCharUpper = false;
  106. for (let i = 0; i < result.length; i++) {
  107. const character = result[i];
  108. if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
  109. result = `${result.slice(0, i)}-${result.slice(i)}`;
  110. isLastCharLower = false;
  111. isLastLastCharUpper = isLastCharUpper;
  112. isLastCharUpper = true;
  113. i += 1;
  114. } else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
  115. result = `${result.slice(0, i - 1)}-${result.slice(i - 1)}`;
  116. isLastLastCharUpper = isLastCharUpper;
  117. isLastCharUpper = false;
  118. isLastCharLower = true;
  119. } else {
  120. isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character;
  121. isLastLastCharUpper = isLastCharUpper;
  122. isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character;
  123. }
  124. }
  125. return result;
  126. };
  127. function camelCase(input) {
  128. let result = input.trim();
  129. if (result.length === 0) {
  130. return "";
  131. }
  132. if (result.length === 1) {
  133. return result.toLowerCase();
  134. }
  135. const hasUpperCase = result !== result.toLowerCase();
  136. if (hasUpperCase) {
  137. result = preserveCamelCase(result);
  138. }
  139. return result.replace(/^[_.\- ]+/, "").toLowerCase().replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toUpperCase()).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toUpperCase());
  140. }
  141. function escape(string) {
  142. let output = "";
  143. let counter = 0;
  144. while (counter < string.length) {
  145. // eslint-disable-next-line no-plusplus
  146. const character = string.charAt(counter++);
  147. let value; // eslint-disable-next-line no-control-regex
  148. if (/[\t\n\f\r\x0B]/.test(character)) {
  149. const codePoint = character.charCodeAt();
  150. value = `\\${codePoint.toString(16).toUpperCase()} `;
  151. } else if (character === "\\" || regexSingleEscape.test(character)) {
  152. value = `\\${character}`;
  153. } else {
  154. value = character;
  155. }
  156. output += value;
  157. }
  158. const firstChar = string.charAt(0);
  159. if (/^-[-\d]/.test(output)) {
  160. output = `\\-${output.slice(1)}`;
  161. } else if (/\d/.test(firstChar)) {
  162. output = `\\3${firstChar} ${output.slice(1)}`;
  163. } // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  164. // since they’re redundant. Note that this is only possible if the escape
  165. // sequence isn’t preceded by an odd number of backslashes.
  166. output = output.replace(regexExcessiveSpaces, ($0, $1, $2) => {
  167. if ($1 && $1.length % 2) {
  168. // It’s not safe to remove the space, so don’t.
  169. return $0;
  170. } // Strip the space.
  171. return ($1 || "") + $2;
  172. });
  173. return output;
  174. }
  175. function gobbleHex(str) {
  176. const lower = str.toLowerCase();
  177. let hex = "";
  178. let spaceTerminated = false; // eslint-disable-next-line no-undefined
  179. for (let i = 0; i < 6 && lower[i] !== undefined; i++) {
  180. const code = lower.charCodeAt(i); // check to see if we are dealing with a valid hex char [a-f|0-9]
  181. const valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  182. spaceTerminated = code === 32;
  183. if (!valid) {
  184. break;
  185. }
  186. hex += lower[i];
  187. }
  188. if (hex.length === 0) {
  189. // eslint-disable-next-line no-undefined
  190. return undefined;
  191. }
  192. const codePoint = parseInt(hex, 16);
  193. const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff; // Add special case for
  194. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  195. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  196. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10ffff) {
  197. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  198. }
  199. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  200. }
  201. const CONTAINS_ESCAPE = /\\/;
  202. function unescape(str) {
  203. const needToProcess = CONTAINS_ESCAPE.test(str);
  204. if (!needToProcess) {
  205. return str;
  206. }
  207. let ret = "";
  208. for (let i = 0; i < str.length; i++) {
  209. if (str[i] === "\\") {
  210. const gobbled = gobbleHex(str.slice(i + 1, i + 7)); // eslint-disable-next-line no-undefined
  211. if (gobbled !== undefined) {
  212. ret += gobbled[0];
  213. i += gobbled[1]; // eslint-disable-next-line no-continue
  214. continue;
  215. } // Retain a pair of \\ if double escaped `\\\\`
  216. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  217. if (str[i + 1] === "\\") {
  218. ret += "\\";
  219. i += 1; // eslint-disable-next-line no-continue
  220. continue;
  221. } // if \\ is at the end of the string retain it
  222. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  223. if (str.length === i + 1) {
  224. ret += str[i];
  225. } // eslint-disable-next-line no-continue
  226. continue;
  227. }
  228. ret += str[i];
  229. }
  230. return ret;
  231. }
  232. function normalizePath(file) {
  233. return _path.default.sep === "\\" ? file.replace(/\\/g, "/") : file;
  234. } // eslint-disable-next-line no-control-regex
  235. const filenameReservedRegex = /[<>:"/\\|?*]/g; // eslint-disable-next-line no-control-regex
  236. const reControlChars = /[\u0000-\u001f\u0080-\u009f]/g;
  237. function escapeLocalIdent(localident) {
  238. // TODO simplify in the next major release
  239. return escape(localident // For `[hash]` placeholder
  240. .replace(/^((-?[0-9])|--)/, "_$1").replace(filenameReservedRegex, "-").replace(reControlChars, "-").replace(/\./g, "-"));
  241. }
  242. function defaultGetLocalIdent(loaderContext, localIdentName, localName, options) {
  243. const {
  244. context,
  245. hashSalt,
  246. hashStrategy
  247. } = options;
  248. const {
  249. resourcePath
  250. } = loaderContext;
  251. const relativeResourcePath = normalizePath(_path.default.relative(context, resourcePath)); // eslint-disable-next-line no-param-reassign
  252. options.content = hashStrategy === "minimal-subset" && /\[local\]/.test(localIdentName) ? relativeResourcePath : `${relativeResourcePath}\x00${localName}`;
  253. let {
  254. hashFunction,
  255. hashDigest,
  256. hashDigestLength
  257. } = options;
  258. const matches = localIdentName.match(/\[(?:([^:\]]+):)?(?:(hash|contenthash|fullhash))(?::([a-z]+\d*))?(?::(\d+))?\]/i);
  259. if (matches) {
  260. const hashName = matches[2] || hashFunction;
  261. hashFunction = matches[1] || hashFunction;
  262. hashDigest = matches[3] || hashDigest;
  263. hashDigestLength = matches[4] || hashDigestLength; // `hash` and `contenthash` are same in `loader-utils` context
  264. // let's keep `hash` for backward compatibility
  265. // eslint-disable-next-line no-param-reassign
  266. localIdentName = localIdentName.replace(/\[(?:([^:\]]+):)?(?:hash|contenthash|fullhash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi, () => hashName === "fullhash" ? "[fullhash]" : "[contenthash]");
  267. }
  268. let localIdentHash = "";
  269. for (let tier = 0; localIdentHash.length < hashDigestLength; tier++) {
  270. // TODO remove this in the next major release
  271. const hash = loaderContext.utils && typeof loaderContext.utils.createHash === "function" ? loaderContext.utils.createHash(hashFunction) : // eslint-disable-next-line no-underscore-dangle
  272. loaderContext._compiler.webpack.util.createHash(hashFunction);
  273. if (hashSalt) {
  274. hash.update(hashSalt);
  275. }
  276. const tierSalt = Buffer.allocUnsafe(4);
  277. tierSalt.writeUInt32LE(tier);
  278. hash.update(tierSalt); // TODO: bug in webpack with unicode characters with strings
  279. hash.update(Buffer.from(options.content, "utf8"));
  280. localIdentHash = (localIdentHash + hash.digest(hashDigest) // Remove all leading digits
  281. ).replace(/^\d+/, "") // Replace all slashes with underscores (same as in base64url)
  282. .replace(/\//g, "_") // Remove everything that is not an alphanumeric or underscore
  283. .replace(/[^A-Za-z0-9_]+/g, "").slice(0, hashDigestLength);
  284. } // TODO need improve on webpack side, we should allow to pass hash/contentHash without chunk property, also `data` for `getPath` should be looks good without chunk property
  285. const ext = _path.default.extname(resourcePath);
  286. const base = _path.default.basename(resourcePath);
  287. const name = base.slice(0, base.length - ext.length);
  288. const data = {
  289. filename: _path.default.relative(context, resourcePath),
  290. contentHash: localIdentHash,
  291. chunk: {
  292. name,
  293. hash: localIdentHash,
  294. contentHash: localIdentHash
  295. }
  296. }; // eslint-disable-next-line no-underscore-dangle
  297. let result = loaderContext._compilation.getPath(localIdentName, data);
  298. if (/\[folder\]/gi.test(result)) {
  299. const dirname = _path.default.dirname(resourcePath);
  300. let directory = normalizePath(_path.default.relative(context, `${dirname + _path.default.sep}_`));
  301. directory = directory.substr(0, directory.length - 1);
  302. let folder = "";
  303. if (directory.length > 1) {
  304. folder = _path.default.basename(directory);
  305. }
  306. result = result.replace(/\[folder\]/gi, () => folder);
  307. }
  308. if (options.regExp) {
  309. const match = resourcePath.match(options.regExp);
  310. if (match) {
  311. match.forEach((matched, i) => {
  312. result = result.replace(new RegExp(`\\[${i}\\]`, "ig"), matched);
  313. });
  314. }
  315. }
  316. return result;
  317. }
  318. function fixedEncodeURIComponent(str) {
  319. return str.replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16)}`);
  320. }
  321. function isDataUrl(url) {
  322. if (/^data:/i.test(url)) {
  323. return true;
  324. }
  325. return false;
  326. }
  327. const NATIVE_WIN32_PATH = /^[A-Z]:[/\\]|^\\\\/i;
  328. function normalizeUrl(url, isStringValue) {
  329. let normalizedUrl = url.replace(/^( |\t\n|\r\n|\r|\f)*/g, "").replace(/( |\t\n|\r\n|\r|\f)*$/g, "");
  330. if (isStringValue && /\\(\n|\r\n|\r|\f)/.test(normalizedUrl)) {
  331. normalizedUrl = normalizedUrl.replace(/\\(\n|\r\n|\r|\f)/g, "");
  332. }
  333. if (NATIVE_WIN32_PATH.test(url)) {
  334. try {
  335. normalizedUrl = decodeURI(normalizedUrl);
  336. } catch (error) {// Ignore
  337. }
  338. return normalizedUrl;
  339. }
  340. normalizedUrl = unescape(normalizedUrl);
  341. if (isDataUrl(url)) {
  342. // Todo fixedEncodeURIComponent is workaround. Webpack resolver shouldn't handle "!" in dataURL
  343. return fixedEncodeURIComponent(normalizedUrl);
  344. }
  345. try {
  346. normalizedUrl = decodeURI(normalizedUrl);
  347. } catch (error) {// Ignore
  348. }
  349. return normalizedUrl;
  350. }
  351. function requestify(url, rootContext, needToResolveURL = true) {
  352. if (needToResolveURL) {
  353. if (/^file:/i.test(url)) {
  354. return (0, _url.fileURLToPath)(url);
  355. }
  356. return url.charAt(0) === "/" ? urlToRequest(url, rootContext) : urlToRequest(url);
  357. }
  358. if (url.charAt(0) === "/" || /^file:/i.test(url)) {
  359. return url;
  360. } // A `~` makes the url an module
  361. if (IS_MODULE_REQUEST.test(url)) {
  362. return url.replace(IS_MODULE_REQUEST, "");
  363. }
  364. return url;
  365. }
  366. function getFilter(filter, resourcePath) {
  367. return (...args) => {
  368. if (typeof filter === "function") {
  369. return filter(...args, resourcePath);
  370. }
  371. return true;
  372. };
  373. }
  374. function getValidLocalName(localName, exportLocalsConvention) {
  375. const result = exportLocalsConvention(localName);
  376. return Array.isArray(result) ? result[0] : result;
  377. }
  378. const IS_MODULES = /\.module(s)?\.\w+$/i;
  379. const IS_ICSS = /\.icss\.\w+$/i;
  380. function getModulesOptions(rawOptions, exportType, loaderContext) {
  381. if (typeof rawOptions.modules === "boolean" && rawOptions.modules === false) {
  382. return false;
  383. }
  384. const resourcePath = // eslint-disable-next-line no-underscore-dangle
  385. loaderContext._module && loaderContext._module.matchResource || loaderContext.resourcePath;
  386. let auto;
  387. let rawModulesOptions;
  388. if (typeof rawOptions.modules === "undefined") {
  389. rawModulesOptions = {};
  390. auto = true;
  391. } else if (typeof rawOptions.modules === "boolean") {
  392. rawModulesOptions = {};
  393. } else if (typeof rawOptions.modules === "string") {
  394. rawModulesOptions = {
  395. mode: rawOptions.modules
  396. };
  397. } else {
  398. rawModulesOptions = rawOptions.modules;
  399. ({
  400. auto
  401. } = rawModulesOptions);
  402. } // eslint-disable-next-line no-underscore-dangle
  403. const {
  404. outputOptions
  405. } = loaderContext._compilation;
  406. const needNamedExport = exportType === "css-style-sheet" || exportType === "string";
  407. const modulesOptions = {
  408. auto,
  409. mode: "local",
  410. exportGlobals: false,
  411. localIdentName: "[hash:base64]",
  412. localIdentContext: loaderContext.rootContext,
  413. localIdentHashSalt: outputOptions.hashSalt,
  414. localIdentHashFunction: outputOptions.hashFunction,
  415. localIdentHashDigest: outputOptions.hashDigest,
  416. localIdentHashDigestLength: outputOptions.hashDigestLength,
  417. // eslint-disable-next-line no-undefined
  418. localIdentRegExp: undefined,
  419. // eslint-disable-next-line no-undefined
  420. getLocalIdent: undefined,
  421. namedExport: needNamedExport || false,
  422. exportLocalsConvention: (rawModulesOptions.namedExport === true || needNamedExport) && typeof rawModulesOptions.exportLocalsConvention === "undefined" ? "camelCaseOnly" : "asIs",
  423. exportOnlyLocals: false,
  424. ...rawModulesOptions
  425. };
  426. let exportLocalsConventionType;
  427. if (typeof modulesOptions.exportLocalsConvention === "string") {
  428. exportLocalsConventionType = modulesOptions.exportLocalsConvention;
  429. modulesOptions.exportLocalsConvention = name => {
  430. switch (exportLocalsConventionType) {
  431. case "camelCase":
  432. {
  433. return [name, camelCase(name)];
  434. }
  435. case "camelCaseOnly":
  436. {
  437. return camelCase(name);
  438. }
  439. case "dashes":
  440. {
  441. return [name, dashesCamelCase(name)];
  442. }
  443. case "dashesOnly":
  444. {
  445. return dashesCamelCase(name);
  446. }
  447. case "asIs":
  448. default:
  449. return name;
  450. }
  451. };
  452. }
  453. if (typeof modulesOptions.auto === "boolean") {
  454. const isModules = modulesOptions.auto && IS_MODULES.test(resourcePath);
  455. let isIcss;
  456. if (!isModules) {
  457. isIcss = IS_ICSS.test(resourcePath);
  458. if (isIcss) {
  459. modulesOptions.mode = "icss";
  460. }
  461. }
  462. if (!isModules && !isIcss) {
  463. return false;
  464. }
  465. } else if (modulesOptions.auto instanceof RegExp) {
  466. const isModules = modulesOptions.auto.test(resourcePath);
  467. if (!isModules) {
  468. return false;
  469. }
  470. } else if (typeof modulesOptions.auto === "function") {
  471. const isModule = modulesOptions.auto(resourcePath);
  472. if (!isModule) {
  473. return false;
  474. }
  475. }
  476. if (typeof modulesOptions.mode === "function") {
  477. modulesOptions.mode = modulesOptions.mode(loaderContext.resourcePath);
  478. }
  479. if (needNamedExport) {
  480. if (rawOptions.esModule === false) {
  481. throw new Error("The 'exportType' option with the 'css-style-sheet' or 'string' value requires the 'esModules' option to be enabled");
  482. }
  483. if (modulesOptions.namedExport === false) {
  484. throw new Error("The 'exportType' option with the 'css-style-sheet' or 'string' value requires the 'modules.namedExport' option to be enabled");
  485. }
  486. }
  487. if (modulesOptions.namedExport === true) {
  488. if (rawOptions.esModule === false) {
  489. throw new Error("The 'modules.namedExport' option requires the 'esModules' option to be enabled");
  490. }
  491. if (typeof exportLocalsConventionType === "string" && exportLocalsConventionType !== "camelCaseOnly" && exportLocalsConventionType !== "dashesOnly") {
  492. throw new Error('The "modules.namedExport" option requires the "modules.exportLocalsConvention" option to be "camelCaseOnly" or "dashesOnly"');
  493. }
  494. }
  495. return modulesOptions;
  496. }
  497. function normalizeOptions(rawOptions, loaderContext) {
  498. const exportType = typeof rawOptions.exportType === "undefined" ? "array" : rawOptions.exportType;
  499. const modulesOptions = getModulesOptions(rawOptions, exportType, loaderContext);
  500. return {
  501. url: typeof rawOptions.url === "undefined" ? true : rawOptions.url,
  502. import: typeof rawOptions.import === "undefined" ? true : rawOptions.import,
  503. modules: modulesOptions,
  504. sourceMap: typeof rawOptions.sourceMap === "boolean" ? rawOptions.sourceMap : loaderContext.sourceMap,
  505. importLoaders: typeof rawOptions.importLoaders === "string" ? parseInt(rawOptions.importLoaders, 10) : rawOptions.importLoaders,
  506. esModule: typeof rawOptions.esModule === "undefined" ? true : rawOptions.esModule,
  507. exportType
  508. };
  509. }
  510. function shouldUseImportPlugin(options) {
  511. if (options.modules.exportOnlyLocals) {
  512. return false;
  513. }
  514. if (typeof options.import === "boolean") {
  515. return options.import;
  516. }
  517. return true;
  518. }
  519. function shouldUseURLPlugin(options) {
  520. if (options.modules.exportOnlyLocals) {
  521. return false;
  522. }
  523. if (typeof options.url === "boolean") {
  524. return options.url;
  525. }
  526. return true;
  527. }
  528. function shouldUseModulesPlugins(options) {
  529. if (typeof options.modules === "boolean" && options.modules === false) {
  530. return false;
  531. }
  532. return options.modules.mode !== "icss";
  533. }
  534. function shouldUseIcssPlugin(options) {
  535. return Boolean(options.modules);
  536. }
  537. function getModulesPlugins(options, loaderContext) {
  538. const {
  539. mode,
  540. getLocalIdent,
  541. localIdentName,
  542. localIdentContext,
  543. localIdentHashSalt,
  544. localIdentHashFunction,
  545. localIdentHashDigest,
  546. localIdentHashDigestLength,
  547. localIdentRegExp,
  548. hashStrategy
  549. } = options.modules;
  550. let plugins = [];
  551. try {
  552. plugins = [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  553. mode
  554. }), (0, _postcssModulesExtractImports.default)(), (0, _postcssModulesScope.default)({
  555. generateScopedName(exportName) {
  556. let localIdent;
  557. if (typeof getLocalIdent !== "undefined") {
  558. localIdent = getLocalIdent(loaderContext, localIdentName, unescape(exportName), {
  559. context: localIdentContext,
  560. hashSalt: localIdentHashSalt,
  561. hashFunction: localIdentHashFunction,
  562. hashDigest: localIdentHashDigest,
  563. hashDigestLength: localIdentHashDigestLength,
  564. hashStrategy,
  565. regExp: localIdentRegExp
  566. });
  567. } // A null/undefined value signals that we should invoke the default
  568. // getLocalIdent method.
  569. if (typeof localIdent === "undefined" || localIdent === null) {
  570. localIdent = defaultGetLocalIdent(loaderContext, localIdentName, unescape(exportName), {
  571. context: localIdentContext,
  572. hashSalt: localIdentHashSalt,
  573. hashFunction: localIdentHashFunction,
  574. hashDigest: localIdentHashDigest,
  575. hashDigestLength: localIdentHashDigestLength,
  576. hashStrategy,
  577. regExp: localIdentRegExp
  578. });
  579. return escapeLocalIdent(localIdent).replace(/\\\[local\\]/gi, exportName);
  580. }
  581. return escapeLocalIdent(localIdent);
  582. },
  583. exportGlobals: options.modules.exportGlobals
  584. })];
  585. } catch (error) {
  586. loaderContext.emitError(error);
  587. }
  588. return plugins;
  589. }
  590. const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
  591. function getURLType(source) {
  592. if (source[0] === "/") {
  593. if (source[1] === "/") {
  594. return "scheme-relative";
  595. }
  596. return "path-absolute";
  597. }
  598. if (IS_NATIVE_WIN32_PATH.test(source)) {
  599. return "path-absolute";
  600. }
  601. return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
  602. }
  603. function normalizeSourceMap(map, resourcePath) {
  604. let newMap = map; // Some loader emit source map as string
  605. // Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
  606. if (typeof newMap === "string") {
  607. newMap = JSON.parse(newMap);
  608. }
  609. delete newMap.file;
  610. const {
  611. sourceRoot
  612. } = newMap;
  613. delete newMap.sourceRoot;
  614. if (newMap.sources) {
  615. // Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
  616. // We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
  617. newMap.sources = newMap.sources.map(source => {
  618. // Non-standard syntax from `postcss`
  619. if (source.indexOf("<") === 0) {
  620. return source;
  621. }
  622. const sourceType = getURLType(source); // Do no touch `scheme-relative` and `absolute` URLs
  623. if (sourceType === "path-relative" || sourceType === "path-absolute") {
  624. const absoluteSource = sourceType === "path-relative" && sourceRoot ? _path.default.resolve(sourceRoot, normalizePath(source)) : normalizePath(source);
  625. return _path.default.relative(_path.default.dirname(resourcePath), absoluteSource);
  626. }
  627. return source;
  628. });
  629. }
  630. return newMap;
  631. }
  632. function getPreRequester({
  633. loaders,
  634. loaderIndex
  635. }) {
  636. const cache = Object.create(null);
  637. return number => {
  638. if (cache[number]) {
  639. return cache[number];
  640. }
  641. if (number === false) {
  642. cache[number] = "";
  643. } else {
  644. const loadersRequest = loaders.slice(loaderIndex, loaderIndex + 1 + (typeof number !== "number" ? 0 : number)).map(x => x.request).join("!");
  645. cache[number] = `-!${loadersRequest}!`;
  646. }
  647. return cache[number];
  648. };
  649. }
  650. function getImportCode(imports, options) {
  651. let code = "";
  652. for (const item of imports) {
  653. const {
  654. importName,
  655. url,
  656. icss,
  657. type
  658. } = item;
  659. if (options.esModule) {
  660. if (icss && options.modules.namedExport) {
  661. code += `import ${options.modules.exportOnlyLocals ? "" : `${importName}, `}* as ${importName}_NAMED___ from ${url};\n`;
  662. } else {
  663. code += type === "url" ? `var ${importName} = new URL(${url}, import.meta.url);\n` : `import ${importName} from ${url};\n`;
  664. }
  665. } else {
  666. code += `var ${importName} = require(${url});\n`;
  667. }
  668. }
  669. return code ? `// Imports\n${code}` : "";
  670. }
  671. function normalizeSourceMapForRuntime(map, loaderContext) {
  672. const resultMap = map ? map.toJSON() : null;
  673. if (resultMap) {
  674. delete resultMap.file;
  675. /* eslint-disable no-underscore-dangle */
  676. if (loaderContext._compilation && loaderContext._compilation.options && loaderContext._compilation.options.devtool && loaderContext._compilation.options.devtool.includes("nosources")) {
  677. /* eslint-enable no-underscore-dangle */
  678. delete resultMap.sourcesContent;
  679. }
  680. resultMap.sourceRoot = "";
  681. resultMap.sources = resultMap.sources.map(source => {
  682. // Non-standard syntax from `postcss`
  683. if (source.indexOf("<") === 0) {
  684. return source;
  685. }
  686. const sourceType = getURLType(source);
  687. if (sourceType !== "path-relative") {
  688. return source;
  689. }
  690. const resourceDirname = _path.default.dirname(loaderContext.resourcePath);
  691. const absoluteSource = _path.default.resolve(resourceDirname, source);
  692. const contextifyPath = normalizePath(_path.default.relative(loaderContext.rootContext, absoluteSource));
  693. return `webpack://./${contextifyPath}`;
  694. });
  695. }
  696. return JSON.stringify(resultMap);
  697. }
  698. function printParams(media, dedupe, supports, layer) {
  699. let result = "";
  700. if (typeof layer !== "undefined") {
  701. result = `, ${JSON.stringify(layer)}`;
  702. }
  703. if (typeof supports !== "undefined") {
  704. result = `, ${JSON.stringify(supports)}${result}`;
  705. } else if (result.length > 0) {
  706. result = `, undefined${result}`;
  707. }
  708. if (dedupe) {
  709. result = `, true${result}`;
  710. } else if (result.length > 0) {
  711. result = `, false${result}`;
  712. }
  713. if (media) {
  714. result = `${JSON.stringify(media)}${result}`;
  715. } else if (result.length > 0) {
  716. result = `""${result}`;
  717. }
  718. return result;
  719. }
  720. function getModuleCode(result, api, replacements, options, loaderContext) {
  721. if (options.modules.exportOnlyLocals === true) {
  722. return "";
  723. }
  724. let sourceMapValue = "";
  725. if (options.sourceMap) {
  726. const sourceMap = result.map;
  727. sourceMapValue = `,${normalizeSourceMapForRuntime(sourceMap, loaderContext)}`;
  728. }
  729. let code = JSON.stringify(result.css);
  730. let beforeCode = `var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(${options.sourceMap ? "___CSS_LOADER_API_SOURCEMAP_IMPORT___" : "___CSS_LOADER_API_NO_SOURCEMAP_IMPORT___"});\n`;
  731. for (const item of api) {
  732. const {
  733. url,
  734. layer,
  735. supports,
  736. media,
  737. dedupe
  738. } = item;
  739. if (url) {
  740. // eslint-disable-next-line no-undefined
  741. const printedParam = printParams(media, undefined, supports, layer);
  742. beforeCode += `___CSS_LOADER_EXPORT___.push([module.id, ${JSON.stringify(`@import url(${url});`)}${printedParam.length > 0 ? `, ${printedParam}` : ""}]);\n`;
  743. } else {
  744. const printedParam = printParams(media, dedupe, supports, layer);
  745. beforeCode += `___CSS_LOADER_EXPORT___.i(${item.importName}${printedParam.length > 0 ? `, ${printedParam}` : ""});\n`;
  746. }
  747. }
  748. for (const item of replacements) {
  749. const {
  750. replacementName,
  751. importName,
  752. localName
  753. } = item;
  754. if (localName) {
  755. code = code.replace(new RegExp(replacementName, "g"), () => options.modules.namedExport ? `" + ${importName}_NAMED___[${JSON.stringify(getValidLocalName(localName, options.modules.exportLocalsConvention))}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
  756. } else {
  757. const {
  758. hash,
  759. needQuotes
  760. } = item;
  761. const getUrlOptions = [].concat(hash ? [`hash: ${JSON.stringify(hash)}`] : []).concat(needQuotes ? "needQuotes: true" : []);
  762. const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(", ")} }` : "";
  763. beforeCode += `var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});\n`;
  764. code = code.replace(new RegExp(replacementName, "g"), () => `" + ${replacementName} + "`);
  765. }
  766. } // Indexes description:
  767. // 0 - module id
  768. // 1 - CSS code
  769. // 2 - media
  770. // 3 - source map
  771. // 4 - supports
  772. // 5 - layer
  773. return `${beforeCode}// Module\n___CSS_LOADER_EXPORT___.push([module.id, ${code}, ""${sourceMapValue}]);\n`;
  774. }
  775. function dashesCamelCase(str) {
  776. return str.replace(/-+(\w)/g, (match, firstLetter) => firstLetter.toUpperCase());
  777. }
  778. function getExportCode(exports, replacements, icssPluginUsed, options) {
  779. let code = "// Exports\n";
  780. if (icssPluginUsed) {
  781. let localsCode = "";
  782. const addExportToLocalsCode = (names, value) => {
  783. const normalizedNames = Array.isArray(names) ? new Set(names) : new Set([names]);
  784. for (const name of normalizedNames) {
  785. if (options.modules.namedExport) {
  786. localsCode += `export var ${name} = ${JSON.stringify(value)};\n`;
  787. } else {
  788. if (localsCode) {
  789. localsCode += `,\n`;
  790. }
  791. localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
  792. }
  793. }
  794. };
  795. for (const {
  796. name,
  797. value
  798. } of exports) {
  799. addExportToLocalsCode(options.modules.exportLocalsConvention(name), value);
  800. }
  801. for (const item of replacements) {
  802. const {
  803. replacementName,
  804. localName
  805. } = item;
  806. if (localName) {
  807. const {
  808. importName
  809. } = item;
  810. localsCode = localsCode.replace(new RegExp(replacementName, "g"), () => {
  811. if (options.modules.namedExport) {
  812. return `" + ${importName}_NAMED___[${JSON.stringify(getValidLocalName(localName, options.modules.exportLocalsConvention))}] + "`;
  813. } else if (options.modules.exportOnlyLocals) {
  814. return `" + ${importName}[${JSON.stringify(localName)}] + "`;
  815. }
  816. return `" + ${importName}.locals[${JSON.stringify(localName)}] + "`;
  817. });
  818. } else {
  819. localsCode = localsCode.replace(new RegExp(replacementName, "g"), () => `" + ${replacementName} + "`);
  820. }
  821. }
  822. if (options.modules.exportOnlyLocals) {
  823. code += options.modules.namedExport ? localsCode : `${options.esModule ? "export default" : "module.exports ="} {\n${localsCode}\n};\n`;
  824. return code;
  825. }
  826. code += options.modules.namedExport ? localsCode : `___CSS_LOADER_EXPORT___.locals = {${localsCode ? `\n${localsCode}\n` : ""}};\n`;
  827. }
  828. const isCSSStyleSheetExport = options.exportType === "css-style-sheet";
  829. if (isCSSStyleSheetExport) {
  830. code += "var ___CSS_LOADER_STYLE_SHEET___ = new CSSStyleSheet();\n";
  831. code += "___CSS_LOADER_STYLE_SHEET___.replaceSync(___CSS_LOADER_EXPORT___.toString());\n";
  832. }
  833. let finalExport;
  834. switch (options.exportType) {
  835. case "string":
  836. finalExport = "___CSS_LOADER_EXPORT___.toString()";
  837. break;
  838. case "css-style-sheet":
  839. finalExport = "___CSS_LOADER_STYLE_SHEET___";
  840. break;
  841. default:
  842. case "array":
  843. finalExport = "___CSS_LOADER_EXPORT___";
  844. break;
  845. }
  846. code += `${options.esModule ? "export default" : "module.exports ="} ${finalExport};\n`;
  847. return code;
  848. }
  849. async function resolveRequests(resolve, context, possibleRequests) {
  850. return resolve(context, possibleRequests[0]).then(result => result).catch(error => {
  851. const [, ...tailPossibleRequests] = possibleRequests;
  852. if (tailPossibleRequests.length === 0) {
  853. throw error;
  854. }
  855. return resolveRequests(resolve, context, tailPossibleRequests);
  856. });
  857. }
  858. function isURLRequestable(url, options = {}) {
  859. // Protocol-relative URLs
  860. if (/^\/\//.test(url)) {
  861. return {
  862. requestable: false,
  863. needResolve: false
  864. };
  865. } // `#` URLs
  866. if (/^#/.test(url)) {
  867. return {
  868. requestable: false,
  869. needResolve: false
  870. };
  871. } // Data URI
  872. if (isDataUrl(url) && options.isSupportDataURL) {
  873. try {
  874. decodeURIComponent(url);
  875. } catch (ignoreError) {
  876. return {
  877. requestable: false,
  878. needResolve: false
  879. };
  880. }
  881. return {
  882. requestable: true,
  883. needResolve: false
  884. };
  885. } // `file:` protocol
  886. if (/^file:/i.test(url)) {
  887. return {
  888. requestable: true,
  889. needResolve: true
  890. };
  891. } // Absolute URLs
  892. if (/^[a-z][a-z0-9+.-]*:/i.test(url) && !NATIVE_WIN32_PATH.test(url)) {
  893. if (options.isSupportAbsoluteURL && /^https?:/i.test(url)) {
  894. return {
  895. requestable: true,
  896. needResolve: false
  897. };
  898. }
  899. return {
  900. requestable: false,
  901. needResolve: false
  902. };
  903. }
  904. return {
  905. requestable: true,
  906. needResolve: true
  907. };
  908. }
  909. function sort(a, b) {
  910. return a.index - b.index;
  911. }
  912. function combineRequests(preRequest, url) {
  913. const idx = url.indexOf("!=!");
  914. return idx !== -1 ? url.slice(0, idx + 3) + preRequest + url.slice(idx + 3) : preRequest + url;
  915. }