utils.js 37 KB

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