compat.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. const { compare, filterOutStabilizedProposals, has, intersection } = require('./helpers');
  3. const data = require('./data');
  4. const entries = require('./entries');
  5. const getModulesListForTargetVersion = require('./get-modules-list-for-target-version');
  6. const allModules = require('./modules');
  7. const targetsParser = require('./targets-parser');
  8. function throwInvalidFilter(filter) {
  9. throw new TypeError(`Specified invalid module name or pattern: ${ filter }`);
  10. }
  11. function atLeastSomeModules(modules, filter) {
  12. if (!modules.length) throwInvalidFilter(filter);
  13. return modules;
  14. }
  15. function getModules(filter) {
  16. if (typeof filter == 'string') {
  17. if (has(entries, filter)) return entries[filter];
  18. return atLeastSomeModules(allModules.filter(it => it.startsWith(filter)), filter);
  19. } else if (filter instanceof RegExp) return atLeastSomeModules(allModules.filter(it => filter.test(it)), filter);
  20. throwInvalidFilter(filter);
  21. }
  22. function normalizeModules(option) {
  23. // TODO: use `.flatMap` in core-js@4
  24. return new Set(Array.isArray(option) ? [].concat(...option.map(getModules)) : getModules(option));
  25. }
  26. function checkModule(name, targets) {
  27. const result = {
  28. required: !targets,
  29. targets: {},
  30. };
  31. if (!targets) return result;
  32. const requirements = data[name];
  33. for (const [engine, version] of targets) {
  34. if (!has(requirements, engine) || compare(version, '<', requirements[engine])) {
  35. result.required = true;
  36. result.targets[engine] = version;
  37. }
  38. }
  39. return result;
  40. }
  41. module.exports = function ({
  42. filter = null, // TODO: Obsolete, remove from `core-js@4`
  43. modules = null,
  44. exclude = [],
  45. targets = null,
  46. version = null,
  47. inverse = false,
  48. } = {}) {
  49. if (modules === null || modules === undefined) modules = filter;
  50. inverse = !!inverse;
  51. const parsedTargets = targets ? targetsParser(targets) : null;
  52. const result = {
  53. list: [],
  54. targets: {},
  55. };
  56. exclude = normalizeModules(exclude);
  57. modules = modules ? [...normalizeModules(modules)] : allModules;
  58. if (exclude.size) modules = modules.filter(it => !exclude.has(it));
  59. modules = intersection(modules, version ? getModulesListForTargetVersion(version) : allModules);
  60. if (!inverse) modules = filterOutStabilizedProposals(modules);
  61. for (const key of modules) {
  62. const check = checkModule(key, parsedTargets);
  63. if (check.required ^ inverse) {
  64. result.list.push(key);
  65. result.targets[key] = check.targets;
  66. }
  67. }
  68. return result;
  69. };