getFormatter.cjs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // NOTICE: This file is generated by Rollup. To modify it,
  2. // please instead edit the ESM counterpart and rebuild with Rollup (npm run build).
  3. 'use strict';
  4. const fs = require('node:fs');
  5. const path = require('node:path');
  6. const dynamicImport = require('./dynamicImport.cjs');
  7. const index = require('../formatters/index.cjs');
  8. const getFormatterOptionsText = require('./getFormatterOptionsText.cjs');
  9. const resolveOptionValue = require('./resolveOptionValue.cjs');
  10. /** @import {Formatter, FormatterType, InternalApi} from 'stylelint' */
  11. /**
  12. * @param {InternalApi} stylelint
  13. * @returns {Promise<Formatter>}
  14. */
  15. async function getFormatter(stylelint) {
  16. /** @type {FormatterType | undefined} */
  17. let formatter = await resolveOptionValue({ stylelint, name: 'formatter' });
  18. if (typeof formatter === 'string') {
  19. let formatterFunction = index[formatter];
  20. if (formatterFunction === undefined) {
  21. if (fs.existsSync(formatter)) {
  22. formatterFunction = await dynamicImport(path.resolve(formatter)).then((m) => m.default);
  23. } else {
  24. const formattersText = getFormatterOptionsText(', ', '"');
  25. throw new Error(`You must use a valid formatter option: ${formattersText} or a function`);
  26. }
  27. }
  28. return formatterFunction;
  29. }
  30. // Assume a function or a promise of a function.
  31. if (typeof formatter === 'function' || formatter) {
  32. return Promise.resolve(formatter);
  33. }
  34. formatter ??= stylelint._options._defaultFormatter ?? 'json';
  35. return index[formatter];
  36. }
  37. module.exports = getFormatter;