BasicMatcherRulePlugin.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("../../declarations/WebpackOptions").RuleSetConditionOrConditions} RuleSetConditionOrConditions */
  7. /** @typedef {import("../../declarations/WebpackOptions").RuleSetConditionOrConditionsAbsolute} RuleSetConditionOrConditionsAbsolute */
  8. /** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */
  9. /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */
  10. /**
  11. * Defines the keys of types type used by this module.
  12. * @template T
  13. * @template {T[keyof T]} V
  14. * @typedef {import("./RuleSetCompiler").KeysOfTypes<T, V>} KeysOfTypes
  15. */
  16. /** @typedef {KeysOfTypes<RuleSetRule, RuleSetConditionOrConditions | RuleSetConditionOrConditionsAbsolute>} BasicMatcherRuleKeys */
  17. const PLUGIN_NAME = "BasicMatcherRulePlugin";
  18. class BasicMatcherRulePlugin {
  19. /**
  20. * Creates an instance of BasicMatcherRulePlugin.
  21. * @param {BasicMatcherRuleKeys} ruleProperty the rule property
  22. * @param {string=} dataProperty the data property
  23. * @param {boolean=} invert if true, inverts the condition
  24. */
  25. constructor(ruleProperty, dataProperty, invert) {
  26. /** @type {BasicMatcherRuleKeys} */
  27. this.ruleProperty = ruleProperty;
  28. /** @type {string | BasicMatcherRuleKeys} */
  29. this.dataProperty = dataProperty || ruleProperty;
  30. /** @type {boolean} */
  31. this.invert = invert || false;
  32. }
  33. /**
  34. * Applies the plugin by registering its hooks on the compiler.
  35. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  36. * @returns {void}
  37. */
  38. apply(ruleSetCompiler) {
  39. ruleSetCompiler.hooks.rule.tap(
  40. PLUGIN_NAME,
  41. (path, rule, unhandledProperties, result) => {
  42. if (unhandledProperties.has(this.ruleProperty)) {
  43. unhandledProperties.delete(this.ruleProperty);
  44. const value = rule[this.ruleProperty];
  45. const condition = ruleSetCompiler.compileCondition(
  46. `${path}.${this.ruleProperty}`,
  47. /** @type {RuleSetConditionOrConditions | RuleSetConditionOrConditionsAbsolute} */
  48. (value)
  49. );
  50. const fn = condition.fn;
  51. result.conditions.push({
  52. property: this.dataProperty,
  53. matchWhenEmpty: this.invert
  54. ? !condition.matchWhenEmpty
  55. : condition.matchWhenEmpty,
  56. fn: this.invert ? (v) => !fn(v) : fn
  57. });
  58. }
  59. }
  60. );
  61. }
  62. }
  63. module.exports = BasicMatcherRulePlugin;