index.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. let { writeFileSync, readFileSync, existsSync } = require('fs')
  2. let { execSync } = require('child_process')
  3. let { join } = require('path')
  4. let escalade = require('escalade/sync')
  5. let pico = require('picocolors')
  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 = join(packageDir, 'package-lock.json')
  31. let lockfileShrinkwrap = join(packageDir, 'npm-shrinkwrap.json')
  32. let lockfileYarn = join(packageDir, 'yarn.lock')
  33. let lockfilePnpm = join(packageDir, 'pnpm-lock.yaml')
  34. if (existsSync(lockfilePnpm)) {
  35. return { mode: 'pnpm', file: lockfilePnpm }
  36. } else if (existsSync(lockfileNpm)) {
  37. return { mode: 'npm', file: lockfileNpm }
  38. } else if (existsSync(lockfileYarn)) {
  39. let lock = { mode: 'yarn', file: lockfileYarn }
  40. lock.content = readFileSync(lock.file).toString()
  41. lock.version = /# yarn lockfile v1/.test(lock.content) ? 1 : 2
  42. return lock
  43. } else if (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(execSync('yarn info caniuse-lite --json').toString())
  54. .data
  55. } else {
  56. return JSON.parse(
  57. execSync('yarn npm info caniuse-lite --json').toString()
  58. )
  59. }
  60. }
  61. if (lock.mode === 'pnpm') {
  62. return JSON.parse(execSync('pnpm info caniuse-lite --json').toString())
  63. }
  64. return JSON.parse(execSync('npm show caniuse-lite --json').toString())
  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. if (node.packages) {
  112. for (let path in node.packages) {
  113. if (path.endsWith('/caniuse-lite')) {
  114. metadata.versions[node.packages[path].version] = true
  115. delete node.packages[path]
  116. }
  117. }
  118. }
  119. return node
  120. }
  121. let yarnVersionRe = /version "(.*?)"/
  122. function updateYarnLockfile(lock, latest) {
  123. let blocks = lock.content.split(/(\n{2,})/).map(block => {
  124. return block.split('\n')
  125. })
  126. let versions = {}
  127. blocks.forEach(lines => {
  128. if (lines[0].indexOf('caniuse-lite@') !== -1) {
  129. let match = yarnVersionRe.exec(lines[1])
  130. versions[match[1]] = true
  131. if (match[1] !== latest.version) {
  132. lines[1] = lines[1].replace(
  133. /version "[^"]+"/,
  134. 'version "' + latest.version + '"'
  135. )
  136. lines[2] = lines[2].replace(
  137. /resolved "[^"]+"/,
  138. 'resolved "' + latest.dist.tarball + '"'
  139. )
  140. if (lines.length === 4) {
  141. lines[3] = latest.dist.integrity
  142. ? lines[3].replace(
  143. /integrity .+/,
  144. 'integrity ' + latest.dist.integrity
  145. )
  146. : ''
  147. }
  148. }
  149. }
  150. })
  151. let content = blocks.map(lines => lines.join('\n')).join('')
  152. return { content, versions }
  153. }
  154. function updateLockfile(lock, latest) {
  155. if (!lock.content) lock.content = readFileSync(lock.file).toString()
  156. let updatedLockFile
  157. if (lock.mode === 'yarn') {
  158. updatedLockFile = updateYarnLockfile(lock, latest)
  159. } else {
  160. updatedLockFile = updateNpmLockfile(lock, latest)
  161. }
  162. updatedLockFile.content = updatedLockFile.content.replace(
  163. /\n/g,
  164. detectEOL(lock.content)
  165. )
  166. return updatedLockFile
  167. }
  168. function updatePackageManually(print, lock, latest) {
  169. let lockfileData = updateLockfile(lock, latest)
  170. let caniuseVersions = Object.keys(lockfileData.versions).sort()
  171. if (caniuseVersions.length === 1 && caniuseVersions[0] === latest.version) {
  172. print(
  173. 'Installed version: ' +
  174. pico.bold(pico.green(caniuseVersions[0])) +
  175. '\n' +
  176. pico.bold(pico.green('caniuse-lite is up to date')) +
  177. '\n'
  178. )
  179. return
  180. }
  181. if (caniuseVersions.length === 0) {
  182. caniuseVersions[0] = 'none'
  183. }
  184. print(
  185. 'Installed version' +
  186. (caniuseVersions.length === 1 ? ': ' : 's: ') +
  187. pico.bold(pico.red(caniuseVersions.join(', '))) +
  188. '\n' +
  189. 'Removing old caniuse-lite from lock file\n'
  190. )
  191. writeFileSync(lock.file, lockfileData.content)
  192. let install = lock.mode === 'yarn' ? 'yarn add -W' : lock.mode + ' install'
  193. print(
  194. 'Installing new caniuse-lite version\n' +
  195. pico.yellow('$ ' + install + ' caniuse-lite') +
  196. '\n'
  197. )
  198. try {
  199. execSync(install + ' caniuse-lite')
  200. } catch (e) /* c8 ignore start */ {
  201. print(
  202. pico.red(
  203. '\n' +
  204. e.stack +
  205. '\n\n' +
  206. 'Problem with `' +
  207. install +
  208. ' caniuse-lite` call. ' +
  209. 'Run it manually.\n'
  210. )
  211. )
  212. process.exit(1)
  213. } /* c8 ignore end */
  214. let del = lock.mode === 'yarn' ? 'yarn remove -W' : lock.mode + ' uninstall'
  215. print(
  216. 'Cleaning package.json dependencies from caniuse-lite\n' +
  217. pico.yellow('$ ' + del + ' caniuse-lite') +
  218. '\n'
  219. )
  220. execSync(del + ' caniuse-lite')
  221. }
  222. function updateWith(print, cmd) {
  223. print('Updating caniuse-lite version\n' + pico.yellow('$ ' + cmd) + '\n')
  224. try {
  225. execSync(cmd)
  226. } catch (e) /* c8 ignore start */ {
  227. print(pico.red(e.stdout.toString()))
  228. print(
  229. pico.red(
  230. '\n' +
  231. e.stack +
  232. '\n\n' +
  233. 'Problem with `' +
  234. cmd +
  235. '` call. ' +
  236. 'Run it manually.\n'
  237. )
  238. )
  239. process.exit(1)
  240. } /* c8 ignore end */
  241. }
  242. module.exports = function updateDB(print = defaultPrint) {
  243. let lock = detectLockfile()
  244. let latest = getLatestInfo(lock)
  245. let listError
  246. let oldList
  247. try {
  248. oldList = getBrowsers()
  249. } catch (e) {
  250. listError = e
  251. }
  252. print('Latest version: ' + pico.bold(pico.green(latest.version)) + '\n')
  253. if (lock.mode === 'yarn' && lock.version !== 1) {
  254. updateWith(print, 'yarn up -R caniuse-lite')
  255. } else if (lock.mode === 'pnpm') {
  256. updateWith(print, 'pnpm up caniuse-lite')
  257. } else {
  258. updatePackageManually(print, lock, latest)
  259. }
  260. print('caniuse-lite has been successfully updated\n')
  261. let newList
  262. if (!listError) {
  263. try {
  264. newList = getBrowsers()
  265. } catch (e) /* c8 ignore start */ {
  266. listError = e
  267. } /* c8 ignore end */
  268. }
  269. if (listError) {
  270. print(
  271. pico.red(
  272. '\n' +
  273. listError.stack +
  274. '\n\n' +
  275. 'Problem with browser list retrieval.\n' +
  276. 'Target browser changes won’t be shown.\n'
  277. )
  278. )
  279. } else {
  280. let changes = diffBrowsers(oldList, newList)
  281. if (changes) {
  282. print('\nTarget browser changes:\n')
  283. print(changes + '\n')
  284. } else {
  285. print('\n' + pico.green('No target browser changes') + '\n')
  286. }
  287. }
  288. }