BasicMatcherRulePlugin.js 2.2 KB

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