utils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.exec = exec;
  6. exports.findPackageJSONDir = findPackageJSONDir;
  7. exports.getPostcssImplementation = getPostcssImplementation;
  8. exports.getPostcssOptions = getPostcssOptions;
  9. exports.loadConfig = loadConfig;
  10. exports.normalizeSourceMap = normalizeSourceMap;
  11. exports.normalizeSourceMapAfterPostcss = normalizeSourceMapAfterPostcss;
  12. exports.reportError = reportError;
  13. exports.warningFactory = warningFactory;
  14. var _path = _interopRequireDefault(require("path"));
  15. var _url = _interopRequireDefault(require("url"));
  16. var _module = _interopRequireDefault(require("module"));
  17. var _cosmiconfig = require("cosmiconfig");
  18. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  19. const parentModule = module;
  20. const stat = (inputFileSystem, filePath) => new Promise((resolve, reject) => {
  21. inputFileSystem.stat(filePath, (err, stats) => {
  22. if (err) {
  23. reject(err);
  24. }
  25. resolve(stats);
  26. });
  27. });
  28. function exec(code, loaderContext) {
  29. const {
  30. resource,
  31. context
  32. } = loaderContext;
  33. const module = new _module.default(resource, parentModule);
  34. // eslint-disable-next-line no-underscore-dangle
  35. module.paths = _module.default._nodeModulePaths(context);
  36. module.filename = resource;
  37. // eslint-disable-next-line no-underscore-dangle
  38. module._compile(code, resource);
  39. return module.exports;
  40. }
  41. let tsLoader;
  42. async function loadConfig(loaderContext, config, postcssOptions) {
  43. const searchPath = typeof config === "string" ? _path.default.resolve(config) : _path.default.dirname(loaderContext.resourcePath);
  44. let stats;
  45. try {
  46. stats = await stat(loaderContext.fs, searchPath);
  47. } catch (errorIgnore) {
  48. throw new Error(`No PostCSS config found in: ${searchPath}`);
  49. }
  50. const moduleName = "postcss";
  51. const searchPlaces = [
  52. // Prefer popular format
  53. "package.json", `${moduleName}.config.js`, `${moduleName}.config.mjs`, `${moduleName}.config.cjs`, `${moduleName}.config.ts`, `${moduleName}.config.mts`, `${moduleName}.config.cts`, `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.js`, `.${moduleName}rc.mjs`, `.${moduleName}rc.cjs`, `.${moduleName}rc.ts`, `.${moduleName}rc.mts`, `.${moduleName}rc.cts`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.config/${moduleName}rc`, `.config/${moduleName}rc.json`, `.config/${moduleName}rc.yaml`, `.config/${moduleName}rc.yml`, `.config/${moduleName}rc.js`, `.config/${moduleName}rc.mjs`, `.config/${moduleName}rc.cjs`, `.config/${moduleName}rc.ts`, `.config/${moduleName}rc.mts`, `.config/${moduleName}rc.cts`];
  54. const loaders = {
  55. ".js": async (...args) => {
  56. let result;
  57. try {
  58. result = _cosmiconfig.defaultLoadersSync[".js"](...args);
  59. } catch (error) {
  60. let importESM;
  61. try {
  62. // eslint-disable-next-line no-new-func
  63. importESM = new Function("id", "return import(id);");
  64. } catch (e) {
  65. importESM = null;
  66. }
  67. if (error.code === "ERR_REQUIRE_ESM" && _url.default.pathToFileURL && importESM) {
  68. const urlForConfig = _url.default.pathToFileURL(args[0]);
  69. result = await importESM(urlForConfig);
  70. } else {
  71. throw error;
  72. }
  73. }
  74. return result;
  75. },
  76. ".cjs": _cosmiconfig.defaultLoadersSync[".cjs"],
  77. ".mjs": async (...args) => {
  78. let result;
  79. let importESM;
  80. try {
  81. // eslint-disable-next-line no-new-func
  82. importESM = new Function("id", "return import(id);");
  83. } catch (e) {
  84. importESM = null;
  85. }
  86. if (_url.default.pathToFileURL && importESM) {
  87. const urlForConfig = _url.default.pathToFileURL(args[0]);
  88. result = await importESM(urlForConfig);
  89. } else {
  90. throw new Error("ESM is not supported");
  91. }
  92. return result;
  93. }
  94. };
  95. if (!tsLoader) {
  96. const opts = {
  97. interopDefault: true
  98. };
  99. // eslint-disable-next-line global-require, import/no-extraneous-dependencies
  100. const jiti = require("jiti")(__filename, opts);
  101. tsLoader = filepath => jiti(filepath);
  102. }
  103. loaders[".cts"] = tsLoader;
  104. loaders[".mts"] = tsLoader;
  105. loaders[".ts"] = tsLoader;
  106. const explorer = (0, _cosmiconfig.cosmiconfig)(moduleName, {
  107. searchPlaces,
  108. loaders
  109. });
  110. let result;
  111. try {
  112. if (stats.isFile()) {
  113. result = await explorer.load(searchPath);
  114. } else {
  115. result = await explorer.search(searchPath);
  116. }
  117. } catch (error) {
  118. throw error;
  119. }
  120. if (!result) {
  121. return {};
  122. }
  123. loaderContext.addBuildDependency(result.filepath);
  124. loaderContext.addDependency(result.filepath);
  125. if (result.isEmpty) {
  126. return result;
  127. }
  128. if (typeof result.config === "function") {
  129. const api = {
  130. mode: loaderContext.mode,
  131. file: loaderContext.resourcePath,
  132. // For complex use
  133. webpackLoaderContext: loaderContext,
  134. // Partial compatibility with `postcss-cli`
  135. env: loaderContext.mode,
  136. options: postcssOptions || {}
  137. };
  138. return {
  139. ...result,
  140. config: result.config(api)
  141. };
  142. }
  143. return result;
  144. }
  145. function loadPlugin(plugin, options, file) {
  146. try {
  147. // eslint-disable-next-line global-require, import/no-dynamic-require
  148. let loadedPlugin = require(plugin);
  149. if (loadedPlugin.default) {
  150. loadedPlugin = loadedPlugin.default;
  151. }
  152. if (!options || Object.keys(options).length === 0) {
  153. return loadedPlugin;
  154. }
  155. return loadedPlugin(options);
  156. } catch (error) {
  157. throw new Error(`Loading PostCSS "${plugin}" plugin failed: ${error.message}\n\n(@${file})`);
  158. }
  159. }
  160. function pluginFactory() {
  161. const listOfPlugins = new Map();
  162. return plugins => {
  163. if (typeof plugins === "undefined") {
  164. return listOfPlugins;
  165. }
  166. if (Array.isArray(plugins)) {
  167. for (const plugin of plugins) {
  168. if (Array.isArray(plugin)) {
  169. const [name, options] = plugin;
  170. listOfPlugins.set(name, options);
  171. } else if (plugin && typeof plugin === "function") {
  172. listOfPlugins.set(plugin);
  173. } else if (plugin && Object.keys(plugin).length === 1 && (typeof plugin[Object.keys(plugin)[0]] === "object" || typeof plugin[Object.keys(plugin)[0]] === "boolean") && plugin[Object.keys(plugin)[0]] !== null) {
  174. const [name] = Object.keys(plugin);
  175. const options = plugin[name];
  176. if (options === false) {
  177. listOfPlugins.delete(name);
  178. } else {
  179. listOfPlugins.set(name, options);
  180. }
  181. } else if (plugin) {
  182. listOfPlugins.set(plugin);
  183. }
  184. }
  185. } else {
  186. const objectPlugins = Object.entries(plugins);
  187. for (const [name, options] of objectPlugins) {
  188. if (options === false) {
  189. listOfPlugins.delete(name);
  190. } else {
  191. listOfPlugins.set(name, options);
  192. }
  193. }
  194. }
  195. return listOfPlugins;
  196. };
  197. }
  198. async function tryRequireThenImport(module) {
  199. let exports;
  200. try {
  201. // eslint-disable-next-line import/no-dynamic-require, global-require
  202. exports = require(module);
  203. return exports;
  204. } catch (requireError) {
  205. let importESM;
  206. try {
  207. // eslint-disable-next-line no-new-func
  208. importESM = new Function("id", "return import(id);");
  209. } catch (e) {
  210. importESM = null;
  211. }
  212. if (requireError.code === "ERR_REQUIRE_ESM" && importESM) {
  213. exports = await importESM(module);
  214. return exports.default;
  215. }
  216. throw requireError;
  217. }
  218. }
  219. async function getPostcssOptions(loaderContext, loadedConfig = {}, postcssOptions = {}) {
  220. const file = loaderContext.resourcePath;
  221. let normalizedPostcssOptions = postcssOptions;
  222. if (typeof normalizedPostcssOptions === "function") {
  223. normalizedPostcssOptions = normalizedPostcssOptions(loaderContext);
  224. }
  225. let plugins = [];
  226. try {
  227. const factory = pluginFactory();
  228. if (loadedConfig.config && loadedConfig.config.plugins) {
  229. factory(loadedConfig.config.plugins);
  230. }
  231. factory(normalizedPostcssOptions.plugins);
  232. plugins = [...factory()].map(item => {
  233. const [plugin, options] = item;
  234. if (typeof plugin === "string") {
  235. return loadPlugin(plugin, options, file);
  236. }
  237. return plugin;
  238. });
  239. } catch (error) {
  240. loaderContext.emitError(error);
  241. }
  242. const processOptionsFromConfig = {
  243. ...loadedConfig.config
  244. } || {};
  245. if (processOptionsFromConfig.from) {
  246. processOptionsFromConfig.from = _path.default.resolve(_path.default.dirname(loadedConfig.filepath), processOptionsFromConfig.from);
  247. }
  248. if (processOptionsFromConfig.to) {
  249. processOptionsFromConfig.to = _path.default.resolve(_path.default.dirname(loadedConfig.filepath), processOptionsFromConfig.to);
  250. }
  251. const processOptionsFromOptions = {
  252. ...normalizedPostcssOptions
  253. };
  254. if (processOptionsFromOptions.from) {
  255. processOptionsFromOptions.from = _path.default.resolve(loaderContext.rootContext, processOptionsFromOptions.from);
  256. }
  257. if (processOptionsFromOptions.to) {
  258. processOptionsFromOptions.to = _path.default.resolve(loaderContext.rootContext, processOptionsFromOptions.to);
  259. }
  260. // No need `plugins` and `config` for processOptions
  261. const {
  262. plugins: __plugins,
  263. ...optionsFromConfig
  264. } = processOptionsFromConfig;
  265. const {
  266. config: _config,
  267. plugins: _plugins,
  268. ...optionsFromOptions
  269. } = processOptionsFromOptions;
  270. const processOptions = {
  271. from: file,
  272. to: file,
  273. map: false,
  274. ...optionsFromConfig,
  275. ...optionsFromOptions
  276. };
  277. if (typeof processOptions.parser === "string") {
  278. try {
  279. processOptions.parser = await tryRequireThenImport(processOptions.parser);
  280. } catch (error) {
  281. loaderContext.emitError(new Error(`Loading PostCSS "${processOptions.parser}" parser failed: ${error.message}\n\n(@${file})`));
  282. }
  283. }
  284. if (typeof processOptions.stringifier === "string") {
  285. try {
  286. processOptions.stringifier = await tryRequireThenImport(processOptions.stringifier);
  287. } catch (error) {
  288. loaderContext.emitError(new Error(`Loading PostCSS "${processOptions.stringifier}" stringifier failed: ${error.message}\n\n(@${file})`));
  289. }
  290. }
  291. if (typeof processOptions.syntax === "string") {
  292. try {
  293. processOptions.syntax = await tryRequireThenImport(processOptions.syntax);
  294. } catch (error) {
  295. loaderContext.emitError(new Error(`Loading PostCSS "${processOptions.syntax}" syntax failed: ${error.message}\n\n(@${file})`));
  296. }
  297. }
  298. if (processOptions.map === true) {
  299. // https://github.com/postcss/postcss/blob/master/docs/source-maps.md
  300. processOptions.map = {
  301. inline: true
  302. };
  303. }
  304. return {
  305. plugins,
  306. processOptions
  307. };
  308. }
  309. const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
  310. const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
  311. function getURLType(source) {
  312. if (source[0] === "/") {
  313. if (source[1] === "/") {
  314. return "scheme-relative";
  315. }
  316. return "path-absolute";
  317. }
  318. if (IS_NATIVE_WIN32_PATH.test(source)) {
  319. return "path-absolute";
  320. }
  321. return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
  322. }
  323. function normalizeSourceMap(map, resourceContext) {
  324. let newMap = map;
  325. // Some loader emit source map as string
  326. // Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
  327. if (typeof newMap === "string") {
  328. newMap = JSON.parse(newMap);
  329. }
  330. delete newMap.file;
  331. const {
  332. sourceRoot
  333. } = newMap;
  334. delete newMap.sourceRoot;
  335. if (newMap.sources) {
  336. newMap.sources = newMap.sources.map(source => {
  337. const sourceType = getURLType(source);
  338. // Do no touch `scheme-relative` and `absolute` URLs
  339. if (sourceType === "path-relative" || sourceType === "path-absolute") {
  340. const absoluteSource = sourceType === "path-relative" && sourceRoot ? _path.default.resolve(sourceRoot, _path.default.normalize(source)) : _path.default.normalize(source);
  341. return _path.default.relative(resourceContext, absoluteSource);
  342. }
  343. return source;
  344. });
  345. }
  346. return newMap;
  347. }
  348. function normalizeSourceMapAfterPostcss(map, resourceContext) {
  349. const newMap = map;
  350. // result.map.file is an optional property that provides the output filename.
  351. // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
  352. // eslint-disable-next-line no-param-reassign
  353. delete newMap.file;
  354. // eslint-disable-next-line no-param-reassign
  355. newMap.sourceRoot = "";
  356. // eslint-disable-next-line no-param-reassign
  357. newMap.sources = newMap.sources.map(source => {
  358. if (source.indexOf("<") === 0) {
  359. return source;
  360. }
  361. const sourceType = getURLType(source);
  362. // Do no touch `scheme-relative`, `path-absolute` and `absolute` types
  363. if (sourceType === "path-relative") {
  364. return _path.default.resolve(resourceContext, source);
  365. }
  366. return source;
  367. });
  368. return newMap;
  369. }
  370. function findPackageJSONDir(cwd, statSync) {
  371. let dir = cwd;
  372. for (;;) {
  373. try {
  374. if (statSync(_path.default.join(dir, "package.json")).isFile()) {
  375. break;
  376. }
  377. } catch (error) {
  378. // Nothing
  379. }
  380. const parent = _path.default.dirname(dir);
  381. if (dir === parent) {
  382. dir = null;
  383. break;
  384. }
  385. dir = parent;
  386. }
  387. return dir;
  388. }
  389. function getPostcssImplementation(loaderContext, implementation) {
  390. let resolvedImplementation = implementation;
  391. if (!implementation || typeof implementation === "string") {
  392. const postcssImplPkg = implementation || "postcss";
  393. // eslint-disable-next-line import/no-dynamic-require, global-require
  394. resolvedImplementation = require(postcssImplPkg);
  395. }
  396. // eslint-disable-next-line consistent-return
  397. return resolvedImplementation;
  398. }
  399. function reportError(loaderContext, callback, error) {
  400. if (error.file) {
  401. loaderContext.addDependency(error.file);
  402. }
  403. if (error.name === "CssSyntaxError") {
  404. callback(syntaxErrorFactory(error));
  405. } else {
  406. callback(error);
  407. }
  408. }
  409. function warningFactory(warning) {
  410. let message = "";
  411. if (typeof warning.line !== "undefined") {
  412. message += `(${warning.line}:${warning.column}) `;
  413. }
  414. if (typeof warning.plugin !== "undefined") {
  415. message += `from "${warning.plugin}" plugin: `;
  416. }
  417. message += warning.text;
  418. if (warning.node) {
  419. message += `\n\nCode:\n ${warning.node.toString()}\n`;
  420. }
  421. const obj = new Error(message, {
  422. cause: warning
  423. });
  424. obj.stack = null;
  425. return obj;
  426. }
  427. function syntaxErrorFactory(error) {
  428. let message = "\nSyntaxError\n\n";
  429. if (typeof error.line !== "undefined") {
  430. message += `(${error.line}:${error.column}) `;
  431. }
  432. if (typeof error.plugin !== "undefined") {
  433. message += `from "${error.plugin}" plugin: `;
  434. }
  435. message += error.file ? `${error.file} ` : "<css input> ";
  436. message += `${error.reason}`;
  437. const code = error.showSourceCode();
  438. if (code) {
  439. message += `\n\n${code}\n`;
  440. }
  441. const obj = new Error(message, {
  442. cause: error
  443. });
  444. obj.stack = null;
  445. return obj;
  446. }