ObjectMatcherRulePlugin.js 2.4 KB

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