BasicMatcherRulePlugin.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */
  7. /** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */
  8. class BasicMatcherRulePlugin {
  9. /**
  10. * @param {string} ruleProperty the rule property
  11. * @param {string=} dataProperty the data property
  12. * @param {boolean=} invert if true, inverts the condition
  13. */
  14. constructor(ruleProperty, dataProperty, invert) {
  15. this.ruleProperty = ruleProperty;
  16. this.dataProperty = dataProperty || ruleProperty;
  17. this.invert = invert || false;
  18. }
  19. /**
  20. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  21. * @returns {void}
  22. */
  23. apply(ruleSetCompiler) {
  24. ruleSetCompiler.hooks.rule.tap(
  25. "BasicMatcherRulePlugin",
  26. (path, rule, unhandledProperties, result) => {
  27. if (unhandledProperties.has(this.ruleProperty)) {
  28. unhandledProperties.delete(this.ruleProperty);
  29. const value = rule[this.ruleProperty];
  30. const condition = ruleSetCompiler.compileCondition(
  31. `${path}.${this.ruleProperty}`,
  32. value
  33. );
  34. const fn = condition.fn;
  35. result.conditions.push({
  36. property: this.dataProperty,
  37. matchWhenEmpty: this.invert
  38. ? !condition.matchWhenEmpty
  39. : condition.matchWhenEmpty,
  40. fn: this.invert ? v => !fn(v) : fn
  41. });
  42. }
  43. }
  44. );
  45. }
  46. }
  47. module.exports = BasicMatcherRulePlugin;