node.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. var feature = require('caniuse-lite/dist/unpacker/feature').default
  2. var region = require('caniuse-lite/dist/unpacker/region').default
  3. var path = require('path')
  4. var fs = require('fs')
  5. var BrowserslistError = require('./error')
  6. var IS_SECTION = /^\s*\[(.+)]\s*$/
  7. var CONFIG_PATTERN = /^browserslist-config-/
  8. var SCOPED_CONFIG__PATTERN = /@[^/]+\/browserslist-config(-|$|\/)/
  9. var TIME_TO_UPDATE_CANIUSE = 6 * 30 * 24 * 60 * 60 * 1000
  10. var FORMAT =
  11. 'Browserslist config should be a string or an array ' +
  12. 'of strings with browser queries'
  13. var dataTimeChecked = false
  14. var filenessCache = {}
  15. var configCache = {}
  16. function checkExtend(name) {
  17. var use = ' Use `dangerousExtend` option to disable.'
  18. if (!CONFIG_PATTERN.test(name) && !SCOPED_CONFIG__PATTERN.test(name)) {
  19. throw new BrowserslistError(
  20. 'Browserslist config needs `browserslist-config-` prefix. ' + use
  21. )
  22. }
  23. if (name.replace(/^@[^/]+\//, '').indexOf('.') !== -1) {
  24. throw new BrowserslistError(
  25. '`.` not allowed in Browserslist config name. ' + use
  26. )
  27. }
  28. if (name.indexOf('node_modules') !== -1) {
  29. throw new BrowserslistError(
  30. '`node_modules` not allowed in Browserslist config.' + use
  31. )
  32. }
  33. }
  34. function isFile(file) {
  35. if (file in filenessCache) {
  36. return filenessCache[file]
  37. }
  38. var result = fs.existsSync(file) && fs.statSync(file).isFile()
  39. if (!process.env.BROWSERSLIST_DISABLE_CACHE) {
  40. filenessCache[file] = result
  41. }
  42. return result
  43. }
  44. function eachParent(file, callback) {
  45. var dir = isFile(file) ? path.dirname(file) : file
  46. var loc = path.resolve(dir)
  47. do {
  48. var result = callback(loc)
  49. if (typeof result !== 'undefined') return result
  50. } while (loc !== (loc = path.dirname(loc)))
  51. return undefined
  52. }
  53. function check(section) {
  54. if (Array.isArray(section)) {
  55. for (var i = 0; i < section.length; i++) {
  56. if (typeof section[i] !== 'string') {
  57. throw new BrowserslistError(FORMAT)
  58. }
  59. }
  60. } else if (typeof section !== 'string') {
  61. throw new BrowserslistError(FORMAT)
  62. }
  63. }
  64. function pickEnv(config, opts) {
  65. if (typeof config !== 'object') return config
  66. var name
  67. if (typeof opts.env === 'string') {
  68. name = opts.env
  69. } else if (process.env.BROWSERSLIST_ENV) {
  70. name = process.env.BROWSERSLIST_ENV
  71. } else if (process.env.NODE_ENV) {
  72. name = process.env.NODE_ENV
  73. } else {
  74. name = 'production'
  75. }
  76. if (opts.throwOnMissing) {
  77. if (name && name !== 'defaults' && !config[name]) {
  78. throw new BrowserslistError(
  79. 'Missing config for Browserslist environment `' + name + '`'
  80. )
  81. }
  82. }
  83. return config[name] || config.defaults
  84. }
  85. function parsePackage(file) {
  86. var config = JSON.parse(
  87. fs
  88. .readFileSync(file)
  89. .toString()
  90. .replace(/^\uFEFF/m, '')
  91. )
  92. if (config.browserlist && !config.browserslist) {
  93. throw new BrowserslistError(
  94. '`browserlist` key instead of `browserslist` in ' + file
  95. )
  96. }
  97. var list = config.browserslist
  98. if (Array.isArray(list) || typeof list === 'string') {
  99. list = { defaults: list }
  100. }
  101. for (var i in list) {
  102. check(list[i])
  103. }
  104. return list
  105. }
  106. function latestReleaseTime(agents) {
  107. var latest = 0
  108. for (var name in agents) {
  109. var dates = agents[name].releaseDate || {}
  110. for (var key in dates) {
  111. if (latest < dates[key]) {
  112. latest = dates[key]
  113. }
  114. }
  115. }
  116. return latest * 1000
  117. }
  118. function normalizeStats(data, stats) {
  119. if (!data) {
  120. data = {}
  121. }
  122. if (stats && 'dataByBrowser' in stats) {
  123. stats = stats.dataByBrowser
  124. }
  125. if (typeof stats !== 'object') return undefined
  126. var normalized = {}
  127. for (var i in stats) {
  128. var versions = Object.keys(stats[i])
  129. if (versions.length === 1 && data[i] && data[i].versions.length === 1) {
  130. var normal = data[i].versions[0]
  131. normalized[i] = {}
  132. normalized[i][normal] = stats[i][versions[0]]
  133. } else {
  134. normalized[i] = stats[i]
  135. }
  136. }
  137. return normalized
  138. }
  139. function normalizeUsageData(usageData, data) {
  140. for (var browser in usageData) {
  141. var browserUsage = usageData[browser]
  142. // eslint-disable-next-line max-len
  143. // https://github.com/browserslist/browserslist/issues/431#issuecomment-565230615
  144. // caniuse-db returns { 0: "percentage" } for `and_*` regional stats
  145. if ('0' in browserUsage) {
  146. var versions = data[browser].versions
  147. browserUsage[versions[versions.length - 1]] = browserUsage[0]
  148. delete browserUsage[0]
  149. }
  150. }
  151. }
  152. module.exports = {
  153. loadQueries: function loadQueries(ctx, name) {
  154. if (!ctx.dangerousExtend && !process.env.BROWSERSLIST_DANGEROUS_EXTEND) {
  155. checkExtend(name)
  156. }
  157. var queries = require(require.resolve(name, { paths: ['.', ctx.path] }))
  158. if (queries) {
  159. if (Array.isArray(queries)) {
  160. return queries
  161. } else if (typeof queries === 'object') {
  162. if (!queries.defaults) queries.defaults = []
  163. return pickEnv(queries, ctx, name)
  164. }
  165. }
  166. throw new BrowserslistError(
  167. '`' +
  168. name +
  169. '` config exports not an array of queries' +
  170. ' or an object of envs'
  171. )
  172. },
  173. loadStat: function loadStat(ctx, name, data) {
  174. if (!ctx.dangerousExtend && !process.env.BROWSERSLIST_DANGEROUS_EXTEND) {
  175. checkExtend(name)
  176. }
  177. var stats = require(require.resolve(
  178. path.join(name, 'browserslist-stats.json'),
  179. { paths: ['.'] }
  180. ))
  181. return normalizeStats(data, stats)
  182. },
  183. getStat: function getStat(opts, data) {
  184. var stats
  185. if (opts.stats) {
  186. stats = opts.stats
  187. } else if (process.env.BROWSERSLIST_STATS) {
  188. stats = process.env.BROWSERSLIST_STATS
  189. } else if (opts.path && path.resolve && fs.existsSync) {
  190. stats = eachParent(opts.path, function (dir) {
  191. var file = path.join(dir, 'browserslist-stats.json')
  192. return isFile(file) ? file : undefined
  193. })
  194. }
  195. if (typeof stats === 'string') {
  196. try {
  197. stats = JSON.parse(fs.readFileSync(stats))
  198. } catch (e) {
  199. throw new BrowserslistError("Can't read " + stats)
  200. }
  201. }
  202. return normalizeStats(data, stats)
  203. },
  204. loadConfig: function loadConfig(opts) {
  205. if (process.env.BROWSERSLIST) {
  206. return process.env.BROWSERSLIST
  207. } else if (opts.config || process.env.BROWSERSLIST_CONFIG) {
  208. var file = opts.config || process.env.BROWSERSLIST_CONFIG
  209. if (path.basename(file) === 'package.json') {
  210. return pickEnv(parsePackage(file), opts)
  211. } else {
  212. return pickEnv(module.exports.readConfig(file), opts)
  213. }
  214. } else if (opts.path) {
  215. return pickEnv(module.exports.findConfig(opts.path), opts)
  216. } else {
  217. return undefined
  218. }
  219. },
  220. loadCountry: function loadCountry(usage, country, data) {
  221. var code = country.replace(/[^\w-]/g, '')
  222. if (!usage[code]) {
  223. var compressed = require('caniuse-lite/data/regions/' + code + '.js')
  224. var usageData = region(compressed)
  225. normalizeUsageData(usageData, data)
  226. usage[country] = {}
  227. for (var i in usageData) {
  228. for (var j in usageData[i]) {
  229. usage[country][i + ' ' + j] = usageData[i][j]
  230. }
  231. }
  232. }
  233. },
  234. loadFeature: function loadFeature(features, name) {
  235. name = name.replace(/[^\w-]/g, '')
  236. if (features[name]) return
  237. var compressed = require('caniuse-lite/data/features/' + name + '.js')
  238. var stats = feature(compressed).stats
  239. features[name] = {}
  240. for (var i in stats) {
  241. for (var j in stats[i]) {
  242. features[name][i + ' ' + j] = stats[i][j]
  243. }
  244. }
  245. },
  246. parseConfig: function parseConfig(string) {
  247. var result = { defaults: [] }
  248. var sections = ['defaults']
  249. string
  250. .toString()
  251. .replace(/#[^\n]*/g, '')
  252. .split(/\n|,/)
  253. .map(function (line) {
  254. return line.trim()
  255. })
  256. .filter(function (line) {
  257. return line !== ''
  258. })
  259. .forEach(function (line) {
  260. if (IS_SECTION.test(line)) {
  261. sections = line.match(IS_SECTION)[1].trim().split(' ')
  262. sections.forEach(function (section) {
  263. if (result[section]) {
  264. throw new BrowserslistError(
  265. 'Duplicate section ' + section + ' in Browserslist config'
  266. )
  267. }
  268. result[section] = []
  269. })
  270. } else {
  271. sections.forEach(function (section) {
  272. result[section].push(line)
  273. })
  274. }
  275. })
  276. return result
  277. },
  278. readConfig: function readConfig(file) {
  279. if (!isFile(file)) {
  280. throw new BrowserslistError("Can't read " + file + ' config')
  281. }
  282. return module.exports.parseConfig(fs.readFileSync(file))
  283. },
  284. findConfig: function findConfig(from) {
  285. from = path.resolve(from)
  286. var passed = []
  287. var resolved = eachParent(from, function (dir) {
  288. if (dir in configCache) {
  289. return configCache[dir]
  290. }
  291. passed.push(dir)
  292. var config = path.join(dir, 'browserslist')
  293. var pkg = path.join(dir, 'package.json')
  294. var rc = path.join(dir, '.browserslistrc')
  295. var pkgBrowserslist
  296. if (isFile(pkg)) {
  297. try {
  298. pkgBrowserslist = parsePackage(pkg)
  299. } catch (e) {
  300. if (e.name === 'BrowserslistError') throw e
  301. console.warn(
  302. '[Browserslist] Could not parse ' + pkg + '. Ignoring it.'
  303. )
  304. }
  305. }
  306. if (isFile(config) && pkgBrowserslist) {
  307. throw new BrowserslistError(
  308. dir + ' contains both browserslist and package.json with browsers'
  309. )
  310. } else if (isFile(rc) && pkgBrowserslist) {
  311. throw new BrowserslistError(
  312. dir + ' contains both .browserslistrc and package.json with browsers'
  313. )
  314. } else if (isFile(config) && isFile(rc)) {
  315. throw new BrowserslistError(
  316. dir + ' contains both .browserslistrc and browserslist'
  317. )
  318. } else if (isFile(config)) {
  319. return module.exports.readConfig(config)
  320. } else if (isFile(rc)) {
  321. return module.exports.readConfig(rc)
  322. } else {
  323. return pkgBrowserslist
  324. }
  325. })
  326. if (!process.env.BROWSERSLIST_DISABLE_CACHE) {
  327. passed.forEach(function (dir) {
  328. configCache[dir] = resolved
  329. })
  330. }
  331. return resolved
  332. },
  333. clearCaches: function clearCaches() {
  334. dataTimeChecked = false
  335. filenessCache = {}
  336. configCache = {}
  337. this.cache = {}
  338. },
  339. oldDataWarning: function oldDataWarning(agentsObj) {
  340. if (dataTimeChecked) return
  341. dataTimeChecked = true
  342. if (process.env.BROWSERSLIST_IGNORE_OLD_DATA) return
  343. var latest = latestReleaseTime(agentsObj)
  344. var halfYearAgo = Date.now() - TIME_TO_UPDATE_CANIUSE
  345. if (latest !== 0 && latest < halfYearAgo) {
  346. console.warn(
  347. 'Browserslist: caniuse-lite is outdated. Please run:\n' +
  348. ' npx update-browserslist-db@latest\n' +
  349. ' Why you should do it regularly: ' +
  350. 'https://github.com/browserslist/update-db#readme'
  351. )
  352. }
  353. },
  354. currentNode: function currentNode() {
  355. return 'node ' + process.versions.node
  356. }
  357. }