emitWarning.mjs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import process from 'node:process';
  2. // Each code must be unique across all warning types.
  3. const DEPRECATION_CODES = {
  4. COMMONJS_PLUGINS: '001',
  5. COMMONJS_NODEJS_API: '002',
  6. RESULT_OUTPUT_PROPERTY: '003',
  7. GITHUB_FORMATTER: '004',
  8. CONTEXT_FIX: '005',
  9. RULE: '006', // either removal or renaming
  10. REPORT_AMBIGUOUS_POSITION: '007',
  11. };
  12. const EXPERIMENTAL_CODES = {
  13. SUPPRESSIONS: '101',
  14. };
  15. const emittedWarnings = new Set();
  16. /**
  17. * @typedef {DEPRECATION_CODES[keyof DEPRECATION_CODES] |
  18. * EXPERIMENTAL_CODES[keyof EXPERIMENTAL_CODES]} WarningCode
  19. */
  20. /**
  21. * Emit a warning with the specified type.
  22. *
  23. * @param {string} message
  24. * @param {'DeprecationWarning' | 'ExperimentalWarning'} type - See https://nodejs.org/api/process.html#nodejs-warning-names
  25. * @param {WarningCode} code
  26. * @param {string} detail
  27. * @returns {void}
  28. */
  29. function emitWarning(message, type, code, detail) {
  30. const key = JSON.stringify({
  31. message,
  32. options: { type, code: `stylelint:${code}`, detail },
  33. });
  34. if (emittedWarnings.has(key)) return;
  35. emittedWarnings.add(key);
  36. process.emitWarning(message, { type, code: `stylelint:${code}`, detail });
  37. }
  38. /**
  39. * Use this function for deprecation warnings, instead of `process.emitWarning()`.
  40. *
  41. * @param {string} message
  42. * @param {keyof DEPRECATION_CODES} codeKey
  43. * @param {string} detail
  44. * @returns {void}
  45. */
  46. export function emitDeprecationWarning(message, codeKey, detail) {
  47. emitWarning(message, 'DeprecationWarning', DEPRECATION_CODES[codeKey], detail);
  48. }
  49. /**
  50. * Use this function for experimental warnings, instead of `process.emitWarning()`.
  51. *
  52. * @param {string} message
  53. * @param {keyof EXPERIMENTAL_CODES} codeKey
  54. * @param {string} detail
  55. * @returns {void}
  56. */
  57. export function emitExperimentalWarning(message, codeKey, detail) {
  58. emitWarning(message, 'ExperimentalWarning', EXPERIMENTAL_CODES[codeKey], detail);
  59. }
  60. /**
  61. * Clear the already emitted warnings.
  62. * Only useful in tests.
  63. *
  64. * @private
  65. */
  66. export function clearEmittedWarnings() {
  67. if (process.env.NODE_ENV !== 'test') {
  68. throw new Error('This function can only be called in test environments!');
  69. }
  70. emittedWarnings.clear();
  71. }