utils.js 24 KB

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