1'use strict'; 2const url = require('url'); 3const got = require('got'); 4const registryUrl = require('registry-url'); 5const registryAuthToken = require('registry-auth-token'); 6const semver = require('semver'); 7 8module.exports = (name, opts) => { 9 const scope = name.split('/')[0]; 10 const regUrl = registryUrl(scope); 11 const pkgUrl = url.resolve(regUrl, encodeURIComponent(name).replace(/^%40/, '@')); 12 const authInfo = registryAuthToken(regUrl, {recursive: true}); 13 14 opts = Object.assign({ 15 version: 'latest' 16 }, opts); 17 18 const headers = { 19 accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*' 20 }; 21 22 if (opts.fullMetadata) { 23 delete headers.accept; 24 } 25 26 if (authInfo) { 27 headers.authorization = `${authInfo.type} ${authInfo.token}`; 28 } 29 30 return got(pkgUrl, {json: true, headers}) 31 .then(res => { 32 let data = res.body; 33 let version = opts.version; 34 35 if (opts.allVersions) { 36 return data; 37 } 38 39 if (data['dist-tags'][version]) { 40 data = data.versions[data['dist-tags'][version]]; 41 } else if (version) { 42 if (!data.versions[version]) { 43 const versions = Object.keys(data.versions); 44 version = semver.maxSatisfying(versions, version); 45 46 if (!version) { 47 throw new Error('Version doesn\'t exist'); 48 } 49 } 50 51 data = data.versions[version]; 52 53 if (!data) { 54 throw new Error('Version doesn\'t exist'); 55 } 56 } 57 58 return data; 59 }) 60 .catch(err => { 61 if (err.statusCode === 404) { 62 throw new Error(`Package \`${name}\` doesn't exist`); 63 } 64 65 throw err; 66 }); 67}; 68