browsers.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. let browserslist = require('browserslist')
  2. let { agents } = require('caniuse-lite/dist/unpacker/agents')
  3. let utils = require('./utils')
  4. class Browsers {
  5. constructor(data, requirements, options, browserslistOpts) {
  6. this.data = data
  7. this.options = options || {}
  8. this.browserslistOpts = browserslistOpts || {}
  9. this.selected = this.parse(requirements)
  10. }
  11. /**
  12. * Return all prefixes for default browser data
  13. */
  14. static prefixes() {
  15. if (this.prefixesCache) {
  16. return this.prefixesCache
  17. }
  18. this.prefixesCache = []
  19. for (let name in agents) {
  20. this.prefixesCache.push(`-${agents[name].prefix}-`)
  21. }
  22. this.prefixesCache = utils
  23. .uniq(this.prefixesCache)
  24. .sort((a, b) => b.length - a.length)
  25. return this.prefixesCache
  26. }
  27. /**
  28. * Check is value contain any possible prefix
  29. */
  30. static withPrefix(value) {
  31. if (!this.prefixesRegexp) {
  32. this.prefixesRegexp = new RegExp(this.prefixes().join('|'))
  33. }
  34. return this.prefixesRegexp.test(value)
  35. }
  36. /**
  37. * Is browser is selected by requirements
  38. */
  39. isSelected(browser) {
  40. return this.selected.includes(browser)
  41. }
  42. /**
  43. * Return browsers selected by requirements
  44. */
  45. parse(requirements) {
  46. let opts = {}
  47. for (let i in this.browserslistOpts) {
  48. opts[i] = this.browserslistOpts[i]
  49. }
  50. opts.path = this.options.from
  51. return browserslist(requirements, opts)
  52. }
  53. /**
  54. * Return prefix for selected browser
  55. */
  56. prefix(browser) {
  57. let [name, version] = browser.split(' ')
  58. let data = this.data[name]
  59. let prefix = data.prefix_exceptions && data.prefix_exceptions[version]
  60. if (!prefix) {
  61. prefix = data.prefix
  62. }
  63. return `-${prefix}-`
  64. }
  65. }
  66. module.exports = Browsers