source: trip-planner-front/node_modules/sass-loader/dist/utils.js@ fa375fe

Last change on this file since fa375fe was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

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