prefetch.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict'
  2. const BB = require('bluebird')
  3. const cacache = require('cacache')
  4. const finished = BB.promisify(require('mississippi').finished)
  5. const optCheck = require('./lib/util/opt-check')
  6. const npa = require('npm-package-arg')
  7. module.exports = prefetch
  8. function prefetch (spec, opts) {
  9. opts = optCheck(opts)
  10. spec = npa(spec, opts.where)
  11. opts.log.warn('prefetch', 'pacote.prefetch() is deprecated. Please use pacote.tarball() instead.')
  12. const startTime = Date.now()
  13. if (!opts.cache) {
  14. opts.log.info('prefetch', 'skipping prefetch: no cache provided')
  15. return BB.resolve({ spec })
  16. }
  17. if (opts.integrity && !opts.preferOnline) {
  18. opts.log.silly('prefetch', 'checking if', opts.integrity, 'is already cached')
  19. return cacache.get.hasContent(opts.cache, opts.integrity).then(info => {
  20. if (info) {
  21. opts.log.silly('prefetch', `content already exists for ${spec} (${Date.now() - startTime}ms)`)
  22. return {
  23. spec,
  24. integrity: info.integrity,
  25. size: info.size,
  26. byDigest: true
  27. }
  28. } else {
  29. return prefetchByManifest(startTime, spec, opts)
  30. }
  31. })
  32. } else {
  33. opts.log.silly('prefetch', `no integrity hash provided for ${spec} - fetching by manifest`)
  34. return prefetchByManifest(startTime, spec, opts)
  35. }
  36. }
  37. let fetch
  38. function prefetchByManifest (start, spec, opts) {
  39. let manifest
  40. let integrity
  41. return BB.resolve().then(() => {
  42. if (!fetch) {
  43. fetch = require('./lib/fetch')
  44. }
  45. const stream = fetch.tarball(spec, opts)
  46. if (!stream) { return }
  47. stream.on('data', function () {})
  48. stream.on('manifest', m => { manifest = m })
  49. stream.on('integrity', i => { integrity = i })
  50. return finished(stream)
  51. }).then(() => {
  52. opts.log.silly('prefetch', `${spec} done in ${Date.now() - start}ms`)
  53. return {
  54. manifest,
  55. spec,
  56. integrity: integrity || (manifest && manifest._integrity),
  57. byDigest: false
  58. }
  59. })
  60. }