// npm view [pkg [pkg ...]]
const BB = require('bluebird')
const byteSize = require('byte-size')
const color = require('ansicolors')
const columns = require('cli-columns')
const npmConfig = require('./config/figgy-config.js')
const log = require('npmlog')
const figgyPudding = require('figgy-pudding')
const npa = require('libnpm/parse-arg')
const npm = require('./npm.js')
const packument = require('libnpm/packument')
const path = require('path')
const readJson = require('libnpm/read-json')
const relativeDate = require('tiny-relative-date')
const semver = require('semver')
const style = require('ansistyles')
const usage = require('./utils/usage')
const util = require('util')
const validateName = require('validate-npm-package-name')
const ViewConfig = figgyPudding({
'npm view [<@scope>/]<pkg>[@<version>] [<field>[.subfield]...]'
view.completion = function (opts, cb) {
if (opts.conf.argv.remain.length <= 2) {
// FIXME: there used to be registry completion here, but it stopped making
// sense somewhere around 50,000 packages on the registry
// have the package, get the fields.
const config = ViewConfig(npmConfig())
const spec = npa(opts.conf.argv.remain[2])
return packument(spec, config).then(d => {
const dv = d.versions[d['dist-tags'][tag]]
d.versions = Object.keys(d.versions).sort(semver.compareLoose)
return getFields(d).concat(getFields(dv))
function getFields (d, f, pref) {
Object.keys(d).forEach(function (k) {
if (k.charAt(0) === '_' || k.indexOf('.') !== -1) return
const p = pref.concat(k).join('.')
if (Array.isArray(d[k])) {
d[k].forEach(function (val, i) {
const pi = p + '[' + i + ']'
if (val && typeof val === 'object') getFields(val, f, [p])
if (typeof d[k] === 'object') getFields(d[k], f, [p])
function view (args, silent, cb) {
if (typeof cb !== 'function') {
if (!args.length) args = ['.']
const opts = ViewConfig(npmConfig())
nv = npa.resolve(null, pkg.slice(2))
const local = (name === '.' || !name)
if (opts.global && local) {
return cb(new Error('Cannot use view command in global mode.'))
BB.resolve(readJson(path.resolve(dir, 'package.json'))).nodeify((er, d) => {
if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
if (!d.name) return cb(new Error('Invalid package.json'))
if (pkg && ~pkg.indexOf('@')) {
nv.rawSpec = pkg.split('@')[pkg.indexOf('@')]
fetchAndRead(nv, args, silent, opts, cb)
fetchAndRead(nv, args, silent, opts, cb)
function fetchAndRead (nv, args, silent, opts, cb) {
// get the data about this package
let version = nv.rawSpec || npm.config.get('tag')
return packument(nv, opts.concat({
// TODO - this should probably go into pacote, but the tests expect it.
if (err.code === 'E404') {
err.message = `'${nv.name}' is not in the npm registry.`
const validated = validateName(nv.name)
if (!validated.validForNewPackages) {
err.message += (validated.errors || []).join('\n')
err.message += (validated.warnings || []).join('\n')
err.message += '\nYou should bug the author to publish it'
err.message += '\n(or use the name yourself!)'
err.message += '\nNote that you can also install from a'
err.message += '\ntarball, folder, http url, or git url.'
if (data['dist-tags'] && data['dist-tags'][version]) {
version = data['dist-tags'][version]
if (data.time && data.time.unpublished) {
const u = data.time.unpublished
let er = new Error('Unpublished by ' + u.name + ' on ' + u.time)
const versions = data.versions || {}
data.versions = Object.keys(versions).sort(semver.compareLoose)
if (!args.length) args = ['']
// remove readme unless we asked for it
if (args.indexOf('readme') === -1) {
Object.keys(versions).forEach(function (v) {
if (semver.satisfies(v, version, true)) {
args.forEach(function (args) {
// remove readme unless we asked for it
if (args.indexOf('readme') !== -1) {
delete versions[v].readme
results.push(showFields(data, versions[v], args))
let retval = results.reduce(reducer, {})
if (args.length === 1 && args[0] === '') {
retval = cleanBlanks(retval)
log.silly('view', retval)
results.map((v) => prettyView(data, v[Object.keys(v)[0]][''], opts))
return BB.fromNode(cb => {
printData(retval, data._id, opts, cb)
function prettyView (packument, manifest, opts) {
// More modern, pretty printing of default view
const unicode = opts.unicode
'No matching versions.\n' +
'To see a list of versions, run:\n' +
`> npm view ${packument.name} versions`
Object.keys(packument['dist-tags']).forEach((t) => {
const version = packument['dist-tags'][t]
tags.push(`${style.bright(color.green(t))}: ${version}`)
const unpackedSize = manifest.dist.unpackedSize &&
byteSize(manifest.dist.unpackedSize)
const licenseField = manifest.license || manifest.licence || 'Proprietary'
name: color.green(manifest.name),
version: color.green(manifest.version),
bins: Object.keys(manifest.bin || {}).map(color.yellow),
versions: color.yellow(packument.versions.length + ''),
description: manifest.description,
deprecated: manifest.deprecated,
keywords: (packument.keywords || []).map(color.yellow),
license: typeof licenseField === 'string'
: (licenseField.type || 'Proprietary'),
deps: Object.keys(manifest.dependencies || {}).map((dep) => {
return `${color.yellow(dep)}: ${manifest.dependencies[dep]}`
publisher: manifest._npmUser && unparsePerson({
name: color.yellow(manifest._npmUser.name),
email: color.cyan(manifest._npmUser.email)
modified: packument.time ? color.yellow(relativeDate(packument.time[packument.version])) : undefined,
maintainers: (packument.maintainers || []).map((u) => unparsePerson({
name: color.yellow(u.name),
email: color.cyan(u.email)
manifest.bugs && (manifest.bugs.url || manifest.bugs)
manifest.repository && (manifest.repository.url || manifest.repository)
manifest.homepage && (manifest.homepage.url || manifest.homepage)
stars: color.yellow('' + packument.users ? Object.keys(packument.users || {}).length : 0),
tarball: color.cyan(manifest.dist.tarball),
shasum: color.yellow(manifest.dist.shasum),
integrity: manifest.dist.integrity && color.yellow(manifest.dist.integrity),
fileCount: manifest.dist.fileCount && color.yellow(manifest.dist.fileCount),
unpackedSize: unpackedSize && color.yellow(unpackedSize.value) + ' ' + unpackedSize.unit
if (info.license.toLowerCase().trim() === 'proprietary') {
info.license = style.bright(color.red(info.license))
info.license = color.green(info.license)
style.underline(style.bright(`${info.name}@${info.version}`)) +
' | deps: ' + (info.deps.length ? color.cyan(info.deps.length) : color.green('none')) +
' | versions: ' + info.versions
info.description && console.log(info.description)
if (info.repo || info.site) {
info.site && console.log(color.cyan(info.site))
const warningSign = unicode ? ' ⚠️ ' : '!!'
info.deprecated && console.log(
`\n${style.bright(color.red('DEPRECATED'))}${
if (info.keywords.length) {
console.log('keywords:', info.keywords.join(', '))
console.log('bin:', info.bins.join(', '))
console.log('.tarball:', info.tarball)
console.log('.shasum:', info.shasum)
info.integrity && console.log('.integrity:', info.integrity)
info.unpackedSize && console.log('.unpackedSize:', info.unpackedSize)
console.log('dependencies:')
console.log(columns(info.deps.slice(0, maxDeps), {padding: 1}))
if (info.deps.length > maxDeps) {
console.log(`(...and ${info.deps.length - maxDeps} more.)`)
if (info.maintainers && info.maintainers.length) {
console.log('maintainers:')
info.maintainers.forEach((u) => console.log('-', u))
console.log('dist-tags:')
console.log(columns(info.tags))
if (info.publisher || info.modified) {
let publishInfo = 'published'
if (info.modified) { publishInfo += ` ${info.modified}` }
if (info.publisher) { publishInfo += ` by ${info.publisher}` }
function cleanBlanks (obj) {
Object.keys(obj).forEach(function (version) {
clean[version] = obj[version]['']
function reducer (l, r) {
Object.keys(r).forEach(function (v) {
Object.keys(r[v]).forEach(function (t) {
// return whatever was printed
function showFields (data, version, fields) {
;[data, version].forEach(function (s) {
Object.keys(s).forEach(function (k) {
return search(o, fields.split('.'), version.version, fields)
function search (data, fields, version, title) {
while (!field && fields.length) field = tail.shift()
fields = [field].concat(tail)
if (!field && !tail.length) {
let index = field.match(/(.+)\[([^\]]+)\]$/)
if (data.field && data.field.hasOwnProperty(index)) {
return search(data[field][index], tail, version, title)
field = field + '[' + index + ']'
if (Array.isArray(data)) {
return search(data[0], fields, version, title)
data.forEach(function (data, i) {
const newt = title.substr(0, tl - fields.join('.').length - 1) +
'[' + i + ']' + [''].concat(fields).join('.')
results.push(search(data, fields.slice(), version, newt))
results = results.reduce(reducer, {})
if (!data.hasOwnProperty(field)) return undefined
if (typeof data === 'object') {
// there are more fields to deal with.
return search(data, tail, version, title)
return new Error('Not an object: ' + data)
function printData (data, name, opts, cb) {
const versions = Object.keys(data)
const includeVersions = versions.length > 1
versions.forEach(function (v) {
const fields = Object.keys(data[v])
includeFields = includeFields || (fields.length > 1)
if (opts.json) msgJson.push({})
fields.forEach(function (f) {
let d = cleanup(data[v][f])
if (fields.length === 1 && opts.json) {
msgJson[msgJson.length - 1][f] = d
if (includeVersions || includeFields || typeof d !== 'string') {
msgJson[msgJson.length - 1][f] = d
d = util.inspect(d, { showHidden: false, depth: 5, colors: npm.color, maxArrayLength: null })
} else if (typeof d === 'string' && opts.json) {
if (f && includeFields) f += ' = '
if (d.indexOf('\n') !== -1) d = ' \n' + d
msg += (includeVersions ? name + '@' + v + ' ' : '') +
(includeFields ? f : '') + d + '\n'
if (msgJson.length && Object.keys(msgJson[0]).length === 1) {
const k = Object.keys(msgJson[0])[0]
msgJson = msgJson.map(function (m) { return m[k] })
if (msgJson.length === 1) {
msg = JSON.stringify(msgJson[0], null, 2) + '\n'
} else if (msgJson.length > 1) {
msg = JSON.stringify(msgJson, null, 2) + '\n'
// preserve output symmetry by adding a whitespace-only line at the end if
// there's one at the beginning
if (/^\s*\n/.test(msg)) msg += '\n'
// disable the progress bar entirely, as we can't meaningfully update it if
// we may have partial lines printed.
// print directly to stdout to not unnecessarily add blank lines
process.stdout.write(msg, () => cb(null, data))
function cleanup (data) {
if (Array.isArray(data)) {
if (!data || typeof data !== 'object') return data
if (typeof data.versions === 'object' &&
!Array.isArray(data.versions)) {
data.versions = Object.keys(data.versions || {})
let keys = Object.keys(data)
keys.forEach(function (d) {
if (d.charAt(0) === '_') delete data[d]
else if (typeof data[d] === 'object') data[d] = cleanup(data[d])