BasicMatcherRulePlugin.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. * @template T
  12. * @template {T[keyof T]} V
  13. * @typedef {import("./RuleSetCompiler").KeysOfTypes<T, V>} KeysOfTypes
  14. */
  15. /** @typedef {KeysOfTypes<RuleSetRule, RuleSetConditionOrConditions | RuleSetConditionOrConditionsAbsolute>} BasicMatcherRuleKeys */
  16. const PLUGIN_NAME = "BasicMatcherRulePlugin";
  17. class BasicMatcherRulePlugin {
  18. /**
  19. * @param {BasicMatcherRuleKeys} ruleProperty the rule property
  20. * @param {string=} dataProperty the data property
  21. * @param {boolean=} invert if true, inverts the condition
  22. */
  23. constructor(ruleProperty, dataProperty, invert) {
  24. /** @type {BasicMatcherRuleKeys} */
  25. this.ruleProperty = ruleProperty;
  26. /** @type {string | BasicMatcherRuleKeys} */
  27. this.dataProperty = dataProperty || ruleProperty;
  28. /** @type {boolean} */
  29. this.invert = invert || false;
  30. }
  31. /**
  32. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  33. * @returns {void}
  34. */
  35. apply(ruleSetCompiler) {
  36. ruleSetCompiler.hooks.rule.tap(
  37. PLUGIN_NAME,
  38. (path, rule, unhandledProperties, result) => {
  39. if (unhandledProperties.has(this.ruleProperty)) {
  40. unhandledProperties.delete(this.ruleProperty);
  41. const value = rule[this.ruleProperty];
  42. const condition = ruleSetCompiler.compileCondition(
  43. `${path}.${this.ruleProperty}`,
  44. /** @type {RuleSetConditionOrConditions | RuleSetConditionOrConditionsAbsolute} */
  45. (value)
  46. );
  47. const fn = condition.fn;
  48. result.conditions.push({
  49. property: this.dataProperty,
  50. matchWhenEmpty: this.invert
  51. ? !condition.matchWhenEmpty
  52. : condition.matchWhenEmpty,
  53. fn: this.invert ? (v) => !fn(v) : fn
  54. });
  55. }
  56. }
  57. );
  58. }
  59. }
  60. module.exports = BasicMatcherRulePlugin;