RuleSetCompiler.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { SyncHook } = require("tapable");
  7. /** @typedef {import("../../declarations/WebpackOptions").Falsy} Falsy */
  8. /** @typedef {import("../../declarations/WebpackOptions").RuleSetLoaderOptions} RuleSetLoaderOptions */
  9. /** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */
  10. /** @typedef {(Falsy | RuleSetRule)[]} RuleSetRules */
  11. /** @typedef {(value: string | EffectData) => boolean} RuleConditionFunction */
  12. /**
  13. * @typedef {object} RuleCondition
  14. * @property {string | string[]} property
  15. * @property {boolean} matchWhenEmpty
  16. * @property {RuleConditionFunction} fn
  17. */
  18. /**
  19. * @typedef {object} Condition
  20. * @property {boolean} matchWhenEmpty
  21. * @property {RuleConditionFunction} fn
  22. */
  23. /**
  24. * @typedef {Record<string, TODO>} EffectData
  25. */
  26. /**
  27. * @typedef {object} CompiledRule
  28. * @property {RuleCondition[]} conditions
  29. * @property {(Effect | ((effectData: EffectData) => Effect[]))[]} effects
  30. * @property {CompiledRule[]=} rules
  31. * @property {CompiledRule[]=} oneOf
  32. */
  33. /**
  34. * @typedef {object} Effect
  35. * @property {string} type
  36. * @property {TODO} value
  37. */
  38. /** @typedef {Map<string, RuleSetLoaderOptions>} References */
  39. /**
  40. * @typedef {object} RuleSet
  41. * @property {References} references map of references in the rule set (may grow over time)
  42. * @property {(effectData: EffectData) => Effect[]} exec execute the rule set
  43. */
  44. /**
  45. * @template T
  46. * @template {T[keyof T]} V
  47. * @typedef {({ [P in keyof Required<T>]: Required<T>[P] extends V ? P : never })[keyof T]} KeysOfTypes
  48. */
  49. /** @typedef {{ apply: (ruleSetCompiler: RuleSetCompiler) => void }} RuleSetPlugin */
  50. class RuleSetCompiler {
  51. /**
  52. * @param {RuleSetPlugin[]} plugins plugins
  53. */
  54. constructor(plugins) {
  55. this.hooks = Object.freeze({
  56. /** @type {SyncHook<[string, RuleSetRule, Set<string>, CompiledRule, References]>} */
  57. rule: new SyncHook([
  58. "path",
  59. "rule",
  60. "unhandledProperties",
  61. "compiledRule",
  62. "references"
  63. ])
  64. });
  65. if (plugins) {
  66. for (const plugin of plugins) {
  67. plugin.apply(this);
  68. }
  69. }
  70. }
  71. /**
  72. * @param {RuleSetRules} ruleSet raw user provided rules
  73. * @returns {RuleSet} compiled RuleSet
  74. */
  75. compile(ruleSet) {
  76. const refs = new Map();
  77. const rules = this.compileRules("ruleSet", ruleSet, refs);
  78. /**
  79. * @param {EffectData} data data passed in
  80. * @param {CompiledRule} rule the compiled rule
  81. * @param {Effect[]} effects an array where effects are pushed to
  82. * @returns {boolean} true, if the rule has matched
  83. */
  84. const execRule = (data, rule, effects) => {
  85. for (const condition of rule.conditions) {
  86. const p = condition.property;
  87. if (Array.isArray(p)) {
  88. /** @type {EffectData | string | undefined} */
  89. let current = data;
  90. for (const subProperty of p) {
  91. if (
  92. current &&
  93. typeof current === "object" &&
  94. Object.prototype.hasOwnProperty.call(current, subProperty)
  95. ) {
  96. current = current[subProperty];
  97. } else {
  98. current = undefined;
  99. break;
  100. }
  101. }
  102. if (current !== undefined) {
  103. if (!condition.fn(current)) return false;
  104. continue;
  105. }
  106. } else if (p in data) {
  107. const value = data[p];
  108. if (value !== undefined) {
  109. if (!condition.fn(value)) return false;
  110. continue;
  111. }
  112. }
  113. if (!condition.matchWhenEmpty) {
  114. return false;
  115. }
  116. }
  117. for (const effect of rule.effects) {
  118. if (typeof effect === "function") {
  119. const returnedEffects = effect(data);
  120. for (const effect of returnedEffects) {
  121. effects.push(effect);
  122. }
  123. } else {
  124. effects.push(effect);
  125. }
  126. }
  127. if (rule.rules) {
  128. for (const childRule of rule.rules) {
  129. execRule(data, childRule, effects);
  130. }
  131. }
  132. if (rule.oneOf) {
  133. for (const childRule of rule.oneOf) {
  134. if (execRule(data, childRule, effects)) {
  135. break;
  136. }
  137. }
  138. }
  139. return true;
  140. };
  141. return {
  142. references: refs,
  143. exec: data => {
  144. /** @type {Effect[]} */
  145. const effects = [];
  146. for (const rule of rules) {
  147. execRule(data, rule, effects);
  148. }
  149. return effects;
  150. }
  151. };
  152. }
  153. /**
  154. * @param {string} path current path
  155. * @param {RuleSetRules} rules the raw rules provided by user
  156. * @param {References} refs references
  157. * @returns {CompiledRule[]} rules
  158. */
  159. compileRules(path, rules, refs) {
  160. return rules
  161. .filter(Boolean)
  162. .map((rule, i) =>
  163. this.compileRule(
  164. `${path}[${i}]`,
  165. /** @type {RuleSetRule} */ (rule),
  166. refs
  167. )
  168. );
  169. }
  170. /**
  171. * @param {string} path current path
  172. * @param {RuleSetRule} rule the raw rule provided by user
  173. * @param {References} refs references
  174. * @returns {CompiledRule} normalized and compiled rule for processing
  175. */
  176. compileRule(path, rule, refs) {
  177. const unhandledProperties = new Set(
  178. Object.keys(rule).filter(
  179. key => rule[/** @type {keyof RuleSetRule} */ (key)] !== undefined
  180. )
  181. );
  182. /** @type {CompiledRule} */
  183. const compiledRule = {
  184. conditions: [],
  185. effects: [],
  186. rules: undefined,
  187. oneOf: undefined
  188. };
  189. this.hooks.rule.call(path, rule, unhandledProperties, compiledRule, refs);
  190. if (unhandledProperties.has("rules")) {
  191. unhandledProperties.delete("rules");
  192. const rules = rule.rules;
  193. if (!Array.isArray(rules))
  194. throw this.error(path, rules, "Rule.rules must be an array of rules");
  195. compiledRule.rules = this.compileRules(`${path}.rules`, rules, refs);
  196. }
  197. if (unhandledProperties.has("oneOf")) {
  198. unhandledProperties.delete("oneOf");
  199. const oneOf = rule.oneOf;
  200. if (!Array.isArray(oneOf))
  201. throw this.error(path, oneOf, "Rule.oneOf must be an array of rules");
  202. compiledRule.oneOf = this.compileRules(`${path}.oneOf`, oneOf, refs);
  203. }
  204. if (unhandledProperties.size > 0) {
  205. throw this.error(
  206. path,
  207. rule,
  208. `Properties ${Array.from(unhandledProperties).join(", ")} are unknown`
  209. );
  210. }
  211. return compiledRule;
  212. }
  213. /**
  214. * @param {string} path current path
  215. * @param {RuleSetLoaderOptions} condition user provided condition value
  216. * @returns {Condition} compiled condition
  217. */
  218. compileCondition(path, condition) {
  219. if (condition === "") {
  220. return {
  221. matchWhenEmpty: true,
  222. fn: str => str === ""
  223. };
  224. }
  225. if (!condition) {
  226. throw this.error(
  227. path,
  228. condition,
  229. "Expected condition but got falsy value"
  230. );
  231. }
  232. if (typeof condition === "string") {
  233. return {
  234. matchWhenEmpty: condition.length === 0,
  235. fn: str => typeof str === "string" && str.startsWith(condition)
  236. };
  237. }
  238. if (typeof condition === "function") {
  239. try {
  240. return {
  241. matchWhenEmpty: condition(""),
  242. fn: /** @type {RuleConditionFunction} */ (condition)
  243. };
  244. } catch (_err) {
  245. throw this.error(
  246. path,
  247. condition,
  248. "Evaluation of condition function threw error"
  249. );
  250. }
  251. }
  252. if (condition instanceof RegExp) {
  253. return {
  254. matchWhenEmpty: condition.test(""),
  255. fn: v => typeof v === "string" && condition.test(v)
  256. };
  257. }
  258. if (Array.isArray(condition)) {
  259. const items = condition.map((c, i) =>
  260. this.compileCondition(`${path}[${i}]`, c)
  261. );
  262. return this.combineConditionsOr(items);
  263. }
  264. if (typeof condition !== "object") {
  265. throw this.error(
  266. path,
  267. condition,
  268. `Unexpected ${typeof condition} when condition was expected`
  269. );
  270. }
  271. const conditions = [];
  272. for (const key of Object.keys(condition)) {
  273. const value = condition[key];
  274. switch (key) {
  275. case "or":
  276. if (value) {
  277. if (!Array.isArray(value)) {
  278. throw this.error(
  279. `${path}.or`,
  280. condition.or,
  281. "Expected array of conditions"
  282. );
  283. }
  284. conditions.push(this.compileCondition(`${path}.or`, value));
  285. }
  286. break;
  287. case "and":
  288. if (value) {
  289. if (!Array.isArray(value)) {
  290. throw this.error(
  291. `${path}.and`,
  292. condition.and,
  293. "Expected array of conditions"
  294. );
  295. }
  296. let i = 0;
  297. for (const item of value) {
  298. conditions.push(this.compileCondition(`${path}.and[${i}]`, item));
  299. i++;
  300. }
  301. }
  302. break;
  303. case "not":
  304. if (value) {
  305. const matcher = this.compileCondition(`${path}.not`, value);
  306. const fn = matcher.fn;
  307. conditions.push({
  308. matchWhenEmpty: !matcher.matchWhenEmpty,
  309. fn: /** @type {RuleConditionFunction} */ (v => !fn(v))
  310. });
  311. }
  312. break;
  313. default:
  314. throw this.error(
  315. `${path}.${key}`,
  316. condition[key],
  317. `Unexpected property ${key} in condition`
  318. );
  319. }
  320. }
  321. if (conditions.length === 0) {
  322. throw this.error(
  323. path,
  324. condition,
  325. "Expected condition, but got empty thing"
  326. );
  327. }
  328. return this.combineConditionsAnd(conditions);
  329. }
  330. /**
  331. * @param {Condition[]} conditions some conditions
  332. * @returns {Condition} merged condition
  333. */
  334. combineConditionsOr(conditions) {
  335. if (conditions.length === 0) {
  336. return {
  337. matchWhenEmpty: false,
  338. fn: () => false
  339. };
  340. } else if (conditions.length === 1) {
  341. return conditions[0];
  342. }
  343. return {
  344. matchWhenEmpty: conditions.some(c => c.matchWhenEmpty),
  345. fn: v => conditions.some(c => c.fn(v))
  346. };
  347. }
  348. /**
  349. * @param {Condition[]} conditions some conditions
  350. * @returns {Condition} merged condition
  351. */
  352. combineConditionsAnd(conditions) {
  353. if (conditions.length === 0) {
  354. return {
  355. matchWhenEmpty: false,
  356. fn: () => false
  357. };
  358. } else if (conditions.length === 1) {
  359. return conditions[0];
  360. }
  361. return {
  362. matchWhenEmpty: conditions.every(c => c.matchWhenEmpty),
  363. fn: v => conditions.every(c => c.fn(v))
  364. };
  365. }
  366. /**
  367. * @param {string} path current path
  368. * @param {EXPECTED_ANY} value value at the error location
  369. * @param {string} message message explaining the problem
  370. * @returns {Error} an error object
  371. */
  372. error(path, value, message) {
  373. return new Error(
  374. `Compiling RuleSet failed: ${message} (at ${path}: ${value})`
  375. );
  376. }
  377. }
  378. module.exports = RuleSetCompiler;