utils.js 24 KB

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