compat.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 getModules(filter) {
  9. if (typeof filter == 'string') {
  10. if (has(entries, filter)) return entries[filter];
  11. return allModules.filter(it => it.startsWith(filter));
  12. } else if (filter instanceof RegExp) return allModules.filter(it => filter.test(it));
  13. throw TypeError('Wrong filter!');
  14. }
  15. function normalizeModules(option) {
  16. // TODO: use `.flatMap` in core-js@4
  17. return new Set(Array.isArray(option) ? [].concat.apply([], option.map(getModules)) : getModules(option));
  18. }
  19. function checkModule(name, targets) {
  20. const result = {
  21. required: !targets,
  22. targets: {},
  23. };
  24. if (!targets) return result;
  25. const requirements = data[name];
  26. for (const [engine, version] of targets) {
  27. if (!has(requirements, engine) || compare(version, '<', requirements[engine])) {
  28. result.required = true;
  29. result.targets[engine] = version;
  30. }
  31. }
  32. return result;
  33. }
  34. module.exports = function ({
  35. filter = null, // TODO: Obsolete, remove from `core-js@4`
  36. modules = null,
  37. exclude = [],
  38. targets = null,
  39. version = null,
  40. } = {}) {
  41. if (modules == null) modules = filter;
  42. const parsedTargets = targets ? targetsParser(targets) : null;
  43. const result = {
  44. list: [],
  45. targets: {},
  46. };
  47. exclude = normalizeModules(exclude);
  48. modules = modules ? [...normalizeModules(modules)] : allModules;
  49. if (exclude.size) modules = modules.filter(it => !exclude.has(it));
  50. modules = intersection(modules, version ? getModulesListForTargetVersion(version) : allModules);
  51. modules = filterOutStabilizedProposals(modules);
  52. for (const key of modules) {
  53. const check = checkModule(key, parsedTargets);
  54. if (check.required) {
  55. result.list.push(key);
  56. result.targets[key] = check.targets;
  57. }
  58. }
  59. return result;
  60. };