utils.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.errorFactory = errorFactory;
  6. exports.getCompileFn = getCompileFn;
  7. exports.getModernWebpackImporter = getModernWebpackImporter;
  8. exports.getSassImplementation = getSassImplementation;
  9. exports.getSassOptions = getSassOptions;
  10. exports.getWebpackImporter = getWebpackImporter;
  11. exports.getWebpackResolver = getWebpackResolver;
  12. exports.isSupportedFibers = isSupportedFibers;
  13. exports.normalizeSourceMap = normalizeSourceMap;
  14. var _url = _interopRequireDefault(require("url"));
  15. var _path = _interopRequireDefault(require("path"));
  16. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17. function getDefaultSassImplementation() {
  18. let sassImplPkg = "sass";
  19. try {
  20. require.resolve("sass");
  21. } catch (ignoreError) {
  22. try {
  23. require.resolve("node-sass");
  24. sassImplPkg = "node-sass";
  25. } catch (_ignoreError) {
  26. try {
  27. require.resolve("sass-embedded");
  28. sassImplPkg = "sass-embedded";
  29. } catch (__ignoreError) {
  30. sassImplPkg = "sass";
  31. }
  32. }
  33. }
  34. // eslint-disable-next-line import/no-dynamic-require, global-require
  35. return require(sassImplPkg);
  36. }
  37. /**
  38. * This function is not Webpack-specific and can be used by tools wishing to mimic `sass-loader`'s behaviour, so its signature should not be changed.
  39. */
  40. function getSassImplementation(loaderContext, implementation) {
  41. let resolvedImplementation = implementation;
  42. if (!resolvedImplementation) {
  43. resolvedImplementation = getDefaultSassImplementation();
  44. }
  45. if (typeof resolvedImplementation === "string") {
  46. // eslint-disable-next-line import/no-dynamic-require, global-require
  47. resolvedImplementation = require(resolvedImplementation);
  48. }
  49. const {
  50. info
  51. } = resolvedImplementation;
  52. if (!info) {
  53. throw new Error("Unknown Sass implementation.");
  54. }
  55. const infoParts = info.split("\t");
  56. if (infoParts.length < 2) {
  57. throw new Error(`Unknown Sass implementation "${info}".`);
  58. }
  59. const [implementationName] = infoParts;
  60. if (implementationName === "dart-sass") {
  61. // eslint-disable-next-line consistent-return
  62. return resolvedImplementation;
  63. } else if (implementationName === "node-sass") {
  64. // eslint-disable-next-line consistent-return
  65. return resolvedImplementation;
  66. } else if (implementationName === "sass-embedded") {
  67. // eslint-disable-next-line consistent-return
  68. return resolvedImplementation;
  69. }
  70. throw new Error(`Unknown Sass implementation "${implementationName}".`);
  71. }
  72. /**
  73. * @param {any} loaderContext
  74. * @returns {boolean}
  75. */
  76. function isProductionLikeMode(loaderContext) {
  77. return loaderContext.mode === "production" || !loaderContext.mode;
  78. }
  79. function proxyCustomImporters(importers, loaderContext) {
  80. return [].concat(importers).map(importer => function proxyImporter(...args) {
  81. const self = {
  82. ...this,
  83. webpackLoaderContext: loaderContext
  84. };
  85. return importer.apply(self, args);
  86. });
  87. }
  88. function isSupportedFibers() {
  89. const [nodeVersion] = process.versions.node.split(".");
  90. return Number(nodeVersion) < 16;
  91. }
  92. /**
  93. * Derives the sass options from the loader context and normalizes its values with sane defaults.
  94. *
  95. * @param {object} loaderContext
  96. * @param {object} loaderOptions
  97. * @param {string} content
  98. * @param {object} implementation
  99. * @param {boolean} useSourceMap
  100. * @returns {Object}
  101. */
  102. async function getSassOptions(loaderContext, loaderOptions, content, implementation, useSourceMap) {
  103. const options = loaderOptions.sassOptions ? typeof loaderOptions.sassOptions === "function" ? loaderOptions.sassOptions(loaderContext) || {} : loaderOptions.sassOptions : {};
  104. const sassOptions = {
  105. ...options,
  106. data: loaderOptions.additionalData ? typeof loaderOptions.additionalData === "function" ? await loaderOptions.additionalData(content, loaderContext) : `${loaderOptions.additionalData}\n${content}` : content
  107. };
  108. if (!sassOptions.logger) {
  109. const needEmitWarning = loaderOptions.warnRuleAsWarning !== false;
  110. const logger = loaderContext.getLogger("sass-loader");
  111. const formatSpan = span => `Warning on line ${span.start.line}, column ${span.start.column} of ${span.url || "-"}:${span.start.line}:${span.start.column}:\n`;
  112. const formatDebugSpan = span => `[debug:${span.start.line}:${span.start.column}] `;
  113. sassOptions.logger = {
  114. debug(message, loggerOptions) {
  115. let builtMessage = "";
  116. if (loggerOptions.span) {
  117. builtMessage = formatDebugSpan(loggerOptions.span);
  118. }
  119. builtMessage += message;
  120. logger.debug(builtMessage);
  121. },
  122. warn(message, loggerOptions) {
  123. let builtMessage = "";
  124. if (loggerOptions.deprecation) {
  125. builtMessage += "Deprecation ";
  126. }
  127. if (loggerOptions.span) {
  128. builtMessage += formatSpan(loggerOptions.span);
  129. }
  130. builtMessage += message;
  131. if (loggerOptions.span && loggerOptions.span.context) {
  132. builtMessage += `\n\n${loggerOptions.span.start.line} | ${loggerOptions.span.context}`;
  133. }
  134. if (loggerOptions.stack && loggerOptions.stack !== "null") {
  135. builtMessage += `\n\n${loggerOptions.stack}`;
  136. }
  137. if (needEmitWarning) {
  138. const warning = new Error(builtMessage);
  139. warning.name = "SassWarning";
  140. warning.stack = null;
  141. loaderContext.emitWarning(warning);
  142. } else {
  143. logger.warn(builtMessage);
  144. }
  145. }
  146. };
  147. }
  148. const isModernAPI = loaderOptions.api === "modern";
  149. const {
  150. resourcePath
  151. } = loaderContext;
  152. if (isModernAPI) {
  153. sassOptions.url = _url.default.pathToFileURL(resourcePath);
  154. // opt.outputStyle
  155. if (!sassOptions.style && isProductionLikeMode(loaderContext)) {
  156. sassOptions.style = "compressed";
  157. }
  158. if (useSourceMap) {
  159. sassOptions.sourceMap = true;
  160. }
  161. // If we are compiling sass and indentedSyntax isn't set, automatically set it.
  162. if (typeof sassOptions.syntax === "undefined") {
  163. const ext = _path.default.extname(resourcePath);
  164. if (ext && ext.toLowerCase() === ".scss") {
  165. sassOptions.syntax = "scss";
  166. } else if (ext && ext.toLowerCase() === ".sass") {
  167. sassOptions.syntax = "indented";
  168. } else if (ext && ext.toLowerCase() === ".css") {
  169. sassOptions.syntax = "css";
  170. }
  171. }
  172. sassOptions.importers = sassOptions.importers ? Array.isArray(sassOptions.importers) ? sassOptions.importers.slice() : [sassOptions.importers] : [];
  173. } else {
  174. sassOptions.file = resourcePath;
  175. const isDartSass = implementation.info.includes("dart-sass");
  176. if (isDartSass && isSupportedFibers()) {
  177. const shouldTryToResolveFibers = !sassOptions.fiber && sassOptions.fiber !== false;
  178. if (shouldTryToResolveFibers) {
  179. let fibers;
  180. try {
  181. fibers = require.resolve("fibers");
  182. } catch (_error) {
  183. // Nothing
  184. }
  185. if (fibers) {
  186. // eslint-disable-next-line global-require, import/no-dynamic-require
  187. sassOptions.fiber = require(fibers);
  188. }
  189. } else if (sassOptions.fiber === false) {
  190. // Don't pass the `fiber` option for `sass` (`Dart Sass`)
  191. delete sassOptions.fiber;
  192. }
  193. } else {
  194. // Don't pass the `fiber` option for `node-sass`
  195. delete sassOptions.fiber;
  196. }
  197. // opt.outputStyle
  198. if (!sassOptions.outputStyle && isProductionLikeMode(loaderContext)) {
  199. sassOptions.outputStyle = "compressed";
  200. }
  201. if (useSourceMap) {
  202. // Deliberately overriding the sourceMap option here.
  203. // node-sass won't produce source maps if the data option is used and options.sourceMap is not a string.
  204. // In case it is a string, options.sourceMap should be a path where the source map is written.
  205. // But since we're using the data option, the source map will not actually be written, but
  206. // all paths in sourceMap.sources will be relative to that path.
  207. // Pretty complicated... :(
  208. sassOptions.sourceMap = true;
  209. sassOptions.outFile = _path.default.join(loaderContext.rootContext, "style.css.map");
  210. sassOptions.sourceMapContents = true;
  211. sassOptions.omitSourceMapUrl = true;
  212. sassOptions.sourceMapEmbed = false;
  213. }
  214. const ext = _path.default.extname(resourcePath);
  215. // If we are compiling sass and indentedSyntax isn't set, automatically set it.
  216. if (ext && ext.toLowerCase() === ".sass" && typeof sassOptions.indentedSyntax === "undefined") {
  217. sassOptions.indentedSyntax = true;
  218. } else {
  219. sassOptions.indentedSyntax = Boolean(sassOptions.indentedSyntax);
  220. }
  221. // Allow passing custom importers to `sass`/`node-sass`. Accepts `Function` or an array of `Function`s.
  222. sassOptions.importer = sassOptions.importer ? proxyCustomImporters(Array.isArray(sassOptions.importer) ? sassOptions.importer.slice() : [sassOptions.importer], loaderContext) : [];
  223. // Regression on the `sass-embedded` side
  224. if (loaderOptions.webpackImporter === false && sassOptions.importer.length === 0) {
  225. sassOptions.importer = undefined;
  226. }
  227. sassOptions.includePaths = [].concat(process.cwd()).concat(
  228. // We use `includePaths` in context for resolver, so it should be always absolute
  229. (sassOptions.includePaths ? sassOptions.includePaths.slice() : []).map(includePath => _path.default.isAbsolute(includePath) ? includePath : _path.default.join(process.cwd(), includePath))).concat(process.env.SASS_PATH ? process.env.SASS_PATH.split(process.platform === "win32" ? ";" : ":") : []);
  230. if (typeof sassOptions.charset === "undefined") {
  231. sassOptions.charset = true;
  232. }
  233. }
  234. return sassOptions;
  235. }
  236. const MODULE_REQUEST_REGEX = /^[^?]*~/;
  237. // Examples:
  238. // - ~package
  239. // - ~package/
  240. // - ~@org
  241. // - ~@org/
  242. // - ~@org/package
  243. // - ~@org/package/
  244. const IS_MODULE_IMPORT = /^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;
  245. /**
  246. * When `sass`/`node-sass` tries to resolve an import, it uses a special algorithm.
  247. * Since the `sass-loader` uses webpack to resolve the modules, we need to simulate that algorithm.
  248. * This function returns an array of import paths to try.
  249. * The last entry in the array is always the original url to enable straight-forward webpack.config aliases.
  250. *
  251. * We don't need emulate `dart-sass` "It's not clear which file to import." errors (when "file.ext" and "_file.ext" files are present simultaneously in the same directory).
  252. * This reduces performance and `dart-sass` always do it on own side.
  253. *
  254. * @param {string} url
  255. * @param {boolean} forWebpackResolver
  256. * @param {boolean} fromImport
  257. * @returns {Array<string>}
  258. */
  259. function getPossibleRequests(
  260. // eslint-disable-next-line no-shadow
  261. url, forWebpackResolver = false, fromImport = false) {
  262. let request = url;
  263. // In case there is module request, send this to webpack resolver
  264. if (forWebpackResolver) {
  265. if (MODULE_REQUEST_REGEX.test(url)) {
  266. request = request.replace(MODULE_REQUEST_REGEX, "");
  267. }
  268. if (IS_MODULE_IMPORT.test(url)) {
  269. request = request[request.length - 1] === "/" ? request : `${request}/`;
  270. return [...new Set([request, url])];
  271. }
  272. }
  273. // Keep in mind: ext can also be something like '.datepicker' when the true extension is omitted and the filename contains a dot.
  274. // @see https://github.com/webpack-contrib/sass-loader/issues/167
  275. const extension = _path.default.extname(request).toLowerCase();
  276. // Because @import is also defined in CSS, Sass needs a way of compiling plain CSS @imports without trying to import the files at compile time.
  277. // To accomplish this, and to ensure SCSS is as much of a superset of CSS as possible, Sass will compile any @imports with the following characteristics to plain CSS imports:
  278. // - imports where the URL ends with .css.
  279. // - imports where the URL begins http:// or https://.
  280. // - imports where the URL is written as a url().
  281. // - imports that have media queries.
  282. //
  283. // The `node-sass` package sends `@import` ending on `.css` to importer, it is bug, so we skip resolve
  284. if (extension === ".css") {
  285. return [];
  286. }
  287. const dirname = _path.default.dirname(request);
  288. const normalizedDirname = dirname === "." ? "" : `${dirname}/`;
  289. const basename = _path.default.basename(request);
  290. const basenameWithoutExtension = _path.default.basename(request, extension);
  291. return [...new Set([].concat(fromImport ? [`${normalizedDirname}_${basenameWithoutExtension}.import${extension}`, `${normalizedDirname}${basenameWithoutExtension}.import${extension}`] : []).concat([`${normalizedDirname}_${basename}`, `${normalizedDirname}${basename}`]).concat(forWebpackResolver ? [url] : []))];
  292. }
  293. function promiseResolve(callbackResolve) {
  294. return (context, request) => new Promise((resolve, reject) => {
  295. callbackResolve(context, request, (error, result) => {
  296. if (error) {
  297. reject(error);
  298. } else {
  299. resolve(result);
  300. }
  301. });
  302. });
  303. }
  304. async function startResolving(resolutionMap) {
  305. if (resolutionMap.length === 0) {
  306. return Promise.reject();
  307. }
  308. const [{
  309. possibleRequests
  310. }] = resolutionMap;
  311. if (possibleRequests.length === 0) {
  312. return Promise.reject();
  313. }
  314. const [{
  315. resolve,
  316. context
  317. }] = resolutionMap;
  318. try {
  319. return await resolve(context, possibleRequests[0]);
  320. } catch (_ignoreError) {
  321. const [, ...tailResult] = possibleRequests;
  322. if (tailResult.length === 0) {
  323. const [, ...tailResolutionMap] = resolutionMap;
  324. return startResolving(tailResolutionMap);
  325. }
  326. // eslint-disable-next-line no-param-reassign
  327. resolutionMap[0].possibleRequests = tailResult;
  328. return startResolving(resolutionMap);
  329. }
  330. }
  331. const IS_SPECIAL_MODULE_IMPORT = /^~[^/]+$/;
  332. // `[drive_letter]:\` + `\\[server]\[sharename]\`
  333. const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
  334. /**
  335. * @public
  336. * Create the resolve function used in the custom Sass importer.
  337. *
  338. * Can be used by external tools to mimic how `sass-loader` works, for example
  339. * in a Jest transform. Such usages will want to wrap `resolve.create` from
  340. * [`enhanced-resolve`]{@link https://github.com/webpack/enhanced-resolve} to
  341. * pass as the `resolverFactory` argument.
  342. *
  343. * @param {Function} resolverFactory - A factory function for creating a Webpack
  344. * resolver.
  345. * @param {Object} implementation - The imported Sass implementation, both
  346. * `sass` (Dart Sass) and `node-sass` are supported.
  347. * @param {string[]} [includePaths] - The list of include paths passed to Sass.
  348. *
  349. * @throws If a compatible Sass implementation cannot be found.
  350. */
  351. function getWebpackResolver(resolverFactory, implementation, includePaths = []) {
  352. const isDartSass = implementation && implementation.info.includes("dart-sass");
  353. // We only have one difference with the built-in sass resolution logic and out resolution logic:
  354. // First, we look at the files starting with `_`, then without `_` (i.e. `_name.sass`, `_name.scss`, `_name.css`, `name.sass`, `name.scss`, `name.css`),
  355. // although `sass` look together by extensions (i.e. `_name.sass`/`name.sass`/`_name.scss`/`name.scss`/`_name.css`/`name.css`).
  356. // It shouldn't be a problem because `sass` throw errors:
  357. // - on having `_name.sass` and `name.sass` (extension can be `sass`, `scss` or `css`) in the same directory
  358. // - on having `_name.sass` and `_name.scss` in the same directory
  359. //
  360. // Also `sass` prefer `sass`/`scss` over `css`.
  361. const sassModuleResolve = promiseResolve(resolverFactory({
  362. alias: [],
  363. aliasFields: [],
  364. conditionNames: [],
  365. descriptionFiles: [],
  366. extensions: [".sass", ".scss", ".css"],
  367. exportsFields: [],
  368. mainFields: [],
  369. mainFiles: ["_index", "index"],
  370. modules: [],
  371. restrictions: [/\.((sa|sc|c)ss)$/i],
  372. preferRelative: true
  373. }));
  374. const sassImportResolve = promiseResolve(resolverFactory({
  375. alias: [],
  376. aliasFields: [],
  377. conditionNames: [],
  378. descriptionFiles: [],
  379. extensions: [".sass", ".scss", ".css"],
  380. exportsFields: [],
  381. mainFields: [],
  382. mainFiles: ["_index.import", "_index", "index.import", "index"],
  383. modules: [],
  384. restrictions: [/\.((sa|sc|c)ss)$/i],
  385. preferRelative: true
  386. }));
  387. const webpackModuleResolve = promiseResolve(resolverFactory({
  388. dependencyType: "sass",
  389. conditionNames: ["sass", "style", "..."],
  390. mainFields: ["sass", "style", "main", "..."],
  391. mainFiles: ["_index", "index", "..."],
  392. extensions: [".sass", ".scss", ".css"],
  393. restrictions: [/\.((sa|sc|c)ss)$/i],
  394. preferRelative: true
  395. }));
  396. const webpackImportResolve = promiseResolve(resolverFactory({
  397. dependencyType: "sass",
  398. conditionNames: ["sass", "style", "..."],
  399. mainFields: ["sass", "style", "main", "..."],
  400. mainFiles: ["_index.import", "_index", "index.import", "index", "..."],
  401. extensions: [".sass", ".scss", ".css"],
  402. restrictions: [/\.((sa|sc|c)ss)$/i],
  403. preferRelative: true
  404. }));
  405. return (context, request, fromImport) => {
  406. // See https://github.com/webpack/webpack/issues/12340
  407. // Because `node-sass` calls our importer before `1. Filesystem imports relative to the base file.`
  408. // custom importer may not return `{ file: '/path/to/name.ext' }` and therefore our `context` will be relative
  409. if (!isDartSass && !_path.default.isAbsolute(context)) {
  410. return Promise.reject();
  411. }
  412. const originalRequest = request;
  413. const isFileScheme = originalRequest.slice(0, 5).toLowerCase() === "file:";
  414. if (isFileScheme) {
  415. try {
  416. // eslint-disable-next-line no-param-reassign
  417. request = _url.default.fileURLToPath(originalRequest);
  418. } catch (ignoreError) {
  419. // eslint-disable-next-line no-param-reassign
  420. request = request.slice(7);
  421. }
  422. }
  423. let resolutionMap = [];
  424. const needEmulateSassResolver =
  425. // `sass` doesn't support module import
  426. !IS_SPECIAL_MODULE_IMPORT.test(request) &&
  427. // We need improve absolute paths handling.
  428. // Absolute paths should be resolved:
  429. // - Server-relative URLs - `<context>/path/to/file.ext` (where `<context>` is root context)
  430. // - Absolute path - `/full/path/to/file.ext` or `C:\\full\path\to\file.ext`
  431. !isFileScheme && !originalRequest.startsWith("/") && !IS_NATIVE_WIN32_PATH.test(originalRequest);
  432. if (includePaths.length > 0 && needEmulateSassResolver) {
  433. // The order of import precedence is as follows:
  434. //
  435. // 1. Filesystem imports relative to the base file.
  436. // 2. Custom importer imports.
  437. // 3. Filesystem imports relative to the working directory.
  438. // 4. Filesystem imports relative to an `includePaths` path.
  439. // 5. Filesystem imports relative to a `SASS_PATH` path.
  440. //
  441. // `sass` run custom importers before `3`, `4` and `5` points, we need to emulate this behavior to avoid wrong resolution.
  442. const sassPossibleRequests = getPossibleRequests(request, false, fromImport);
  443. // `node-sass` calls our importer before `1. Filesystem imports relative to the base file.`, so we need emulate this too
  444. if (!isDartSass) {
  445. resolutionMap = resolutionMap.concat({
  446. resolve: fromImport ? sassImportResolve : sassModuleResolve,
  447. context: _path.default.dirname(context),
  448. possibleRequests: sassPossibleRequests
  449. });
  450. }
  451. resolutionMap = resolutionMap.concat(
  452. // eslint-disable-next-line no-shadow
  453. includePaths.map(context => {
  454. return {
  455. resolve: fromImport ? sassImportResolve : sassModuleResolve,
  456. context,
  457. possibleRequests: sassPossibleRequests
  458. };
  459. }));
  460. }
  461. const webpackPossibleRequests = getPossibleRequests(request, true, fromImport);
  462. resolutionMap = resolutionMap.concat({
  463. resolve: fromImport ? webpackImportResolve : webpackModuleResolve,
  464. context: _path.default.dirname(context),
  465. possibleRequests: webpackPossibleRequests
  466. });
  467. return startResolving(resolutionMap);
  468. };
  469. }
  470. const MATCH_CSS = /\.css$/i;
  471. function getModernWebpackImporter() {
  472. return {
  473. async canonicalize() {
  474. return null;
  475. },
  476. load() {
  477. // TODO implement
  478. }
  479. };
  480. }
  481. function getWebpackImporter(loaderContext, implementation, includePaths) {
  482. const resolve = getWebpackResolver(loaderContext.getResolve, implementation, includePaths);
  483. return function importer(originalUrl, prev, done) {
  484. const {
  485. fromImport
  486. } = this;
  487. resolve(prev, originalUrl, fromImport).then(result => {
  488. // Add the result as dependency.
  489. // Although we're also using stats.includedFiles, this might come in handy when an error occurs.
  490. // In this case, we don't get stats.includedFiles from node-sass/sass.
  491. loaderContext.addDependency(_path.default.normalize(result));
  492. // By removing the CSS file extension, we trigger node-sass to include the CSS file instead of just linking it.
  493. done({
  494. file: result.replace(MATCH_CSS, "")
  495. });
  496. })
  497. // Catch all resolving errors, return the original file and pass responsibility back to other custom importers
  498. .catch(() => {
  499. done({
  500. file: originalUrl
  501. });
  502. });
  503. };
  504. }
  505. let nodeSassJobQueue = null;
  506. /**
  507. * Verifies that the implementation and version of Sass is supported by this loader.
  508. *
  509. * @param {Object} implementation
  510. * @param {Object} options
  511. * @returns {Function}
  512. */
  513. function getCompileFn(implementation, options) {
  514. const isNewSass = implementation.info.includes("dart-sass") || implementation.info.includes("sass-embedded");
  515. if (isNewSass) {
  516. if (options.api === "modern") {
  517. return sassOptions => {
  518. const {
  519. data,
  520. ...rest
  521. } = sassOptions;
  522. return implementation.compileStringAsync(data, rest);
  523. };
  524. }
  525. return sassOptions => new Promise((resolve, reject) => {
  526. implementation.render(sassOptions, (error, result) => {
  527. if (error) {
  528. reject(error);
  529. return;
  530. }
  531. resolve(result);
  532. });
  533. });
  534. }
  535. if (options.api === "modern") {
  536. throw new Error("Modern API is not supported for 'node-sass'");
  537. }
  538. // There is an issue with node-sass when async custom importers are used
  539. // See https://github.com/sass/node-sass/issues/857#issuecomment-93594360
  540. // We need to use a job queue to make sure that one thread is always available to the UV lib
  541. if (nodeSassJobQueue === null) {
  542. const threadPoolSize = Number(process.env.UV_THREADPOOL_SIZE || 4);
  543. // Only used for `node-sass`, so let's load it lazily
  544. // eslint-disable-next-line global-require
  545. const async = require("neo-async");
  546. nodeSassJobQueue = async.queue(implementation.render.bind(implementation), threadPoolSize - 1);
  547. }
  548. return sassOptions => new Promise((resolve, reject) => {
  549. nodeSassJobQueue.push.bind(nodeSassJobQueue)(sassOptions, (error, result) => {
  550. if (error) {
  551. reject(error);
  552. return;
  553. }
  554. resolve(result);
  555. });
  556. });
  557. }
  558. const ABSOLUTE_SCHEME = /^[A-Za-z0-9+\-.]+:/;
  559. /**
  560. * @param {string} source
  561. * @returns {"absolute" | "scheme-relative" | "path-absolute" | "path-absolute"}
  562. */
  563. function getURLType(source) {
  564. if (source[0] === "/") {
  565. if (source[1] === "/") {
  566. return "scheme-relative";
  567. }
  568. return "path-absolute";
  569. }
  570. if (IS_NATIVE_WIN32_PATH.test(source)) {
  571. return "path-absolute";
  572. }
  573. return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
  574. }
  575. function normalizeSourceMap(map, rootContext) {
  576. const newMap = map;
  577. // result.map.file is an optional property that provides the output filename.
  578. // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
  579. // eslint-disable-next-line no-param-reassign
  580. if (typeof newMap.file !== "undefined") {
  581. delete newMap.file;
  582. }
  583. // eslint-disable-next-line no-param-reassign
  584. newMap.sourceRoot = "";
  585. // node-sass returns POSIX paths, that's why we need to transform them back to native paths.
  586. // This fixes an error on windows where the source-map module cannot resolve the source maps.
  587. // @see https://github.com/webpack-contrib/sass-loader/issues/366#issuecomment-279460722
  588. // eslint-disable-next-line no-param-reassign
  589. newMap.sources = newMap.sources.map(source => {
  590. const sourceType = getURLType(source);
  591. // Do no touch `scheme-relative`, `path-absolute` and `absolute` types (except `file:`)
  592. if (sourceType === "absolute" && /^file:/i.test(source)) {
  593. return _url.default.fileURLToPath(source);
  594. } else if (sourceType === "path-relative") {
  595. return _path.default.resolve(rootContext, _path.default.normalize(source));
  596. }
  597. return source;
  598. });
  599. return newMap;
  600. }
  601. function errorFactory(error) {
  602. let message;
  603. if (error.formatted) {
  604. message = error.formatted.replace(/^Error: /, "");
  605. } else {
  606. // Keep original error if `sassError.formatted` is unavailable
  607. ({
  608. message
  609. } = error);
  610. }
  611. const obj = new Error(message, {
  612. cause: error
  613. });
  614. obj.stack = null;
  615. return obj;
  616. }