index.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. let childProcess = require('child_process')
  2. let escalade = require('escalade/sync')
  3. let pico = require('picocolors')
  4. let path = require('path')
  5. let fs = require('fs')
  6. const { detectIndent, detectEOL } = require('./utils')
  7. function BrowserslistUpdateError(message) {
  8. this.name = 'BrowserslistUpdateError'
  9. this.message = message
  10. this.browserslist = true
  11. if (Error.captureStackTrace) {
  12. Error.captureStackTrace(this, BrowserslistUpdateError)
  13. }
  14. }
  15. BrowserslistUpdateError.prototype = Error.prototype
  16. /* c8 ignore next 3 */
  17. function defaultPrint(str) {
  18. process.stdout.write(str)
  19. }
  20. function detectLockfile() {
  21. let packageDir = escalade('.', (dir, names) => {
  22. return names.indexOf('package.json') !== -1 ? dir : ''
  23. })
  24. if (!packageDir) {
  25. throw new BrowserslistUpdateError(
  26. 'Cannot find package.json. ' +
  27. 'Is this the right directory to run `npx update-browserslist-db` in?'
  28. )
  29. }
  30. let lockfileNpm = path.join(packageDir, 'package-lock.json')
  31. let lockfileShrinkwrap = path.join(packageDir, 'npm-shrinkwrap.json')
  32. let lockfileYarn = path.join(packageDir, 'yarn.lock')
  33. let lockfilePnpm = path.join(packageDir, 'pnpm-lock.yaml')
  34. if (fs.existsSync(lockfilePnpm)) {
  35. return { mode: 'pnpm', file: lockfilePnpm }
  36. } else if (fs.existsSync(lockfileNpm)) {
  37. return { mode: 'npm', file: lockfileNpm }
  38. } else if (fs.existsSync(lockfileYarn)) {
  39. let lock = { mode: 'yarn', file: lockfileYarn }
  40. lock.content = fs.readFileSync(lock.file).toString()
  41. lock.version = /# yarn lockfile v1/.test(lock.content) ? 1 : 2
  42. return lock
  43. } else if (fs.existsSync(lockfileShrinkwrap)) {
  44. return { mode: 'npm', file: lockfileShrinkwrap }
  45. }
  46. throw new BrowserslistUpdateError(
  47. 'No lockfile found. Run "npm install", "yarn install" or "pnpm install"'
  48. )
  49. }
  50. function getLatestInfo(lock) {
  51. if (lock.mode === 'yarn') {
  52. if (lock.version === 1) {
  53. return JSON.parse(
  54. childProcess.execSync('yarn info caniuse-lite --json').toString()
  55. ).data
  56. } else {
  57. return JSON.parse(
  58. childProcess.execSync('yarn npm info caniuse-lite --json').toString()
  59. )
  60. }
  61. }
  62. return JSON.parse(
  63. childProcess.execSync('npm show caniuse-lite --json').toString()
  64. )
  65. }
  66. function getBrowsers() {
  67. let browserslist = require('browserslist')
  68. return browserslist().reduce((result, entry) => {
  69. if (!result[entry[0]]) {
  70. result[entry[0]] = []
  71. }
  72. result[entry[0]].push(entry[1])
  73. return result
  74. }, {})
  75. }
  76. function diffBrowsers(old, current) {
  77. let browsers = Object.keys(old).concat(
  78. Object.keys(current).filter(browser => old[browser] === undefined)
  79. )
  80. return browsers
  81. .map(browser => {
  82. let oldVersions = old[browser] || []
  83. let currentVersions = current[browser] || []
  84. let common = oldVersions.filter(v => currentVersions.includes(v))
  85. let added = currentVersions.filter(v => !common.includes(v))
  86. let removed = oldVersions.filter(v => !common.includes(v))
  87. return removed
  88. .map(v => pico.red('- ' + browser + ' ' + v))
  89. .concat(added.map(v => pico.green('+ ' + browser + ' ' + v)))
  90. })
  91. .reduce((result, array) => result.concat(array), [])
  92. .join('\n')
  93. }
  94. function updateNpmLockfile(lock, latest) {
  95. let metadata = { latest, versions: [] }
  96. let content = deletePackage(JSON.parse(lock.content), metadata)
  97. metadata.content = JSON.stringify(content, null, detectIndent(lock.content))
  98. return metadata
  99. }
  100. function deletePackage(node, metadata) {
  101. if (node.dependencies) {
  102. if (node.dependencies['caniuse-lite']) {
  103. let version = node.dependencies['caniuse-lite'].version
  104. metadata.versions[version] = true
  105. delete node.dependencies['caniuse-lite']
  106. }
  107. for (let i in node.dependencies) {
  108. node.dependencies[i] = deletePackage(node.dependencies[i], metadata)
  109. }
  110. }
  111. return node
  112. }
  113. let yarnVersionRe = /version "(.*?)"/
  114. function updateYarnLockfile(lock, latest) {
  115. let blocks = lock.content.split(/(\n{2,})/).map(block => {
  116. return block.split('\n')
  117. })
  118. let versions = {}
  119. blocks.forEach(lines => {
  120. if (lines[0].indexOf('caniuse-lite@') !== -1) {
  121. let match = yarnVersionRe.exec(lines[1])
  122. versions[match[1]] = true
  123. if (match[1] !== latest.version) {
  124. lines[1] = lines[1].replace(
  125. /version "[^"]+"/,
  126. 'version "' + latest.version + '"'
  127. )
  128. lines[2] = lines[2].replace(
  129. /resolved "[^"]+"/,
  130. 'resolved "' + latest.dist.tarball + '"'
  131. )
  132. if (lines.length === 4) {
  133. lines[3] = latest.dist.integrity
  134. ? lines[3].replace(
  135. /integrity .+/,
  136. 'integrity ' + latest.dist.integrity
  137. )
  138. : ''
  139. }
  140. }
  141. }
  142. })
  143. let content = blocks.map(lines => lines.join('\n')).join('')
  144. return { content, versions }
  145. }
  146. function updateLockfile(lock, latest) {
  147. if (!lock.content) lock.content = fs.readFileSync(lock.file).toString()
  148. let updatedLockFile
  149. if (lock.mode === 'yarn') {
  150. updatedLockFile = updateYarnLockfile(lock, latest)
  151. } else {
  152. updatedLockFile = updateNpmLockfile(lock, latest)
  153. }
  154. updatedLockFile.content = updatedLockFile.content.replace(
  155. /\n/g,
  156. detectEOL(lock.content)
  157. )
  158. return updatedLockFile
  159. }
  160. function updatePackageManually(print, lock, latest) {
  161. let lockfileData = updateLockfile(lock, latest)
  162. let caniuseVersions = Object.keys(lockfileData.versions).sort()
  163. if (caniuseVersions.length === 1 && caniuseVersions[0] === latest.version) {
  164. print(
  165. 'Installed version: ' +
  166. pico.bold(pico.green(latest.version)) +
  167. '\n' +
  168. pico.bold(pico.green('caniuse-lite is up to date')) +
  169. '\n'
  170. )
  171. return
  172. }
  173. if (caniuseVersions.length === 0) {
  174. caniuseVersions[0] = 'none'
  175. }
  176. print(
  177. 'Installed version' +
  178. (caniuseVersions.length === 1 ? ': ' : 's: ') +
  179. pico.bold(pico.red(caniuseVersions.join(', '))) +
  180. '\n' +
  181. 'Removing old caniuse-lite from lock file\n'
  182. )
  183. fs.writeFileSync(lock.file, lockfileData.content)
  184. let install = lock.mode === 'yarn' ? 'yarn add -W' : lock.mode + ' install'
  185. print(
  186. 'Installing new caniuse-lite version\n' +
  187. pico.yellow('$ ' + install + ' caniuse-lite') +
  188. '\n'
  189. )
  190. try {
  191. childProcess.execSync(install + ' caniuse-lite')
  192. } catch (e) /* c8 ignore start */ {
  193. print(
  194. pico.red(
  195. '\n' +
  196. e.stack +
  197. '\n\n' +
  198. 'Problem with `' +
  199. install +
  200. ' caniuse-lite` call. ' +
  201. 'Run it manually.\n'
  202. )
  203. )
  204. process.exit(1)
  205. } /* c8 ignore end */
  206. let del = lock.mode === 'yarn' ? 'yarn remove -W' : lock.mode + ' uninstall'
  207. print(
  208. 'Cleaning package.json dependencies from caniuse-lite\n' +
  209. pico.yellow('$ ' + del + ' caniuse-lite') +
  210. '\n'
  211. )
  212. childProcess.execSync(del + ' caniuse-lite')
  213. }
  214. function updateWith(print, cmd) {
  215. print('Updating caniuse-lite version\n' + pico.yellow('$ ' + cmd) + '\n')
  216. try {
  217. childProcess.execSync(cmd)
  218. } catch (e) /* c8 ignore start */ {
  219. print(pico.red(e.stdout.toString()))
  220. print(
  221. pico.red(
  222. '\n' +
  223. e.stack +
  224. '\n\n' +
  225. 'Problem with `' +
  226. cmd +
  227. '` call. ' +
  228. 'Run it manually.\n'
  229. )
  230. )
  231. process.exit(1)
  232. } /* c8 ignore end */
  233. }
  234. module.exports = function updateDB(print = defaultPrint) {
  235. let lock = detectLockfile()
  236. let latest = getLatestInfo(lock)
  237. let listError
  238. let oldList
  239. try {
  240. oldList = getBrowsers()
  241. } catch (e) {
  242. listError = e
  243. }
  244. print('Latest version: ' + pico.bold(pico.green(latest.version)) + '\n')
  245. if (lock.mode === 'yarn' && lock.version !== 1) {
  246. updateWith(print, 'yarn up -R caniuse-lite')
  247. } else if (lock.mode === 'pnpm') {
  248. updateWith(print, 'pnpm up caniuse-lite')
  249. } else {
  250. updatePackageManually(print, lock, latest)
  251. }
  252. print('caniuse-lite has been successfully updated\n')
  253. let newList
  254. if (!listError) {
  255. try {
  256. newList = getBrowsers()
  257. } catch (e) /* c8 ignore start */ {
  258. listError = e
  259. } /* c8 ignore end */
  260. }
  261. if (listError) {
  262. print(
  263. pico.red(
  264. '\n' +
  265. listError.stack +
  266. '\n\n' +
  267. 'Problem with browser list retrieval.\n' +
  268. 'Target browser changes won’t be shown.\n'
  269. )
  270. )
  271. } else {
  272. let changes = diffBrowsers(oldList, newList)
  273. if (changes) {
  274. print('\nTarget browser changes:\n')
  275. print(changes + '\n')
  276. } else {
  277. print('\n' + pico.green('No target browser changes') + '\n')
  278. }
  279. }
  280. }