index.js 9.6 KB

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