cache.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. const fs = require('node:fs/promises')
  2. const { join } = require('node:path')
  3. const cacache = require('cacache')
  4. const pacote = require('pacote')
  5. const semver = require('semver')
  6. const npa = require('npm-package-arg')
  7. const jsonParse = require('json-parse-even-better-errors')
  8. const localeCompare = require('@isaacs/string-locale-compare')('en')
  9. const { log, output } = require('proc-log')
  10. const PkgJson = require('@npmcli/package-json')
  11. const abbrev = require('abbrev')
  12. const BaseCommand = require('../base-cmd.js')
  13. const searchCachePackage = async (path, parsed, cacheKeys) => {
  14. const searchMFH = new RegExp(`^make-fetch-happen:request-cache:.*(?<!/[@a-zA-Z]+)/${parsed.name}/-/(${parsed.name}[^/]+.tgz)$`)
  15. const searchPack = new RegExp(`^make-fetch-happen:request-cache:.*/${parsed.escapedName}$`)
  16. const results = new Set()
  17. cacheKeys = new Set(cacheKeys)
  18. for (const key of cacheKeys) {
  19. // match on the public key registry url format
  20. if (searchMFH.test(key)) {
  21. // extract the version from the filename
  22. const filename = key.match(searchMFH)[1]
  23. const noExt = filename.slice(0, -4)
  24. const noScope = `${parsed.name.split('/').pop()}-`
  25. const ver = noExt.slice(noScope.length)
  26. if (semver.satisfies(ver, parsed.rawSpec)) {
  27. results.add(key)
  28. }
  29. continue
  30. }
  31. // is this key a packument?
  32. if (!searchPack.test(key)) {
  33. continue
  34. }
  35. results.add(key)
  36. let packument, details
  37. try {
  38. details = await cacache.get(path, key)
  39. packument = jsonParse(details.data)
  40. } catch {
  41. // if we couldn't parse the packument, abort
  42. continue
  43. }
  44. if (!packument.versions || typeof packument.versions !== 'object') {
  45. continue
  46. }
  47. // assuming this is a packument
  48. for (const ver of Object.keys(packument.versions)) {
  49. if (semver.satisfies(ver, parsed.rawSpec)) {
  50. if (packument.versions[ver].dist &&
  51. typeof packument.versions[ver].dist === 'object' &&
  52. packument.versions[ver].dist.tarball !== undefined &&
  53. cacheKeys.has(`make-fetch-happen:request-cache:${packument.versions[ver].dist.tarball}`)
  54. ) {
  55. results.add(`make-fetch-happen:request-cache:${packument.versions[ver].dist.tarball}`)
  56. }
  57. }
  58. }
  59. }
  60. return results
  61. }
  62. class Cache extends BaseCommand {
  63. static description = 'Manipulates packages and npx cache'
  64. static name = 'cache'
  65. static params = ['cache']
  66. static usage = [
  67. 'add <package-spec>',
  68. 'clean [<key>]',
  69. 'ls [<name>@<version>]',
  70. 'verify',
  71. 'npx ls',
  72. 'npx rm [<key>...]',
  73. 'npx info <key>...',
  74. ]
  75. static async completion (opts) {
  76. const argv = opts.conf.argv.remain
  77. if (argv.length === 2) {
  78. return ['add', 'clean', 'verify', 'ls', 'npx']
  79. }
  80. // TODO - eventually...
  81. switch (argv[2]) {
  82. case 'verify':
  83. case 'clean':
  84. case 'add':
  85. case 'ls':
  86. return []
  87. }
  88. }
  89. async exec (args) {
  90. const cmd = args.shift()
  91. switch (cmd) {
  92. case 'rm': case 'clear': case 'clean':
  93. return await this.clean(args)
  94. case 'add':
  95. return await this.add(args)
  96. case 'verify': case 'check':
  97. return await this.verify()
  98. case 'ls':
  99. return await this.ls(args)
  100. case 'npx':
  101. return await this.npx(args)
  102. default:
  103. throw this.usageError()
  104. }
  105. }
  106. // npm cache npx
  107. async npx ([cmd, ...keys]) {
  108. switch (cmd) {
  109. case 'ls':
  110. return await this.npxLs(keys)
  111. case 'rm':
  112. return await this.npxRm(keys)
  113. case 'info':
  114. return await this.npxInfo(keys)
  115. default:
  116. throw this.usageError()
  117. }
  118. }
  119. // npm cache clean [spec]*
  120. async clean (args) {
  121. // this is a derived value
  122. const cachePath = this.npm.flatOptions.cache
  123. if (args.length === 0) {
  124. if (!this.npm.config.get('force')) {
  125. throw new Error(`As of npm@5, the npm cache self-heals from corruption issues by treating integrity mismatches as cache misses.
  126. As a result, data extracted from the cache is guaranteed to be valid.
  127. If you want to make sure everything is consistent, use \`npm cache verify\` instead.
  128. Deleting the cache can only make npm go slower, and is not likely to correct any problems you may be encountering!
  129. On the other hand, if you're debugging an issue with the installer, or race conditions that depend on the timing of writing to an empty cache, you can use \`npm install --cache /tmp/empty-cache\` to use a temporary cache instead of removing the actual one.
  130. If you're sure you want to delete the entire cache, rerun this command with --force.`)
  131. }
  132. return fs.rm(cachePath, { recursive: true, force: true })
  133. }
  134. for (const key of args) {
  135. let entry
  136. try {
  137. entry = await cacache.get(cachePath, key)
  138. } catch {
  139. log.warn('cache', `Not Found: ${key}`)
  140. break
  141. }
  142. output.standard(`Deleted: ${key}`)
  143. await cacache.rm.entry(cachePath, key)
  144. // XXX this could leave other entries without content!
  145. await cacache.rm.content(cachePath, entry.integrity)
  146. }
  147. }
  148. // npm cache add <tarball-url>...
  149. // npm cache add <pkg> <ver>...
  150. // npm cache add <tarball>...
  151. // npm cache add <folder>...
  152. async add (args) {
  153. log.silly('cache add', 'args', args)
  154. if (args.length === 0) {
  155. throw this.usageError('First argument to `add` is required')
  156. }
  157. await Promise.all(args.map(async spec => {
  158. log.silly('cache add', 'spec', spec)
  159. // we ask pacote for the thing, and then just throw the data away so that it tee-pipes it into the cache like it does for a normal request.
  160. await pacote.tarball.stream(spec, stream => {
  161. stream.resume()
  162. return stream.promise()
  163. }, { ...this.npm.flatOptions, _isRoot: true })
  164. await pacote.manifest(spec, {
  165. ...this.npm.flatOptions,
  166. fullMetadata: true,
  167. _isRoot: true,
  168. })
  169. }))
  170. }
  171. async verify () {
  172. // this is a derived value
  173. const cachePath = this.npm.flatOptions.cache
  174. const prefix = cachePath.indexOf(process.env.HOME) === 0
  175. ? `~${cachePath.slice(process.env.HOME.length)}`
  176. : cachePath
  177. const stats = await cacache.verify(cachePath)
  178. output.standard(`Cache verified and compressed (${prefix})`)
  179. output.standard(`Content verified: ${stats.verifiedContent} (${stats.keptSize} bytes)`)
  180. if (stats.badContentCount) {
  181. output.standard(`Corrupted content removed: ${stats.badContentCount}`)
  182. }
  183. if (stats.reclaimedCount) {
  184. output.standard(`Content garbage-collected: ${stats.reclaimedCount} (${stats.reclaimedSize} bytes)`)
  185. }
  186. if (stats.missingContent) {
  187. output.standard(`Missing content: ${stats.missingContent}`)
  188. }
  189. output.standard(`Index entries: ${stats.totalEntries}`)
  190. output.standard(`Finished in ${stats.runTime.total / 1000}s`)
  191. }
  192. // npm cache ls [<spec> ...]
  193. async ls (specs) {
  194. // This is a derived value
  195. const { cache: cachePath } = this.npm.flatOptions
  196. const cacheKeys = Object.keys(await cacache.ls(cachePath))
  197. if (specs.length > 0) {
  198. // get results for each package spec specified
  199. const results = new Set()
  200. for (const spec of specs) {
  201. const parsed = npa(spec)
  202. if (parsed.rawSpec !== '' && parsed.type === 'tag') {
  203. throw this.usageError('Cannot list cache keys for a tagged package.')
  204. }
  205. const keySet = await searchCachePackage(cachePath, parsed, cacheKeys)
  206. for (const key of keySet) {
  207. results.add(key)
  208. }
  209. }
  210. [...results].sort(localeCompare).forEach(key => output.standard(key))
  211. return
  212. }
  213. cacheKeys.sort(localeCompare).forEach(key => output.standard(key))
  214. }
  215. async #npxCache (keys = []) {
  216. // This is a derived value
  217. const { npxCache } = this.npm.flatOptions
  218. let dirs
  219. try {
  220. dirs = await fs.readdir(npxCache, { encoding: 'utf-8' })
  221. } catch {
  222. output.standard('npx cache does not exist')
  223. return
  224. }
  225. const cache = {}
  226. const { default: pMap } = await import('p-map')
  227. await pMap(dirs, async e => {
  228. const pkgPath = join(npxCache, e)
  229. cache[e] = {
  230. hash: e,
  231. path: pkgPath,
  232. valid: false,
  233. }
  234. try {
  235. const pkgJson = await PkgJson.load(pkgPath)
  236. cache[e].package = pkgJson.content
  237. cache[e].valid = true
  238. } catch {
  239. // Defaults to not valid already
  240. }
  241. }, { concurrency: 20 })
  242. if (!keys.length) {
  243. return cache
  244. }
  245. const result = {}
  246. const abbrevs = abbrev(Object.keys(cache))
  247. for (const key of keys) {
  248. if (!abbrevs[key]) {
  249. throw this.usageError(`Invalid npx key ${key}`)
  250. }
  251. result[abbrevs[key]] = cache[abbrevs[key]]
  252. }
  253. return result
  254. }
  255. async npxLs () {
  256. const cache = await this.#npxCache()
  257. for (const key in cache) {
  258. const { hash, valid, package: pkg } = cache[key]
  259. let result = `${hash}:`
  260. if (!valid) {
  261. result = `${result} (empty/invalid)`
  262. } else if (pkg?._npx) {
  263. result = `${result} ${pkg._npx.packages.join(', ')}`
  264. } else {
  265. result = `${result} (unknown)`
  266. }
  267. output.standard(result)
  268. }
  269. }
  270. async npxRm (keys) {
  271. if (!keys.length) {
  272. if (!this.npm.config.get('force')) {
  273. throw this.usageError('Please use --force to remove entire npx cache')
  274. }
  275. const { npxCache } = this.npm.flatOptions
  276. if (!this.npm.config.get('dry-run')) {
  277. return fs.rm(npxCache, { recursive: true, force: true })
  278. }
  279. }
  280. const cache = await this.#npxCache(keys)
  281. for (const key in cache) {
  282. const { path: cachePath } = cache[key]
  283. output.standard(`Removing npx key at ${cachePath}`)
  284. if (!this.npm.config.get('dry-run')) {
  285. await fs.rm(cachePath, { recursive: true })
  286. }
  287. }
  288. }
  289. async npxInfo (keys) {
  290. const chalk = this.npm.chalk
  291. if (!keys.length) {
  292. throw this.usageError()
  293. }
  294. const cache = await this.#npxCache(keys)
  295. const Arborist = require('@npmcli/arborist')
  296. for (const key in cache) {
  297. const { hash, path, package: pkg } = cache[key]
  298. let valid = cache[key].valid
  299. const results = []
  300. try {
  301. if (valid) {
  302. const arb = new Arborist({ path })
  303. const tree = await arb.loadVirtual()
  304. if (pkg._npx) {
  305. results.push('packages:')
  306. for (const p of pkg._npx.packages) {
  307. const parsed = npa(p)
  308. if (parsed.type === 'directory') {
  309. // in the tree the spec is relative, even if the dependency spec is absolute, so we can't find it by name or spec.
  310. results.push(`- ${chalk.cyan(p)}`)
  311. } else {
  312. results.push(`- ${chalk.cyan(p)} (${chalk.blue(tree.children.get(parsed.name).pkgid)})`)
  313. }
  314. }
  315. } else {
  316. results.push('packages: (unknown)')
  317. results.push(`dependencies:`)
  318. for (const dep in pkg.dependencies) {
  319. const child = tree.children.get(dep)
  320. if (child.isLink) {
  321. results.push(`- ${chalk.cyan(child.realpath)}`)
  322. } else {
  323. results.push(`- ${chalk.cyan(child.pkgid)}`)
  324. }
  325. }
  326. }
  327. }
  328. } catch (ex) {
  329. valid = false
  330. }
  331. const v = valid ? chalk.green('valid') : chalk.red('invalid')
  332. output.standard(`${v} npx cache entry with key ${chalk.blue(hash)}`)
  333. output.standard(`location: ${chalk.blue(path)}`)
  334. if (valid) {
  335. output.standard(results.join('\n'))
  336. }
  337. output.standard()
  338. }
  339. }
  340. }
  341. module.exports = Cache