RuleSetCompiler.js 10 KB

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