targets-parser.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. const browserslist = require('browserslist');
  3. const { compare, has } = require('./helpers');
  4. const external = require('./external');
  5. const aliases = new Map([
  6. ['and_chr', 'chrome'],
  7. ['and_ff', 'firefox'],
  8. ['ie_mob', 'ie'],
  9. ['ios_saf', 'ios'],
  10. ['op_mob', 'opera_mobile'],
  11. ]);
  12. const validTargets = new Set([
  13. 'android',
  14. 'bun',
  15. 'chrome',
  16. 'deno',
  17. 'edge',
  18. 'electron',
  19. 'firefox',
  20. 'hermes',
  21. 'ie',
  22. 'ios',
  23. 'node',
  24. 'oculus',
  25. 'opera',
  26. 'opera_mobile',
  27. 'phantom',
  28. 'rhino',
  29. 'safari',
  30. 'samsung',
  31. ]);
  32. const toLowerKeys = function (object) {
  33. return Object.entries(object).reduce((accumulator, [key, value]) => {
  34. accumulator[key.toLowerCase()] = value;
  35. return accumulator;
  36. }, {});
  37. };
  38. module.exports = function (targets) {
  39. const { browsers, esmodules, node, ...rest } = (typeof targets != 'object' || Array.isArray(targets))
  40. ? { browsers: targets } : toLowerKeys(targets);
  41. const list = Object.entries(rest);
  42. if (browsers) {
  43. if (typeof browsers == 'string' || Array.isArray(browsers)) {
  44. list.push(...browserslist(browsers).map(it => it.split(' ')));
  45. } else {
  46. list.push(...Object.entries(browsers));
  47. }
  48. }
  49. if (esmodules) {
  50. list.push(...Object.entries(external.modules));
  51. }
  52. if (node) {
  53. list.push(['node', node === 'current' ? process.versions.node : node]);
  54. }
  55. const normalized = list.map(([engine, version]) => {
  56. if (has(browserslist.aliases, engine)) {
  57. engine = browserslist.aliases[engine];
  58. }
  59. if (aliases.has(engine)) {
  60. engine = aliases.get(engine);
  61. }
  62. return [engine, String(version)];
  63. }).filter(([engine]) => {
  64. return validTargets.has(engine);
  65. }).sort(([a], [b]) => {
  66. return a < b ? -1 : a > b ? 1 : 0;
  67. });
  68. const reducedByMinVersion = new Map();
  69. for (const [engine, version] of normalized) {
  70. if (!reducedByMinVersion.has(engine) || compare(version, '<=', reducedByMinVersion.get(engine))) {
  71. reducedByMinVersion.set(engine, version);
  72. }
  73. }
  74. return reducedByMinVersion;
  75. };