ObjectMatcherRulePlugin.js 2.5 KB

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