ObjectMatcherRulePlugin.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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").RuleSetRule} RuleSetRule */
  7. /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */
  8. /** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */
  9. /** @typedef {import("./RuleSetCompiler").RuleConditionFunction} RuleConditionFunction */
  10. class ObjectMatcherRulePlugin {
  11. /**
  12. * @param {string} ruleProperty the rule property
  13. * @param {string=} dataProperty the data property
  14. * @param {RuleConditionFunction=} additionalConditionFunction need to check
  15. */
  16. constructor(ruleProperty, dataProperty, additionalConditionFunction) {
  17. this.ruleProperty = ruleProperty;
  18. this.dataProperty = dataProperty || ruleProperty;
  19. this.additionalConditionFunction = additionalConditionFunction;
  20. }
  21. /**
  22. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  23. * @returns {void}
  24. */
  25. apply(ruleSetCompiler) {
  26. const { ruleProperty, dataProperty } = this;
  27. ruleSetCompiler.hooks.rule.tap(
  28. "ObjectMatcherRulePlugin",
  29. (path, rule, unhandledProperties, result) => {
  30. if (unhandledProperties.has(ruleProperty)) {
  31. unhandledProperties.delete(ruleProperty);
  32. const value =
  33. /** @type {Record<string, any>} */
  34. (rule[/** @type {keyof RuleSetRule} */ (ruleProperty)]);
  35. for (const property of Object.keys(value)) {
  36. const nestedDataProperties = property.split(".");
  37. const condition = ruleSetCompiler.compileCondition(
  38. `${path}.${ruleProperty}.${property}`,
  39. value[property]
  40. );
  41. if (this.additionalConditionFunction) {
  42. result.conditions.push({
  43. property: [dataProperty],
  44. matchWhenEmpty: condition.matchWhenEmpty,
  45. fn: this.additionalConditionFunction
  46. });
  47. }
  48. result.conditions.push({
  49. property: [dataProperty, ...nestedDataProperties],
  50. matchWhenEmpty: condition.matchWhenEmpty,
  51. fn: condition.fn
  52. });
  53. }
  54. }
  55. }
  56. );
  57. }
  58. }
  59. module.exports = ObjectMatcherRulePlugin;