utils.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.errorFactory = errorFactory;
  6. exports.getLessImplementation = getLessImplementation;
  7. exports.getLessOptions = getLessOptions;
  8. exports.isUnsupportedUrl = isUnsupportedUrl;
  9. exports.normalizeSourceMap = normalizeSourceMap;
  10. var _path = _interopRequireDefault(require("path"));
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. /* eslint-disable class-methods-use-this */
  13. const trailingSlash = /[/\\]$/;
  14. // This somewhat changed in Less 3.x. Now the file name comes without the
  15. // automatically added extension whereas the extension is passed in as `options.ext`.
  16. // So, if the file name matches this regexp, we simply ignore the proposed extension.
  17. const IS_SPECIAL_MODULE_IMPORT = /^~[^/]+$/;
  18. // `[drive_letter]:\` + `\\[server]\[share_name]\`
  19. const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
  20. // Examples:
  21. // - ~package
  22. // - ~package/
  23. // - ~@org
  24. // - ~@org/
  25. // - ~@org/package
  26. // - ~@org/package/
  27. const IS_MODULE_IMPORT = /^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;
  28. const MODULE_REQUEST_REGEX = /^[^?]*~/;
  29. /**
  30. * Creates a Less plugin that uses webpack's resolving engine that is provided by the loaderContext.
  31. *
  32. * @param {LoaderContext} loaderContext
  33. * @param {object} implementation
  34. * @returns {LessPlugin}
  35. */
  36. function createWebpackLessPlugin(loaderContext, implementation) {
  37. const resolve = loaderContext.getResolve({
  38. dependencyType: "less",
  39. conditionNames: ["less", "style", "..."],
  40. mainFields: ["less", "style", "main", "..."],
  41. mainFiles: ["index", "..."],
  42. extensions: [".less", ".css"],
  43. preferRelative: true
  44. });
  45. class WebpackFileManager extends implementation.FileManager {
  46. supports(filename) {
  47. if (filename[0] === "/" || IS_NATIVE_WIN32_PATH.test(filename)) {
  48. return true;
  49. }
  50. if (this.isPathAbsolute(filename)) {
  51. return false;
  52. }
  53. return true;
  54. }
  55. // Sync resolving is used at least by the `data-uri` function.
  56. // This file manager doesn't know how to do it, so let's delegate it
  57. // to the default file manager of Less.
  58. // We could probably use loaderContext.resolveSync, but it's deprecated,
  59. // see https://webpack.js.org/api/loaders/#this-resolvesync
  60. supportsSync() {
  61. return false;
  62. }
  63. async resolveFilename(filename, currentDirectory) {
  64. // Less is giving us trailing slashes, but the context should have no trailing slash
  65. const context = currentDirectory.replace(trailingSlash, "");
  66. let request = filename;
  67. // A `~` makes the url an module
  68. if (MODULE_REQUEST_REGEX.test(filename)) {
  69. request = request.replace(MODULE_REQUEST_REGEX, "");
  70. }
  71. if (IS_MODULE_IMPORT.test(filename)) {
  72. request = request[request.length - 1] === "/" ? request : `${request}/`;
  73. }
  74. return this.resolveRequests(context, [...new Set([request, filename])]);
  75. }
  76. async resolveRequests(context, possibleRequests) {
  77. if (possibleRequests.length === 0) {
  78. return Promise.reject();
  79. }
  80. let result;
  81. try {
  82. result = await resolve(context, possibleRequests[0]);
  83. } catch (error) {
  84. const [, ...tailPossibleRequests] = possibleRequests;
  85. if (tailPossibleRequests.length === 0) {
  86. throw error;
  87. }
  88. result = await this.resolveRequests(context, tailPossibleRequests);
  89. }
  90. return result;
  91. }
  92. async loadFile(filename, ...args) {
  93. let result;
  94. try {
  95. if (IS_SPECIAL_MODULE_IMPORT.test(filename)) {
  96. const error = new Error();
  97. error.type = "Next";
  98. throw error;
  99. }
  100. result = await super.loadFile(filename, ...args);
  101. } catch (error) {
  102. if (error.type !== "File" && error.type !== "Next") {
  103. return Promise.reject(error);
  104. }
  105. try {
  106. result = await this.resolveFilename(filename, ...args);
  107. } catch (webpackResolveError) {
  108. error.message = `Less resolver error:\n${error.message}\n\n` + `Webpack resolver error details:\n${webpackResolveError.details}\n\n` + `Webpack resolver error missing:\n${webpackResolveError.missing}\n\n`;
  109. return Promise.reject(error);
  110. }
  111. loaderContext.addDependency(result);
  112. return super.loadFile(result, ...args);
  113. }
  114. loaderContext.addDependency(_path.default.normalize(result.filename));
  115. return result;
  116. }
  117. }
  118. return {
  119. install(lessInstance, pluginManager) {
  120. pluginManager.addFileManager(new WebpackFileManager());
  121. },
  122. minVersion: [3, 0, 0]
  123. };
  124. }
  125. /**
  126. * Get the `less` options from the loader context and normalizes its values
  127. *
  128. * @param {object} loaderContext
  129. * @param {object} loaderOptions
  130. * @param {object} implementation
  131. * @returns {Object}
  132. */
  133. function getLessOptions(loaderContext, loaderOptions, implementation) {
  134. const options = typeof loaderOptions.lessOptions === "function" ? loaderOptions.lessOptions(loaderContext) || {} : loaderOptions.lessOptions || {};
  135. const lessOptions = {
  136. plugins: [],
  137. relativeUrls: true,
  138. // We need to set the filename because otherwise our WebpackFileManager will receive an undefined path for the entry
  139. filename: loaderContext.resourcePath,
  140. ...options
  141. };
  142. const plugins = lessOptions.plugins.slice();
  143. const shouldUseWebpackImporter = typeof loaderOptions.webpackImporter === "boolean" ? loaderOptions.webpackImporter : true;
  144. if (shouldUseWebpackImporter) {
  145. plugins.unshift(createWebpackLessPlugin(loaderContext, implementation));
  146. }
  147. plugins.unshift({
  148. install(lessProcessor, pluginManager) {
  149. // eslint-disable-next-line no-param-reassign
  150. pluginManager.webpackLoaderContext = loaderContext;
  151. lessOptions.pluginManager = pluginManager;
  152. }
  153. });
  154. lessOptions.plugins = plugins;
  155. return lessOptions;
  156. }
  157. function isUnsupportedUrl(url) {
  158. // Is Windows path
  159. if (IS_NATIVE_WIN32_PATH.test(url)) {
  160. return false;
  161. }
  162. // Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
  163. // Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
  164. return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url);
  165. }
  166. function normalizeSourceMap(map) {
  167. const newMap = map;
  168. // map.file is an optional property that provides the output filename.
  169. // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
  170. // eslint-disable-next-line no-param-reassign
  171. delete newMap.file;
  172. // eslint-disable-next-line no-param-reassign
  173. newMap.sourceRoot = "";
  174. // `less` returns POSIX paths, that's why we need to transform them back to native paths.
  175. // eslint-disable-next-line no-param-reassign
  176. newMap.sources = newMap.sources.map(source => _path.default.normalize(source));
  177. return newMap;
  178. }
  179. function getLessImplementation(loaderContext, implementation) {
  180. let resolvedImplementation = implementation;
  181. if (!implementation || typeof implementation === "string") {
  182. const lessImplPkg = implementation || "less";
  183. // eslint-disable-next-line import/no-dynamic-require, global-require
  184. resolvedImplementation = require(lessImplPkg);
  185. }
  186. // eslint-disable-next-line consistent-return
  187. return resolvedImplementation;
  188. }
  189. function getFileExcerptIfPossible(error) {
  190. if (typeof error.extract === "undefined") {
  191. return [];
  192. }
  193. const excerpt = error.extract.slice(0, 2);
  194. const column = Math.max(error.column - 1, 0);
  195. if (typeof excerpt[0] === "undefined") {
  196. excerpt.shift();
  197. }
  198. excerpt.push(`${new Array(column).join(" ")}^`);
  199. return excerpt;
  200. }
  201. function errorFactory(error) {
  202. const message = ["\n", ...getFileExcerptIfPossible(error), error.message.charAt(0).toUpperCase() + error.message.slice(1), error.filename ? ` Error in ${_path.default.normalize(error.filename)} (line ${error.line}, column ${error.column})` : ""].join("\n");
  203. const obj = new Error(message, {
  204. cause: error
  205. });
  206. obj.stack = null;
  207. return obj;
  208. }