RuleSet.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. /*
  6. <rules>: <rule>
  7. <rules>: [<rule>]
  8. <rule>: {
  9. resource: {
  10. test: <condition>,
  11. include: <condition>,
  12. exclude: <condition>,
  13. },
  14. resource: <condition>, -> resource.test
  15. test: <condition>, -> resource.test
  16. include: <condition>, -> resource.include
  17. exclude: <condition>, -> resource.exclude
  18. resourceQuery: <condition>,
  19. compiler: <condition>,
  20. issuer: <condition>,
  21. use: "loader", -> use[0].loader
  22. loader: <>, -> use[0].loader
  23. loaders: <>, -> use
  24. options: {}, -> use[0].options,
  25. query: {}, -> options
  26. parser: {},
  27. use: [
  28. "loader" -> use[x].loader
  29. ],
  30. use: [
  31. {
  32. loader: "loader",
  33. options: {}
  34. }
  35. ],
  36. rules: [
  37. <rule>
  38. ],
  39. oneOf: [
  40. <rule>
  41. ]
  42. }
  43. <condition>: /regExp/
  44. <condition>: function(arg) {}
  45. <condition>: "starting"
  46. <condition>: [<condition>] // or
  47. <condition>: { and: [<condition>] }
  48. <condition>: { or: [<condition>] }
  49. <condition>: { not: [<condition>] }
  50. <condition>: { test: <condition>, include: <condition>, exclude: <condition> }
  51. normalized:
  52. {
  53. resource: function(),
  54. resourceQuery: function(),
  55. compiler: function(),
  56. issuer: function(),
  57. use: [
  58. {
  59. loader: string,
  60. options: string,
  61. <any>: <any>
  62. }
  63. ],
  64. rules: [<rule>],
  65. oneOf: [<rule>],
  66. <any>: <any>,
  67. }
  68. */
  69. "use strict";
  70. const notMatcher = matcher => {
  71. return str => {
  72. return !matcher(str);
  73. };
  74. };
  75. const orMatcher = items => {
  76. return str => {
  77. for (let i = 0; i < items.length; i++) {
  78. if (items[i](str)) return true;
  79. }
  80. return false;
  81. };
  82. };
  83. const andMatcher = items => {
  84. return str => {
  85. for (let i = 0; i < items.length; i++) {
  86. if (!items[i](str)) return false;
  87. }
  88. return true;
  89. };
  90. };
  91. module.exports = class RuleSet {
  92. constructor(rules) {
  93. this.references = Object.create(null);
  94. this.rules = RuleSet.normalizeRules(rules, this.references, "ref-");
  95. }
  96. static normalizeRules(rules, refs, ident) {
  97. if (Array.isArray(rules)) {
  98. return rules.map((rule, idx) => {
  99. return RuleSet.normalizeRule(rule, refs, `${ident}-${idx}`);
  100. });
  101. } else if (rules) {
  102. return [RuleSet.normalizeRule(rules, refs, ident)];
  103. } else {
  104. return [];
  105. }
  106. }
  107. static normalizeRule(rule, refs, ident) {
  108. if (typeof rule === "string") {
  109. return {
  110. use: [
  111. {
  112. loader: rule
  113. }
  114. ]
  115. };
  116. }
  117. if (!rule) {
  118. throw new Error("Unexcepted null when object was expected as rule");
  119. }
  120. if (typeof rule !== "object") {
  121. throw new Error(
  122. "Unexcepted " +
  123. typeof rule +
  124. " when object was expected as rule (" +
  125. rule +
  126. ")"
  127. );
  128. }
  129. const newRule = {};
  130. let useSource;
  131. let resourceSource;
  132. let condition;
  133. const checkUseSource = newSource => {
  134. if (useSource && useSource !== newSource) {
  135. throw new Error(
  136. RuleSet.buildErrorMessage(
  137. rule,
  138. new Error(
  139. "Rule can only have one result source (provided " +
  140. newSource +
  141. " and " +
  142. useSource +
  143. ")"
  144. )
  145. )
  146. );
  147. }
  148. useSource = newSource;
  149. };
  150. const checkResourceSource = newSource => {
  151. if (resourceSource && resourceSource !== newSource) {
  152. throw new Error(
  153. RuleSet.buildErrorMessage(
  154. rule,
  155. new Error(
  156. "Rule can only have one resource source (provided " +
  157. newSource +
  158. " and " +
  159. resourceSource +
  160. ")"
  161. )
  162. )
  163. );
  164. }
  165. resourceSource = newSource;
  166. };
  167. if (rule.test || rule.include || rule.exclude) {
  168. checkResourceSource("test + include + exclude");
  169. condition = {
  170. test: rule.test,
  171. include: rule.include,
  172. exclude: rule.exclude
  173. };
  174. try {
  175. newRule.resource = RuleSet.normalizeCondition(condition);
  176. } catch (error) {
  177. throw new Error(RuleSet.buildErrorMessage(condition, error));
  178. }
  179. }
  180. if (rule.resource) {
  181. checkResourceSource("resource");
  182. try {
  183. newRule.resource = RuleSet.normalizeCondition(rule.resource);
  184. } catch (error) {
  185. throw new Error(RuleSet.buildErrorMessage(rule.resource, error));
  186. }
  187. }
  188. if (rule.realResource) {
  189. try {
  190. newRule.realResource = RuleSet.normalizeCondition(rule.realResource);
  191. } catch (error) {
  192. throw new Error(RuleSet.buildErrorMessage(rule.realResource, error));
  193. }
  194. }
  195. if (rule.resourceQuery) {
  196. try {
  197. newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery);
  198. } catch (error) {
  199. throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error));
  200. }
  201. }
  202. if (rule.compiler) {
  203. try {
  204. newRule.compiler = RuleSet.normalizeCondition(rule.compiler);
  205. } catch (error) {
  206. throw new Error(RuleSet.buildErrorMessage(rule.compiler, error));
  207. }
  208. }
  209. if (rule.issuer) {
  210. try {
  211. newRule.issuer = RuleSet.normalizeCondition(rule.issuer);
  212. } catch (error) {
  213. throw new Error(RuleSet.buildErrorMessage(rule.issuer, error));
  214. }
  215. }
  216. if (rule.loader && rule.loaders) {
  217. throw new Error(
  218. RuleSet.buildErrorMessage(
  219. rule,
  220. new Error(
  221. "Provided loader and loaders for rule (use only one of them)"
  222. )
  223. )
  224. );
  225. }
  226. const loader = rule.loaders || rule.loader;
  227. if (typeof loader === "string" && !rule.options && !rule.query) {
  228. checkUseSource("loader");
  229. newRule.use = RuleSet.normalizeUse(loader.split("!"), ident);
  230. } else if (typeof loader === "string" && (rule.options || rule.query)) {
  231. checkUseSource("loader + options/query");
  232. newRule.use = RuleSet.normalizeUse(
  233. {
  234. loader: loader,
  235. options: rule.options,
  236. query: rule.query
  237. },
  238. ident
  239. );
  240. } else if (loader && (rule.options || rule.query)) {
  241. throw new Error(
  242. RuleSet.buildErrorMessage(
  243. rule,
  244. new Error(
  245. "options/query cannot be used with loaders (use options for each array item)"
  246. )
  247. )
  248. );
  249. } else if (loader) {
  250. checkUseSource("loaders");
  251. newRule.use = RuleSet.normalizeUse(loader, ident);
  252. } else if (rule.options || rule.query) {
  253. throw new Error(
  254. RuleSet.buildErrorMessage(
  255. rule,
  256. new Error(
  257. "options/query provided without loader (use loader + options)"
  258. )
  259. )
  260. );
  261. }
  262. if (rule.use) {
  263. checkUseSource("use");
  264. newRule.use = RuleSet.normalizeUse(rule.use, ident);
  265. }
  266. if (rule.rules) {
  267. newRule.rules = RuleSet.normalizeRules(
  268. rule.rules,
  269. refs,
  270. `${ident}-rules`
  271. );
  272. }
  273. if (rule.oneOf) {
  274. newRule.oneOf = RuleSet.normalizeRules(
  275. rule.oneOf,
  276. refs,
  277. `${ident}-oneOf`
  278. );
  279. }
  280. const keys = Object.keys(rule).filter(key => {
  281. return ![
  282. "resource",
  283. "resourceQuery",
  284. "compiler",
  285. "test",
  286. "include",
  287. "exclude",
  288. "issuer",
  289. "loader",
  290. "options",
  291. "query",
  292. "loaders",
  293. "use",
  294. "rules",
  295. "oneOf"
  296. ].includes(key);
  297. });
  298. for (const key of keys) {
  299. newRule[key] = rule[key];
  300. }
  301. if (Array.isArray(newRule.use)) {
  302. for (const item of newRule.use) {
  303. if (item.ident) {
  304. refs[item.ident] = item.options;
  305. }
  306. }
  307. }
  308. return newRule;
  309. }
  310. static buildErrorMessage(condition, error) {
  311. const conditionAsText = JSON.stringify(
  312. condition,
  313. (key, value) => {
  314. return value === undefined ? "undefined" : value;
  315. },
  316. 2
  317. );
  318. return error.message + " in " + conditionAsText;
  319. }
  320. static normalizeUse(use, ident) {
  321. if (typeof use === "function") {
  322. return data => RuleSet.normalizeUse(use(data), ident);
  323. }
  324. if (Array.isArray(use)) {
  325. return use
  326. .map((item, idx) => RuleSet.normalizeUse(item, `${ident}-${idx}`))
  327. .reduce((arr, items) => arr.concat(items), []);
  328. }
  329. return [RuleSet.normalizeUseItem(use, ident)];
  330. }
  331. static normalizeUseItemString(useItemString) {
  332. const idx = useItemString.indexOf("?");
  333. if (idx >= 0) {
  334. return {
  335. loader: useItemString.substr(0, idx),
  336. options: useItemString.substr(idx + 1)
  337. };
  338. }
  339. return {
  340. loader: useItemString,
  341. options: undefined
  342. };
  343. }
  344. static normalizeUseItem(item, ident) {
  345. if (typeof item === "string") {
  346. return RuleSet.normalizeUseItemString(item);
  347. }
  348. const newItem = {};
  349. if (item.options && item.query) {
  350. throw new Error("Provided options and query in use");
  351. }
  352. if (!item.loader) {
  353. throw new Error("No loader specified");
  354. }
  355. newItem.options = item.options || item.query;
  356. if (typeof newItem.options === "object" && newItem.options) {
  357. if (newItem.options.ident) {
  358. newItem.ident = newItem.options.ident;
  359. } else {
  360. newItem.ident = ident;
  361. }
  362. }
  363. const keys = Object.keys(item).filter(function(key) {
  364. return !["options", "query"].includes(key);
  365. });
  366. for (const key of keys) {
  367. newItem[key] = item[key];
  368. }
  369. return newItem;
  370. }
  371. static normalizeCondition(condition) {
  372. if (!condition) throw new Error("Expected condition but got falsy value");
  373. if (typeof condition === "string") {
  374. return str => str.indexOf(condition) === 0;
  375. }
  376. if (typeof condition === "function") {
  377. return condition;
  378. }
  379. if (condition instanceof RegExp) {
  380. return condition.test.bind(condition);
  381. }
  382. if (Array.isArray(condition)) {
  383. const items = condition.map(c => RuleSet.normalizeCondition(c));
  384. return orMatcher(items);
  385. }
  386. if (typeof condition !== "object") {
  387. throw Error(
  388. "Unexcepted " +
  389. typeof condition +
  390. " when condition was expected (" +
  391. condition +
  392. ")"
  393. );
  394. }
  395. const matchers = [];
  396. Object.keys(condition).forEach(key => {
  397. const value = condition[key];
  398. switch (key) {
  399. case "or":
  400. case "include":
  401. case "test":
  402. if (value) matchers.push(RuleSet.normalizeCondition(value));
  403. break;
  404. case "and":
  405. if (value) {
  406. const items = value.map(c => RuleSet.normalizeCondition(c));
  407. matchers.push(andMatcher(items));
  408. }
  409. break;
  410. case "not":
  411. case "exclude":
  412. if (value) {
  413. const matcher = RuleSet.normalizeCondition(value);
  414. matchers.push(notMatcher(matcher));
  415. }
  416. break;
  417. default:
  418. throw new Error("Unexcepted property " + key + " in condition");
  419. }
  420. });
  421. if (matchers.length === 0) {
  422. throw new Error("Excepted condition but got " + condition);
  423. }
  424. if (matchers.length === 1) {
  425. return matchers[0];
  426. }
  427. return andMatcher(matchers);
  428. }
  429. exec(data) {
  430. const result = [];
  431. this._run(
  432. data,
  433. {
  434. rules: this.rules
  435. },
  436. result
  437. );
  438. return result;
  439. }
  440. _run(data, rule, result) {
  441. // test conditions
  442. if (rule.resource && !data.resource) return false;
  443. if (rule.realResource && !data.realResource) return false;
  444. if (rule.resourceQuery && !data.resourceQuery) return false;
  445. if (rule.compiler && !data.compiler) return false;
  446. if (rule.issuer && !data.issuer) return false;
  447. if (rule.resource && !rule.resource(data.resource)) return false;
  448. if (rule.realResource && !rule.realResource(data.realResource))
  449. return false;
  450. if (data.issuer && rule.issuer && !rule.issuer(data.issuer)) return false;
  451. if (
  452. data.resourceQuery &&
  453. rule.resourceQuery &&
  454. !rule.resourceQuery(data.resourceQuery)
  455. ) {
  456. return false;
  457. }
  458. if (data.compiler && rule.compiler && !rule.compiler(data.compiler)) {
  459. return false;
  460. }
  461. // apply
  462. const keys = Object.keys(rule).filter(key => {
  463. return ![
  464. "resource",
  465. "realResource",
  466. "resourceQuery",
  467. "compiler",
  468. "issuer",
  469. "rules",
  470. "oneOf",
  471. "use",
  472. "enforce"
  473. ].includes(key);
  474. });
  475. for (const key of keys) {
  476. result.push({
  477. type: key,
  478. value: rule[key]
  479. });
  480. }
  481. if (rule.use) {
  482. const process = use => {
  483. if (typeof use === "function") {
  484. process(use(data));
  485. } else if (Array.isArray(use)) {
  486. use.forEach(process);
  487. } else {
  488. result.push({
  489. type: "use",
  490. value: use,
  491. enforce: rule.enforce
  492. });
  493. }
  494. };
  495. process(rule.use);
  496. }
  497. if (rule.rules) {
  498. for (let i = 0; i < rule.rules.length; i++) {
  499. this._run(data, rule.rules[i], result);
  500. }
  501. }
  502. if (rule.oneOf) {
  503. for (let i = 0; i < rule.oneOf.length; i++) {
  504. if (this._run(data, rule.oneOf[i], result)) break;
  505. }
  506. }
  507. return true;
  508. }
  509. findOptionsByIdent(ident) {
  510. const options = this.references[ident];
  511. if (!options) {
  512. throw new Error("Can't find options with ident '" + ident + "'");
  513. }
  514. return options;
  515. }
  516. };