-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathview.js
451 lines (382 loc) · 11.9 KB
/
view.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
const columns = require('cli-columns')
const { readFile } = require('fs/promises')
const jsonParse = require('json-parse-even-better-errors')
const { log, output } = require('proc-log')
const npa = require('npm-package-arg')
const { resolve } = require('path')
const formatBytes = require('../utils/format-bytes.js')
const relativeDate = require('tiny-relative-date')
const semver = require('semver')
const { inspect } = require('util')
const { packument } = require('pacote')
const Queryable = require('../utils/queryable.js')
const BaseCommand = require('../base-cmd.js')
const readJson = file => readFile(file, 'utf8').then(jsonParse)
class View extends BaseCommand {
static description = 'View registry info'
static name = 'view'
static params = [
'json',
'workspace',
'workspaces',
'include-workspace-root',
]
static workspaces = true
static ignoreImplicitWorkspace = false
static usage = ['[<package-spec>] [<field>[.subfield]...]']
static async completion (opts, npm) {
if (opts.conf.argv.remain.length <= 2) {
// There used to be registry completion here, but it stopped
// making sense somewhere around 50,000 packages on the registry
return
}
// have the package, get the fields
const config = {
...npm.flatOptions,
fullMetadata: true,
preferOnline: true,
}
const spec = npa(opts.conf.argv.remain[2])
const pckmnt = await packument(spec, config)
const defaultTag = npm.config.get('tag')
const dv = pckmnt.versions[pckmnt['dist-tags'][defaultTag]]
pckmnt.versions = Object.keys(pckmnt.versions).sort(semver.compareLoose)
return getCompletionFields(pckmnt).concat(getCompletionFields(dv))
}
async exec (args) {
let { pkg, local, rest } = parseArgs(args)
if (local) {
if (this.npm.global) {
throw new Error('Cannot use view command in global mode.')
}
const dir = this.npm.prefix
const manifest = await readJson(resolve(dir, 'package.json'))
if (!manifest.name) {
throw new Error('Invalid package.json, no "name" field')
}
// put the version back if it existed
pkg = `${manifest.name}${pkg.slice(1)}`
}
await this.#viewPackage(pkg, rest)
}
async execWorkspaces (args) {
const { pkg, local, rest } = parseArgs(args)
if (!local) {
log.warn('Ignoring workspaces for specified package(s)')
return this.exec([pkg, ...rest])
}
await this.setWorkspaces()
for (const name of this.workspaceNames) {
await this.#viewPackage(`${name}${pkg.slice(1)}`, rest, { workspace: true })
}
}
async #viewPackage (name, args, { workspace } = {}) {
const wholePackument = !args.length
const json = this.npm.config.get('json')
// If we are viewing many packages and outputting individual fields then
// output the name before doing any async activity
if (!json && !wholePackument && workspace) {
output.standard(`${name}:`)
}
const [pckmnt, data] = await this.#getData(name, args, wholePackument)
if (!json && wholePackument) {
// pretty view (entire packument)
for (const v of data) {
output.standard(this.#prettyView(pckmnt, Object.values(v)[0][Queryable.ALL]))
}
return
}
const res = this.#packageOutput(cleanData(data, wholePackument), pckmnt._id)
if (res) {
if (json) {
output.buffer(workspace ? { [name]: res } : res)
} else {
output.standard(res)
}
}
}
async #getData (pkg, args) {
const spec = npa(pkg)
const pckmnt = await packument(spec, {
...this.npm.flatOptions,
preferOnline: true,
fullMetadata: true,
})
// get the data about this package
let version = this.npm.config.get('tag')
// rawSpec is the git url if this is from git
if (spec.type !== 'git' && spec.type !== 'directory' && spec.rawSpec !== '*') {
version = spec.rawSpec
}
if (pckmnt['dist-tags']?.[version]) {
version = pckmnt['dist-tags'][version]
}
if (pckmnt.time?.unpublished) {
const u = pckmnt.time.unpublished
throw Object.assign(new Error(`Unpublished on ${u.time}`), {
statusCode: 404,
code: 'E404',
pkgid: pckmnt._id,
})
}
const versions = pckmnt.versions || {}
pckmnt.versions = Object.keys(versions).filter(v => {
if (semver.valid(v)) {
return true
}
log.info('view', `Ignoring invalid version: ${v}`)
return false
}).sort(semver.compareLoose)
// remove readme unless we asked for it
if (args.indexOf('readme') === -1) {
delete pckmnt.readme
}
const data = Object.entries(versions)
.filter(([v]) => semver.satisfies(v, version, true))
.flatMap(([, v]) => {
// remove readme unless we asked for it
if (args.indexOf('readme') !== -1) {
delete v.readme
}
return showFields({
data: pckmnt,
version: v,
fields: args,
json: this.npm.config.get('json'),
})
})
// No data has been pushed because no data is matching the specified version
if (!data.length && version !== 'latest') {
throw Object.assign(new Error(`No match found for version ${version}`), {
statusCode: 404,
code: 'E404',
pkgid: `${pckmnt._id}@${version}`,
})
}
return [pckmnt, data]
}
#packageOutput (data, name) {
const json = this.npm.config.get('json')
const versions = Object.keys(data)
const includeVersions = versions.length > 1
let includeFields
const res = versions.flatMap((v) => {
const fields = Object.entries(data[v])
includeFields ||= (fields.length > 1)
const msg = json ? {} : []
for (let [f, d] of fields) {
d = cleanup(d)
if (json) {
msg[f] = d
continue
}
if (includeVersions || includeFields || typeof d !== 'string') {
d = inspect(d, {
showHidden: false,
depth: 5,
colors: this.npm.color,
maxArrayLength: null,
})
}
if (f && includeFields) {
f += ' = '
}
msg.push(`${includeVersions ? `${name}@${v} ` : ''}${includeFields ? f : ''}${d}`)
}
return msg
})
if (json) {
const first = Object.keys(res[0] || {})
const jsonRes = first.length === 1 ? res.map(m => m[first[0]]) : res
if (jsonRes.length === 0) {
return
}
if (jsonRes.length === 1) {
return jsonRes[0]
}
return jsonRes
}
return res.join('\n').trim()
}
#prettyView (packu, manifest) {
// More modern, pretty printing of default view
const unicode = this.npm.config.get('unicode')
const chalk = this.npm.chalk
const deps = Object.entries(manifest.dependencies || {}).map(([k, dep]) =>
`${chalk.blue(k)}: ${dep}`
)
const site = manifest.homepage?.url || manifest.homepage
const bins = Object.keys(manifest.bin || {})
const licenseField = manifest.license || 'Proprietary'
const license = typeof licenseField === 'string'
? licenseField
: (licenseField.type || 'Proprietary')
const res = []
res.push('')
res.push([
chalk.underline.cyan(`${manifest.name}@${manifest.version}`),
license.toLowerCase().trim() === 'proprietary'
? chalk.red(license)
: chalk.green(license),
`deps: ${deps.length ? chalk.cyan(deps.length) : chalk.cyan('none')}`,
`versions: ${chalk.cyan(packu.versions.length + '')}`,
].join(' | '))
manifest.description && res.push(manifest.description)
if (site) {
res.push(chalk.blue(site))
}
manifest.deprecated && res.push(
`\n${chalk.redBright('DEPRECATED')}${unicode ? ' ⚠️ ' : '!!'} - ${manifest.deprecated}`
)
if (packu.keywords?.length) {
res.push(`\nkeywords: ${
packu.keywords.map(k => chalk.cyan(k)).join(', ')
}`)
}
if (bins.length) {
res.push(`\nbin: ${chalk.cyan(bins.join(', '))}`)
}
res.push('\ndist')
res.push(`.tarball: ${chalk.blue(manifest.dist.tarball)}`)
res.push(`.shasum: ${chalk.green(manifest.dist.shasum)}`)
if (manifest.dist.integrity) {
res.push(`.integrity: ${chalk.green(manifest.dist.integrity)}`)
}
if (manifest.dist.unpackedSize) {
res.push(`.unpackedSize: ${chalk.blue(formatBytes(manifest.dist.unpackedSize, true))}`)
}
if (deps.length) {
const maxDeps = 24
res.push('\ndependencies:')
res.push(columns(deps.slice(0, maxDeps), { padding: 1 }))
if (deps.length > maxDeps) {
res.push(chalk.dim(`(...and ${deps.length - maxDeps} more.)`))
}
}
if (packu.maintainers?.length) {
res.push('\nmaintainers:')
packu.maintainers.forEach(u =>
res.push(`- ${unparsePerson({
name: chalk.blue(u.name),
email: chalk.dim(u.email) })}`)
)
}
res.push('\ndist-tags:')
res.push(columns(Object.entries(packu['dist-tags']).map(([k, t]) =>
`${chalk.blue(k)}: ${t}`
)))
const publisher = manifest._npmUser && unparsePerson({
name: chalk.blue(manifest._npmUser.name),
email: chalk.dim(manifest._npmUser.email),
})
if (publisher || packu.time) {
let publishInfo = 'published'
if (packu.time) {
publishInfo += ` ${chalk.cyan(relativeDate(packu.time[manifest.version]))}`
}
if (publisher) {
publishInfo += ` by ${publisher}`
}
res.push('')
res.push(publishInfo)
}
return res.join('\n')
}
}
module.exports = View
function parseArgs (args) {
if (!args.length) {
args = ['.']
}
const pkg = args.shift()
return {
pkg,
local: /^\.@/.test(pkg) || pkg === '.',
rest: args,
}
}
function cleanData (obj, wholePackument) {
// JSON formatted output (JSON or specific attributes from packument)
const data = obj.reduce((acc, cur) => {
if (cur) {
Object.entries(cur).forEach(([k, v]) => {
acc[k] ||= {}
Object.keys(v).forEach((t) => {
acc[k][t] = cur[k][t]
})
})
}
return acc
}, {})
if (wholePackument) {
const cleaned = Object.entries(data).reduce((acc, [k, v]) => {
acc[k] = v[Queryable.ALL]
return acc
}, {})
log.silly('view', cleaned)
return cleaned
}
return data
}
// return whatever was printed
function showFields ({ data, version, fields, json }) {
const o = [data, version].reduce((acc, s) => {
Object.entries(s).forEach(([k, v]) => {
acc[k] = v
})
return acc
}, {})
const queryable = new Queryable(o)
if (!fields.length) {
return { [version.version]: queryable.query(Queryable.ALL) }
}
return fields.map((field) => {
const s = queryable.query(field, { unwrapSingleItemArrays: !json })
if (s) {
return { [version.version]: s }
}
})
}
function cleanup (data) {
if (Array.isArray(data)) {
return data.map(cleanup)
}
if (!data || typeof data !== 'object') {
return data
}
const keys = Object.keys(data)
if (keys.length <= 3 && data.name && (
(keys.length === 1) ||
(keys.length === 3 && data.email && data.url) ||
(keys.length === 2 && (data.email || data.url))
)) {
data = unparsePerson(data)
}
return data
}
const unparsePerson = (d) =>
`${d.name}${d.email ? ` <${d.email}>` : ''}${d.url ? ` (${d.url})` : ''}`
function getCompletionFields (d, f = [], pref = []) {
Object.entries(d).forEach(([k, v]) => {
if (k.charAt(0) === '_' || k.indexOf('.') !== -1) {
return
}
const p = pref.concat(k).join('.')
f.push(p)
if (Array.isArray(v)) {
v.forEach((val, i) => {
const pi = p + '[' + i + ']'
if (val && typeof val === 'object') {
getCompletionFields(val, f, [p])
} else {
f.push(pi)
}
})
return
}
if (typeof v === 'object') {
getCompletionFields(v, f, [p])
}
})
return f
}