mirror of
https://github.com/nodejs/node.git
synced 2026-11-27 17:52:27 -05:00
deps: upgrade npm to 10.7.0
PR-URL: https://github.com/nodejs/node/pull/52767 Reviewed-By: Richard Lau <rlau@redhat.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Michaël Zasso <targos@protonmail.com>
This commit is contained in:
1 parent
78f84ebb09
commit
7f5dd44ca6
418 files changed
+9157
-16454
No files matched your search
Vendored
+18
-21
@@ -1,35 +1,32 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
$NODE_EXE="$PSScriptRoot/node.exe"
|
||||
if (-not (Test-Path $NODE_EXE)) {
|
||||
$NODE_EXE="$PSScriptRoot/node"
|
||||
}
|
||||
$ret=0
|
||||
|
||||
$nodeexe = "node$exe"
|
||||
$nodebin = $(Get-Command $nodeexe -ErrorAction SilentlyContinue -ErrorVariable F).Source
|
||||
if ($nodebin -eq $null) {
|
||||
Write-Host "$nodeexe not found."
|
||||
exit 1
|
||||
if (-not (Test-Path $NODE_EXE)) {
|
||||
$NODE_EXE="node"
|
||||
}
|
||||
$nodedir = $(New-Object -ComObject Scripting.FileSystemObject).GetFile("$nodebin").ParentFolder.Path
|
||||
|
||||
$npmprefixjs="$nodedir/node_modules/npm/bin/npm-prefix.js"
|
||||
$npmprefix=(& $nodeexe $npmprefixjs)
|
||||
$NPM_PREFIX_JS="$PSScriptRoot/node_modules/npm/bin/npm-prefix.js"
|
||||
$NPM_CLI_JS="$PSScriptRoot/node_modules/npm/bin/npm-cli.js"
|
||||
$NPM_PREFIX=(& $NODE_EXE $NPM_PREFIX_JS)
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "Could not determine Node.js install directory"
|
||||
exit 1
|
||||
}
|
||||
$npmprefixclijs="$npmprefix/node_modules/npm/bin/npm-cli.js"
|
||||
|
||||
$NPM_PREFIX_NPM_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npm-cli.js"
|
||||
if (Test-Path $NPM_PREFIX_NPM_CLI_JS) {
|
||||
$NPM_CLI_JS=$NPM_PREFIX_NPM_CLI_JS
|
||||
}
|
||||
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & $nodeexe $npmprefixclijs $args
|
||||
$input | & $NODE_EXE $NPM_CLI_JS $args
|
||||
} else {
|
||||
& $nodeexe $npmprefixclijs $args
|
||||
& $NODE_EXE $NPM_CLI_JS $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
exit $ret
|
||||
|
||||
exit $LASTEXITCODE
|
||||
Vendored
+1
-1
@@ -26,7 +26,7 @@ const removed = new Set([
|
||||
|
||||
const { definitions, shorthands } = require('@npmcli/config/lib/definitions')
|
||||
const npmSwitches = Object.entries(definitions)
|
||||
.filter(([key, { type }]) => type === Boolean ||
|
||||
.filter(([, { type }]) => type === Boolean ||
|
||||
(Array.isArray(type) && type.includes(Boolean)))
|
||||
.map(([key]) => key)
|
||||
|
||||
|
||||
Vendored
+18
-21
@@ -1,35 +1,32 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
$NODE_EXE="$PSScriptRoot/node.exe"
|
||||
if (-not (Test-Path $NODE_EXE)) {
|
||||
$NODE_EXE="$PSScriptRoot/node"
|
||||
}
|
||||
$ret=0
|
||||
|
||||
$nodeexe = "node$exe"
|
||||
$nodebin = $(Get-Command $nodeexe -ErrorAction SilentlyContinue -ErrorVariable F).Source
|
||||
if ($nodebin -eq $null) {
|
||||
Write-Host "$nodeexe not found."
|
||||
exit 1
|
||||
if (-not (Test-Path $NODE_EXE)) {
|
||||
$NODE_EXE="node"
|
||||
}
|
||||
$nodedir = $(New-Object -ComObject Scripting.FileSystemObject).GetFile("$nodebin").ParentFolder.Path
|
||||
|
||||
$npmprefixjs="$nodedir/node_modules/npm/bin/npm-prefix.js"
|
||||
$npmprefix=(& $nodeexe $npmprefixjs)
|
||||
$NPM_PREFIX_JS="$PSScriptRoot/node_modules/npm/bin/npm-prefix.js"
|
||||
$NPX_CLI_JS="$PSScriptRoot/node_modules/npm/bin/npx-cli.js"
|
||||
$NPM_PREFIX=(& $NODE_EXE $NPM_PREFIX_JS)
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "Could not determine Node.js install directory"
|
||||
exit 1
|
||||
}
|
||||
$npmprefixclijs="$npmprefix/node_modules/npm/bin/npx-cli.js"
|
||||
|
||||
$NPM_PREFIX_NPX_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npx-cli.js"
|
||||
if (Test-Path $NPM_PREFIX_NPX_CLI_JS) {
|
||||
$NPX_CLI_JS=$NPM_PREFIX_NPX_CLI_JS
|
||||
}
|
||||
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & $nodeexe $npmprefixclijs $args
|
||||
$input | & $NODE_EXE $NPX_CLI_JS $args
|
||||
} else {
|
||||
& $nodeexe $npmprefixclijs $args
|
||||
& $NODE_EXE $NPX_CLI_JS $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
exit $ret
|
||||
|
||||
exit $LASTEXITCODE
|
||||
+1
-1
@@ -7,7 +7,7 @@ description: Set access level on published packages
|
||||
### Synopsis
|
||||
|
||||
```bash
|
||||
npm access list packages [<user>|<scope>|<scope:team> [<package>]
|
||||
npm access list packages [<user>|<scope>|<scope:team>] [<package>]
|
||||
npm access list collaborators [<package> [<user>]]
|
||||
npm access get status [<package>]
|
||||
npm access set status=public|private [<package>]
|
||||
|
||||
+11
-10
@@ -7,7 +7,7 @@ description: Check the health of your npm environment
|
||||
### Synopsis
|
||||
|
||||
```bash
|
||||
npm doctor [ping] [registry] [versions] [environment] [permissions] [cache]
|
||||
npm doctor [connection] [registry] [versions] [environment] [permissions] [cache]
|
||||
```
|
||||
|
||||
Note: This command is unaware of workspaces.
|
||||
@@ -38,20 +38,21 @@ there are any recommended changes, it will display them. By default npm
|
||||
runs all of these checks. You can limit what checks are ran by
|
||||
specifying them as extra arguments.
|
||||
|
||||
#### `npm ping`
|
||||
#### `Connecting to the registry`
|
||||
|
||||
By default, npm installs from the primary npm registry,
|
||||
`registry.npmjs.org`. `npm doctor` hits a special ping endpoint within the
|
||||
registry. This can also be checked with `npm ping`. If this check fails,
|
||||
you may be using a proxy that needs to be configured, or may need to talk
|
||||
to your IT staff to get access over HTTPS to `registry.npmjs.org`.
|
||||
`registry.npmjs.org`. `npm doctor` hits a special connection testing
|
||||
endpoint within the registry. This can also be checked with `npm ping`.
|
||||
If this check fails, you may be using a proxy that needs to be
|
||||
configured, or may need to talk to your IT staff to get access over
|
||||
HTTPS to `registry.npmjs.org`.
|
||||
|
||||
This check is done against whichever registry you've configured (you can
|
||||
see what that is by running `npm config get registry`), and if you're using
|
||||
a private registry that doesn't support the `/whoami` endpoint supported by
|
||||
the primary registry, this check may fail.
|
||||
|
||||
#### `npm -v`
|
||||
#### `Checking npm version`
|
||||
|
||||
While Node.js may come bundled with a particular version of npm, it's the
|
||||
policy of the CLI team that we recommend all users run `npm@latest` if they
|
||||
@@ -61,7 +62,7 @@ support releases typically only receive critical security and regression
|
||||
fixes. The team believes that the latest tested version of npm is almost
|
||||
always likely to be the most functional and defect-free version of npm.
|
||||
|
||||
#### `node -v`
|
||||
#### `Checking node version`
|
||||
|
||||
For most users, in most circumstances, the best version of Node will be the
|
||||
latest long-term support (LTS) release. Those of you who want access to new
|
||||
@@ -70,7 +71,7 @@ be running a newer version, and some may be required to run an older
|
||||
version of Node because of enterprise change control policies. That's OK!
|
||||
But in general, the npm team recommends that most users run Node.js LTS.
|
||||
|
||||
#### `npm config get registry`
|
||||
#### `Checking configured npm registry`
|
||||
|
||||
You may be installing from private package registries for your project or
|
||||
company. That's great! Others may be following tutorials or StackOverflow
|
||||
@@ -79,7 +80,7 @@ Sometimes, this may entail changing the registry you're pointing at. This
|
||||
part of `npm doctor` just lets you, and maybe whoever's helping you with
|
||||
support, know that you're not using the default registry.
|
||||
|
||||
#### `which git`
|
||||
#### `Checking for git executable in PATH`
|
||||
|
||||
While it's documented in the README, it may not be obvious that npm needs
|
||||
Git installed to do many of the things that it does. Also, in some cases
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ packages will *also* show the paths to the specified packages. For
|
||||
example, running `npm ls promzard` in npm's source tree will show:
|
||||
|
||||
```bash
|
||||
npm@10.5.2 /path/to/npm
|
||||
npm@10.7.0 /path/to/npm
|
||||
└─┬ init-package-json@0.0.4
|
||||
└── promzard@0.1.5
|
||||
```
|
||||
|
||||
+11
-22
@@ -24,28 +24,17 @@ support this interface.
|
||||
* `npm profile get [<property>]`: Display all of the properties of your
|
||||
profile, or one or more specific properties. It looks like:
|
||||
|
||||
```bash
|
||||
+-----------------+---------------------------+
|
||||
| name | example |
|
||||
+-----------------+---------------------------+
|
||||
| email | me@example.com (verified) |
|
||||
+-----------------+---------------------------+
|
||||
| two factor auth | auth-and-writes |
|
||||
+-----------------+---------------------------+
|
||||
| fullname | Example User |
|
||||
+-----------------+---------------------------+
|
||||
| homepage | |
|
||||
+-----------------+---------------------------+
|
||||
| freenode | |
|
||||
+-----------------+---------------------------+
|
||||
| twitter | |
|
||||
+-----------------+---------------------------+
|
||||
| github | |
|
||||
+-----------------+---------------------------+
|
||||
| created | 2015-02-26T01:38:35.892Z |
|
||||
+-----------------+---------------------------+
|
||||
| updated | 2017-10-02T21:29:45.922Z |
|
||||
+-----------------+---------------------------+
|
||||
```
|
||||
name: example
|
||||
email: e@example.com (verified)
|
||||
two-factor auth: auth-and-writes
|
||||
fullname: Example User
|
||||
homepage:
|
||||
freenode:
|
||||
twitter:
|
||||
github:
|
||||
created: 2015-02-26T01:38:35.892Z
|
||||
updated: 2017-10-02T21:29:45.922Z
|
||||
```
|
||||
|
||||
* `npm profile set <property> <value>`: Set the value of a profile
|
||||
|
||||
+1
-10
@@ -7,7 +7,7 @@ description: Search for packages
|
||||
### Synopsis
|
||||
|
||||
```bash
|
||||
npm search [search terms ...]
|
||||
npm search <search term> [<search term> ...]
|
||||
|
||||
aliases: find, s, se
|
||||
```
|
||||
@@ -39,15 +39,6 @@ expression characters in most shells.)
|
||||
|
||||
### Configuration
|
||||
|
||||
#### `long`
|
||||
|
||||
* Default: false
|
||||
* Type: Boolean
|
||||
|
||||
Show extended information in `ls`, `search`, and `help-search`.
|
||||
|
||||
|
||||
|
||||
#### `json`
|
||||
|
||||
* Default: false
|
||||
|
||||
+10
-28
@@ -22,24 +22,14 @@ This lets you list, create and revoke authentication tokens.
|
||||
Shows a table of all active authentication tokens. You can request
|
||||
this as JSON with `--json` or tab-separated values with `--parseable`.
|
||||
|
||||
```bash
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| id | token | created | read-only | CIDR whitelist |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 7f3134 | 1fa9ba… | 2017-10-02 | yes | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| c03241 | af7aef… | 2017-10-02 | no | 192.168.0.1/24 |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| e0cf92 | 3a436a… | 2017-10-02 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 63eb9d | 74ef35… | 2017-09-28 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 2daaa8 | cbad5f… | 2017-09-26 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 68c2fe | 127e51… | 2017-09-23 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 6334e1 | 1dadd1… | 2017-09-23 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
```
|
||||
Read only token npm_1f… with id 7f3134 created 2017-10-21
|
||||
|
||||
Publish token npm_af… with id c03241 created 2017-10-02
|
||||
with IP Whitelist: 192.168.0.1/24
|
||||
|
||||
Publish token npm_… with id e0cf92 created 2017-10-02
|
||||
|
||||
```
|
||||
|
||||
* `npm token create [--read-only] [--cidr=<cidr-ranges>]`:
|
||||
@@ -55,16 +45,8 @@ This lets you list, create and revoke authentication tokens.
|
||||
website](https://docs.npmjs.com/creating-and-viewing-access-tokens)
|
||||
for more information on generating automation tokens.
|
||||
|
||||
```bash
|
||||
+----------------+--------------------------------------+
|
||||
| token | a73c9572-f1b9-8983-983d-ba3ac3cc913d |
|
||||
+----------------+--------------------------------------+
|
||||
| cidr_whitelist | |
|
||||
+----------------+--------------------------------------+
|
||||
| readonly | false |
|
||||
+----------------+--------------------------------------+
|
||||
| created | 2017-10-02T07:52:24.838Z |
|
||||
+----------------+--------------------------------------+
|
||||
```
|
||||
Created publish token a73c9572-f1b9-8983-983d-ba3ac3cc913d
|
||||
```
|
||||
|
||||
* `npm token revoke <token|id>`:
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ Note: This command is unaware of workspaces.
|
||||
|
||||
### Version
|
||||
|
||||
10.5.2
|
||||
10.7.0
|
||||
|
||||
### Description
|
||||
|
||||
|
||||
@@ -928,6 +928,13 @@ Overrides provide a way to replace a package in your dependency tree with
|
||||
another version, or another package entirely. These changes can be scoped as
|
||||
specific or as vague as desired.
|
||||
|
||||
Overrides are only considered in the root `package.json` file for a project.
|
||||
Overrides in installed dependencies (including
|
||||
[workspaces](/using-npm/workspaces)) are not considered in dependency tree
|
||||
resolution. Published packages may dictate their resolutions by pinning
|
||||
dependencies or using an
|
||||
[`npm-shrinkwrap.json`](/configuring-npm/npm-shrinkwrap-json) file.
|
||||
|
||||
To make sure the package `foo` is always installed as version `1.0.0` no matter
|
||||
what version your dependencies rely on:
|
||||
|
||||
|
||||
@@ -31,6 +31,8 @@ various purposes:
|
||||
picture of the package tree, reducing the need to read `package.json`
|
||||
files, and allowing for significant performance improvements.
|
||||
|
||||
When `npm` creates or updates `package-lock.json`, it will infer line endings and indentation from `package.json` so that the formatting of both files matches.
|
||||
|
||||
### `package-lock.json` vs `npm-shrinkwrap.json`
|
||||
|
||||
Both of these files have the same format, and perform similar functions in
|
||||
|
||||
Vendored
+1
-1
@@ -119,7 +119,7 @@ const replaceConfig = (src, { path }) => {
|
||||
}
|
||||
|
||||
const allConfig = Object.entries(definitions).sort(sort)
|
||||
.map(([_, def]) => def.describe())
|
||||
.map(([, def]) => def.describe())
|
||||
.join('\n\n')
|
||||
|
||||
return src.replace(replacer, allConfig)
|
||||
|
||||
+1
-1
@@ -146,7 +146,7 @@ npm command-line interface
|
||||
</section>
|
||||
|
||||
<div id="_content"><h3 id="synopsis">Synopsis</h3>
|
||||
<pre><code class="language-bash">npm access list packages [<user>|<scope>|<scope:team> [<package>]
|
||||
<pre><code class="language-bash">npm access list packages [<user>|<scope>|<scope:team>] [<package>]
|
||||
npm access list collaborators [<package> [<user>]]
|
||||
npm access get status [<package>]
|
||||
npm access set status=public|private [<package>]
|
||||
|
||||
+12
-11
@@ -142,11 +142,11 @@ npm command-line interface
|
||||
|
||||
<section id="table_of_contents">
|
||||
<h2 id="table-of-contents">Table of contents</h2>
|
||||
<div id="_table_of_contents"><ul><li><a href="#synopsis">Synopsis</a></li><li><a href="#description">Description</a></li><ul><li><a href="#npm-ping"><code>npm ping</code></a></li><li><a href="#npm--v"><code>npm -v</code></a></li><li><a href="#node--v"><code>node -v</code></a></li><li><a href="#npm-config-get-registry"><code>npm config get registry</code></a></li><li><a href="#which-git"><code>which git</code></a></li><li><a href="#permissions-checks">Permissions checks</a></li><li><a href="#validate-the-checksums-of-cached-packages">Validate the checksums of cached packages</a></li></ul><li><a href="#configuration">Configuration</a></li><ul><li><a href="#registry"><code>registry</code></a></li></ul><li><a href="#see-also">See Also</a></li></ul></div>
|
||||
<div id="_table_of_contents"><ul><li><a href="#synopsis">Synopsis</a></li><li><a href="#description">Description</a></li><ul><li><a href="#connecting-to-the-registry"><code>Connecting to the registry</code></a></li><li><a href="#checking-npm-version"><code>Checking npm version</code></a></li><li><a href="#checking-node-version"><code>Checking node version</code></a></li><li><a href="#checking-configured-npm-registry"><code>Checking configured npm registry</code></a></li><li><a href="#checking-for-git-executable-in-path"><code>Checking for git executable in PATH</code></a></li><li><a href="#permissions-checks">Permissions checks</a></li><li><a href="#validate-the-checksums-of-cached-packages">Validate the checksums of cached packages</a></li></ul><li><a href="#configuration">Configuration</a></li><ul><li><a href="#registry"><code>registry</code></a></li></ul><li><a href="#see-also">See Also</a></li></ul></div>
|
||||
</section>
|
||||
|
||||
<div id="_content"><h3 id="synopsis">Synopsis</h3>
|
||||
<pre><code class="language-bash">npm doctor [ping] [registry] [versions] [environment] [permissions] [cache]
|
||||
<pre><code class="language-bash">npm doctor [connection] [registry] [versions] [environment] [permissions] [cache]
|
||||
</code></pre>
|
||||
<p>Note: This command is unaware of workspaces.</p>
|
||||
<h3 id="description">Description</h3>
|
||||
@@ -171,17 +171,18 @@ using old versions of npm. Since npm is constantly improving, running
|
||||
there are any recommended changes, it will display them. By default npm
|
||||
runs all of these checks. You can limit what checks are ran by
|
||||
specifying them as extra arguments.</p>
|
||||
<h4 id="npm-ping"><code>npm ping</code></h4>
|
||||
<h4 id="connecting-to-the-registry"><code>Connecting to the registry</code></h4>
|
||||
<p>By default, npm installs from the primary npm registry,
|
||||
<code>registry.npmjs.org</code>. <code>npm doctor</code> hits a special ping endpoint within the
|
||||
registry. This can also be checked with <code>npm ping</code>. If this check fails,
|
||||
you may be using a proxy that needs to be configured, or may need to talk
|
||||
to your IT staff to get access over HTTPS to <code>registry.npmjs.org</code>.</p>
|
||||
<code>registry.npmjs.org</code>. <code>npm doctor</code> hits a special connection testing
|
||||
endpoint within the registry. This can also be checked with <code>npm ping</code>.
|
||||
If this check fails, you may be using a proxy that needs to be
|
||||
configured, or may need to talk to your IT staff to get access over
|
||||
HTTPS to <code>registry.npmjs.org</code>.</p>
|
||||
<p>This check is done against whichever registry you've configured (you can
|
||||
see what that is by running <code>npm config get registry</code>), and if you're using
|
||||
a private registry that doesn't support the <code>/whoami</code> endpoint supported by
|
||||
the primary registry, this check may fail.</p>
|
||||
<h4 id="npm--v"><code>npm -v</code></h4>
|
||||
<h4 id="checking-npm-version"><code>Checking npm version</code></h4>
|
||||
<p>While Node.js may come bundled with a particular version of npm, it's the
|
||||
policy of the CLI team that we recommend all users run <code>npm@latest</code> if they
|
||||
can. As the CLI is maintained by a small team of contributors, there are
|
||||
@@ -189,21 +190,21 @@ only resources for a single line of development, so npm's own long-term
|
||||
support releases typically only receive critical security and regression
|
||||
fixes. The team believes that the latest tested version of npm is almost
|
||||
always likely to be the most functional and defect-free version of npm.</p>
|
||||
<h4 id="node--v"><code>node -v</code></h4>
|
||||
<h4 id="checking-node-version"><code>Checking node version</code></h4>
|
||||
<p>For most users, in most circumstances, the best version of Node will be the
|
||||
latest long-term support (LTS) release. Those of you who want access to new
|
||||
ECMAscript features or bleeding-edge changes to Node's standard library may
|
||||
be running a newer version, and some may be required to run an older
|
||||
version of Node because of enterprise change control policies. That's OK!
|
||||
But in general, the npm team recommends that most users run Node.js LTS.</p>
|
||||
<h4 id="npm-config-get-registry"><code>npm config get registry</code></h4>
|
||||
<h4 id="checking-configured-npm-registry"><code>Checking configured npm registry</code></h4>
|
||||
<p>You may be installing from private package registries for your project or
|
||||
company. That's great! Others may be following tutorials or StackOverflow
|
||||
questions in an effort to troubleshoot problems you may be having.
|
||||
Sometimes, this may entail changing the registry you're pointing at. This
|
||||
part of <code>npm doctor</code> just lets you, and maybe whoever's helping you with
|
||||
support, know that you're not using the default registry.</p>
|
||||
<h4 id="which-git"><code>which git</code></h4>
|
||||
<h4 id="checking-for-git-executable-in-path"><code>Checking for git executable in PATH</code></h4>
|
||||
<p>While it's documented in the README, it may not be obvious that npm needs
|
||||
Git installed to do many of the things that it does. Also, in some cases
|
||||
– especially on Windows – you may have Git set up in such a way that it's
|
||||
|
||||
+1
-1
@@ -160,7 +160,7 @@ tree at all, use <a href="../commands/npm-explain.html"><code>npm explain</code>
|
||||
the results to only the paths to the packages named. Note that nested
|
||||
packages will <em>also</em> show the paths to the specified packages. For
|
||||
example, running <code>npm ls promzard</code> in npm's source tree will show:</p>
|
||||
<pre><code class="language-bash">npm@10.5.2 /path/to/npm
|
||||
<pre><code class="language-bash">npm@10.7.0 /path/to/npm
|
||||
└─┬ init-package-json@0.0.4
|
||||
└── promzard@0.1.5
|
||||
</code></pre>
|
||||
|
||||
+10
-21
@@ -160,27 +160,16 @@ support this interface.</p>
|
||||
<li><code>npm profile get [<property>]</code>: Display all of the properties of your
|
||||
profile, or one or more specific properties. It looks like:</li>
|
||||
</ul>
|
||||
<pre><code class="language-bash">+-----------------+---------------------------+
|
||||
| name | example |
|
||||
+-----------------+---------------------------+
|
||||
| email | me@example.com (verified) |
|
||||
+-----------------+---------------------------+
|
||||
| two factor auth | auth-and-writes |
|
||||
+-----------------+---------------------------+
|
||||
| fullname | Example User |
|
||||
+-----------------+---------------------------+
|
||||
| homepage | |
|
||||
+-----------------+---------------------------+
|
||||
| freenode | |
|
||||
+-----------------+---------------------------+
|
||||
| twitter | |
|
||||
+-----------------+---------------------------+
|
||||
| github | |
|
||||
+-----------------+---------------------------+
|
||||
| created | 2015-02-26T01:38:35.892Z |
|
||||
+-----------------+---------------------------+
|
||||
| updated | 2017-10-02T21:29:45.922Z |
|
||||
+-----------------+---------------------------+
|
||||
<pre><code>name: example
|
||||
email: e@example.com (verified)
|
||||
two-factor auth: auth-and-writes
|
||||
fullname: Example User
|
||||
homepage:
|
||||
freenode:
|
||||
twitter:
|
||||
github:
|
||||
created: 2015-02-26T01:38:35.892Z
|
||||
updated: 2017-10-02T21:29:45.922Z
|
||||
</code></pre>
|
||||
<ul>
|
||||
<li>
|
||||
|
||||
+2
-8
@@ -142,11 +142,11 @@ npm command-line interface
|
||||
|
||||
<section id="table_of_contents">
|
||||
<h2 id="table-of-contents">Table of contents</h2>
|
||||
<div id="_table_of_contents"><ul><li><a href="#synopsis">Synopsis</a></li><li><a href="#description">Description</a></li><li><a href="#configuration">Configuration</a></li><ul><li><a href="#long"><code>long</code></a></li><li><a href="#json"><code>json</code></a></li><li><a href="#color"><code>color</code></a></li><li><a href="#parseable"><code>parseable</code></a></li><li><a href="#description2"><code>description</code></a></li><li><a href="#searchlimit"><code>searchlimit</code></a></li><li><a href="#searchopts"><code>searchopts</code></a></li><li><a href="#searchexclude"><code>searchexclude</code></a></li><li><a href="#registry"><code>registry</code></a></li><li><a href="#prefer-online"><code>prefer-online</code></a></li><li><a href="#prefer-offline"><code>prefer-offline</code></a></li><li><a href="#offline"><code>offline</code></a></li></ul><li><a href="#see-also">See Also</a></li></ul></div>
|
||||
<div id="_table_of_contents"><ul><li><a href="#synopsis">Synopsis</a></li><li><a href="#description">Description</a></li><li><a href="#configuration">Configuration</a></li><ul><li><a href="#json"><code>json</code></a></li><li><a href="#color"><code>color</code></a></li><li><a href="#parseable"><code>parseable</code></a></li><li><a href="#description2"><code>description</code></a></li><li><a href="#searchlimit"><code>searchlimit</code></a></li><li><a href="#searchopts"><code>searchopts</code></a></li><li><a href="#searchexclude"><code>searchexclude</code></a></li><li><a href="#registry"><code>registry</code></a></li><li><a href="#prefer-online"><code>prefer-online</code></a></li><li><a href="#prefer-offline"><code>prefer-offline</code></a></li><li><a href="#offline"><code>offline</code></a></li></ul><li><a href="#see-also">See Also</a></li></ul></div>
|
||||
</section>
|
||||
|
||||
<div id="_content"><h3 id="synopsis">Synopsis</h3>
|
||||
<pre><code class="language-bash">npm search [search terms ...]
|
||||
<pre><code class="language-bash">npm search <search term> [<search term> ...]
|
||||
|
||||
aliases: find, s, se
|
||||
</code></pre>
|
||||
@@ -170,12 +170,6 @@ and supports standard JavaScript RegExp syntax. In this case search will
|
||||
ignore a trailing <code>/</code> . (Note you must escape or quote many regular
|
||||
expression characters in most shells.)</p>
|
||||
<h3 id="configuration">Configuration</h3>
|
||||
<h4 id="long"><code>long</code></h4>
|
||||
<ul>
|
||||
<li>Default: false</li>
|
||||
<li>Type: Boolean</li>
|
||||
</ul>
|
||||
<p>Show extended information in <code>ls</code>, <code>search</code>, and <code>help-search</code>.</p>
|
||||
<h4 id="json"><code>json</code></h4>
|
||||
<ul>
|
||||
<li>Default: false</li>
|
||||
|
||||
+8
-26
@@ -158,23 +158,13 @@ npm token create [--read-only] [--cidr=list]
|
||||
Shows a table of all active authentication tokens. You can request
|
||||
this as JSON with <code>--json</code> or tab-separated values with <code>--parseable</code>.</li>
|
||||
</ul>
|
||||
<pre><code class="language-bash">+--------+---------+------------+----------+----------------+
|
||||
| id | token | created | read-only | CIDR whitelist |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 7f3134 | 1fa9ba… | 2017-10-02 | yes | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| c03241 | af7aef… | 2017-10-02 | no | 192.168.0.1/24 |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| e0cf92 | 3a436a… | 2017-10-02 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 63eb9d | 74ef35… | 2017-09-28 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 2daaa8 | cbad5f… | 2017-09-26 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 68c2fe | 127e51… | 2017-09-23 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
| 6334e1 | 1dadd1… | 2017-09-23 | no | |
|
||||
+--------+---------+------------+----------+----------------+
|
||||
<pre><code>Read only token npm_1f… with id 7f3134 created 2017-10-21
|
||||
|
||||
Publish token npm_af… with id c03241 created 2017-10-02
|
||||
with IP Whitelist: 192.168.0.1/24
|
||||
|
||||
Publish token npm_… with id e0cf92 created 2017-10-02
|
||||
|
||||
</code></pre>
|
||||
<ul>
|
||||
<li>
|
||||
@@ -191,15 +181,7 @@ website</a>
|
||||
for more information on generating automation tokens.</p>
|
||||
</li>
|
||||
</ul>
|
||||
<pre><code class="language-bash">+----------------+--------------------------------------+
|
||||
| token | a73c9572-f1b9-8983-983d-ba3ac3cc913d |
|
||||
+----------------+--------------------------------------+
|
||||
| cidr_whitelist | |
|
||||
+----------------+--------------------------------------+
|
||||
| readonly | false |
|
||||
+----------------+--------------------------------------+
|
||||
| created | 2017-10-02T07:52:24.838Z |
|
||||
+----------------+--------------------------------------+
|
||||
<pre><code>Created publish token a73c9572-f1b9-8983-983d-ba3ac3cc913d
|
||||
</code></pre>
|
||||
<ul>
|
||||
<li><code>npm token revoke <token|id></code>:
|
||||
|
||||
+1
-1
@@ -150,7 +150,7 @@ npm command-line interface
|
||||
</code></pre>
|
||||
<p>Note: This command is unaware of workspaces.</p>
|
||||
<h3 id="version">Version</h3>
|
||||
<p>10.5.2</p>
|
||||
<p>10.7.0</p>
|
||||
<h3 id="description">Description</h3>
|
||||
<p>npm is the package manager for the Node JavaScript platform. It puts
|
||||
modules in place so that node can find them, and manages dependency
|
||||
|
||||
@@ -850,6 +850,12 @@ version of a package is used everywhere, then you may add an override.</p>
|
||||
<p>Overrides provide a way to replace a package in your dependency tree with
|
||||
another version, or another package entirely. These changes can be scoped as
|
||||
specific or as vague as desired.</p>
|
||||
<p>Overrides are only considered in the root <code>package.json</code> file for a project.
|
||||
Overrides in installed dependencies (including
|
||||
<a href="../using-npm/workspaces.html">workspaces</a>) are not considered in dependency tree
|
||||
resolution. Published packages may dictate their resolutions by pinning
|
||||
dependencies or using an
|
||||
<a href="../configuring-npm/npm-shrinkwrap-json.html"><code>npm-shrinkwrap.json</code></a> file.</p>
|
||||
<p>To make sure the package <code>foo</code> is always installed as version <code>1.0.0</code> no matter
|
||||
what version your dependencies rely on:</p>
|
||||
<pre><code class="language-json">{
|
||||
|
||||
@@ -176,6 +176,7 @@ picture of the package tree, reducing the need to read <code>package.json</code>
|
||||
files, and allowing for significant performance improvements.</p>
|
||||
</li>
|
||||
</ul>
|
||||
<p>When <code>npm</code> creates or updates <code>package-lock.json</code>, it will infer line endings and indentation from <code>package.json</code> so that the formatting of both files matches.</p>
|
||||
<h3 id="package-lockjson-vs-npm-shrinkwrapjson"><code>package-lock.json</code> vs <code>npm-shrinkwrap.json</code></h3>
|
||||
<p>Both of these files have the same format, and perform similar functions in
|
||||
the root of a project.</p>
|
||||
|
||||
Vendored
+2
-3
@@ -1,10 +1,9 @@
|
||||
const log = require('./utils/log-shim.js')
|
||||
const { log } = require('proc-log')
|
||||
const BaseCommand = require('./base-cmd.js')
|
||||
|
||||
// This is the base for all commands whose execWorkspaces just gets
|
||||
// a list of workspace names and passes it on to new Arborist() to
|
||||
// be able to run a filtered Arborist.reify() at some point.
|
||||
|
||||
const BaseCommand = require('./base-command.js')
|
||||
class ArboristCmd extends BaseCommand {
|
||||
get isArboristCmd () {
|
||||
return true
|
||||
|
||||
+8
-9
@@ -1,10 +1,4 @@
|
||||
// Base class for npm commands
|
||||
|
||||
const { relative } = require('path')
|
||||
|
||||
const { definitions } = require('@npmcli/config/lib/definitions')
|
||||
const { aliases: cmdAliases } = require('./utils/cmd-list')
|
||||
const log = require('./utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
|
||||
class BaseCommand {
|
||||
static workspaces = false
|
||||
@@ -18,6 +12,8 @@ class BaseCommand {
|
||||
// this is a static so that we can read from it without instantiating a command
|
||||
// which would require loading the config
|
||||
static get describeUsage () {
|
||||
const { definitions } = require('@npmcli/config/lib/definitions')
|
||||
const { aliases: cmdAliases } = require('./utils/cmd-list')
|
||||
const seenExclusive = new Set()
|
||||
const wrapWidth = 80
|
||||
const { description, usage = [''], name, params } = this
|
||||
@@ -119,7 +115,7 @@ class BaseCommand {
|
||||
const { config } = this.npm
|
||||
|
||||
if (config.get('usage')) {
|
||||
return this.npm.output(this.usage)
|
||||
return output.standard(this.usage)
|
||||
}
|
||||
|
||||
const hasWsConfig = config.get('workspaces') || config.get('workspace').length
|
||||
@@ -161,6 +157,8 @@ class BaseCommand {
|
||||
}
|
||||
|
||||
async setWorkspaces () {
|
||||
const { relative } = require('node:path')
|
||||
|
||||
const includeWorkspaceRoot = this.isArboristCmd
|
||||
? false
|
||||
: this.npm.config.get('include-workspace-root')
|
||||
@@ -169,7 +167,7 @@ class BaseCommand {
|
||||
const relativeFrom = prefixInsideCwd ? this.npm.localPrefix : process.cwd()
|
||||
|
||||
const filters = this.npm.config.get('workspace')
|
||||
const getWorkspaces = require('./workspaces/get-workspaces.js')
|
||||
const getWorkspaces = require('./utils/get-workspaces.js')
|
||||
const ws = await getWorkspaces(filters, {
|
||||
path: this.npm.localPrefix,
|
||||
includeWorkspaceRoot,
|
||||
@@ -181,4 +179,5 @@ class BaseCommand {
|
||||
this.workspacePaths = [...ws.values()]
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BaseCommand
|
||||
Vendored
+2
-2
@@ -1,4 +1,4 @@
|
||||
const validateEngines = require('./es6/validate-engines.js')
|
||||
const cliEntry = require('path').resolve(__dirname, 'cli-entry.js')
|
||||
const validateEngines = require('./cli/validate-engines.js')
|
||||
const cliEntry = require('node:path').resolve(__dirname, 'cli/entry.js')
|
||||
|
||||
module.exports = (process) => validateEngines(process, () => require(cliEntry))
|
||||
+35
-22
@@ -11,14 +11,17 @@ module.exports = async (process, validateEngines) => {
|
||||
process.argv.splice(1, 1, 'npm', '-g')
|
||||
}
|
||||
|
||||
// Patch the global fs module here at the app level
|
||||
require('graceful-fs').gracefulify(require('fs'))
|
||||
|
||||
const satisfies = require('semver/functions/satisfies')
|
||||
const exitHandler = require('./utils/exit-handler.js')
|
||||
const Npm = require('./npm.js')
|
||||
const exitHandler = require('./exit-handler.js')
|
||||
const Npm = require('../npm.js')
|
||||
const npm = new Npm()
|
||||
exitHandler.setNpm(npm)
|
||||
|
||||
// only log node and npm paths in argv initially since argv can contain sensitive info. a cleaned version will be logged later
|
||||
const log = require('./utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
log.verbose('cli', process.argv.slice(0, 2).join(' '))
|
||||
log.info('using', 'npm@%s', npm.version)
|
||||
log.info('using', 'node@%s', process.version)
|
||||
@@ -33,39 +36,49 @@ module.exports = async (process, validateEngines) => {
|
||||
log.warn('cli', validateEngines.unsupportedMessage)
|
||||
}
|
||||
|
||||
let cmd
|
||||
// Now actually fire up npm and run the command.
|
||||
// This is how to use npm programmatically:
|
||||
try {
|
||||
await npm.load()
|
||||
const { exec, command, args } = await npm.load()
|
||||
|
||||
// npm -v
|
||||
if (npm.config.get('version', 'cli')) {
|
||||
npm.output(npm.version)
|
||||
if (!exec) {
|
||||
return exitHandler()
|
||||
}
|
||||
|
||||
// npm --versions
|
||||
if (npm.config.get('versions', 'cli')) {
|
||||
npm.argv = ['version']
|
||||
npm.config.set('usage', false, 'cli')
|
||||
}
|
||||
|
||||
cmd = npm.argv.shift()
|
||||
if (!cmd) {
|
||||
npm.output(npm.usage)
|
||||
if (!command) {
|
||||
output.standard(npm.usage)
|
||||
process.exitCode = 1
|
||||
return exitHandler()
|
||||
}
|
||||
|
||||
await npm.exec(cmd)
|
||||
// Options are prefixed by a hyphen-minus (-, \u2d).
|
||||
// Other dash-type chars look similar but are invalid.
|
||||
const nonDashArgs = npm.argv.filter(a => /^[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]/.test(a))
|
||||
if (nonDashArgs.length) {
|
||||
log.error(
|
||||
'arg',
|
||||
'Argument starts with non-ascii dash, this is probably invalid:',
|
||||
require('@npmcli/redact').redactLog(nonDashArgs.join(', '))
|
||||
)
|
||||
}
|
||||
|
||||
const execPromise = npm.exec(command, args)
|
||||
|
||||
// this is async but we dont await it, since its ok if it doesnt
|
||||
// finish before the command finishes running. it uses command and argv
|
||||
// so it must be initiated here, after the command name is set
|
||||
const updateNotifier = require('./update-notifier.js')
|
||||
// eslint-disable-next-line promise/catch-or-return
|
||||
updateNotifier(npm).then((msg) => (npm.updateNotification = msg))
|
||||
|
||||
await execPromise
|
||||
return exitHandler()
|
||||
} catch (err) {
|
||||
if (err.code === 'EUNKNOWNCOMMAND') {
|
||||
const didYouMean = require('./utils/did-you-mean.js')
|
||||
const suggestions = await didYouMean(npm.localPrefix, cmd)
|
||||
npm.output(`Unknown command: "${cmd}"${suggestions}\n`)
|
||||
npm.output('To see a list of supported npm commands, run:\n npm help')
|
||||
const didYouMean = require('../utils/did-you-mean.js')
|
||||
const suggestions = await didYouMean(npm.localPrefix, err.command)
|
||||
output.standard(`Unknown command: "${err.command}"${suggestions}\n`)
|
||||
output.standard('To see a list of supported npm commands, run:\n npm help')
|
||||
process.exitCode = 1
|
||||
return exitHandler()
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
const os = require('os')
|
||||
const fs = require('fs')
|
||||
|
||||
const log = require('./log-shim.js')
|
||||
const errorMessage = require('./error-message.js')
|
||||
const { log, output, META } = require('proc-log')
|
||||
const errorMessage = require('../utils/error-message.js')
|
||||
const { redactLog: replaceInfo } = require('@npmcli/redact')
|
||||
|
||||
let npm = null // set by the cli
|
||||
@@ -10,21 +7,8 @@ let exitHandlerCalled = false
|
||||
let showLogFileError = false
|
||||
|
||||
process.on('exit', code => {
|
||||
log.disableProgress()
|
||||
|
||||
// process.emit is synchronous, so the timeEnd handler will run before the
|
||||
// unfinished timer check below
|
||||
process.emit('timeEnd', 'npm')
|
||||
|
||||
const hasLoadedNpm = npm?.config.loaded
|
||||
|
||||
// Unfinished timers can be read before config load
|
||||
if (npm) {
|
||||
for (const [name, timer] of npm.unfinishedTimers) {
|
||||
log.verbose('unfinished npm timer', name, timer)
|
||||
}
|
||||
}
|
||||
|
||||
if (!code) {
|
||||
log.info('ok')
|
||||
} else {
|
||||
@@ -34,66 +18,16 @@ process.on('exit', code => {
|
||||
if (!exitHandlerCalled) {
|
||||
process.exitCode = code || 1
|
||||
log.error('', 'Exit handler never called!')
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('')
|
||||
log.error('', 'This is an error with npm itself. Please report this error at:')
|
||||
log.error('', ' <https://github.com/npm/cli/issues>')
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('')
|
||||
showLogFileError = true
|
||||
}
|
||||
|
||||
// npm must be loaded to know where the log file was written
|
||||
if (hasLoadedNpm) {
|
||||
// write the timing file now, this might do nothing based on the configs set.
|
||||
// we need to call it here in case it errors so we dont tell the user
|
||||
// about a timing file that doesn't exist
|
||||
npm.writeTimingFile()
|
||||
|
||||
const logsDir = npm.logsDir
|
||||
const logFiles = npm.logFiles
|
||||
|
||||
const timingDir = npm.timingDir
|
||||
const timingFile = npm.timingFile
|
||||
|
||||
const timing = npm.config.get('timing')
|
||||
const logsMax = npm.config.get('logs-max')
|
||||
|
||||
// Determine whether to show log file message and why it is
|
||||
// being shown since in timing mode we always show the log file message
|
||||
const logMethod = showLogFileError ? 'error' : timing ? 'info' : null
|
||||
|
||||
if (logMethod) {
|
||||
if (!npm.silent) {
|
||||
// just a line break if not in silent mode
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('')
|
||||
}
|
||||
|
||||
const message = []
|
||||
|
||||
if (timingFile) {
|
||||
message.push(`Timing info written to: ${timingFile}`)
|
||||
} else if (timing) {
|
||||
message.push(
|
||||
`The timing file was not written due to an error writing to the directory: ${timingDir}`
|
||||
)
|
||||
}
|
||||
|
||||
if (logFiles.length) {
|
||||
message.push(`A complete log of this run can be found in: ${logFiles}`)
|
||||
} else if (logsMax <= 0) {
|
||||
// user specified no log file
|
||||
message.push(`Log files were not written due to the config logs-max=${logsMax}`)
|
||||
} else {
|
||||
// could be an error writing to the directory
|
||||
message.push(
|
||||
`Log files were not written due to an error writing to the directory: ${logsDir}`,
|
||||
'You can rerun the command with `--loglevel=verbose` to see the logs in your terminal'
|
||||
)
|
||||
}
|
||||
|
||||
log[logMethod]('', message.join('\n'))
|
||||
}
|
||||
|
||||
npm.finish({ showLogFileError })
|
||||
// This removes any listeners npm setup, mostly for tests to avoid max listener warnings
|
||||
npm.unload()
|
||||
}
|
||||
@@ -106,12 +40,11 @@ process.on('exit', code => {
|
||||
const exitHandler = err => {
|
||||
exitHandlerCalled = true
|
||||
|
||||
log.disableProgress()
|
||||
|
||||
const hasLoadedNpm = npm?.config.loaded
|
||||
|
||||
if (!npm) {
|
||||
err = err || new Error('Exit prior to setting npm in exit handler')
|
||||
// Don't use proc-log here since npm was never set
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(err.stack || err.message)
|
||||
return process.exit(1)
|
||||
@@ -119,16 +52,14 @@ const exitHandler = err => {
|
||||
|
||||
if (!hasLoadedNpm) {
|
||||
err = err || new Error('Exit prior to config file resolving.')
|
||||
// Don't use proc-log here since npm was never loaded
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(err.stack || err.message)
|
||||
}
|
||||
|
||||
// only show the notification if it finished.
|
||||
if (typeof npm.updateNotification === 'string') {
|
||||
const { level } = log
|
||||
log.level = 'notice'
|
||||
log.notice('', npm.updateNotification)
|
||||
log.level = level
|
||||
log.notice('', npm.updateNotification, { [META]: true, force: true })
|
||||
}
|
||||
|
||||
let exitCode = process.exitCode || 0
|
||||
@@ -154,6 +85,8 @@ const exitHandler = err => {
|
||||
log.error('weird error', err)
|
||||
noLogMessage = true
|
||||
} else {
|
||||
const os = require('node:os')
|
||||
const fs = require('node:fs')
|
||||
if (!err.code) {
|
||||
const matchErrorCode = err.message.match(/^(?:Error: )?(E[A-Z]+)/)
|
||||
err.code = matchErrorCode && matchErrorCode[1]
|
||||
@@ -205,7 +138,7 @@ const exitHandler = err => {
|
||||
}
|
||||
|
||||
if (hasLoadedNpm) {
|
||||
npm.flushOutput(jsonError)
|
||||
output.flush({ [META]: true, jsonError })
|
||||
}
|
||||
|
||||
log.verbose('exit', exitCode || 0)
|
||||
+7
-13
@@ -49,7 +49,6 @@ const updateCheck = async (npm, spec, version, current) => {
|
||||
return null
|
||||
}
|
||||
|
||||
const useColor = npm.logColor
|
||||
const chalk = npm.logChalk
|
||||
|
||||
// ok! notify the user about this update they should get.
|
||||
@@ -60,19 +59,14 @@ const updateCheck = async (npm, spec, version, current) => {
|
||||
: update.minor !== current.minor ? 'minor'
|
||||
: update.patch !== current.patch ? 'patch'
|
||||
: 'prerelease'
|
||||
const typec = type === 'major' ? chalk.red(type)
|
||||
: type === 'minor' ? chalk.yellow(type)
|
||||
: chalk.green(type)
|
||||
const oldc = chalk.red(current)
|
||||
const latestc = chalk.green(latest)
|
||||
const changelog = `https://github.com/npm/cli/releases/tag/v${latest}`
|
||||
const changelogc = !useColor ? `<${changelog}>` : chalk.cyan(changelog)
|
||||
const typec = type === 'major' ? 'red'
|
||||
: type === 'minor' ? 'yellow'
|
||||
: 'cyan'
|
||||
const cmd = `npm install -g npm@${latest}`
|
||||
const cmdc = !useColor ? `\`${cmd}\`` : chalk.green(cmd)
|
||||
const message = `\nNew ${typec} version of npm available! ` +
|
||||
`${oldc} -> ${latestc}\n` +
|
||||
`Changelog: ${changelogc}\n` +
|
||||
`Run ${cmdc} to update!\n`
|
||||
const message = `\nNew ${chalk[typec](type)} version of npm available! ` +
|
||||
`${chalk[typec](current)} -> ${chalk.blue(latest)}\n` +
|
||||
`Changelog: ${chalk.blue(`https://github.com/npm/cli/releases/tag/v${latest}`)}\n` +
|
||||
`To update run: ${chalk.underline(cmd)}\n`
|
||||
|
||||
return message
|
||||
}
|
||||
File renamed without changes.
Vendored
+8
-8
@@ -1,11 +1,11 @@
|
||||
const libnpmaccess = require('libnpmaccess')
|
||||
const npa = require('npm-package-arg')
|
||||
const { output } = require('proc-log')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
const localeCompare = require('@isaacs/string-locale-compare')('en')
|
||||
|
||||
const otplease = require('../utils/otplease.js')
|
||||
const getIdentity = require('../utils/get-identity.js')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const commands = [
|
||||
'get',
|
||||
@@ -36,7 +36,7 @@ class Access extends BaseCommand {
|
||||
]
|
||||
|
||||
static usage = [
|
||||
'list packages [<user>|<scope>|<scope:team> [<package>]',
|
||||
'list packages [<user>|<scope>|<scope:team>] [<package>]',
|
||||
'list collaborators [<package> [<user>]]',
|
||||
'get status [<package>]',
|
||||
'set status=public|private [<package>]',
|
||||
@@ -197,7 +197,7 @@ class Access extends BaseCommand {
|
||||
}
|
||||
|
||||
#output (items, limiter) {
|
||||
const output = {}
|
||||
const outputs = {}
|
||||
const lookup = {
|
||||
__proto__: null,
|
||||
read: 'read-only',
|
||||
@@ -205,14 +205,14 @@ class Access extends BaseCommand {
|
||||
}
|
||||
for (const item in items) {
|
||||
const val = items[item]
|
||||
output[item] = lookup[val] || val
|
||||
outputs[item] = lookup[val] || val
|
||||
}
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(JSON.stringify(output, null, 2))
|
||||
output.standard(JSON.stringify(outputs, null, 2))
|
||||
} else {
|
||||
for (const item of Object.keys(output).sort(localeCompare)) {
|
||||
for (const item of Object.keys(outputs).sort(localeCompare)) {
|
||||
if (!limiter || limiter === item) {
|
||||
this.npm.output(`${item}: ${output[item]}`)
|
||||
output.standard(`${item}: ${outputs[item]}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+5
-6
@@ -1,8 +1,7 @@
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const { redactLog: replaceInfo } = require('@npmcli/redact')
|
||||
const auth = require('../utils/auth.js')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class AddUser extends BaseCommand {
|
||||
static description = 'Add a registry user account'
|
||||
@@ -13,7 +12,7 @@ class AddUser extends BaseCommand {
|
||||
'auth-type',
|
||||
]
|
||||
|
||||
async exec (args) {
|
||||
async exec () {
|
||||
const scope = this.npm.config.get('scope')
|
||||
let registry = this.npm.config.get('registry')
|
||||
|
||||
@@ -27,7 +26,6 @@ class AddUser extends BaseCommand {
|
||||
|
||||
const creds = this.npm.config.getCredentialsByURI(registry)
|
||||
|
||||
log.disableProgress()
|
||||
log.notice('', `Log in on ${replaceInfo(registry)}`)
|
||||
|
||||
const { message, newCreds } = await auth.adduser(this.npm, {
|
||||
@@ -45,7 +43,8 @@ class AddUser extends BaseCommand {
|
||||
|
||||
await this.npm.config.save('user')
|
||||
|
||||
this.npm.output(message)
|
||||
output.standard(message)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AddUser
|
||||
Vendored
+3
-393
@@ -1,399 +1,9 @@
|
||||
const npmAuditReport = require('npm-audit-report')
|
||||
const fetch = require('npm-registry-fetch')
|
||||
const localeCompare = require('@isaacs/string-locale-compare')('en')
|
||||
const npa = require('npm-package-arg')
|
||||
const pacote = require('pacote')
|
||||
const pMap = require('p-map')
|
||||
const tufClient = require('@sigstore/tuf')
|
||||
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
const auditError = require('../utils/audit-error.js')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const reifyFinish = require('../utils/reify-finish.js')
|
||||
|
||||
const sortAlphabetically = (a, b) => localeCompare(a.name, b.name)
|
||||
|
||||
class VerifySignatures {
|
||||
constructor (tree, filterSet, npm, opts) {
|
||||
this.tree = tree
|
||||
this.filterSet = filterSet
|
||||
this.npm = npm
|
||||
this.opts = opts
|
||||
this.keys = new Map()
|
||||
this.invalid = []
|
||||
this.missing = []
|
||||
this.checkedPackages = new Set()
|
||||
this.auditedWithKeysCount = 0
|
||||
this.verifiedSignatureCount = 0
|
||||
this.verifiedAttestationCount = 0
|
||||
this.exitCode = 0
|
||||
}
|
||||
|
||||
async run () {
|
||||
const start = process.hrtime.bigint()
|
||||
|
||||
// Find all deps in tree
|
||||
const { edges, registries } = this.getEdgesOut(this.tree.inventory.values(), this.filterSet)
|
||||
if (edges.size === 0) {
|
||||
throw new Error('found no installed dependencies to audit')
|
||||
}
|
||||
|
||||
const tuf = await tufClient.initTUF({
|
||||
cachePath: this.opts.tufCache,
|
||||
retry: this.opts.retry,
|
||||
timeout: this.opts.timeout,
|
||||
})
|
||||
await Promise.all([...registries].map(registry => this.setKeys({ registry, tuf })))
|
||||
|
||||
const progress = log.newItem('verifying registry signatures', edges.size)
|
||||
const mapper = async (edge) => {
|
||||
progress.completeWork(1)
|
||||
await this.getVerifiedInfo(edge)
|
||||
}
|
||||
await pMap(edges, mapper, { concurrency: 20, stopOnError: true })
|
||||
|
||||
// Didn't find any dependencies that could be verified, e.g. only local
|
||||
// deps, missing version, not on a registry etc.
|
||||
if (!this.auditedWithKeysCount) {
|
||||
throw new Error('found no dependencies to audit that were installed from ' +
|
||||
'a supported registry')
|
||||
}
|
||||
|
||||
const invalid = this.invalid.sort(sortAlphabetically)
|
||||
const missing = this.missing.sort(sortAlphabetically)
|
||||
|
||||
const hasNoInvalidOrMissing = invalid.length === 0 && missing.length === 0
|
||||
|
||||
if (!hasNoInvalidOrMissing) {
|
||||
process.exitCode = 1
|
||||
}
|
||||
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(JSON.stringify({
|
||||
invalid,
|
||||
missing,
|
||||
}, null, 2))
|
||||
return
|
||||
}
|
||||
const end = process.hrtime.bigint()
|
||||
const elapsed = end - start
|
||||
|
||||
const auditedPlural = this.auditedWithKeysCount > 1 ? 's' : ''
|
||||
const timing = `audited ${this.auditedWithKeysCount} package${auditedPlural} in ` +
|
||||
`${Math.floor(Number(elapsed) / 1e9)}s`
|
||||
this.npm.output(timing)
|
||||
this.npm.output('')
|
||||
|
||||
const verifiedBold = this.npm.chalk.bold('verified')
|
||||
if (this.verifiedSignatureCount) {
|
||||
if (this.verifiedSignatureCount === 1) {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`${this.verifiedSignatureCount} package has a ${verifiedBold} registry signature`)
|
||||
} else {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`${this.verifiedSignatureCount} packages have ${verifiedBold} registry signatures`)
|
||||
}
|
||||
this.npm.output('')
|
||||
}
|
||||
|
||||
if (this.verifiedAttestationCount) {
|
||||
if (this.verifiedAttestationCount === 1) {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`${this.verifiedAttestationCount} package has a ${verifiedBold} attestation`)
|
||||
} else {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`${this.verifiedAttestationCount} packages have ${verifiedBold} attestations`)
|
||||
}
|
||||
this.npm.output('')
|
||||
}
|
||||
|
||||
if (missing.length) {
|
||||
const missingClr = this.npm.chalk.bold(this.npm.chalk.red('missing'))
|
||||
if (missing.length === 1) {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`1 package has a ${missingClr} registry signature but the registry is providing signing keys:`)
|
||||
} else {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`${missing.length} packages have ${missingClr} registry signatures but the registry is providing signing keys:`)
|
||||
}
|
||||
this.npm.output('')
|
||||
missing.map(m =>
|
||||
this.npm.output(`${this.npm.chalk.red(`${m.name}@${m.version}`)} (${m.registry})`)
|
||||
)
|
||||
}
|
||||
|
||||
if (invalid.length) {
|
||||
if (missing.length) {
|
||||
this.npm.output('')
|
||||
}
|
||||
const invalidClr = this.npm.chalk.bold(this.npm.chalk.red('invalid'))
|
||||
// We can have either invalid signatures or invalid provenance
|
||||
const invalidSignatures = this.invalid.filter(i => i.code === 'EINTEGRITYSIGNATURE')
|
||||
if (invalidSignatures.length) {
|
||||
if (invalidSignatures.length === 1) {
|
||||
this.npm.output(`1 package has an ${invalidClr} registry signature:`)
|
||||
} else {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`${invalidSignatures.length} packages have ${invalidClr} registry signatures:`)
|
||||
}
|
||||
this.npm.output('')
|
||||
invalidSignatures.map(i =>
|
||||
this.npm.output(`${this.npm.chalk.red(`${i.name}@${i.version}`)} (${i.registry})`)
|
||||
)
|
||||
this.npm.output('')
|
||||
}
|
||||
|
||||
const invalidAttestations = this.invalid.filter(i => i.code === 'EATTESTATIONVERIFY')
|
||||
if (invalidAttestations.length) {
|
||||
if (invalidAttestations.length === 1) {
|
||||
this.npm.output(`1 package has an ${invalidClr} attestation:`)
|
||||
} else {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`${invalidAttestations.length} packages have ${invalidClr} attestations:`)
|
||||
}
|
||||
this.npm.output('')
|
||||
invalidAttestations.map(i =>
|
||||
this.npm.output(`${this.npm.chalk.red(`${i.name}@${i.version}`)} (${i.registry})`)
|
||||
)
|
||||
this.npm.output('')
|
||||
}
|
||||
|
||||
if (invalid.length === 1) {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`Someone might have tampered with this package since it was published on the registry!`)
|
||||
} else {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`Someone might have tampered with these packages since they were published on the registry!`)
|
||||
}
|
||||
this.npm.output('')
|
||||
}
|
||||
}
|
||||
|
||||
getEdgesOut (nodes, filterSet) {
|
||||
const edges = new Set()
|
||||
const registries = new Set()
|
||||
for (const node of nodes) {
|
||||
for (const edge of node.edgesOut.values()) {
|
||||
const filteredOut =
|
||||
edge.from
|
||||
&& filterSet
|
||||
&& filterSet.size > 0
|
||||
&& !filterSet.has(edge.from.target)
|
||||
|
||||
if (!filteredOut) {
|
||||
const spec = this.getEdgeSpec(edge)
|
||||
if (spec) {
|
||||
// Prefetch and cache public keys from used registries
|
||||
registries.add(this.getSpecRegistry(spec))
|
||||
}
|
||||
edges.add(edge)
|
||||
}
|
||||
}
|
||||
}
|
||||
return { edges, registries }
|
||||
}
|
||||
|
||||
async setKeys ({ registry, tuf }) {
|
||||
const { host, pathname } = new URL(registry)
|
||||
// Strip any trailing slashes from pathname
|
||||
const regKey = `${host}${pathname.replace(/\/$/, '')}/keys.json`
|
||||
let keys = await tuf.getTarget(regKey)
|
||||
.then((target) => JSON.parse(target))
|
||||
.then(({ keys: ks }) => ks.map((key) => ({
|
||||
...key,
|
||||
keyid: key.keyId,
|
||||
pemkey: `-----BEGIN PUBLIC KEY-----\n${key.publicKey.rawBytes}\n-----END PUBLIC KEY-----`,
|
||||
expires: key.publicKey.validFor.end || null,
|
||||
}))).catch(err => {
|
||||
if (err.code === 'TUF_FIND_TARGET_ERROR') {
|
||||
return null
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
})
|
||||
|
||||
// If keys not found in Sigstore TUF repo, fallback to registry keys API
|
||||
if (!keys) {
|
||||
keys = await fetch.json('/-/npm/v1/keys', {
|
||||
...this.npm.flatOptions,
|
||||
registry,
|
||||
}).then(({ keys: ks }) => ks.map((key) => ({
|
||||
...key,
|
||||
pemkey: `-----BEGIN PUBLIC KEY-----\n${key.key}\n-----END PUBLIC KEY-----`,
|
||||
}))).catch(err => {
|
||||
if (err.code === 'E404' || err.code === 'E400') {
|
||||
return null
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (keys) {
|
||||
this.keys.set(registry, keys)
|
||||
}
|
||||
}
|
||||
|
||||
getEdgeType (edge) {
|
||||
return edge.optional ? 'optionalDependencies'
|
||||
: edge.peer ? 'peerDependencies'
|
||||
: edge.dev ? 'devDependencies'
|
||||
: 'dependencies'
|
||||
}
|
||||
|
||||
getEdgeSpec (edge) {
|
||||
let name = edge.name
|
||||
try {
|
||||
name = npa(edge.spec).subSpec.name
|
||||
} catch {
|
||||
// leave it as edge.name
|
||||
}
|
||||
try {
|
||||
return npa(`${name}@${edge.spec}`)
|
||||
} catch {
|
||||
// Skip packages with invalid spec
|
||||
}
|
||||
}
|
||||
|
||||
buildRegistryConfig (registry) {
|
||||
const keys = this.keys.get(registry) || []
|
||||
const parsedRegistry = new URL(registry)
|
||||
const regKey = `//${parsedRegistry.host}${parsedRegistry.pathname}`
|
||||
return {
|
||||
[`${regKey}:_keys`]: keys,
|
||||
}
|
||||
}
|
||||
|
||||
getSpecRegistry (spec) {
|
||||
return fetch.pickRegistry(spec, this.npm.flatOptions)
|
||||
}
|
||||
|
||||
getValidPackageInfo (edge) {
|
||||
const type = this.getEdgeType(edge)
|
||||
// Skip potentially optional packages that are not on disk, as these could
|
||||
// be omitted during install
|
||||
if (edge.error === 'MISSING' && type !== 'dependencies') {
|
||||
return
|
||||
}
|
||||
|
||||
const spec = this.getEdgeSpec(edge)
|
||||
// Skip invalid version requirements
|
||||
if (!spec) {
|
||||
return
|
||||
}
|
||||
const node = edge.to || edge
|
||||
const { version } = node.package || {}
|
||||
|
||||
if (node.isWorkspace || // Skip local workspaces packages
|
||||
!version || // Skip packages that don't have a installed version, e.g. optonal dependencies
|
||||
!spec.registry) { // Skip if not from registry, e.g. git package
|
||||
return
|
||||
}
|
||||
|
||||
for (const omitType of this.npm.config.get('omit')) {
|
||||
if (node[omitType]) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: spec.name,
|
||||
version,
|
||||
type,
|
||||
location: node.location,
|
||||
registry: this.getSpecRegistry(spec),
|
||||
}
|
||||
}
|
||||
|
||||
async verifySignatures (name, version, registry) {
|
||||
const {
|
||||
_integrity: integrity,
|
||||
_signatures,
|
||||
_attestations,
|
||||
_resolved: resolved,
|
||||
} = await pacote.manifest(`${name}@${version}`, {
|
||||
verifySignatures: true,
|
||||
verifyAttestations: true,
|
||||
...this.buildRegistryConfig(registry),
|
||||
...this.npm.flatOptions,
|
||||
})
|
||||
const signatures = _signatures || []
|
||||
const result = {
|
||||
integrity,
|
||||
signatures,
|
||||
attestations: _attestations,
|
||||
resolved,
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async getVerifiedInfo (edge) {
|
||||
const info = this.getValidPackageInfo(edge)
|
||||
if (!info) {
|
||||
return
|
||||
}
|
||||
const { name, version, location, registry, type } = info
|
||||
if (this.checkedPackages.has(location)) {
|
||||
// we already did or are doing this one
|
||||
return
|
||||
}
|
||||
this.checkedPackages.add(location)
|
||||
|
||||
// We only "audit" or verify the signature, or the presence of it, on
|
||||
// packages whose registry returns signing keys
|
||||
const keys = this.keys.get(registry) || []
|
||||
if (keys.length) {
|
||||
this.auditedWithKeysCount += 1
|
||||
}
|
||||
|
||||
try {
|
||||
const { integrity, signatures, attestations, resolved } = await this.verifySignatures(
|
||||
name, version, registry
|
||||
)
|
||||
|
||||
// Currently we only care about missing signatures on registries that provide a public key
|
||||
// We could make this configurable in the future with a strict/paranoid mode
|
||||
if (signatures.length) {
|
||||
this.verifiedSignatureCount += 1
|
||||
} else if (keys.length) {
|
||||
this.missing.push({
|
||||
integrity,
|
||||
location,
|
||||
name,
|
||||
registry,
|
||||
resolved,
|
||||
version,
|
||||
})
|
||||
}
|
||||
|
||||
// Track verified attestations separately to registry signatures, as all
|
||||
// packages on registries with signing keys are expected to have registry
|
||||
// signatures, but not all packages have provenance and publish attestations.
|
||||
if (attestations) {
|
||||
this.verifiedAttestationCount += 1
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.code === 'EINTEGRITYSIGNATURE' || e.code === 'EATTESTATIONVERIFY') {
|
||||
this.invalid.push({
|
||||
code: e.code,
|
||||
message: e.message,
|
||||
integrity: e.integrity,
|
||||
keyid: e.keyid,
|
||||
location,
|
||||
name,
|
||||
registry,
|
||||
resolved: e.resolved,
|
||||
signature: e.signature,
|
||||
predicateType: e.predicateType,
|
||||
type,
|
||||
version,
|
||||
})
|
||||
} else {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const VerifySignatures = require('../utils/verify-signatures.js')
|
||||
|
||||
class Audit extends ArboristWorkspaceCmd {
|
||||
static description = 'Run a security audit'
|
||||
@@ -467,7 +77,7 @@ class Audit extends ArboristWorkspaceCmd {
|
||||
chalk: this.npm.chalk,
|
||||
})
|
||||
process.exitCode = process.exitCode || result.exitCode
|
||||
this.npm.output(result.report)
|
||||
output.standard(result.report)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
+12
-12
@@ -3,11 +3,11 @@ const pacote = require('pacote')
|
||||
const fs = require('fs/promises')
|
||||
const { join } = require('path')
|
||||
const semver = require('semver')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
const npa = require('npm-package-arg')
|
||||
const jsonParse = require('json-parse-even-better-errors')
|
||||
const localeCompare = require('@isaacs/string-locale-compare')('en')
|
||||
const log = require('../utils/log-shim')
|
||||
const { log, output } = require('proc-log')
|
||||
|
||||
const searchCachePackage = async (path, parsed, cacheKeys) => {
|
||||
/* eslint-disable-next-line max-len */
|
||||
@@ -135,7 +135,7 @@ class Cache extends BaseCommand {
|
||||
log.warn(`Not Found: ${key}`)
|
||||
break
|
||||
}
|
||||
this.npm.output(`Deleted: ${key}`)
|
||||
output.standard(`Deleted: ${key}`)
|
||||
await cacache.rm.entry(cachePath, key)
|
||||
// XXX this could leave other entries without content!
|
||||
await cacache.rm.content(cachePath, entry.integrity)
|
||||
@@ -170,20 +170,20 @@ class Cache extends BaseCommand {
|
||||
? `~${cache.slice(process.env.HOME.length)}`
|
||||
: cache
|
||||
const stats = await cacache.verify(cache)
|
||||
this.npm.output(`Cache verified and compressed (${prefix})`)
|
||||
this.npm.output(`Content verified: ${stats.verifiedContent} (${stats.keptSize} bytes)`)
|
||||
output.standard(`Cache verified and compressed (${prefix})`)
|
||||
output.standard(`Content verified: ${stats.verifiedContent} (${stats.keptSize} bytes)`)
|
||||
if (stats.badContentCount) {
|
||||
this.npm.output(`Corrupted content removed: ${stats.badContentCount}`)
|
||||
output.standard(`Corrupted content removed: ${stats.badContentCount}`)
|
||||
}
|
||||
if (stats.reclaimedCount) {
|
||||
/* eslint-disable-next-line max-len */
|
||||
this.npm.output(`Content garbage-collected: ${stats.reclaimedCount} (${stats.reclaimedSize} bytes)`)
|
||||
output.standard(`Content garbage-collected: ${stats.reclaimedCount} (${stats.reclaimedSize} bytes)`)
|
||||
}
|
||||
if (stats.missingContent) {
|
||||
this.npm.output(`Missing content: ${stats.missingContent}`)
|
||||
output.standard(`Missing content: ${stats.missingContent}`)
|
||||
}
|
||||
this.npm.output(`Index entries: ${stats.totalEntries}`)
|
||||
this.npm.output(`Finished in ${stats.runTime.total / 1000}s`)
|
||||
output.standard(`Index entries: ${stats.totalEntries}`)
|
||||
output.standard(`Finished in ${stats.runTime.total / 1000}s`)
|
||||
}
|
||||
|
||||
// npm cache ls [--package <spec> ...]
|
||||
@@ -203,10 +203,10 @@ class Cache extends BaseCommand {
|
||||
results.add(key)
|
||||
}
|
||||
}
|
||||
[...results].sort(localeCompare).forEach(key => this.npm.output(key))
|
||||
[...results].sort(localeCompare).forEach(key => output.standard(key))
|
||||
return
|
||||
}
|
||||
cacheKeys.sort(localeCompare).forEach(key => this.npm.output(key))
|
||||
cacheKeys.sort(localeCompare).forEach(key => output.standard(key))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
+3
-5
@@ -1,9 +1,8 @@
|
||||
const reifyFinish = require('../utils/reify-finish.js')
|
||||
const runScript = require('@npmcli/run-script')
|
||||
const fs = require('fs/promises')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { log, time } = require('proc-log')
|
||||
const validateLockfile = require('../utils/validate-lockfile.js')
|
||||
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
class CI extends ArboristWorkspaceCmd {
|
||||
@@ -79,10 +78,10 @@ class CI extends ArboristWorkspaceCmd {
|
||||
if (!dryRun) {
|
||||
// Only remove node_modules after we've successfully loaded the virtual
|
||||
// tree and validated the lockfile
|
||||
await this.npm.time('npm-ci:rm', async () => {
|
||||
await time.start('npm-ci:rm', async () => {
|
||||
const path = `${where}/node_modules`
|
||||
// get the list of entries so we can skip the glob for performance
|
||||
const entries = await fs.readdir(path, null).catch(er => [])
|
||||
const entries = await fs.readdir(path, null).catch(() => [])
|
||||
return Promise.all(entries.map(f => fs.rm(`${path}/${f}`,
|
||||
{ force: true, recursive: true })))
|
||||
})
|
||||
@@ -109,7 +108,6 @@ class CI extends ArboristWorkspaceCmd {
|
||||
args: [],
|
||||
scriptShell,
|
||||
stdio: 'inherit',
|
||||
banner: !this.npm.silent,
|
||||
event,
|
||||
})
|
||||
}
|
||||
|
||||
Vendored
+9
-9
@@ -27,22 +27,22 @@
|
||||
// Matches are wrapped with ' to escape them, if necessary, and then printed
|
||||
// one per line for the shell completion method to consume in IFS=$'\n' mode
|
||||
// as an array.
|
||||
//
|
||||
|
||||
const fs = require('fs/promises')
|
||||
const nopt = require('nopt')
|
||||
const { resolve } = require('path')
|
||||
|
||||
const { output } = require('proc-log')
|
||||
const Npm = require('../npm.js')
|
||||
const { definitions, shorthands } = require('@npmcli/config/lib/definitions')
|
||||
const { commands, aliases, deref } = require('../utils/cmd-list.js')
|
||||
const { isWindowsShell } = require('../utils/is-windows.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const fileExists = (file) => fs.stat(file).then(s => s.isFile()).catch(() => false)
|
||||
|
||||
const configNames = Object.keys(definitions)
|
||||
const shorthandNames = Object.keys(shorthands)
|
||||
const allConfs = configNames.concat(shorthandNames)
|
||||
const { isWindowsShell } = require('../utils/is-windows.js')
|
||||
const fileExists = (file) => fs.stat(file).then(s => s.isFile()).catch(() => false)
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
|
||||
class Completion extends BaseCommand {
|
||||
static description = 'Tab Completion for npm'
|
||||
@@ -185,7 +185,7 @@ class Completion extends BaseCommand {
|
||||
}
|
||||
|
||||
if (compls.length > 0) {
|
||||
this.npm.output(compls.join('\n'))
|
||||
output.standard(compls.join('\n'))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,7 +248,7 @@ const configCompl = opts => {
|
||||
|
||||
// expand with the valid values of various config values.
|
||||
// not yet implemented.
|
||||
const configValueCompl = opts => []
|
||||
const configValueCompl = () => []
|
||||
|
||||
// check if the thing is a flag or not.
|
||||
const isFlag = word => {
|
||||
@@ -265,7 +265,7 @@ const isFlag = word => {
|
||||
|
||||
// complete against the npm commands
|
||||
// if they all resolve to the same thing, just return the thing it already is
|
||||
const cmdCompl = (opts, npm) => {
|
||||
const cmdCompl = (opts) => {
|
||||
const allCommands = commands.concat(Object.keys(aliases))
|
||||
const matches = allCommands.filter(c => c.startsWith(opts.partialWord))
|
||||
if (!matches.length) {
|
||||
|
||||
Vendored
+36
-41
@@ -1,12 +1,12 @@
|
||||
const { mkdir, readFile, writeFile } = require('fs/promises')
|
||||
const { dirname, resolve } = require('path')
|
||||
const { spawn } = require('child_process')
|
||||
const { EOL } = require('os')
|
||||
const ini = require('ini')
|
||||
const { mkdir, readFile, writeFile } = require('node:fs/promises')
|
||||
const { dirname, resolve } = require('node:path')
|
||||
const { spawn } = require('node:child_process')
|
||||
const { EOL } = require('node:os')
|
||||
const localeCompare = require('@isaacs/string-locale-compare')('en')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
const { defaults, definitions } = require('@npmcli/config/lib/definitions')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
// These are the configs that we can nerf-dart. Not all of them currently even
|
||||
// *have* config definitions so we have to explicitly validate them here
|
||||
@@ -47,7 +47,6 @@ const publicVar = k => {
|
||||
return true
|
||||
}
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Config extends BaseCommand {
|
||||
static description = 'Manage the npm configuration files'
|
||||
static name = 'config'
|
||||
@@ -111,35 +110,30 @@ class Config extends BaseCommand {
|
||||
}
|
||||
|
||||
async exec ([action, ...args]) {
|
||||
log.disableProgress()
|
||||
try {
|
||||
switch (action) {
|
||||
case 'set':
|
||||
await this.set(args)
|
||||
break
|
||||
case 'get':
|
||||
await this.get(args)
|
||||
break
|
||||
case 'delete':
|
||||
case 'rm':
|
||||
case 'del':
|
||||
await this.del(args)
|
||||
break
|
||||
case 'list':
|
||||
case 'ls':
|
||||
await (this.npm.flatOptions.json ? this.listJson() : this.list())
|
||||
break
|
||||
case 'edit':
|
||||
await this.edit()
|
||||
break
|
||||
case 'fix':
|
||||
await this.fix()
|
||||
break
|
||||
default:
|
||||
throw this.usageError()
|
||||
}
|
||||
} finally {
|
||||
log.enableProgress()
|
||||
switch (action) {
|
||||
case 'set':
|
||||
await this.set(args)
|
||||
break
|
||||
case 'get':
|
||||
await this.get(args)
|
||||
break
|
||||
case 'delete':
|
||||
case 'rm':
|
||||
case 'del':
|
||||
await this.del(args)
|
||||
break
|
||||
case 'list':
|
||||
case 'ls':
|
||||
await (this.npm.flatOptions.json ? this.listJson() : this.list())
|
||||
break
|
||||
case 'edit':
|
||||
await this.edit()
|
||||
break
|
||||
case 'fix':
|
||||
await this.fix()
|
||||
break
|
||||
default:
|
||||
throw this.usageError()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +184,7 @@ class Config extends BaseCommand {
|
||||
const pref = keys.length > 1 ? `${key}=` : ''
|
||||
out.push(pref + this.npm.config.get(key))
|
||||
}
|
||||
this.npm.output(out.join('\n'))
|
||||
output.standard(out.join('\n'))
|
||||
}
|
||||
|
||||
async del (keys) {
|
||||
@@ -206,6 +200,7 @@ class Config extends BaseCommand {
|
||||
}
|
||||
|
||||
async edit () {
|
||||
const ini = require('ini')
|
||||
const e = this.npm.flatOptions.editor
|
||||
const where = this.npm.flatOptions.location
|
||||
const file = this.npm.config.data.get(where).source
|
||||
@@ -287,7 +282,7 @@ ${defData}
|
||||
this.npm.config.repair(problems)
|
||||
const locations = []
|
||||
|
||||
this.npm.output('The following configuration problems have been repaired:\n')
|
||||
output.standard('The following configuration problems have been repaired:\n')
|
||||
const summary = problems.map(({ action, from, to, key, where }) => {
|
||||
// coverage disabled for else branch because it is intentionally omitted
|
||||
// istanbul ignore else
|
||||
@@ -300,7 +295,7 @@ ${defData}
|
||||
return `- \`${key}\` deleted from ${where} config`
|
||||
}
|
||||
}).join('\n')
|
||||
this.npm.output(summary)
|
||||
output.standard(summary)
|
||||
|
||||
return await Promise.all(locations.map((location) => this.npm.config.save(location)))
|
||||
}
|
||||
@@ -359,7 +354,7 @@ ${defData}
|
||||
}
|
||||
}
|
||||
|
||||
this.npm.output(msg.join('\n').trim())
|
||||
output.standard(msg.join('\n').trim())
|
||||
}
|
||||
|
||||
async listJson () {
|
||||
@@ -371,7 +366,7 @@ ${defData}
|
||||
|
||||
publicConf[key] = this.npm.config.get(key)
|
||||
}
|
||||
this.npm.output(JSON.stringify(publicConf, null, 2))
|
||||
output.standard(JSON.stringify(publicConf, null, 2))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
+2
-3
@@ -1,8 +1,7 @@
|
||||
// dedupe duplicated packages, or find them in the tree
|
||||
const reifyFinish = require('../utils/reify-finish.js')
|
||||
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
// dedupe duplicated packages, or find them in the tree
|
||||
class Dedupe extends ArboristWorkspaceCmd {
|
||||
static description = 'Reduce duplication in the package tree'
|
||||
static name = 'dedupe'
|
||||
@@ -22,7 +21,7 @@ class Dedupe extends ArboristWorkspaceCmd {
|
||||
...super.params,
|
||||
]
|
||||
|
||||
async exec (args) {
|
||||
async exec () {
|
||||
if (this.npm.global) {
|
||||
const er = new Error('`npm dedupe` does not work in global mode.')
|
||||
er.code = 'EDEDUPEGLOBAL'
|
||||
|
||||
Vendored
+1
-1
@@ -4,7 +4,7 @@ const npa = require('npm-package-arg')
|
||||
const semver = require('semver')
|
||||
const getIdentity = require('../utils/get-identity.js')
|
||||
const libaccess = require('libnpmaccess')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Deprecate extends BaseCommand {
|
||||
static description = 'Deprecate a version of a package'
|
||||
|
||||
Vendored
+5
-5
@@ -4,9 +4,9 @@ const libnpmdiff = require('libnpmdiff')
|
||||
const npa = require('npm-package-arg')
|
||||
const pacote = require('pacote')
|
||||
const pickManifest = require('npm-pick-manifest')
|
||||
const log = require('../utils/log-shim')
|
||||
const { log, output } = require('proc-log')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Diff extends BaseCommand {
|
||||
static description = 'The registry diff command'
|
||||
@@ -64,7 +64,7 @@ class Diff extends BaseCommand {
|
||||
diffFiles: args,
|
||||
where: this.top,
|
||||
})
|
||||
return this.npm.output(res)
|
||||
return output.standard(res)
|
||||
}
|
||||
|
||||
async execWorkspaces (args) {
|
||||
@@ -78,7 +78,7 @@ class Diff extends BaseCommand {
|
||||
|
||||
// get the package name from the packument at `path`
|
||||
// throws if no packument is present OR if it does not have `name` attribute
|
||||
async packageName (path) {
|
||||
async packageName () {
|
||||
let name
|
||||
try {
|
||||
const { content: pkg } = await pkgJson.normalize(this.prefix)
|
||||
@@ -103,7 +103,7 @@ class Diff extends BaseCommand {
|
||||
// no arguments, defaults to comparing cwd
|
||||
// to its latest published registry version
|
||||
if (!a) {
|
||||
const pkgName = await this.packageName(this.prefix)
|
||||
const pkgName = await this.packageName()
|
||||
return [
|
||||
`${pkgName}@${this.npm.config.get('tag')}`,
|
||||
`file:${this.prefix.replace(/#/g, '%23')}`,
|
||||
|
||||
Vendored
+7
-6
@@ -1,10 +1,10 @@
|
||||
const npa = require('npm-package-arg')
|
||||
const regFetch = require('npm-registry-fetch')
|
||||
const semver = require('semver')
|
||||
const log = require('../utils/log-shim')
|
||||
const { log, output } = require('proc-log')
|
||||
const otplease = require('../utils/otplease.js')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class DistTag extends BaseCommand {
|
||||
static description = 'Modify package distribution tags'
|
||||
@@ -120,7 +120,7 @@ class DistTag extends BaseCommand {
|
||||
spec,
|
||||
}
|
||||
await otplease(this.npm, reqOpts, o => regFetch(url, o))
|
||||
this.npm.output(`+${t}: ${spec.name}@${version}`)
|
||||
output.standard(`+${t}: ${spec.name}@${version}`)
|
||||
}
|
||||
|
||||
async remove (spec, tag, opts) {
|
||||
@@ -146,7 +146,7 @@ class DistTag extends BaseCommand {
|
||||
spec,
|
||||
}
|
||||
await otplease(this.npm, reqOpts, o => regFetch(url, o))
|
||||
this.npm.output(`-${tag}: ${spec.name}@${version}`)
|
||||
output.standard(`-${tag}: ${spec.name}@${version}`)
|
||||
}
|
||||
|
||||
async list (spec, opts) {
|
||||
@@ -167,7 +167,7 @@ class DistTag extends BaseCommand {
|
||||
const tags = await this.fetchTags(spec, opts)
|
||||
const msg =
|
||||
Object.keys(tags).map(k => `${k}: ${tags[k]}`).sort().join('\n')
|
||||
this.npm.output(msg)
|
||||
output.standard(msg)
|
||||
return tags
|
||||
} catch (err) {
|
||||
log.error('dist-tag ls', "Couldn't get dist-tag data for", spec)
|
||||
@@ -180,7 +180,7 @@ class DistTag extends BaseCommand {
|
||||
|
||||
for (const name of this.workspaceNames) {
|
||||
try {
|
||||
this.npm.output(`${name}:`)
|
||||
output.standard(`${name}:`)
|
||||
await this.list(npa(name), this.npm.flatOptions)
|
||||
} catch (err) {
|
||||
// set the exitCode directly, but ignore the error
|
||||
@@ -205,4 +205,5 @@ class DistTag extends BaseCommand {
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DistTag
|
||||
Vendored
+2
@@ -1,4 +1,5 @@
|
||||
const PackageUrlCmd = require('../package-url-cmd.js')
|
||||
|
||||
class Docs extends PackageUrlCmd {
|
||||
static description = 'Open documentation for a package in a web browser'
|
||||
static name = 'docs'
|
||||
@@ -16,4 +17,5 @@ class Docs extends PackageUrlCmd {
|
||||
return `https://www.npmjs.com/package/${mani.name}`
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Docs
|
||||
Vendored
+95
-167
@@ -1,19 +1,14 @@
|
||||
const cacache = require('cacache')
|
||||
const fs = require('fs')
|
||||
const { access, lstat, readdir, constants: { R_OK, W_OK, X_OK } } = require('fs/promises')
|
||||
const fetch = require('make-fetch-happen')
|
||||
const Table = require('cli-table3')
|
||||
const which = require('which')
|
||||
const pacote = require('pacote')
|
||||
const { resolve } = require('path')
|
||||
const semver = require('semver')
|
||||
const { promisify } = require('util')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const ping = require('../utils/ping.js')
|
||||
const { defaults } = require('@npmcli/config/lib/definitions')
|
||||
const lstat = promisify(fs.lstat)
|
||||
const readdir = promisify(fs.readdir)
|
||||
const access = promisify(fs.access)
|
||||
const { R_OK, W_OK, X_OK } = fs.constants
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const maskLabel = mask => {
|
||||
const label = []
|
||||
@@ -34,57 +29,59 @@ const maskLabel = mask => {
|
||||
|
||||
const subcommands = [
|
||||
{
|
||||
groups: ['ping', 'registry'],
|
||||
title: 'npm ping',
|
||||
// Ping is left in as a legacy command but is listed as "connection" to
|
||||
// make more sense to more people
|
||||
groups: ['connection', 'ping', 'registry'],
|
||||
title: 'Connecting to the registry',
|
||||
cmd: 'checkPing',
|
||||
}, {
|
||||
groups: ['versions'],
|
||||
title: 'npm -v',
|
||||
title: 'Checking npm version',
|
||||
cmd: 'getLatestNpmVersion',
|
||||
}, {
|
||||
groups: ['versions'],
|
||||
title: 'node -v',
|
||||
title: 'Checking node version',
|
||||
cmd: 'getLatestNodejsVersion',
|
||||
}, {
|
||||
groups: ['registry'],
|
||||
title: 'npm config get registry',
|
||||
title: 'Checking configured npm registry',
|
||||
cmd: 'checkNpmRegistry',
|
||||
}, {
|
||||
groups: ['environment'],
|
||||
title: 'git executable in PATH',
|
||||
title: 'Checking for git executable in PATH',
|
||||
cmd: 'getGitPath',
|
||||
}, {
|
||||
groups: ['environment'],
|
||||
title: 'global bin folder in PATH',
|
||||
title: 'Checking for global bin folder in PATH',
|
||||
cmd: 'getBinPath',
|
||||
}, {
|
||||
groups: ['permissions', 'cache'],
|
||||
title: 'Perms check on cached files',
|
||||
title: 'Checking permissions on cached files (this may take awhile)',
|
||||
cmd: 'checkCachePermission',
|
||||
windows: false,
|
||||
}, {
|
||||
groups: ['permissions'],
|
||||
title: 'Perms check on local node_modules',
|
||||
title: 'Checking permissions on local node_modules (this may take awhile)',
|
||||
cmd: 'checkLocalModulesPermission',
|
||||
windows: false,
|
||||
}, {
|
||||
groups: ['permissions'],
|
||||
title: 'Perms check on global node_modules',
|
||||
title: 'Checking permissions on global node_modules (this may take awhile)',
|
||||
cmd: 'checkGlobalModulesPermission',
|
||||
windows: false,
|
||||
}, {
|
||||
groups: ['permissions'],
|
||||
title: 'Perms check on local bin folder',
|
||||
title: 'Checking permissions on local bin folder',
|
||||
cmd: 'checkLocalBinPermission',
|
||||
windows: false,
|
||||
}, {
|
||||
groups: ['permissions'],
|
||||
title: 'Perms check on global bin folder',
|
||||
title: 'Checking permissions on global bin folder',
|
||||
cmd: 'checkGlobalBinPermission',
|
||||
windows: false,
|
||||
}, {
|
||||
groups: ['cache'],
|
||||
title: 'Verify cache contents',
|
||||
title: 'Verifying cache contents (this may take awhile)',
|
||||
cmd: 'verifyCachedFiles',
|
||||
windows: false,
|
||||
},
|
||||
@@ -97,50 +94,35 @@ const subcommands = [
|
||||
// - verify all local packages have bins linked
|
||||
// What is the fix for these?
|
||||
]
|
||||
const BaseCommand = require('../base-command.js')
|
||||
|
||||
class Doctor extends BaseCommand {
|
||||
static description = 'Check the health of your npm environment'
|
||||
static name = 'doctor'
|
||||
static params = ['registry']
|
||||
static ignoreImplicitWorkspace = false
|
||||
static usage = [`[${subcommands.flatMap(s => s.groups)
|
||||
.filter((value, index, self) => self.indexOf(value) === index)
|
||||
.filter((value, index, self) => self.indexOf(value) === index && value !== 'ping')
|
||||
.join('] [')}]`]
|
||||
|
||||
static subcommands = subcommands
|
||||
|
||||
// minimum width of check column, enough for the word `Check`
|
||||
#checkWidth = 5
|
||||
|
||||
async exec (args) {
|
||||
log.info('Running checkup')
|
||||
log.info('doctor', 'Running checkup')
|
||||
let allOk = true
|
||||
|
||||
const actions = this.actions(args)
|
||||
this.#checkWidth = actions.reduce((length, item) =>
|
||||
Math.max(item.title.length, length), this.#checkWidth)
|
||||
|
||||
if (!this.npm.silent) {
|
||||
this.output(['Check', 'Value', 'Recommendation/Notes'].map(h => this.npm.chalk.underline(h)))
|
||||
}
|
||||
// Do the actual work
|
||||
const chalk = this.npm.chalk
|
||||
for (const { title, cmd } of actions) {
|
||||
const item = [title]
|
||||
this.output(title)
|
||||
// TODO when we have an in progress indicator that could go here
|
||||
let result
|
||||
try {
|
||||
item.push(true, await this[cmd]())
|
||||
result = await this[cmd]()
|
||||
this.output(`${chalk.green('Ok')}${result ? `\n${result}` : ''}\n`)
|
||||
} catch (err) {
|
||||
item.push(false, err)
|
||||
}
|
||||
if (!item[1]) {
|
||||
allOk = false
|
||||
item[0] = this.npm.chalk.red(item[0])
|
||||
item[1] = this.npm.chalk.red('not ok')
|
||||
item[2] = this.npm.chalk.magenta(String(item[2]))
|
||||
} else {
|
||||
item[1] = this.npm.chalk.green('ok')
|
||||
}
|
||||
if (!this.npm.silent) {
|
||||
this.output(item)
|
||||
this.output(`${chalk.red('Not ok')}\n${chalk.cyan(err)}\n`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,8 +137,7 @@ class Doctor extends BaseCommand {
|
||||
}
|
||||
|
||||
async checkPing () {
|
||||
const tracker = log.newItem('checkPing', 1)
|
||||
tracker.info('checkPing', 'Pinging registry')
|
||||
log.info('doctor', 'Pinging registry')
|
||||
try {
|
||||
await ping({ ...this.npm.flatOptions, retry: false })
|
||||
return ''
|
||||
@@ -166,23 +147,16 @@ class Doctor extends BaseCommand {
|
||||
} else {
|
||||
throw er.message
|
||||
}
|
||||
} finally {
|
||||
tracker.finish()
|
||||
}
|
||||
}
|
||||
|
||||
async getLatestNpmVersion () {
|
||||
const tracker = log.newItem('getLatestNpmVersion', 1)
|
||||
tracker.info('getLatestNpmVersion', 'Getting npm package information')
|
||||
try {
|
||||
const latest = (await pacote.manifest('npm@latest', this.npm.flatOptions)).version
|
||||
if (semver.gte(this.npm.version, latest)) {
|
||||
return `current: v${this.npm.version}, latest: v${latest}`
|
||||
} else {
|
||||
throw `Use npm v${latest}`
|
||||
}
|
||||
} finally {
|
||||
tracker.finish()
|
||||
log.info('doctor', 'Getting npm package information')
|
||||
const latest = (await pacote.manifest('npm@latest', this.npm.flatOptions)).version
|
||||
if (semver.gte(this.npm.version, latest)) {
|
||||
return `current: v${this.npm.version}, latest: v${latest}`
|
||||
} else {
|
||||
throw `Use npm v${latest}`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,36 +165,30 @@ class Doctor extends BaseCommand {
|
||||
const current = process.version
|
||||
const currentRange = `^${current}`
|
||||
const url = 'https://nodejs.org/dist/index.json'
|
||||
const tracker = log.newItem('getLatestNodejsVersion', 1)
|
||||
tracker.info('getLatestNodejsVersion', 'Getting Node.js release information')
|
||||
try {
|
||||
const res = await fetch(url, { method: 'GET', ...this.npm.flatOptions })
|
||||
const data = await res.json()
|
||||
let maxCurrent = '0.0.0'
|
||||
let maxLTS = '0.0.0'
|
||||
for (const { lts, version } of data) {
|
||||
if (lts && semver.gt(version, maxLTS)) {
|
||||
maxLTS = version
|
||||
}
|
||||
log.info('doctor', 'Getting Node.js release information')
|
||||
const res = await fetch(url, { method: 'GET', ...this.npm.flatOptions })
|
||||
const data = await res.json()
|
||||
let maxCurrent = '0.0.0'
|
||||
let maxLTS = '0.0.0'
|
||||
for (const { lts, version } of data) {
|
||||
if (lts && semver.gt(version, maxLTS)) {
|
||||
maxLTS = version
|
||||
}
|
||||
|
||||
if (semver.satisfies(version, currentRange) && semver.gt(version, maxCurrent)) {
|
||||
maxCurrent = version
|
||||
}
|
||||
if (semver.satisfies(version, currentRange) && semver.gt(version, maxCurrent)) {
|
||||
maxCurrent = version
|
||||
}
|
||||
const recommended = semver.gt(maxCurrent, maxLTS) ? maxCurrent : maxLTS
|
||||
if (semver.gte(process.version, recommended)) {
|
||||
return `current: ${current}, recommended: ${recommended}`
|
||||
} else {
|
||||
throw `Use node ${recommended} (current: ${current})`
|
||||
}
|
||||
} finally {
|
||||
tracker.finish()
|
||||
}
|
||||
const recommended = semver.gt(maxCurrent, maxLTS) ? maxCurrent : maxLTS
|
||||
if (semver.gte(process.version, recommended)) {
|
||||
return `current: ${current}, recommended: ${recommended}`
|
||||
} else {
|
||||
throw `Use node ${recommended} (current: ${current})`
|
||||
}
|
||||
}
|
||||
|
||||
async getBinPath (dir) {
|
||||
const tracker = log.newItem('getBinPath', 1)
|
||||
tracker.info('getBinPath', 'Finding npm global bin in your PATH')
|
||||
async getBinPath () {
|
||||
log.info('doctor', 'getBinPath', 'Finding npm global bin in your PATH')
|
||||
if (!process.env.PATH.includes(this.npm.globalBin)) {
|
||||
throw new Error(`Add ${this.npm.globalBin} to your $PATH`)
|
||||
}
|
||||
@@ -250,30 +218,25 @@ class Doctor extends BaseCommand {
|
||||
async checkFilesPermission (root, shouldOwn, mask, missingOk) {
|
||||
let ok = true
|
||||
|
||||
const tracker = log.newItem(root, 1)
|
||||
|
||||
try {
|
||||
const uid = process.getuid()
|
||||
const gid = process.getgid()
|
||||
const files = new Set([root])
|
||||
for (const f of files) {
|
||||
tracker.silly('checkFilesPermission', f.slice(root.length + 1))
|
||||
const st = await lstat(f).catch(er => {
|
||||
// if it can't be missing, or if it can and the error wasn't that it was missing
|
||||
if (!missingOk || er.code !== 'ENOENT') {
|
||||
ok = false
|
||||
tracker.warn('checkFilesPermission', 'error getting info for ' + f)
|
||||
log.warn('doctor', 'checkFilesPermission', 'error getting info for ' + f)
|
||||
}
|
||||
})
|
||||
|
||||
tracker.completeWork(1)
|
||||
|
||||
if (!st) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (shouldOwn && (uid !== st.uid || gid !== st.gid)) {
|
||||
tracker.warn('checkFilesPermission', 'should be owner of ' + f)
|
||||
log.warn('doctor', 'checkFilesPermission', 'should be owner of ' + f)
|
||||
ok = false
|
||||
}
|
||||
|
||||
@@ -286,14 +249,14 @@ class Doctor extends BaseCommand {
|
||||
} catch (er) {
|
||||
ok = false
|
||||
const msg = `Missing permissions on ${f} (expect: ${maskLabel(mask)})`
|
||||
tracker.error('checkFilesPermission', msg)
|
||||
log.error('doctor', 'checkFilesPermission', msg)
|
||||
continue
|
||||
}
|
||||
|
||||
if (st.isDirectory()) {
|
||||
const entries = await readdir(f).catch(er => {
|
||||
const entries = await readdir(f).catch(() => {
|
||||
ok = false
|
||||
tracker.warn('checkFilesPermission', 'error reading directory ' + f)
|
||||
log.warn('doctor', 'checkFilesPermission', 'error reading directory ' + f)
|
||||
return []
|
||||
})
|
||||
for (const entry of entries) {
|
||||
@@ -302,7 +265,6 @@ class Doctor extends BaseCommand {
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
tracker.finish()
|
||||
if (!ok) {
|
||||
throw (
|
||||
`Check the permissions of files in ${root}` +
|
||||
@@ -315,50 +277,43 @@ class Doctor extends BaseCommand {
|
||||
}
|
||||
|
||||
async getGitPath () {
|
||||
const tracker = log.newItem('getGitPath', 1)
|
||||
tracker.info('getGitPath', 'Finding git in your PATH')
|
||||
try {
|
||||
return await which('git').catch(er => {
|
||||
tracker.warn(er)
|
||||
throw new Error("Install git and ensure it's in your PATH.")
|
||||
})
|
||||
} finally {
|
||||
tracker.finish()
|
||||
}
|
||||
log.info('doctor', 'Finding git in your PATH')
|
||||
return await which('git').catch(er => {
|
||||
log.warn('doctor', 'getGitPath', er)
|
||||
throw new Error("Install git and ensure it's in your PATH.")
|
||||
})
|
||||
}
|
||||
|
||||
async verifyCachedFiles () {
|
||||
const tracker = log.newItem('verifyCachedFiles', 1)
|
||||
tracker.info('verifyCachedFiles', 'Verifying the npm cache')
|
||||
try {
|
||||
const stats = await cacache.verify(this.npm.flatOptions.cache)
|
||||
const { badContentCount, reclaimedCount, missingContent, reclaimedSize } = stats
|
||||
if (badContentCount || reclaimedCount || missingContent) {
|
||||
if (badContentCount) {
|
||||
tracker.warn('verifyCachedFiles', `Corrupted content removed: ${badContentCount}`)
|
||||
}
|
||||
log.info('doctor', 'verifyCachedFiles', 'Verifying the npm cache')
|
||||
|
||||
if (reclaimedCount) {
|
||||
tracker.warn(
|
||||
'verifyCachedFiles',
|
||||
`Content garbage-collected: ${reclaimedCount} (${reclaimedSize} bytes)`
|
||||
)
|
||||
}
|
||||
|
||||
if (missingContent) {
|
||||
tracker.warn('verifyCachedFiles', `Missing content: ${missingContent}`)
|
||||
}
|
||||
|
||||
tracker.warn('verifyCachedFiles', 'Cache issues have been fixed')
|
||||
const stats = await cacache.verify(this.npm.flatOptions.cache)
|
||||
const { badContentCount, reclaimedCount, missingContent, reclaimedSize } = stats
|
||||
if (badContentCount || reclaimedCount || missingContent) {
|
||||
if (badContentCount) {
|
||||
log.warn('doctor', 'verifyCachedFiles', `Corrupted content removed: ${badContentCount}`)
|
||||
}
|
||||
tracker.info(
|
||||
'verifyCachedFiles',
|
||||
`Verification complete. Stats: ${JSON.stringify(stats, null, 2)}`
|
||||
)
|
||||
return `verified ${stats.verifiedContent} tarballs`
|
||||
} finally {
|
||||
tracker.finish()
|
||||
|
||||
if (reclaimedCount) {
|
||||
log.warn(
|
||||
'doctor',
|
||||
'verifyCachedFiles',
|
||||
`Content garbage-collected: ${reclaimedCount} (${reclaimedSize} bytes)`
|
||||
)
|
||||
}
|
||||
|
||||
if (missingContent) {
|
||||
log.warn('doctor', 'verifyCachedFiles', `Missing content: ${missingContent}`)
|
||||
}
|
||||
|
||||
log.warn('doctor', 'verifyCachedFiles', 'Cache issues have been fixed')
|
||||
}
|
||||
log.info(
|
||||
'doctor',
|
||||
'verifyCachedFiles',
|
||||
`Verification complete. Stats: ${JSON.stringify(stats, null, 2)}`
|
||||
)
|
||||
return `verified ${stats.verifiedContent} tarballs`
|
||||
}
|
||||
|
||||
async checkNpmRegistry () {
|
||||
@@ -369,38 +324,11 @@ class Doctor extends BaseCommand {
|
||||
}
|
||||
}
|
||||
|
||||
output (row) {
|
||||
const t = new Table({
|
||||
chars: {
|
||||
top: '',
|
||||
'top-mid': '',
|
||||
'top-left': '',
|
||||
'top-right': '',
|
||||
bottom: '',
|
||||
'bottom-mid': '',
|
||||
'bottom-left': '',
|
||||
'bottom-right': '',
|
||||
left: '',
|
||||
'left-mid': '',
|
||||
mid: '',
|
||||
'mid-mid': '',
|
||||
right: '',
|
||||
'right-mid': '',
|
||||
middle: ' ',
|
||||
},
|
||||
style: {
|
||||
'padding-left': 0,
|
||||
'padding-right': 0,
|
||||
// setting border here is not necessary visually since we've already
|
||||
// zeroed out all the chars above, but without it cli-table3 will wrap
|
||||
// some of the separator spaces with ansi codes which show up in
|
||||
// snapshots.
|
||||
border: 0,
|
||||
},
|
||||
colWidths: [this.#checkWidth, 6],
|
||||
})
|
||||
t.push(row)
|
||||
this.npm.output(t.toString())
|
||||
output (...args) {
|
||||
// TODO display layer should do this
|
||||
if (!this.npm.silent) {
|
||||
output.standard(...args)
|
||||
}
|
||||
}
|
||||
|
||||
actions (params) {
|
||||
|
||||
Vendored
+34
-46
@@ -1,34 +1,31 @@
|
||||
const { resolve } = require('path')
|
||||
const { lstat } = require('fs/promises')
|
||||
const cp = require('child_process')
|
||||
const completion = require('../utils/installed-shallow.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const splitPackageNames = (path) => path.split('/')
|
||||
// combine scoped parts
|
||||
.reduce((parts, part) => {
|
||||
if (parts.length === 0) {
|
||||
return [part]
|
||||
}
|
||||
|
||||
const lastPart = parts[parts.length - 1]
|
||||
// check if previous part is the first part of a scoped package
|
||||
if (lastPart[0] === '@' && !lastPart.includes('/')) {
|
||||
parts[parts.length - 1] += '/' + part
|
||||
} else {
|
||||
parts.push(part)
|
||||
}
|
||||
|
||||
return parts
|
||||
}, [])
|
||||
.join('/node_modules/')
|
||||
.replace(/(\/node_modules)+/, '/node_modules')
|
||||
|
||||
// npm edit <pkg>
|
||||
// open the package folder in the $EDITOR
|
||||
|
||||
const { resolve } = require('path')
|
||||
const fs = require('graceful-fs')
|
||||
const cp = require('child_process')
|
||||
const completion = require('../utils/completion/installed-shallow.js')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
|
||||
const splitPackageNames = (path) => {
|
||||
return path.split('/')
|
||||
// combine scoped parts
|
||||
.reduce((parts, part) => {
|
||||
if (parts.length === 0) {
|
||||
return [part]
|
||||
}
|
||||
|
||||
const lastPart = parts[parts.length - 1]
|
||||
// check if previous part is the first part of a scoped package
|
||||
if (lastPart[0] === '@' && !lastPart.includes('/')) {
|
||||
parts[parts.length - 1] += '/' + part
|
||||
} else {
|
||||
parts.push(part)
|
||||
}
|
||||
|
||||
return parts
|
||||
}, [])
|
||||
.join('/node_modules/')
|
||||
.replace(/(\/node_modules)+/, '/node_modules')
|
||||
}
|
||||
|
||||
class Edit extends BaseCommand {
|
||||
static description = 'Edit an installed package'
|
||||
static name = 'edit'
|
||||
@@ -50,27 +47,18 @@ class Edit extends BaseCommand {
|
||||
const path = splitPackageNames(args[0])
|
||||
const dir = resolve(this.npm.dir, path)
|
||||
|
||||
// graceful-fs does not promisify
|
||||
await lstat(dir)
|
||||
await new Promise((res, rej) => {
|
||||
fs.lstat(dir, (err) => {
|
||||
if (err) {
|
||||
return rej(err)
|
||||
const [bin, ...spawnArgs] = this.npm.config.get('editor').split(/\s+/)
|
||||
const editor = cp.spawn(bin, [...spawnArgs, dir], { stdio: 'inherit' })
|
||||
editor.on('exit', async (code) => {
|
||||
if (code) {
|
||||
return rej(new Error(`editor process exited with code: ${code}`))
|
||||
}
|
||||
const [bin, ...spawnArgs] = this.npm.config.get('editor').split(/\s+/)
|
||||
const editor = cp.spawn(bin, [...spawnArgs, dir], { stdio: 'inherit' })
|
||||
editor.on('exit', async (code) => {
|
||||
if (code) {
|
||||
return rej(new Error(`editor process exited with code: ${code}`))
|
||||
}
|
||||
try {
|
||||
await this.npm.exec('rebuild', [dir])
|
||||
} catch (execErr) {
|
||||
rej(execErr)
|
||||
}
|
||||
res()
|
||||
})
|
||||
await this.npm.exec('rebuild', [dir]).then(res).catch(rej)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Edit
|
||||
Vendored
+1
-3
@@ -1,6 +1,6 @@
|
||||
const { resolve } = require('path')
|
||||
const libexec = require('libnpmexec')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Exec extends BaseCommand {
|
||||
static description = 'Run a command from a local or remote npm package'
|
||||
@@ -65,7 +65,6 @@ class Exec extends BaseCommand {
|
||||
globalDir,
|
||||
chalk,
|
||||
} = this.npm
|
||||
const output = this.npm.output.bind(this.npm)
|
||||
const scriptShell = this.npm.config.get('script-shell') || undefined
|
||||
const packages = this.npm.config.get('package')
|
||||
const yes = this.npm.config.get('yes')
|
||||
@@ -93,7 +92,6 @@ class Exec extends BaseCommand {
|
||||
globalPath,
|
||||
localBin,
|
||||
locationMsg,
|
||||
output,
|
||||
packages,
|
||||
path,
|
||||
runPath,
|
||||
|
||||
Vendored
+5
-3
@@ -3,6 +3,7 @@ const npa = require('npm-package-arg')
|
||||
const semver = require('semver')
|
||||
const { relative, resolve } = require('path')
|
||||
const validName = require('validate-npm-package-name')
|
||||
const { output } = require('proc-log')
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
class Explain extends ArboristWorkspaceCmd {
|
||||
@@ -19,7 +20,7 @@ class Explain extends ArboristWorkspaceCmd {
|
||||
// TODO
|
||||
/* istanbul ignore next */
|
||||
static async completion (opts, npm) {
|
||||
const completion = require('../utils/completion/installed-deep.js')
|
||||
const completion = require('../utils/installed-deep.js')
|
||||
return completion(npm, opts)
|
||||
}
|
||||
|
||||
@@ -75,9 +76,9 @@ class Explain extends ArboristWorkspaceCmd {
|
||||
}
|
||||
|
||||
if (this.npm.flatOptions.json) {
|
||||
this.npm.output(JSON.stringify(expls, null, 2))
|
||||
output.standard(JSON.stringify(expls, null, 2))
|
||||
} else {
|
||||
this.npm.output(expls.map(expl => {
|
||||
output.standard(expls.map(expl => {
|
||||
return explainNode(expl, Infinity, this.npm.chalk)
|
||||
}).join('\n\n'))
|
||||
}
|
||||
@@ -125,4 +126,5 @@ class Explain extends ArboristWorkspaceCmd {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Explain
|
||||
Vendored
+22
-27
@@ -1,13 +1,12 @@
|
||||
// npm explore <pkg>[@<version>]
|
||||
// open a subshell to the package folder.
|
||||
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
const runScript = require('@npmcli/run-script')
|
||||
const { join, relative } = require('path')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const completion = require('../utils/completion/installed-shallow.js')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const completion = require('../utils/installed-shallow.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
// npm explore <pkg>[@<version>]
|
||||
// open a subshell to the package folder.
|
||||
class Explore extends BaseCommand {
|
||||
static description = 'Browse an installed package'
|
||||
static name = 'explore'
|
||||
@@ -50,30 +49,26 @@ class Explore extends BaseCommand {
|
||||
}
|
||||
|
||||
if (!args.length) {
|
||||
this.npm.output(`\nExploring ${path}\nType 'exit' or ^D when finished\n`)
|
||||
output.standard(`\nExploring ${path}\nType 'exit' or ^D when finished\n`)
|
||||
}
|
||||
log.disableProgress()
|
||||
try {
|
||||
return await runScript({
|
||||
...this.npm.flatOptions,
|
||||
pkg,
|
||||
banner: false,
|
||||
path,
|
||||
event: '_explore',
|
||||
stdio: 'inherit',
|
||||
}).catch(er => {
|
||||
process.exitCode = typeof er.code === 'number' && er.code !== 0 ? er.code
|
||||
: 1
|
||||
|
||||
return runScript({
|
||||
...this.npm.flatOptions,
|
||||
pkg,
|
||||
path,
|
||||
event: '_explore',
|
||||
stdio: 'inherit',
|
||||
}).catch(er => {
|
||||
process.exitCode = typeof er.code === 'number' && er.code !== 0 ? er.code
|
||||
: 1
|
||||
// if it's not an exit error, or non-interactive, throw it
|
||||
const isProcExit = er.message === 'command failed' &&
|
||||
const isProcExit = er.message === 'command failed' &&
|
||||
(typeof er.code === 'number' || /^SIG/.test(er.signal || ''))
|
||||
if (args.length || !isProcExit) {
|
||||
throw er
|
||||
}
|
||||
})
|
||||
} finally {
|
||||
log.enableProgress()
|
||||
}
|
||||
if (args.length || !isProcExit) {
|
||||
throw er
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Explore
|
||||
Vendored
+3
-2
@@ -1,6 +1,6 @@
|
||||
// dedupe duplicated packages, or find them in the tree
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
// dedupe duplicated packages, or find them in the tree
|
||||
class FindDupes extends ArboristWorkspaceCmd {
|
||||
static description = 'Find duplication in the package tree'
|
||||
static name = 'find-dupes'
|
||||
@@ -19,9 +19,10 @@ class FindDupes extends ArboristWorkspaceCmd {
|
||||
...super.params,
|
||||
]
|
||||
|
||||
async exec (args) {
|
||||
async exec () {
|
||||
this.npm.config.set('dry-run', true)
|
||||
return this.npm.exec('dedupe', [])
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FindDupes
|
||||
Vendored
+22
-21
@@ -1,6 +1,7 @@
|
||||
const archy = require('archy')
|
||||
const pacote = require('pacote')
|
||||
const semver = require('semver')
|
||||
const { output } = require('proc-log')
|
||||
const npa = require('npm-package-arg')
|
||||
const { depth } = require('treeverse')
|
||||
const { readTree: getFundingInfo, normalizeFunding, isValidFunding } = require('libnpmfund')
|
||||
@@ -37,7 +38,7 @@ class Fund extends ArboristWorkspaceCmd {
|
||||
// TODO
|
||||
/* istanbul ignore next */
|
||||
static async completion (opts, npm) {
|
||||
const completion = require('../utils/completion/installed-deep.js')
|
||||
const completion = require('../utils/installed-deep.js')
|
||||
return completion(npm, opts)
|
||||
}
|
||||
|
||||
@@ -85,9 +86,9 @@ class Fund extends ArboristWorkspaceCmd {
|
||||
})
|
||||
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(this.printJSON(fundingInfo))
|
||||
output.standard(this.printJSON(fundingInfo))
|
||||
} else {
|
||||
this.npm.output(this.printHuman(fundingInfo))
|
||||
output.standard(this.printHuman(fundingInfo))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,26 +111,25 @@ class Fund extends ArboristWorkspaceCmd {
|
||||
const [fundingSource] = [].concat(normalizeFunding(funding)).filter(isValidFunding)
|
||||
const { url } = fundingSource || {}
|
||||
const pkgRef = getPrintableName({ name, version })
|
||||
let item = {
|
||||
label: pkgRef,
|
||||
}
|
||||
|
||||
if (url) {
|
||||
item.label = tree({
|
||||
label: this.npm.chalk.bgBlack.white(url),
|
||||
if (!url) {
|
||||
return { label: pkgRef }
|
||||
}
|
||||
let item
|
||||
if (seenUrls.has(url)) {
|
||||
item = seenUrls.get(url)
|
||||
item.label += `${this.npm.chalk.dim(',')} ${pkgRef}`
|
||||
return null
|
||||
}
|
||||
item = {
|
||||
label: tree({
|
||||
label: this.npm.chalk.blue(url),
|
||||
nodes: [pkgRef],
|
||||
}).trim()
|
||||
|
||||
// stacks all packages together under the same item
|
||||
if (seenUrls.has(url)) {
|
||||
item = seenUrls.get(url)
|
||||
item.label += `, ${pkgRef}`
|
||||
return null
|
||||
} else {
|
||||
seenUrls.set(url, item)
|
||||
}
|
||||
}).trim(),
|
||||
}
|
||||
|
||||
// stacks all packages together under the same item
|
||||
seenUrls.set(url, item)
|
||||
return item
|
||||
},
|
||||
|
||||
@@ -153,7 +153,7 @@ class Fund extends ArboristWorkspaceCmd {
|
||||
})
|
||||
|
||||
const res = tree(result)
|
||||
return this.npm.chalk.reset(res)
|
||||
return res
|
||||
}
|
||||
|
||||
async openFundingUrl ({ path, tree, spec, fundingSourceNumber }) {
|
||||
@@ -212,7 +212,7 @@ class Fund extends ArboristWorkspaceCmd {
|
||||
if (fundingSourceNumber) {
|
||||
ambiguousUrlMsg.unshift(`--which=${fundingSourceNumber} is not a valid index`)
|
||||
}
|
||||
this.npm.output(ambiguousUrlMsg.join('\n'))
|
||||
output.standard(ambiguousUrlMsg.join('\n'))
|
||||
}
|
||||
|
||||
urlMessage (source) {
|
||||
@@ -222,4 +222,5 @@ class Fund extends ArboristWorkspaceCmd {
|
||||
return [url, message]
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Fund
|
||||
Vendored
+2
-1
@@ -1,5 +1,5 @@
|
||||
const Npm = require('../npm.js')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Get extends BaseCommand {
|
||||
static description = 'Get a value from the npm configuration'
|
||||
@@ -19,4 +19,5 @@ class Get extends BaseCommand {
|
||||
return this.npm.exec('config', ['get'].concat(args))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Get
|
||||
Vendored
+13
-12
@@ -1,7 +1,8 @@
|
||||
const { readFile } = require('fs/promises')
|
||||
const path = require('path')
|
||||
const { readFile } = require('node:fs/promises')
|
||||
const path = require('node:path')
|
||||
const { glob } = require('glob')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const { output } = require('proc-log')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const globify = pattern => pattern.split('\\').join('/')
|
||||
|
||||
@@ -21,12 +22,12 @@ class HelpSearch extends BaseCommand {
|
||||
// preserve glob@8 behavior
|
||||
files = files.sort((a, b) => a.localeCompare(b, 'en'))
|
||||
const data = await this.readFiles(files)
|
||||
const results = await this.searchFiles(args, data, files)
|
||||
const results = await this.searchFiles(args, data)
|
||||
const formatted = this.formatResults(args, results)
|
||||
if (!formatted.trim()) {
|
||||
this.npm.output(`No matches in help for: ${args.join(' ')}\n`)
|
||||
output.standard(`No matches in help for: ${args.join(' ')}\n`)
|
||||
} else {
|
||||
this.npm.output(formatted)
|
||||
output.standard(formatted)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +40,7 @@ class HelpSearch extends BaseCommand {
|
||||
return res
|
||||
}
|
||||
|
||||
async searchFiles (args, data, files) {
|
||||
async searchFiles (args, data) {
|
||||
const results = []
|
||||
for (const [file, content] of Object.entries(data)) {
|
||||
const lowerCase = content.toLowerCase()
|
||||
@@ -140,7 +141,7 @@ class HelpSearch extends BaseCommand {
|
||||
formatResults (args, results) {
|
||||
const cols = Math.min(process.stdout.columns || Infinity, 80) + 1
|
||||
|
||||
const output = results.map(res => {
|
||||
const formattedOutput = results.map(res => {
|
||||
const out = [res.cmd]
|
||||
const r = Object.keys(res.hits)
|
||||
.map(k => `${k}:${res.hits[k]}`)
|
||||
@@ -169,8 +170,7 @@ class HelpSearch extends BaseCommand {
|
||||
for (const f of finder) {
|
||||
hilitLine.push(line.slice(p, p + f.length))
|
||||
const word = line.slice(p + f.length, p + f.length + arg.length)
|
||||
const hilit = this.npm.chalk.bgBlack.red(word)
|
||||
hilitLine.push(hilit)
|
||||
hilitLine.push(this.npm.chalk.blue(word))
|
||||
p += f.length + arg.length
|
||||
}
|
||||
}
|
||||
@@ -183,12 +183,13 @@ class HelpSearch extends BaseCommand {
|
||||
const finalOut = results.length && !this.npm.config.get('long')
|
||||
? 'Top hits for ' + (args.map(JSON.stringify).join(' ')) + '\n' +
|
||||
'—'.repeat(cols - 1) + '\n' +
|
||||
output + '\n' +
|
||||
formattedOutput + '\n' +
|
||||
'—'.repeat(cols - 1) + '\n' +
|
||||
'(run with -l or --long to see more context)'
|
||||
: output
|
||||
: formattedOutput
|
||||
|
||||
return finalOut.trim()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = HelpSearch
|
||||
Vendored
+4
-2
@@ -2,11 +2,12 @@ const spawn = require('@npmcli/promise-spawn')
|
||||
const path = require('path')
|
||||
const openUrl = require('../utils/open-url.js')
|
||||
const { glob } = require('glob')
|
||||
const { output } = require('proc-log')
|
||||
const localeCompare = require('@isaacs/string-locale-compare')('en')
|
||||
const { deref } = require('../utils/cmd-list.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const globify = pattern => pattern.split('\\').join('/')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
|
||||
// Strips out the number from foo.7 or foo.7. or foo.7.tgz
|
||||
// We don't currently compress our man pages but if we ever did this would
|
||||
@@ -50,7 +51,7 @@ class Help extends BaseCommand {
|
||||
const manSearch = /^\d+$/.test(args[0]) ? `man${args.shift()}` : 'man*'
|
||||
|
||||
if (!args.length) {
|
||||
return this.npm.output(this.npm.usage)
|
||||
return output.standard(this.npm.usage)
|
||||
}
|
||||
|
||||
// npm help foo bar baz: search topics
|
||||
@@ -110,4 +111,5 @@ class Help extends BaseCommand {
|
||||
return 'file:///' + path.resolve(this.npm.npmRoot, `docs/output/${sect}/${f}.html`)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Help
|
||||
Vendored
+29
-45
@@ -1,9 +1,9 @@
|
||||
const hookApi = require('libnpmhook')
|
||||
const otplease = require('../utils/otplease.js')
|
||||
const relativeDate = require('tiny-relative-date')
|
||||
const Table = require('cli-table3')
|
||||
const { output } = require('proc-log')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Hook extends BaseCommand {
|
||||
static description = 'Manage registry hooks'
|
||||
static name = 'hook'
|
||||
@@ -40,86 +40,70 @@ class Hook extends BaseCommand {
|
||||
async add (pkg, uri, secret, opts) {
|
||||
const hook = await hookApi.add(pkg, uri, secret, opts)
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify(hook, null, 2))
|
||||
output.standard(JSON.stringify(hook, null, 2))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(Object.keys(hook).join('\t'))
|
||||
this.npm.output(Object.keys(hook).map(k => hook[k]).join('\t'))
|
||||
output.standard(Object.keys(hook).join('\t'))
|
||||
output.standard(Object.keys(hook).map(k => hook[k]).join('\t'))
|
||||
} else if (!this.npm.silent) {
|
||||
this.npm.output(`+ ${this.hookName(hook)} ${opts.unicode ? ' ➜ ' : ' -> '} ${hook.endpoint}`)
|
||||
output.standard(`+ ${this.hookName(hook)} ${opts.unicode ? ' ➜ ' : ' -> '} ${hook.endpoint}`)
|
||||
}
|
||||
}
|
||||
|
||||
async ls (pkg, opts) {
|
||||
const hooks = await hookApi.ls({ ...opts, package: pkg })
|
||||
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify(hooks, null, 2))
|
||||
output.standard(JSON.stringify(hooks, null, 2))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(Object.keys(hooks[0]).join('\t'))
|
||||
output.standard(Object.keys(hooks[0]).join('\t'))
|
||||
hooks.forEach(hook => {
|
||||
this.npm.output(Object.keys(hook).map(k => hook[k]).join('\t'))
|
||||
output.standard(Object.keys(hook).map(k => hook[k]).join('\t'))
|
||||
})
|
||||
} else if (!hooks.length) {
|
||||
this.npm.output("You don't have any hooks configured yet.")
|
||||
output.standard("You don't have any hooks configured yet.")
|
||||
} else if (!this.npm.silent) {
|
||||
if (hooks.length === 1) {
|
||||
this.npm.output('You have one hook configured.')
|
||||
} else {
|
||||
this.npm.output(`You have ${hooks.length} hooks configured.`)
|
||||
}
|
||||
output.standard(`You have ${hooks.length} hook${hooks.length !== 1 ? 's' : ''} configured.`)
|
||||
|
||||
const table = new Table({ head: ['id', 'target', 'endpoint'] })
|
||||
hooks.forEach((hook) => {
|
||||
table.push([
|
||||
{ rowSpan: 2, content: hook.id },
|
||||
this.hookName(hook),
|
||||
hook.endpoint,
|
||||
])
|
||||
for (const hook of hooks) {
|
||||
output.standard(`Hook ${hook.id}: ${this.hookName(hook)}`)
|
||||
output.standard(`Endpoint: ${hook.endpoint}`)
|
||||
if (hook.last_delivery) {
|
||||
table.push([
|
||||
{
|
||||
colSpan: 1,
|
||||
content: `triggered ${relativeDate(hook.last_delivery)}`,
|
||||
},
|
||||
hook.response_code,
|
||||
])
|
||||
/* eslint-disable-next-line max-len */
|
||||
output.standard(`Triggered ${relativeDate(hook.last_delivery)}, response code was "${hook.response_code}"\n`)
|
||||
} else {
|
||||
table.push([{ colSpan: 2, content: 'never triggered' }])
|
||||
output.standard('Never triggered\n')
|
||||
}
|
||||
})
|
||||
this.npm.output(table.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async rm (id, opts) {
|
||||
const hook = await hookApi.rm(id, opts)
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify(hook, null, 2))
|
||||
output.standard(JSON.stringify(hook, null, 2))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(Object.keys(hook).join('\t'))
|
||||
this.npm.output(Object.keys(hook).map(k => hook[k]).join('\t'))
|
||||
output.standard(Object.keys(hook).join('\t'))
|
||||
output.standard(Object.keys(hook).map(k => hook[k]).join('\t'))
|
||||
} else if (!this.npm.silent) {
|
||||
this.npm.output(`- ${this.hookName(hook)} ${opts.unicode ? ' ✘ ' : ' X '} ${hook.endpoint}`)
|
||||
output.standard(`- ${this.hookName(hook)} ${opts.unicode ? ' ✘ ' : ' X '} ${hook.endpoint}`)
|
||||
}
|
||||
}
|
||||
|
||||
async update (id, uri, secret, opts) {
|
||||
const hook = await hookApi.update(id, uri, secret, opts)
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify(hook, null, 2))
|
||||
output.standard(JSON.stringify(hook, null, 2))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(Object.keys(hook).join('\t'))
|
||||
this.npm.output(Object.keys(hook).map(k => hook[k]).join('\t'))
|
||||
output.standard(Object.keys(hook).join('\t'))
|
||||
output.standard(Object.keys(hook).map(k => hook[k]).join('\t'))
|
||||
} else if (!this.npm.silent) {
|
||||
this.npm.output(`+ ${this.hookName(hook)} ${opts.unicode ? ' ➜ ' : ' -> '} ${hook.endpoint}`)
|
||||
output.standard(`+ ${this.hookName(hook)} ${opts.unicode ? ' ➜ ' : ' -> '} ${hook.endpoint}`)
|
||||
}
|
||||
}
|
||||
|
||||
hookName (hook) {
|
||||
let target = hook.name
|
||||
if (hook.type === 'owner') {
|
||||
target = '~' + target
|
||||
}
|
||||
return target
|
||||
return `${hook.type === 'owner' ? '~' : ''}${hook.name}`
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Hook
|
||||
Vendored
+8
-16
@@ -1,4 +1,4 @@
|
||||
const fs = require('fs')
|
||||
const { statSync } = require('fs')
|
||||
const { relative, resolve } = require('path')
|
||||
const { mkdir } = require('fs/promises')
|
||||
const initJson = require('init-package-json')
|
||||
@@ -6,13 +6,12 @@ const npa = require('npm-package-arg')
|
||||
const libexec = require('libnpmexec')
|
||||
const mapWorkspaces = require('@npmcli/map-workspaces')
|
||||
const PackageJson = require('@npmcli/package-json')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const updateWorkspaces = require('../workspaces/update-workspaces.js')
|
||||
const { log, output, input } = require('proc-log')
|
||||
const updateWorkspaces = require('../utils/update-workspaces.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const posixPath = p => p.split('\\').join('/')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
|
||||
class Init extends BaseCommand {
|
||||
static description = 'Create a package.json file'
|
||||
static params = [
|
||||
@@ -60,7 +59,7 @@ class Init extends BaseCommand {
|
||||
// to create a workspace package.json file or its folders
|
||||
const { content: pkg } = await PackageJson.normalize(this.npm.localPrefix).catch(err => {
|
||||
if (err.code === 'ENOENT') {
|
||||
log.warn('Missing package.json. Try with `--include-workspace-root`.')
|
||||
log.warn('init', 'Missing package.json. Try with `--include-workspace-root`.')
|
||||
}
|
||||
throw err
|
||||
})
|
||||
@@ -130,7 +129,6 @@ class Init extends BaseCommand {
|
||||
globalBin,
|
||||
chalk,
|
||||
} = this.npm
|
||||
const output = this.npm.output.bind(this.npm)
|
||||
const runPath = path
|
||||
const scriptShell = this.npm.config.get('script-shell') || undefined
|
||||
const yes = this.npm.config.get('yes')
|
||||
@@ -150,12 +148,9 @@ class Init extends BaseCommand {
|
||||
}
|
||||
|
||||
async template (path = process.cwd()) {
|
||||
log.pause()
|
||||
log.disableProgress()
|
||||
|
||||
const initFile = this.npm.config.get('init-module')
|
||||
if (!this.npm.config.get('yes') && !this.npm.config.get('force')) {
|
||||
this.npm.output([
|
||||
output.standard([
|
||||
'This utility will walk you through creating a package.json file.',
|
||||
'It only covers the most common items, and tries to guess sensible defaults.',
|
||||
'',
|
||||
@@ -170,7 +165,7 @@ class Init extends BaseCommand {
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await initJson(path, initFile, this.npm.config)
|
||||
const data = await input.read(() => initJson(path, initFile, this.npm.config))
|
||||
log.silly('package data', data)
|
||||
return data
|
||||
} catch (er) {
|
||||
@@ -179,9 +174,6 @@ class Init extends BaseCommand {
|
||||
} else {
|
||||
throw er
|
||||
}
|
||||
} finally {
|
||||
log.resume()
|
||||
log.enableProgress()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,7 +192,7 @@ class Init extends BaseCommand {
|
||||
// mapWorkspaces, so we're just going to avoid touching the
|
||||
// top-level package.json
|
||||
try {
|
||||
fs.statSync(resolve(workspacePath, 'package.json'))
|
||||
statSync(resolve(workspacePath, 'package.json'))
|
||||
} catch (err) {
|
||||
return
|
||||
}
|
||||
|
||||
+3
-3
@@ -1,8 +1,7 @@
|
||||
// npm install-ci-test
|
||||
// Runs `npm ci` and then runs `npm test`
|
||||
|
||||
const CI = require('./ci.js')
|
||||
|
||||
// npm install-ci-test
|
||||
// Runs `npm ci` and then runs `npm test`
|
||||
class InstallCITest extends CI {
|
||||
static description = 'Install a project with a clean slate and run tests'
|
||||
static name = 'install-ci-test'
|
||||
@@ -12,4 +11,5 @@ class InstallCITest extends CI {
|
||||
return this.npm.exec('test', [])
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InstallCITest
|
||||
+3
-3
@@ -1,8 +1,7 @@
|
||||
// npm install-test
|
||||
// Runs `npm install` and then runs `npm test`
|
||||
|
||||
const Install = require('./install.js')
|
||||
|
||||
// npm install-test
|
||||
// Runs `npm install` and then runs `npm test`
|
||||
class InstallTest extends Install {
|
||||
static description = 'Install package(s) and run tests'
|
||||
static name = 'install-test'
|
||||
@@ -12,4 +11,5 @@ class InstallTest extends Install {
|
||||
return this.npm.exec('test', [])
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InstallTest
|
||||
Vendored
+6
-9
@@ -1,15 +1,12 @@
|
||||
/* eslint-disable camelcase */
|
||||
const fs = require('fs')
|
||||
const util = require('util')
|
||||
const readdir = util.promisify(fs.readdir)
|
||||
const reifyFinish = require('../utils/reify-finish.js')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { resolve, join } = require('path')
|
||||
const { readdir } = require('node:fs/promises')
|
||||
const { resolve, join } = require('node:path')
|
||||
const { log } = require('proc-log')
|
||||
const runScript = require('@npmcli/run-script')
|
||||
const pacote = require('pacote')
|
||||
const checks = require('npm-install-checks')
|
||||
|
||||
const reifyFinish = require('../utils/reify-finish.js')
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
class Install extends ArboristWorkspaceCmd {
|
||||
static description = 'Install a package'
|
||||
static name = 'install'
|
||||
@@ -168,7 +165,6 @@ class Install extends ArboristWorkspaceCmd {
|
||||
args: [],
|
||||
scriptShell,
|
||||
stdio: 'inherit',
|
||||
banner: !this.npm.silent,
|
||||
event,
|
||||
})
|
||||
}
|
||||
@@ -176,4 +172,5 @@ class Install extends ArboristWorkspaceCmd {
|
||||
await reifyFinish(this.npm, arb)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Install
|
||||
Vendored
+3
-6
@@ -1,15 +1,11 @@
|
||||
const fs = require('fs')
|
||||
const util = require('util')
|
||||
const readdir = util.promisify(fs.readdir)
|
||||
const { readdir } = require('fs/promises')
|
||||
const { resolve } = require('path')
|
||||
|
||||
const npa = require('npm-package-arg')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
const semver = require('semver')
|
||||
|
||||
const reifyFinish = require('../utils/reify-finish.js')
|
||||
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
class Link extends ArboristWorkspaceCmd {
|
||||
static description = 'Symlink a package folder'
|
||||
static name = 'link'
|
||||
@@ -189,4 +185,5 @@ class Link extends ArboristWorkspaceCmd {
|
||||
return missing
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Link
|
||||
Vendored
+5
-6
@@ -1,8 +1,7 @@
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const { redactLog: replaceInfo } = require('@npmcli/redact')
|
||||
const auth = require('../utils/auth.js')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Login extends BaseCommand {
|
||||
static description = 'Login to a registry user account'
|
||||
@@ -13,7 +12,7 @@ class Login extends BaseCommand {
|
||||
'auth-type',
|
||||
]
|
||||
|
||||
async exec (args) {
|
||||
async exec () {
|
||||
const scope = this.npm.config.get('scope')
|
||||
let registry = this.npm.config.get('registry')
|
||||
|
||||
@@ -27,7 +26,6 @@ class Login extends BaseCommand {
|
||||
|
||||
const creds = this.npm.config.getCredentialsByURI(registry)
|
||||
|
||||
log.disableProgress()
|
||||
log.notice('', `Log in on ${replaceInfo(registry)}`)
|
||||
|
||||
const { message, newCreds } = await auth.login(this.npm, {
|
||||
@@ -45,7 +43,8 @@ class Login extends BaseCommand {
|
||||
|
||||
await this.npm.config.save('user')
|
||||
|
||||
this.npm.output(message)
|
||||
output.standard(message)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Login
|
||||
Vendored
+4
-3
@@ -1,7 +1,7 @@
|
||||
const npmFetch = require('npm-registry-fetch')
|
||||
const { getAuth } = npmFetch
|
||||
const log = require('../utils/log-shim')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const { log } = require('proc-log')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Logout extends BaseCommand {
|
||||
static description = 'Log out of the registry'
|
||||
@@ -11,7 +11,7 @@ class Logout extends BaseCommand {
|
||||
'scope',
|
||||
]
|
||||
|
||||
async exec (args) {
|
||||
async exec () {
|
||||
const registry = this.npm.config.get('registry')
|
||||
const scope = this.npm.config.get('scope')
|
||||
const regRef = scope ? `${scope}:registry` : 'registry'
|
||||
@@ -46,4 +46,5 @@ class Logout extends BaseCommand {
|
||||
await this.npm.config.save(level)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Logout
|
||||
Vendored
+22
-19
@@ -1,10 +1,12 @@
|
||||
const { resolve, relative, sep } = require('path')
|
||||
const relativePrefix = `.${sep}`
|
||||
const { EOL } = require('os')
|
||||
|
||||
const archy = require('archy')
|
||||
const { breadth } = require('treeverse')
|
||||
const npa = require('npm-package-arg')
|
||||
const { output } = require('proc-log')
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
const localeCompare = require('@isaacs/string-locale-compare')('en')
|
||||
|
||||
const relativePrefix = `.${sep}`
|
||||
|
||||
const _depth = Symbol('depth')
|
||||
const _dedupe = Symbol('dedupe')
|
||||
@@ -17,8 +19,6 @@ const _parent = Symbol('parent')
|
||||
const _problems = Symbol('problems')
|
||||
const _required = Symbol('required')
|
||||
const _type = Symbol('type')
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
const localeCompare = require('@isaacs/string-locale-compare')('en')
|
||||
|
||||
class LS extends ArboristWorkspaceCmd {
|
||||
static description = 'List installed packages'
|
||||
@@ -42,7 +42,7 @@ class LS extends ArboristWorkspaceCmd {
|
||||
// TODO
|
||||
/* istanbul ignore next */
|
||||
static async completion (opts, npm) {
|
||||
const completion = require('../utils/completion/installed-deep.js')
|
||||
const completion = require('../utils/installed-deep.js')
|
||||
return completion(npm, opts)
|
||||
}
|
||||
|
||||
@@ -177,7 +177,7 @@ class LS extends ArboristWorkspaceCmd {
|
||||
const [rootError] = tree.errors.filter(e =>
|
||||
e.code === 'EJSONPARSE' && e.path === resolve(path, 'package.json'))
|
||||
|
||||
this.npm.outputBuffer(
|
||||
output.buffer(
|
||||
json ? jsonOutput({ path, problems, result, rootError, seenItems }) :
|
||||
parseable ? parseableOutput({ seenNodes, global, long }) :
|
||||
humanOutput({ chalk, result, seenItems, unicode })
|
||||
@@ -200,7 +200,7 @@ class LS extends ArboristWorkspaceCmd {
|
||||
|
||||
if (shouldThrow) {
|
||||
throw Object.assign(
|
||||
new Error([...problems].join(EOL)),
|
||||
new Error([...problems].join('\n')),
|
||||
{ code: 'ELSPROBLEMS' }
|
||||
)
|
||||
}
|
||||
@@ -219,6 +219,7 @@ class LS extends ArboristWorkspaceCmd {
|
||||
return tree
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = LS
|
||||
|
||||
const isGitNode = (node) => {
|
||||
@@ -280,7 +281,7 @@ const augmentItemWithIncludeMetadata = (node, item) => {
|
||||
|
||||
const getHumanOutputItem = (node, { args, chalk, global, long }) => {
|
||||
const { pkgid, path } = node
|
||||
const workspacePkgId = chalk.green(pkgid)
|
||||
const workspacePkgId = chalk.blueBright(pkgid)
|
||||
let printable = node.isWorkspace ? workspacePkgId : pkgid
|
||||
|
||||
// special formatting for top-level package name
|
||||
@@ -289,14 +290,16 @@ const getHumanOutputItem = (node, { args, chalk, global, long }) => {
|
||||
if (hasNoPackageJson || global) {
|
||||
printable = path
|
||||
} else {
|
||||
printable += `${long ? EOL : ' '}${path}`
|
||||
printable += `${long ? '\n' : ' '}${path}`
|
||||
}
|
||||
}
|
||||
|
||||
// TODO there is a LOT of overlap with lib/utils/explain-dep.js here
|
||||
|
||||
const highlightDepName = args.length && node[_filteredBy]
|
||||
const missingColor = isOptional(node)
|
||||
? chalk.yellow.bgBlack
|
||||
: chalk.red.bgBlack
|
||||
? chalk.yellow
|
||||
: chalk.red
|
||||
const missingMsg = `UNMET ${isOptional(node) ? 'OPTIONAL ' : ''}DEPENDENCY`
|
||||
const targetLocation = node.root
|
||||
? relative(node.root.realpath, node.realpath)
|
||||
@@ -310,30 +313,30 @@ const getHumanOutputItem = (node, { args, chalk, global, long }) => {
|
||||
? missingColor(missingMsg) + ' '
|
||||
: ''
|
||||
) +
|
||||
`${highlightDepName ? chalk.yellow.bgBlack(printable) : printable}` +
|
||||
`${highlightDepName ? chalk.yellow(printable) : printable}` +
|
||||
(
|
||||
node[_dedupe]
|
||||
? ' ' + chalk.gray('deduped')
|
||||
? ' ' + chalk.dim('deduped')
|
||||
: ''
|
||||
) +
|
||||
(
|
||||
invalid
|
||||
? ' ' + chalk.red.bgBlack(invalid)
|
||||
? ' ' + chalk.red(invalid)
|
||||
: ''
|
||||
) +
|
||||
(
|
||||
isExtraneous(node, { global })
|
||||
? ' ' + chalk.green.bgBlack('extraneous')
|
||||
? ' ' + chalk.red('extraneous')
|
||||
: ''
|
||||
) +
|
||||
(
|
||||
node.overridden
|
||||
? ' ' + chalk.gray('overridden')
|
||||
? ' ' + chalk.dim('overridden')
|
||||
: ''
|
||||
) +
|
||||
(isGitNode(node) ? ` (${node.resolved})` : '') +
|
||||
(node.isLink ? ` -> ${relativePrefix}${targetLocation}` : '') +
|
||||
(long ? `${EOL}${node.package.description || ''}` : '')
|
||||
(long ? `\n${node.package.description || ''}` : '')
|
||||
|
||||
return augmentItemWithIncludeMetadata(node, { label, nodes: [] })
|
||||
}
|
||||
@@ -566,7 +569,7 @@ const parseableOutput = ({ global, long, seenNodes }) => {
|
||||
out += node[_invalid] ? ':INVALID' : ''
|
||||
out += node.overridden ? ':OVERRIDDEN' : ''
|
||||
}
|
||||
out += EOL
|
||||
out += '\n'
|
||||
}
|
||||
}
|
||||
return out.trim()
|
||||
|
||||
Vendored
+18
-20
@@ -1,7 +1,7 @@
|
||||
const liborg = require('libnpmorg')
|
||||
const otplease = require('../utils/otplease.js')
|
||||
const Table = require('cli-table3')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
const { output } = require('proc-log')
|
||||
|
||||
class Org extends BaseCommand {
|
||||
static description = 'Manage orgs'
|
||||
@@ -68,14 +68,14 @@ class Org extends BaseCommand {
|
||||
|
||||
const memDeets = await liborg.set(org, user, role, opts)
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify(memDeets, null, 2))
|
||||
output.standard(JSON.stringify(memDeets, null, 2))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(['org', 'orgsize', 'user', 'role'].join('\t'))
|
||||
this.npm.output(
|
||||
output.standard(['org', 'orgsize', 'user', 'role'].join('\t'))
|
||||
output.standard(
|
||||
[memDeets.org.name, memDeets.org.size, memDeets.user, memDeets.role].join('\t')
|
||||
)
|
||||
} else if (!this.npm.silent) {
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
`Added ${memDeets.user} as ${memDeets.role} to ${memDeets.org.name}. You now have ${
|
||||
memDeets.org.size
|
||||
} member${memDeets.org.size === 1 ? '' : 's'} in this org.`
|
||||
@@ -100,7 +100,7 @@ class Org extends BaseCommand {
|
||||
org = org.replace(/^[~@]?/, '')
|
||||
const userCount = Object.keys(roster).length
|
||||
if (opts.json) {
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
JSON.stringify({
|
||||
user,
|
||||
org,
|
||||
@@ -109,10 +109,10 @@ class Org extends BaseCommand {
|
||||
})
|
||||
)
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(['user', 'org', 'userCount', 'deleted'].join('\t'))
|
||||
this.npm.output([user, org, userCount, true].join('\t'))
|
||||
output.standard(['user', 'org', 'userCount', 'deleted'].join('\t'))
|
||||
output.standard([user, org, userCount, true].join('\t'))
|
||||
} else if (!this.npm.silent) {
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
`Successfully removed ${user} from ${org}. You now have ${userCount} member${
|
||||
userCount === 1 ? '' : 's'
|
||||
} in this org.`
|
||||
@@ -135,21 +135,19 @@ class Org extends BaseCommand {
|
||||
roster = newRoster
|
||||
}
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify(roster, null, 2))
|
||||
output.standard(JSON.stringify(roster, null, 2))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(['user', 'role'].join('\t'))
|
||||
output.standard(['user', 'role'].join('\t'))
|
||||
Object.keys(roster).forEach(u => {
|
||||
this.npm.output([u, roster[u]].join('\t'))
|
||||
output.standard([u, roster[u]].join('\t'))
|
||||
})
|
||||
} else if (!this.npm.silent) {
|
||||
const table = new Table({ head: ['user', 'role'] })
|
||||
Object.keys(roster)
|
||||
.sort()
|
||||
.forEach(u => {
|
||||
table.push([u, roster[u]])
|
||||
})
|
||||
this.npm.output(table.toString())
|
||||
const chalk = this.npm.chalk
|
||||
for (const u of Object.keys(roster).sort()) {
|
||||
output.standard(`${u} - ${chalk.cyan(roster[u])}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Org
|
||||
Vendored
+18
-15
@@ -1,12 +1,11 @@
|
||||
const os = require('node:os')
|
||||
const { resolve } = require('node:path')
|
||||
const { stripVTControlCharacters } = require('node:util')
|
||||
const pacote = require('pacote')
|
||||
const table = require('text-table')
|
||||
const npa = require('npm-package-arg')
|
||||
const pickManifest = require('npm-pick-manifest')
|
||||
const { output } = require('proc-log')
|
||||
const localeCompare = require('@isaacs/string-locale-compare')('en')
|
||||
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
class Outdated extends ArboristWorkspaceCmd {
|
||||
@@ -84,9 +83,9 @@ class Outdated extends ArboristWorkspaceCmd {
|
||||
|
||||
// display results
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(this.makeJSON(outdated))
|
||||
output.standard(this.makeJSON(outdated))
|
||||
} else if (this.npm.config.get('parseable')) {
|
||||
this.npm.output(this.makeParseable(outdated))
|
||||
output.standard(this.makeParseable(outdated))
|
||||
} else {
|
||||
const outList = outdated.map(x => this.makePretty(x))
|
||||
const outHead = ['Package',
|
||||
@@ -102,13 +101,13 @@ class Outdated extends ArboristWorkspaceCmd {
|
||||
}
|
||||
const outTable = [outHead].concat(outList)
|
||||
|
||||
outTable[0] = outTable[0].map(heading => this.npm.chalk.underline(heading))
|
||||
outTable[0] = outTable[0].map(heading => this.npm.chalk.bold.underline(heading))
|
||||
|
||||
const tableOpts = {
|
||||
align: ['l', 'r', 'r', 'r', 'l'],
|
||||
stringLength: s => stripVTControlCharacters(s).length,
|
||||
}
|
||||
this.npm.output(table(outTable, tableOpts))
|
||||
output.standard(table(outTable, tableOpts))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +160,7 @@ class Outdated extends ArboristWorkspaceCmd {
|
||||
this.edges.add(edge)
|
||||
}
|
||||
|
||||
getWorkspacesEdges (node) {
|
||||
getWorkspacesEdges () {
|
||||
if (this.npm.global) {
|
||||
return
|
||||
}
|
||||
@@ -278,7 +277,7 @@ class Outdated extends ArboristWorkspaceCmd {
|
||||
: node.name
|
||||
|
||||
return humanOutput
|
||||
? this.npm.chalk.green(workspaceName)
|
||||
? this.npm.chalk.blue(workspaceName)
|
||||
: workspaceName
|
||||
}
|
||||
|
||||
@@ -295,17 +294,20 @@ class Outdated extends ArboristWorkspaceCmd {
|
||||
dependent,
|
||||
} = dep
|
||||
|
||||
const columns = [name, current, wanted, latest, location, dependent]
|
||||
const columns = [
|
||||
this.npm.chalk[current === wanted ? 'yellow' : 'red'](name),
|
||||
current,
|
||||
this.npm.chalk.cyan(wanted),
|
||||
this.npm.chalk.blue(latest),
|
||||
location,
|
||||
dependent,
|
||||
]
|
||||
|
||||
if (this.npm.config.get('long')) {
|
||||
columns[6] = type
|
||||
columns[7] = homepage
|
||||
columns[7] = this.npm.chalk.blue(homepage)
|
||||
}
|
||||
|
||||
columns[0] = this.npm.chalk[current === wanted ? 'yellow' : 'red'](columns[0]) // current
|
||||
columns[2] = this.npm.chalk.green(columns[2]) // wanted
|
||||
columns[3] = this.npm.chalk.magenta(columns[3]) // latest
|
||||
|
||||
return columns
|
||||
}
|
||||
|
||||
@@ -335,7 +337,7 @@ class Outdated extends ArboristWorkspaceCmd {
|
||||
}
|
||||
|
||||
return out.join(':')
|
||||
}).join(os.EOL)
|
||||
}).join('\n')
|
||||
}
|
||||
|
||||
makeJSON (list) {
|
||||
@@ -366,4 +368,5 @@ class Outdated extends ArboristWorkspaceCmd {
|
||||
return JSON.stringify(out, null, 2)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Outdated
|
||||
Vendored
+6
-6
@@ -1,10 +1,10 @@
|
||||
const npa = require('npm-package-arg')
|
||||
const npmFetch = require('npm-registry-fetch')
|
||||
const pacote = require('pacote')
|
||||
const log = require('../utils/log-shim')
|
||||
const { log, output } = require('proc-log')
|
||||
const otplease = require('../utils/otplease.js')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
const { redact } = require('@npmcli/redact')
|
||||
|
||||
const readJson = async (path) => {
|
||||
@@ -115,9 +115,9 @@ class Owner extends BaseCommand {
|
||||
const packumentOpts = { ...this.npm.flatOptions, fullMetadata: true, preferOnline: true }
|
||||
const { maintainers } = await pacote.packument(spec, packumentOpts)
|
||||
if (!maintainers || !maintainers.length) {
|
||||
this.npm.output('no admin found')
|
||||
output.standard('no admin found')
|
||||
} else {
|
||||
this.npm.output(maintainers.map(m => `${m.name} <${m.email}>`).join('\n'))
|
||||
output.standard(maintainers.map(m => `${m.name} <${m.email}>`).join('\n'))
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('owner ls', "Couldn't get owner data", redact(pkg))
|
||||
@@ -216,9 +216,9 @@ class Owner extends BaseCommand {
|
||||
})
|
||||
})
|
||||
if (addOrRm === 'add') {
|
||||
this.npm.output(`+ ${user} (${spec.name})`)
|
||||
output.standard(`+ ${user} (${spec.name})`)
|
||||
} else {
|
||||
this.npm.output(`- ${user} (${spec.name})`)
|
||||
output.standard(`- ${user} (${spec.name})`)
|
||||
}
|
||||
return res
|
||||
} catch (err) {
|
||||
|
||||
Vendored
+5
-4
@@ -1,9 +1,9 @@
|
||||
const pacote = require('pacote')
|
||||
const libpack = require('libnpmpack')
|
||||
const npa = require('npm-package-arg')
|
||||
const log = require('../utils/log-shim')
|
||||
const { log, output } = require('proc-log')
|
||||
const { getContents, logTar } = require('../utils/tar.js')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Pack extends BaseCommand {
|
||||
static description = 'Create a tarball from a package'
|
||||
@@ -58,13 +58,13 @@ class Pack extends BaseCommand {
|
||||
}
|
||||
|
||||
if (json) {
|
||||
this.npm.output(JSON.stringify(tarballs, null, 2))
|
||||
output.standard(JSON.stringify(tarballs, null, 2))
|
||||
return
|
||||
}
|
||||
|
||||
for (const tar of tarballs) {
|
||||
logTar(tar, { unicode })
|
||||
this.npm.output(tar.filename.replace(/^@/, '').replace(/\//, '-'))
|
||||
output.standard(tar.filename.replace(/^@/, '').replace(/\//, '-'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,4 +83,5 @@ class Pack extends BaseCommand {
|
||||
return this.exec([...this.workspacePaths, ...args.filter(a => a !== '.')])
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Pack
|
||||
Vendored
+6
-5
@@ -1,14 +1,14 @@
|
||||
const { redact } = require('@npmcli/redact')
|
||||
const log = require('../utils/log-shim')
|
||||
const { log, output } = require('proc-log')
|
||||
const pingUtil = require('../utils/ping.js')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Ping extends BaseCommand {
|
||||
static description = 'Ping npm registry'
|
||||
static params = ['registry']
|
||||
static name = 'ping'
|
||||
|
||||
async exec (args) {
|
||||
async exec () {
|
||||
const cleanRegistry = redact(this.npm.config.get('registry'))
|
||||
log.notice('PING', cleanRegistry)
|
||||
const start = Date.now()
|
||||
@@ -16,14 +16,15 @@ class Ping extends BaseCommand {
|
||||
const time = Date.now() - start
|
||||
log.notice('PONG', `${time}ms`)
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(JSON.stringify({
|
||||
output.standard(JSON.stringify({
|
||||
registry: cleanRegistry,
|
||||
time,
|
||||
details,
|
||||
}, null, 2))
|
||||
} else if (Object.keys(details).length) {
|
||||
log.notice('PONG', `${JSON.stringify(details, null, 2)}`)
|
||||
log.notice('PONG', JSON.stringify(details, null, 2))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Ping
|
||||
Vendored
+4
-3
@@ -1,5 +1,6 @@
|
||||
const { output } = require('proc-log')
|
||||
const PackageJson = require('@npmcli/package-json')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
const Queryable = require('../utils/queryable.js')
|
||||
|
||||
class Pkg extends BaseCommand {
|
||||
@@ -62,7 +63,7 @@ class Pkg extends BaseCommand {
|
||||
}
|
||||
// when running in workspaces names, make sure to key by workspace
|
||||
// name the results of each value retrieved in each ws
|
||||
this.npm.output(JSON.stringify(result, null, 2))
|
||||
output.standard(JSON.stringify(result, null, 2))
|
||||
}
|
||||
|
||||
async get (args) {
|
||||
@@ -85,7 +86,7 @@ class Pkg extends BaseCommand {
|
||||
// only outputs if not running with workspaces config
|
||||
// execWorkspaces will handle the output otherwise
|
||||
if (!this.workspaces) {
|
||||
this.npm.output(JSON.stringify(result, null, 2))
|
||||
output.standard(JSON.stringify(result, null, 2))
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
Vendored
+5
-3
@@ -1,4 +1,5 @@
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const { output } = require('proc-log')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Prefix extends BaseCommand {
|
||||
static description = 'Display prefix'
|
||||
@@ -6,8 +7,9 @@ class Prefix extends BaseCommand {
|
||||
static params = ['global']
|
||||
static usage = ['[-g]']
|
||||
|
||||
async exec (args) {
|
||||
return this.npm.output(this.npm.prefix)
|
||||
async exec () {
|
||||
return output.standard(this.npm.prefix)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Prefix
|
||||
Vendored
+31
-48
@@ -1,13 +1,11 @@
|
||||
const inspect = require('util').inspect
|
||||
const { inspect } = require('util')
|
||||
const { URL } = require('url')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const npmProfile = require('npm-profile')
|
||||
const qrcodeTerminal = require('qrcode-terminal')
|
||||
const Table = require('cli-table3')
|
||||
|
||||
const otplease = require('../utils/otplease.js')
|
||||
const pulseTillDone = require('../utils/pulse-till-done.js')
|
||||
const readUserInfo = require('../utils/read-user-info.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const qrcode = url =>
|
||||
new Promise((resolve) => qrcodeTerminal.generate(url, resolve))
|
||||
@@ -35,7 +33,6 @@ const writableProfileKeys = [
|
||||
'github',
|
||||
]
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Profile extends BaseCommand {
|
||||
static description = 'Change settings on your registry profile'
|
||||
static name = 'profile'
|
||||
@@ -80,8 +77,6 @@ class Profile extends BaseCommand {
|
||||
throw this.usageError()
|
||||
}
|
||||
|
||||
log.gauge.show('profile')
|
||||
|
||||
const [subcmd, ...opts] = args
|
||||
|
||||
switch (subcmd) {
|
||||
@@ -106,16 +101,14 @@ class Profile extends BaseCommand {
|
||||
|
||||
async get (args) {
|
||||
const tfa = 'two-factor auth'
|
||||
const info = await pulseTillDone.withPromise(
|
||||
npmProfile.get({ ...this.npm.flatOptions })
|
||||
)
|
||||
const info = await npmProfile.get({ ...this.npm.flatOptions })
|
||||
|
||||
if (!info.cidr_whitelist) {
|
||||
delete info.cidr_whitelist
|
||||
}
|
||||
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(JSON.stringify(info, null, 2))
|
||||
output.standard(JSON.stringify(info, null, 2))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -147,23 +140,20 @@ class Profile extends BaseCommand {
|
||||
.filter((arg) => arg.trim() !== '')
|
||||
.map((arg) => cleaned[arg])
|
||||
.join('\t')
|
||||
this.npm.output(values)
|
||||
output.standard(values)
|
||||
} else {
|
||||
if (this.npm.config.get('parseable')) {
|
||||
for (const key of Object.keys(info)) {
|
||||
if (key === 'tfa') {
|
||||
this.npm.output(`${key}\t${cleaned[tfa]}`)
|
||||
output.standard(`${key}\t${cleaned[tfa]}`)
|
||||
} else {
|
||||
this.npm.output(`${key}\t${info[key]}`)
|
||||
output.standard(`${key}\t${info[key]}`)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const table = new Table()
|
||||
for (const key of Object.keys(cleaned)) {
|
||||
table.push({ [this.npm.chalk.bold(key)]: cleaned[key] })
|
||||
for (const [key, value] of Object.entries(cleaned)) {
|
||||
output.standard(`${key}: ${value}`)
|
||||
}
|
||||
|
||||
this.npm.output(table.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -209,7 +199,7 @@ class Profile extends BaseCommand {
|
||||
}
|
||||
|
||||
// FIXME: Work around to not clear everything other than what we're setting
|
||||
const user = await pulseTillDone.withPromise(npmProfile.get(conf))
|
||||
const user = await npmProfile.get(conf)
|
||||
const newUser = {}
|
||||
|
||||
for (const key of writableProfileKeys) {
|
||||
@@ -221,13 +211,13 @@ class Profile extends BaseCommand {
|
||||
const result = await otplease(this.npm, conf, c => npmProfile.set(newUser, c))
|
||||
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(JSON.stringify({ [prop]: result[prop] }, null, 2))
|
||||
output.standard(JSON.stringify({ [prop]: result[prop] }, null, 2))
|
||||
} else if (this.npm.config.get('parseable')) {
|
||||
this.npm.output(prop + '\t' + result[prop])
|
||||
output.standard(prop + '\t' + result[prop])
|
||||
} else if (result[prop] != null) {
|
||||
this.npm.output('Set', prop, 'to', result[prop])
|
||||
output.standard('Set', prop, 'to', result[prop])
|
||||
} else {
|
||||
this.npm.output('Set', prop)
|
||||
output.standard('Set', prop)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,16 +297,12 @@ class Profile extends BaseCommand {
|
||||
info.tfa.password = password
|
||||
|
||||
log.info('profile', 'Determine if tfa is pending')
|
||||
const userInfo = await pulseTillDone.withPromise(
|
||||
npmProfile.get({ ...this.npm.flatOptions })
|
||||
)
|
||||
const userInfo = await npmProfile.get({ ...this.npm.flatOptions })
|
||||
|
||||
const conf = { ...this.npm.flatOptions }
|
||||
if (userInfo && userInfo.tfa && userInfo.tfa.pending) {
|
||||
log.info('profile', 'Resetting two-factor authentication')
|
||||
await pulseTillDone.withPromise(
|
||||
npmProfile.set({ tfa: { password, mode: 'disable' } }, conf)
|
||||
)
|
||||
await npmProfile.set({ tfa: { password, mode: 'disable' } }, conf)
|
||||
} else if (userInfo && userInfo.tfa) {
|
||||
if (!conf.otp) {
|
||||
conf.otp = await readUserInfo.otp(
|
||||
@@ -326,12 +312,10 @@ class Profile extends BaseCommand {
|
||||
}
|
||||
|
||||
log.info('profile', 'Setting two-factor authentication to ' + mode)
|
||||
const challenge = await pulseTillDone.withPromise(
|
||||
npmProfile.set(info, conf)
|
||||
)
|
||||
const challenge = await npmProfile.set(info, conf)
|
||||
|
||||
if (challenge.tfa === null) {
|
||||
this.npm.output('Two factor authentication mode changed to: ' + mode)
|
||||
output.standard('Two factor authentication mode changed to: ' + mode)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -348,7 +332,7 @@ class Profile extends BaseCommand {
|
||||
const secret = otpauth.searchParams.get('secret')
|
||||
const code = await qrcode(challenge.tfa)
|
||||
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
'Scan into your authenticator app:\n' + code + '\n Or enter code:', secret
|
||||
)
|
||||
|
||||
@@ -359,26 +343,26 @@ class Profile extends BaseCommand {
|
||||
|
||||
const result = await npmProfile.set({ tfa: [interactiveOTP] }, conf)
|
||||
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
'2FA successfully enabled. Below are your recovery codes, ' +
|
||||
'please print these out.'
|
||||
)
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
'You will need these to recover access to your account ' +
|
||||
'if you lose your authentication device.'
|
||||
)
|
||||
|
||||
for (const tfaCode of result.tfa) {
|
||||
this.npm.output('\t' + tfaCode)
|
||||
output.standard('\t' + tfaCode)
|
||||
}
|
||||
}
|
||||
|
||||
async disable2fa (args) {
|
||||
async disable2fa () {
|
||||
const conf = { ...this.npm.flatOptions }
|
||||
const info = await pulseTillDone.withPromise(npmProfile.get(conf))
|
||||
const info = await npmProfile.get(conf)
|
||||
|
||||
if (!info.tfa || info.tfa.pending) {
|
||||
this.npm.output('Two factor authentication not enabled.')
|
||||
output.standard('Two factor authentication not enabled.')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -391,17 +375,16 @@ class Profile extends BaseCommand {
|
||||
|
||||
log.info('profile', 'disabling tfa')
|
||||
|
||||
await pulseTillDone.withPromise(npmProfile.set({
|
||||
tfa: { password: password, mode: 'disable' },
|
||||
}, conf))
|
||||
await npmProfile.set({ tfa: { password: password, mode: 'disable' } }, conf)
|
||||
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(JSON.stringify({ tfa: false }, null, 2))
|
||||
output.standard(JSON.stringify({ tfa: false }, null, 2))
|
||||
} else if (this.npm.config.get('parseable')) {
|
||||
this.npm.output('tfa\tfalse')
|
||||
output.standard('tfa\tfalse')
|
||||
} else {
|
||||
this.npm.output('Two factor authentication disabled.')
|
||||
output.standard('Two factor authentication disabled.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Profile
|
||||
Vendored
+3
-2
@@ -1,7 +1,7 @@
|
||||
// prune extraneous packages
|
||||
const reifyFinish = require('../utils/reify-finish.js')
|
||||
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
// prune extraneous packages
|
||||
class Prune extends ArboristWorkspaceCmd {
|
||||
static description = 'Remove extraneous packages'
|
||||
static name = 'prune'
|
||||
@@ -30,4 +30,5 @@ class Prune extends ArboristWorkspaceCmd {
|
||||
await reifyFinish(this.npm, arb)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Prune
|
||||
Vendored
+9
-14
@@ -1,4 +1,4 @@
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const semver = require('semver')
|
||||
const pack = require('libnpmpack')
|
||||
const libpub = require('libnpmpublish').publish
|
||||
@@ -7,18 +7,16 @@ const pacote = require('pacote')
|
||||
const npa = require('npm-package-arg')
|
||||
const npmFetch = require('npm-registry-fetch')
|
||||
const { redactLog: replaceInfo } = require('@npmcli/redact')
|
||||
|
||||
const otplease = require('../utils/otplease.js')
|
||||
const { getContents, logTar } = require('../utils/tar.js')
|
||||
|
||||
// for historical reasons, publishConfig in package.json can contain ANY config
|
||||
// keys that npm supports in .npmrc files and elsewhere. We *may* want to
|
||||
// revisit this at some point, and have a minimal set that's a SemVer-major
|
||||
// change that ought to get a RFC written on it.
|
||||
const { flatten } = require('@npmcli/config/lib/definitions')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Publish extends BaseCommand {
|
||||
static description = 'Publish a package'
|
||||
static name = 'publish'
|
||||
@@ -59,7 +57,6 @@ class Publish extends BaseCommand {
|
||||
}
|
||||
|
||||
const opts = { ...this.npm.flatOptions, progress: false }
|
||||
log.disableProgress()
|
||||
|
||||
// you can publish name@version, ./foo.tgz, etc.
|
||||
// even though the default is the 'file:.' cwd.
|
||||
@@ -73,7 +70,6 @@ class Publish extends BaseCommand {
|
||||
path: spec.fetchSpec,
|
||||
stdio: 'inherit',
|
||||
pkg: manifest,
|
||||
banner: !silent,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -132,7 +128,6 @@ class Publish extends BaseCommand {
|
||||
path: spec.fetchSpec,
|
||||
stdio: 'inherit',
|
||||
pkg: manifest,
|
||||
banner: !silent,
|
||||
})
|
||||
|
||||
await runScript({
|
||||
@@ -140,22 +135,21 @@ class Publish extends BaseCommand {
|
||||
path: spec.fetchSpec,
|
||||
stdio: 'inherit',
|
||||
pkg: manifest,
|
||||
banner: !silent,
|
||||
})
|
||||
}
|
||||
|
||||
if (!this.suppressOutput) {
|
||||
if (!silent && json) {
|
||||
this.npm.output(JSON.stringify(pkgContents, null, 2))
|
||||
output.standard(JSON.stringify(pkgContents, null, 2))
|
||||
} else if (!silent) {
|
||||
this.npm.output(`+ ${pkgContents.id}`)
|
||||
output.standard(`+ ${pkgContents.id}`)
|
||||
}
|
||||
}
|
||||
|
||||
return pkgContents
|
||||
}
|
||||
|
||||
async execWorkspaces (args) {
|
||||
async execWorkspaces () {
|
||||
// Suppresses JSON output in publish() so we can handle it here
|
||||
this.suppressOutput = true
|
||||
|
||||
@@ -173,7 +167,7 @@ class Publish extends BaseCommand {
|
||||
log.warn(
|
||||
'publish',
|
||||
`Skipping workspace ${
|
||||
this.npm.chalk.green(name)
|
||||
this.npm.chalk.cyan(name)
|
||||
}, marked as ${
|
||||
this.npm.chalk.bold('private')
|
||||
}`
|
||||
@@ -185,14 +179,14 @@ class Publish extends BaseCommand {
|
||||
// This needs to be in-line w/ the rest of the output that non-JSON
|
||||
// publish generates
|
||||
if (!silent && !json) {
|
||||
this.npm.output(`+ ${pkgContents.id}`)
|
||||
output.standard(`+ ${pkgContents.id}`)
|
||||
} else {
|
||||
results[name] = pkgContents
|
||||
}
|
||||
}
|
||||
|
||||
if (!silent && json) {
|
||||
this.npm.output(JSON.stringify(results, null, 2))
|
||||
output.standard(JSON.stringify(results, null, 2))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,4 +224,5 @@ class Publish extends BaseCommand {
|
||||
return manifest
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Publish
|
||||
Vendored
+5
-7
@@ -1,8 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const { resolve } = require('path')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { resolve } = require('node:path')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
const { log, output } = require('proc-log')
|
||||
|
||||
class QuerySelectorItem {
|
||||
constructor (node) {
|
||||
@@ -83,7 +81,7 @@ class Query extends BaseCommand {
|
||||
this.buildResponse(items)
|
||||
|
||||
this.checkExpected(this.#response.length)
|
||||
this.npm.output(this.parsedResponse)
|
||||
output.standard(this.parsedResponse)
|
||||
}
|
||||
|
||||
async execWorkspaces (args) {
|
||||
@@ -107,7 +105,7 @@ class Query extends BaseCommand {
|
||||
this.buildResponse(items)
|
||||
}
|
||||
this.checkExpected(this.#response.length)
|
||||
this.npm.output(this.parsedResponse)
|
||||
output.standard(this.parsedResponse)
|
||||
}
|
||||
|
||||
// builds a normalized inventory
|
||||
|
||||
Vendored
+5
-3
@@ -1,8 +1,9 @@
|
||||
const { resolve } = require('path')
|
||||
const { output } = require('proc-log')
|
||||
const npa = require('npm-package-arg')
|
||||
const semver = require('semver')
|
||||
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
class Rebuild extends ArboristWorkspaceCmd {
|
||||
static description = 'Rebuild a package'
|
||||
static name = 'rebuild'
|
||||
@@ -19,7 +20,7 @@ class Rebuild extends ArboristWorkspaceCmd {
|
||||
// TODO
|
||||
/* istanbul ignore next */
|
||||
static async completion (opts, npm) {
|
||||
const completion = require('../utils/completion/installed-deep.js')
|
||||
const completion = require('../utils/installed-deep.js')
|
||||
return completion(npm, opts)
|
||||
}
|
||||
|
||||
@@ -56,7 +57,7 @@ class Rebuild extends ArboristWorkspaceCmd {
|
||||
await arb.rebuild()
|
||||
}
|
||||
|
||||
this.npm.output('rebuilt dependencies successfully')
|
||||
output.standard('rebuilt dependencies successfully')
|
||||
}
|
||||
|
||||
isNode (specs, node) {
|
||||
@@ -79,4 +80,5 @@ class Rebuild extends ArboristWorkspaceCmd {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Rebuild
|
||||
Vendored
+2
-1
@@ -1,6 +1,6 @@
|
||||
const { URL } = require('url')
|
||||
|
||||
const PackageUrlCmd = require('../package-url-cmd.js')
|
||||
|
||||
class Repo extends PackageUrlCmd {
|
||||
static description = 'Open package repository page in the browser'
|
||||
static name = 'repo'
|
||||
@@ -30,6 +30,7 @@ class Repo extends PackageUrlCmd {
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Repo
|
||||
|
||||
const unknownHostedUrl = url => {
|
||||
|
||||
Vendored
+5
-2
@@ -1,11 +1,14 @@
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const { output } = require('proc-log')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Root extends BaseCommand {
|
||||
static description = 'Display npm root'
|
||||
static name = 'root'
|
||||
static params = ['global']
|
||||
|
||||
async exec () {
|
||||
this.npm.output(this.npm.dir)
|
||||
output.standard(this.npm.dir)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Root
|
||||
Vendored
+36
-44
@@ -1,22 +1,7 @@
|
||||
const runScript = require('@npmcli/run-script')
|
||||
const { isServerPackage } = runScript
|
||||
const { log, output } = require('proc-log')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const didYouMean = require('../utils/did-you-mean.js')
|
||||
const { isWindowsShell } = require('../utils/is-windows.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const cmdList = [
|
||||
'publish',
|
||||
'install',
|
||||
'uninstall',
|
||||
'test',
|
||||
'stop',
|
||||
'start',
|
||||
'restart',
|
||||
'version',
|
||||
].reduce((l, p) => l.concat(['pre' + p, p, 'post' + p]), [])
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class RunScript extends BaseCommand {
|
||||
static description = 'Run arbitrary package scripts'
|
||||
static params = [
|
||||
@@ -39,7 +24,7 @@ class RunScript extends BaseCommand {
|
||||
const argv = opts.conf.argv.remain
|
||||
if (argv.length === 2) {
|
||||
const { content: { scripts = {} } } = await pkgJson.normalize(npm.localPrefix)
|
||||
.catch(er => ({ content: {} }))
|
||||
.catch(() => ({ content: {} }))
|
||||
if (opts.isFish) {
|
||||
return Object.keys(scripts).map(s => `${s}\t${scripts[s].slice(0, 30)}`)
|
||||
}
|
||||
@@ -64,9 +49,7 @@ class RunScript extends BaseCommand {
|
||||
}
|
||||
|
||||
async run ([event, ...args], { path = this.npm.localPrefix, pkg } = {}) {
|
||||
// this || undefined is because runScript will be unhappy with the default
|
||||
// null value
|
||||
const scriptShell = this.npm.config.get('script-shell') || undefined
|
||||
const runScript = require('@npmcli/run-script')
|
||||
|
||||
if (!pkg) {
|
||||
const { content } = await pkgJson.normalize(path)
|
||||
@@ -77,6 +60,7 @@ class RunScript extends BaseCommand {
|
||||
if (event === 'restart' && !scripts.restart) {
|
||||
scripts.restart = 'npm stop --if-present && npm start'
|
||||
} else if (event === 'env' && !scripts.env) {
|
||||
const { isWindowsShell } = require('../utils/is-windows.js')
|
||||
scripts.env = isWindowsShell ? 'SET' : 'env'
|
||||
}
|
||||
|
||||
@@ -84,12 +68,13 @@ class RunScript extends BaseCommand {
|
||||
|
||||
if (
|
||||
!Object.prototype.hasOwnProperty.call(scripts, event) &&
|
||||
!(event === 'start' && (await isServerPackage(path)))
|
||||
!(event === 'start' && (await runScript.isServerPackage(path)))
|
||||
) {
|
||||
if (this.npm.config.get('if-present')) {
|
||||
return
|
||||
}
|
||||
|
||||
const didYouMean = require('../utils/did-you-mean.js')
|
||||
const suggestions = await didYouMean(path, event)
|
||||
throw new Error(
|
||||
`Missing script: "${event}"${suggestions}\n\nTo see a list of scripts, run:\n npm run`
|
||||
@@ -108,18 +93,14 @@ class RunScript extends BaseCommand {
|
||||
}
|
||||
}
|
||||
|
||||
const opts = {
|
||||
path,
|
||||
args,
|
||||
scriptShell,
|
||||
stdio: 'inherit',
|
||||
pkg,
|
||||
banner: !this.npm.silent,
|
||||
}
|
||||
|
||||
for (const [ev, evArgs] of events) {
|
||||
await runScript({
|
||||
...opts,
|
||||
path,
|
||||
// this || undefined is because runScript will be unhappy with the
|
||||
// default null value
|
||||
scriptShell: this.npm.config.get('script-shell') || undefined,
|
||||
stdio: 'inherit',
|
||||
pkg,
|
||||
event: ev,
|
||||
args: evArgs,
|
||||
})
|
||||
@@ -141,18 +122,29 @@ class RunScript extends BaseCommand {
|
||||
}
|
||||
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(JSON.stringify(scripts, null, 2))
|
||||
output.standard(JSON.stringify(scripts, null, 2))
|
||||
return allScripts
|
||||
}
|
||||
|
||||
if (this.npm.config.get('parseable')) {
|
||||
for (const [script, cmd] of Object.entries(scripts)) {
|
||||
this.npm.output(`${script}:${cmd}`)
|
||||
output.standard(`${script}:${cmd}`)
|
||||
}
|
||||
|
||||
return allScripts
|
||||
}
|
||||
|
||||
// TODO this is missing things like prepare, prepublishOnly, and dependencies
|
||||
const cmdList = [
|
||||
'preinstall', 'install', 'postinstall',
|
||||
'prepublish', 'publish', 'postpublish',
|
||||
'prerestart', 'restart', 'postrestart',
|
||||
'prestart', 'start', 'poststart',
|
||||
'prestop', 'stop', 'poststop',
|
||||
'pretest', 'test', 'posttest',
|
||||
'preuninstall', 'uninstall', 'postuninstall',
|
||||
'preversion', 'version', 'postversion',
|
||||
]
|
||||
const indent = '\n '
|
||||
const prefix = ' '
|
||||
const cmds = []
|
||||
@@ -164,7 +156,7 @@ class RunScript extends BaseCommand {
|
||||
const colorize = this.npm.chalk
|
||||
|
||||
if (cmds.length) {
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
`${colorize.reset(colorize.bold('Lifecycle scripts'))} included in ${colorize.green(
|
||||
pkgid
|
||||
)}:`
|
||||
@@ -172,28 +164,28 @@ class RunScript extends BaseCommand {
|
||||
}
|
||||
|
||||
for (const script of cmds) {
|
||||
this.npm.output(prefix + script + indent + colorize.dim(scripts[script]))
|
||||
output.standard(prefix + script + indent + colorize.dim(scripts[script]))
|
||||
}
|
||||
|
||||
if (!cmds.length && runScripts.length) {
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
`${colorize.bold('Scripts')} available in ${colorize.green(pkgid)} via \`${colorize.blue(
|
||||
'npm run-script'
|
||||
)}\`:`
|
||||
)
|
||||
} else if (runScripts.length) {
|
||||
this.npm.output(`\navailable via \`${colorize.blue('npm run-script')}\`:`)
|
||||
output.standard(`\navailable via \`${colorize.blue('npm run-script')}\`:`)
|
||||
}
|
||||
|
||||
for (const script of runScripts) {
|
||||
this.npm.output(prefix + script + indent + colorize.dim(scripts[script]))
|
||||
output.standard(prefix + script + indent + colorize.dim(scripts[script]))
|
||||
}
|
||||
|
||||
this.npm.output('')
|
||||
output.standard('')
|
||||
return allScripts
|
||||
}
|
||||
|
||||
async runWorkspaces (args, filters) {
|
||||
async runWorkspaces (args) {
|
||||
const res = []
|
||||
await this.setWorkspaces()
|
||||
|
||||
@@ -213,7 +205,7 @@ class RunScript extends BaseCommand {
|
||||
}
|
||||
}
|
||||
|
||||
async listWorkspaces (args, filters) {
|
||||
async listWorkspaces (args) {
|
||||
await this.setWorkspaces()
|
||||
|
||||
if (this.npm.silent) {
|
||||
@@ -226,7 +218,7 @@ class RunScript extends BaseCommand {
|
||||
const { content: { scripts, name } } = await pkgJson.normalize(workspacePath)
|
||||
res[name] = { ...scripts }
|
||||
}
|
||||
this.npm.output(JSON.stringify(res, null, 2))
|
||||
output.standard(JSON.stringify(res, null, 2))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -234,7 +226,7 @@ class RunScript extends BaseCommand {
|
||||
for (const workspacePath of this.workspacePaths) {
|
||||
const { content: { scripts, name } } = await pkgJson.normalize(workspacePath)
|
||||
for (const [script, cmd] of Object.entries(scripts || {})) {
|
||||
this.npm.output(`${name}:${script}:${cmd}`)
|
||||
output.standard(`${name}:${script}:${cmd}`)
|
||||
}
|
||||
}
|
||||
return
|
||||
|
||||
Vendored
+4
-7
@@ -1,9 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const { EOL } = require('os')
|
||||
const localeCompare = require('@isaacs/string-locale-compare')('en')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const { cyclonedxOutput } = require('../utils/sbom-cyclonedx.js')
|
||||
const { spdxOutput } = require('../utils/sbom-spdx.js')
|
||||
|
||||
@@ -77,7 +74,7 @@ class SBOM extends BaseCommand {
|
||||
|
||||
if (errors.size > 0) {
|
||||
throw Object.assign(
|
||||
new Error([...errors].join(EOL)),
|
||||
new Error([...errors].join('\n')),
|
||||
{ code: 'ESBOMPROBLEMS' }
|
||||
)
|
||||
}
|
||||
@@ -87,7 +84,7 @@ class SBOM extends BaseCommand {
|
||||
items
|
||||
.sort((a, b) => localeCompare(a.location, b.location))
|
||||
)
|
||||
this.npm.output(this.#parsedResponse)
|
||||
output.standard(this.#parsedResponse)
|
||||
}
|
||||
|
||||
async execWorkspaces (args) {
|
||||
|
||||
Vendored
+9
-53
@@ -1,43 +1,13 @@
|
||||
const { Minipass } = require('minipass')
|
||||
const Pipeline = require('minipass-pipeline')
|
||||
const libSearch = require('libnpmsearch')
|
||||
const log = require('../utils/log-shim.js')
|
||||
|
||||
const { log, output } = require('proc-log')
|
||||
const formatSearchStream = require('../utils/format-search-stream.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
function filter (data, include, exclude) {
|
||||
const words = [data.name]
|
||||
.concat(data.maintainers.map(m => `=${m.username}`))
|
||||
.concat(data.keywords || [])
|
||||
.map(f => f && f.trim && f.trim())
|
||||
.filter(f => f)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
|
||||
if (exclude.find(e => match(words, e))) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
function match (words, pattern) {
|
||||
if (pattern.startsWith('/')) {
|
||||
if (pattern.endsWith('/')) {
|
||||
pattern = pattern.slice(0, -1)
|
||||
}
|
||||
pattern = new RegExp(pattern.slice(1))
|
||||
return words.match(pattern)
|
||||
}
|
||||
return words.indexOf(pattern) !== -1
|
||||
}
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Search extends BaseCommand {
|
||||
static description = 'Search for packages'
|
||||
static name = 'search'
|
||||
static params = [
|
||||
'long',
|
||||
'json',
|
||||
'color',
|
||||
'parseable',
|
||||
@@ -51,13 +21,13 @@ class Search extends BaseCommand {
|
||||
'offline',
|
||||
]
|
||||
|
||||
static usage = ['[search terms ...]']
|
||||
static usage = ['<search term> [<search term> ...]']
|
||||
|
||||
async exec (args) {
|
||||
const opts = {
|
||||
...this.npm.flatOptions,
|
||||
...this.npm.flatOptions.search,
|
||||
include: args.map(s => s.toLowerCase()).filter(s => s),
|
||||
include: args.map(s => s.toLowerCase()).filter(Boolean),
|
||||
exclude: this.npm.flatOptions.search.exclude.split(/\s+/),
|
||||
}
|
||||
|
||||
@@ -68,30 +38,16 @@ class Search extends BaseCommand {
|
||||
// Used later to figure out whether we had any packages go out
|
||||
let anyOutput = false
|
||||
|
||||
class FilterStream extends Minipass {
|
||||
constructor () {
|
||||
super({ objectMode: true })
|
||||
}
|
||||
|
||||
write (pkg) {
|
||||
if (filter(pkg, opts.include, opts.exclude)) {
|
||||
super.write(pkg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const filterStream = new FilterStream()
|
||||
|
||||
// Grab a configured output stream that will spit out packages in the desired format.
|
||||
const outputStream = await formatSearchStream({
|
||||
const outputStream = formatSearchStream({
|
||||
args, // --searchinclude options are not highlighted
|
||||
...opts,
|
||||
npm: this.npm,
|
||||
})
|
||||
|
||||
log.silly('search', 'searching packages')
|
||||
const p = new Pipeline(
|
||||
libSearch.stream(opts.include, opts),
|
||||
filterStream,
|
||||
outputStream
|
||||
)
|
||||
|
||||
@@ -99,16 +55,16 @@ class Search extends BaseCommand {
|
||||
if (!anyOutput) {
|
||||
anyOutput = true
|
||||
}
|
||||
this.npm.output(chunk.toString('utf8'))
|
||||
output.standard(chunk.toString('utf8'))
|
||||
})
|
||||
|
||||
await p.promise()
|
||||
if (!anyOutput && !this.npm.config.get('json') && !this.npm.config.get('parseable')) {
|
||||
this.npm.output('No matches found for ' + (args.map(JSON.stringify).join(' ')))
|
||||
output.standard('No matches found for ' + (args.map(JSON.stringify).join(' ')))
|
||||
}
|
||||
|
||||
log.silly('search', 'search completed')
|
||||
log.clearProgress()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Search
|
||||
Vendored
+2
-1
@@ -1,5 +1,5 @@
|
||||
const Npm = require('../npm.js')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Set extends BaseCommand {
|
||||
static description = 'Set a value in the npm configuration'
|
||||
@@ -22,4 +22,5 @@ class Set extends BaseCommand {
|
||||
return this.npm.exec('config', ['set'].concat(args))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Set
|
||||
Vendored
+5
-3
@@ -1,7 +1,8 @@
|
||||
const { resolve, basename } = require('path')
|
||||
const { unlink } = require('fs').promises
|
||||
const log = require('../utils/log-shim')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const { unlink } = require('fs/promises')
|
||||
const { log } = require('proc-log')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Shrinkwrap extends BaseCommand {
|
||||
static description = 'Lock down dependency versions for publication'
|
||||
static name = 'shrinkwrap'
|
||||
@@ -68,4 +69,5 @@ class Shrinkwrap extends BaseCommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Shrinkwrap
|
||||
Vendored
+4
-3
@@ -1,9 +1,9 @@
|
||||
const fetch = require('npm-registry-fetch')
|
||||
const npa = require('npm-package-arg')
|
||||
const log = require('../utils/log-shim')
|
||||
const { log, output } = require('proc-log')
|
||||
const getIdentity = require('../utils/get-identity')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Star extends BaseCommand {
|
||||
static description = 'Mark your favorite packages'
|
||||
static name = 'star'
|
||||
@@ -62,10 +62,11 @@ class Star extends BaseCommand {
|
||||
body,
|
||||
})
|
||||
|
||||
this.npm.output(show + ' ' + pkg.name)
|
||||
output.standard(show + ' ' + pkg.name)
|
||||
log.verbose('star', data)
|
||||
return data
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Star
|
||||
Vendored
+4
-3
@@ -1,8 +1,8 @@
|
||||
const fetch = require('npm-registry-fetch')
|
||||
const log = require('../utils/log-shim')
|
||||
const { log, output } = require('proc-log')
|
||||
const getIdentity = require('../utils/get-identity.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Stars extends BaseCommand {
|
||||
static description = 'View packages marked as favorites'
|
||||
static name = 'stars'
|
||||
@@ -25,7 +25,7 @@ class Stars extends BaseCommand {
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
this.npm.output(row.value)
|
||||
output.standard(row.value)
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.code === 'ENEEDAUTH') {
|
||||
@@ -35,4 +35,5 @@ class Stars extends BaseCommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Stars
|
||||
Vendored
+23
-22
@@ -1,9 +1,9 @@
|
||||
const columns = require('cli-columns')
|
||||
const libteam = require('libnpmteam')
|
||||
|
||||
const { output } = require('proc-log')
|
||||
const otplease = require('../utils/otplease.js')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
class Team extends BaseCommand {
|
||||
static description = 'Manage organization teams and team memberships'
|
||||
static name = 'team'
|
||||
@@ -68,87 +68,88 @@ class Team extends BaseCommand {
|
||||
async create (entity, opts) {
|
||||
await libteam.create(entity, opts)
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify({
|
||||
output.standard(JSON.stringify({
|
||||
created: true,
|
||||
team: entity,
|
||||
}))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(`${entity}\tcreated`)
|
||||
output.standard(`${entity}\tcreated`)
|
||||
} else if (!this.npm.silent) {
|
||||
this.npm.output(`+@${entity}`)
|
||||
output.standard(`+@${entity}`)
|
||||
}
|
||||
}
|
||||
|
||||
async destroy (entity, opts) {
|
||||
await libteam.destroy(entity, opts)
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify({
|
||||
output.standard(JSON.stringify({
|
||||
deleted: true,
|
||||
team: entity,
|
||||
}))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(`${entity}\tdeleted`)
|
||||
output.standard(`${entity}\tdeleted`)
|
||||
} else if (!this.npm.silent) {
|
||||
this.npm.output(`-@${entity}`)
|
||||
output.standard(`-@${entity}`)
|
||||
}
|
||||
}
|
||||
|
||||
async add (entity, user, opts) {
|
||||
await libteam.add(user, entity, opts)
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify({
|
||||
output.standard(JSON.stringify({
|
||||
added: true,
|
||||
team: entity,
|
||||
user,
|
||||
}))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(`${user}\t${entity}\tadded`)
|
||||
output.standard(`${user}\t${entity}\tadded`)
|
||||
} else if (!this.npm.silent) {
|
||||
this.npm.output(`${user} added to @${entity}`)
|
||||
output.standard(`${user} added to @${entity}`)
|
||||
}
|
||||
}
|
||||
|
||||
async rm (entity, user, opts) {
|
||||
await libteam.rm(user, entity, opts)
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify({
|
||||
output.standard(JSON.stringify({
|
||||
removed: true,
|
||||
team: entity,
|
||||
user,
|
||||
}))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(`${user}\t${entity}\tremoved`)
|
||||
output.standard(`${user}\t${entity}\tremoved`)
|
||||
} else if (!this.npm.silent) {
|
||||
this.npm.output(`${user} removed from @${entity}`)
|
||||
output.standard(`${user} removed from @${entity}`)
|
||||
}
|
||||
}
|
||||
|
||||
async listUsers (entity, opts) {
|
||||
const users = (await libteam.lsUsers(entity, opts)).sort()
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify(users, null, 2))
|
||||
output.standard(JSON.stringify(users, null, 2))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(users.join('\n'))
|
||||
output.standard(users.join('\n'))
|
||||
} else if (!this.npm.silent) {
|
||||
const plural = users.length === 1 ? '' : 's'
|
||||
const more = users.length === 0 ? '' : ':\n'
|
||||
this.npm.output(`\n@${entity} has ${users.length} user${plural}${more}`)
|
||||
this.npm.output(columns(users, { padding: 1 }))
|
||||
output.standard(`\n@${entity} has ${users.length} user${plural}${more}`)
|
||||
output.standard(columns(users, { padding: 1 }))
|
||||
}
|
||||
}
|
||||
|
||||
async listTeams (entity, opts) {
|
||||
const teams = (await libteam.lsTeams(entity, opts)).sort()
|
||||
if (opts.json) {
|
||||
this.npm.output(JSON.stringify(teams, null, 2))
|
||||
output.standard(JSON.stringify(teams, null, 2))
|
||||
} else if (opts.parseable) {
|
||||
this.npm.output(teams.join('\n'))
|
||||
output.standard(teams.join('\n'))
|
||||
} else if (!this.npm.silent) {
|
||||
const plural = teams.length === 1 ? '' : 's'
|
||||
const more = teams.length === 0 ? '' : ':\n'
|
||||
this.npm.output(`\n@${entity} has ${teams.length} team${plural}${more}`)
|
||||
this.npm.output(columns(teams.map(t => `@${t}`), { padding: 1 }))
|
||||
output.standard(`\n@${entity} has ${teams.length} team${plural}${more}`)
|
||||
output.standard(columns(teams.map(t => `@${t}`), { padding: 1 }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Team
|
||||
Vendored
+57
-89
@@ -1,12 +1,9 @@
|
||||
const Table = require('cli-table3')
|
||||
const log = require('../utils/log-shim.js')
|
||||
const { log, output } = require('proc-log')
|
||||
const profile = require('npm-profile')
|
||||
|
||||
const otplease = require('../utils/otplease.js')
|
||||
const pulseTillDone = require('../utils/pulse-till-done.js')
|
||||
const readUserInfo = require('../utils/read-user-info.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Token extends BaseCommand {
|
||||
static description = 'Manage your authentication tokens'
|
||||
static name = 'token'
|
||||
@@ -28,7 +25,6 @@ class Token extends BaseCommand {
|
||||
}
|
||||
|
||||
async exec (args) {
|
||||
log.gauge.show('token')
|
||||
if (args.length === 0) {
|
||||
return this.list()
|
||||
}
|
||||
@@ -36,10 +32,10 @@ class Token extends BaseCommand {
|
||||
case 'list':
|
||||
case 'ls':
|
||||
return this.list()
|
||||
case 'rm':
|
||||
case 'delete':
|
||||
case 'revoke':
|
||||
case 'remove':
|
||||
case 'rm':
|
||||
return this.rm(args.slice(1))
|
||||
case 'create':
|
||||
return this.create(args.slice(1))
|
||||
@@ -49,16 +45,18 @@ class Token extends BaseCommand {
|
||||
}
|
||||
|
||||
async list () {
|
||||
const conf = this.config()
|
||||
const json = this.npm.config.get('json')
|
||||
const parseable = this.npm.config.get('parseable')
|
||||
log.info('token', 'getting list')
|
||||
const tokens = await pulseTillDone.withPromise(profile.listTokens(conf))
|
||||
if (conf.json) {
|
||||
this.npm.output(JSON.stringify(tokens, null, 2))
|
||||
const tokens = await profile.listTokens(this.npm.flatOptions)
|
||||
if (json) {
|
||||
output.standard(JSON.stringify(tokens, null, 2))
|
||||
return
|
||||
} else if (conf.parseable) {
|
||||
this.npm.output(['key', 'token', 'created', 'readonly', 'CIDR whitelist'].join('\t'))
|
||||
}
|
||||
if (parseable) {
|
||||
output.standard(['key', 'token', 'created', 'readonly', 'CIDR whitelist'].join('\t'))
|
||||
tokens.forEach(token => {
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
[
|
||||
token.key,
|
||||
token.token,
|
||||
@@ -71,21 +69,17 @@ class Token extends BaseCommand {
|
||||
return
|
||||
}
|
||||
this.generateTokenIds(tokens, 6)
|
||||
const idWidth = tokens.reduce((acc, token) => Math.max(acc, token.id.length), 0)
|
||||
const table = new Table({
|
||||
head: ['id', 'token', 'created', 'readonly', 'CIDR whitelist'],
|
||||
colWidths: [Math.max(idWidth, 2) + 2, 9, 12, 10],
|
||||
})
|
||||
tokens.forEach(token => {
|
||||
table.push([
|
||||
token.id,
|
||||
token.token + '…',
|
||||
String(token.created).slice(0, 10),
|
||||
token.readonly ? 'yes' : 'no',
|
||||
token.cidr_whitelist ? token.cidr_whitelist.join(', ') : '',
|
||||
])
|
||||
})
|
||||
this.npm.output(table.toString())
|
||||
const chalk = this.npm.chalk
|
||||
for (const token of tokens) {
|
||||
const level = token.readonly ? 'Read only token' : 'Publish token'
|
||||
const created = String(token.created).slice(0, 10)
|
||||
/* eslint-disable-next-line max-len */
|
||||
output.standard(`${chalk.blue(level)} ${token.token}… with id ${chalk.cyan(token.id)} created ${created}`)
|
||||
if (token.cidr_whitelist) {
|
||||
output.standard(`with IP whitelist: ${chalk.green(token.cidr_whitelist.join(','))}`)
|
||||
}
|
||||
output.standard()
|
||||
}
|
||||
}
|
||||
|
||||
async rm (args) {
|
||||
@@ -93,11 +87,12 @@ class Token extends BaseCommand {
|
||||
throw this.usageError('`<tokenKey>` argument is required.')
|
||||
}
|
||||
|
||||
const conf = this.config()
|
||||
const json = this.npm.config.get('json')
|
||||
const parseable = this.npm.config.get('parseable')
|
||||
const toRemove = []
|
||||
const progress = log.newItem('removing tokens', toRemove.length)
|
||||
progress.info('token', 'getting existing list')
|
||||
const tokens = await pulseTillDone.withPromise(profile.listTokens(conf))
|
||||
const opts = { ...this.npm.flatOptions }
|
||||
log.info('token', `removing ${toRemove.length} tokens`)
|
||||
const tokens = await profile.listTokens(opts)
|
||||
args.forEach(id => {
|
||||
const matches = tokens.filter(token => token.key.indexOf(id) === 0)
|
||||
if (matches.length === 1) {
|
||||
@@ -118,80 +113,54 @@ class Token extends BaseCommand {
|
||||
})
|
||||
await Promise.all(
|
||||
toRemove.map(key => {
|
||||
return otplease(this.npm, conf, c => profile.removeToken(key, c))
|
||||
return otplease(this.npm, opts, c => profile.removeToken(key, c))
|
||||
})
|
||||
)
|
||||
if (conf.json) {
|
||||
this.npm.output(JSON.stringify(toRemove))
|
||||
} else if (conf.parseable) {
|
||||
this.npm.output(toRemove.join('\t'))
|
||||
if (json) {
|
||||
output.standard(JSON.stringify(toRemove))
|
||||
} else if (parseable) {
|
||||
output.standard(toRemove.join('\t'))
|
||||
} else {
|
||||
this.npm.output('Removed ' + toRemove.length + ' token' + (toRemove.length !== 1 ? 's' : ''))
|
||||
output.standard('Removed ' + toRemove.length + ' token' + (toRemove.length !== 1 ? 's' : ''))
|
||||
}
|
||||
}
|
||||
|
||||
async create (args) {
|
||||
const conf = this.config()
|
||||
const cidr = conf.cidr
|
||||
const readonly = conf.readOnly
|
||||
async create () {
|
||||
const json = this.npm.config.get('json')
|
||||
const parseable = this.npm.config.get('parseable')
|
||||
const cidr = this.npm.config.get('cidr')
|
||||
const readonly = this.npm.config.get('read-only')
|
||||
|
||||
const password = await readUserInfo.password()
|
||||
const validCIDR = await this.validateCIDRList(cidr)
|
||||
const password = await readUserInfo.password()
|
||||
log.info('token', 'creating')
|
||||
const result = await pulseTillDone.withPromise(
|
||||
otplease(this.npm, conf, c => profile.createToken(password, readonly, validCIDR, c))
|
||||
const result = await otplease(
|
||||
this.npm,
|
||||
{ ...this.npm.flatOptions },
|
||||
c => profile.createToken(password, readonly, validCIDR, c)
|
||||
)
|
||||
delete result.key
|
||||
delete result.updated
|
||||
if (conf.json) {
|
||||
this.npm.output(JSON.stringify(result))
|
||||
} else if (conf.parseable) {
|
||||
Object.keys(result).forEach(k => this.npm.output(k + '\t' + result[k]))
|
||||
if (json) {
|
||||
output.standard(JSON.stringify(result))
|
||||
} else if (parseable) {
|
||||
Object.keys(result).forEach(k => output.standard(k + '\t' + result[k]))
|
||||
} else {
|
||||
const table = new Table()
|
||||
for (const k of Object.keys(result)) {
|
||||
table.push({ [this.npm.chalk.bold(k)]: String(result[k]) })
|
||||
const chalk = this.npm.chalk
|
||||
// Identical to list
|
||||
const level = result.readonly ? 'read only' : 'publish'
|
||||
output.standard(`Created ${chalk.blue(level)} token ${result.token}`)
|
||||
if (result.cidr_whitelist?.length) {
|
||||
output.standard(`with IP whitelist: ${chalk.green(result.cidr_whitelist.join(','))}`)
|
||||
}
|
||||
this.npm.output(table.toString())
|
||||
}
|
||||
}
|
||||
|
||||
config () {
|
||||
const conf = { ...this.npm.flatOptions }
|
||||
const creds = this.npm.config.getCredentialsByURI(conf.registry)
|
||||
if (creds.token) {
|
||||
conf.auth = { token: creds.token }
|
||||
} else if (creds.username) {
|
||||
conf.auth = {
|
||||
basic: {
|
||||
username: creds.username,
|
||||
password: creds.password,
|
||||
},
|
||||
}
|
||||
} else if (creds.auth) {
|
||||
const auth = Buffer.from(creds.auth, 'base64').toString().split(':', 2)
|
||||
conf.auth = {
|
||||
basic: {
|
||||
username: auth[0],
|
||||
password: auth[1],
|
||||
},
|
||||
}
|
||||
} else {
|
||||
conf.auth = {}
|
||||
}
|
||||
|
||||
if (conf.otp) {
|
||||
conf.auth.otp = conf.otp
|
||||
}
|
||||
return conf
|
||||
}
|
||||
|
||||
invalidCIDRError (msg) {
|
||||
return Object.assign(new Error(msg), { code: 'EINVALIDCIDR' })
|
||||
}
|
||||
|
||||
generateTokenIds (tokens, minLength) {
|
||||
const byId = {}
|
||||
for (const token of tokens) {
|
||||
token.id = token.key
|
||||
for (let ii = minLength; ii < token.key.length; ++ii) {
|
||||
@@ -203,9 +172,7 @@ class Token extends BaseCommand {
|
||||
break
|
||||
}
|
||||
}
|
||||
byId[token.id] = token
|
||||
}
|
||||
return byId
|
||||
}
|
||||
|
||||
async validateCIDRList (cidrs) {
|
||||
@@ -215,15 +182,16 @@ class Token extends BaseCommand {
|
||||
for (const cidr of list) {
|
||||
if (isCidrV6(cidr)) {
|
||||
throw this.invalidCIDRError(
|
||||
'CIDR whitelist can only contain IPv4 addresses, ' + cidr + ' is IPv6'
|
||||
`CIDR whitelist can only contain IPv4 addresses${cidr} is IPv6`
|
||||
)
|
||||
}
|
||||
|
||||
if (!isCidrV4(cidr)) {
|
||||
throw this.invalidCIDRError('CIDR whitelist contains invalid CIDR entry: ' + cidr)
|
||||
throw this.invalidCIDRError(`CIDR whitelist contains invalid CIDR entry: ${cidr}`)
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Token
|
||||
Vendored
+3
-3
@@ -1,10 +1,9 @@
|
||||
const { resolve } = require('path')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
|
||||
const reifyFinish = require('../utils/reify-finish.js')
|
||||
const completion = require('../utils/completion/installed-shallow.js')
|
||||
|
||||
const completion = require('../utils/installed-shallow.js')
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
class Uninstall extends ArboristWorkspaceCmd {
|
||||
static description = 'Remove a package'
|
||||
static name = 'uninstall'
|
||||
@@ -53,4 +52,5 @@ class Uninstall extends ArboristWorkspaceCmd {
|
||||
await reifyFinish(this.npm, arb)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Uninstall
|
||||
Vendored
+4
-4
@@ -2,18 +2,17 @@ const libaccess = require('libnpmaccess')
|
||||
const libunpub = require('libnpmpublish').unpublish
|
||||
const npa = require('npm-package-arg')
|
||||
const pacote = require('pacote')
|
||||
const { output, log } = require('proc-log')
|
||||
const pkgJson = require('@npmcli/package-json')
|
||||
|
||||
const { flatten } = require('@npmcli/config/lib/definitions')
|
||||
const getIdentity = require('../utils/get-identity.js')
|
||||
const log = require('../utils/log-shim')
|
||||
const otplease = require('../utils/otplease.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const LAST_REMAINING_VERSION_ERROR = 'Refusing to delete the last version of the package. ' +
|
||||
'It will block from republishing a new version for 24 hours.\n' +
|
||||
'Run with --force to do this.'
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Unpublish extends BaseCommand {
|
||||
static description = 'Remove a package from the registry'
|
||||
static name = 'unpublish'
|
||||
@@ -161,7 +160,7 @@ class Unpublish extends BaseCommand {
|
||||
await otplease(this.npm, opts, o => libunpub(spec, o))
|
||||
}
|
||||
if (!silent) {
|
||||
this.npm.output(`- ${spec.name}${pkgVersion}`)
|
||||
output.standard(`- ${spec.name}${pkgVersion}`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,4 +172,5 @@ class Unpublish extends BaseCommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Unpublish
|
||||
Vendored
+1
@@ -4,4 +4,5 @@ class Unstar extends Star {
|
||||
static description = 'Remove an item from your favorite packages'
|
||||
static name = 'unstar'
|
||||
}
|
||||
|
||||
module.exports = Unstar
|
||||
Vendored
+4
-5
@@ -1,10 +1,8 @@
|
||||
const path = require('path')
|
||||
|
||||
const log = require('../utils/log-shim.js')
|
||||
|
||||
const { log } = require('proc-log')
|
||||
const reifyFinish = require('../utils/reify-finish.js')
|
||||
|
||||
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
|
||||
|
||||
class Update extends ArboristWorkspaceCmd {
|
||||
static description = 'Update packages'
|
||||
static name = 'update'
|
||||
@@ -33,7 +31,7 @@ class Update extends ArboristWorkspaceCmd {
|
||||
// TODO
|
||||
/* istanbul ignore next */
|
||||
static async completion (opts, npm) {
|
||||
const completion = require('../utils/completion/installed-deep.js')
|
||||
const completion = require('../utils/installed-deep.js')
|
||||
return completion(npm, opts)
|
||||
}
|
||||
|
||||
@@ -66,4 +64,5 @@ class Update extends ArboristWorkspaceCmd {
|
||||
await reifyFinish(this.npm, arb)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Update
|
||||
Vendored
+25
-30
@@ -1,10 +1,7 @@
|
||||
const libnpmversion = require('libnpmversion')
|
||||
const { resolve } = require('path')
|
||||
const { promisify } = require('util')
|
||||
const readFile = promisify(require('fs').readFile)
|
||||
|
||||
const updateWorkspaces = require('../workspaces/update-workspaces.js')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
const { resolve } = require('node:path')
|
||||
const { readFile } = require('node:fs/promises')
|
||||
const { output } = require('proc-log')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
class Version extends BaseCommand {
|
||||
static description = 'Bump a package version'
|
||||
@@ -73,29 +70,43 @@ class Version extends BaseCommand {
|
||||
}
|
||||
|
||||
async change (args) {
|
||||
const libnpmversion = require('libnpmversion')
|
||||
const prefix = this.npm.config.get('tag-version-prefix')
|
||||
const version = await libnpmversion(args[0], {
|
||||
...this.npm.flatOptions,
|
||||
path: this.npm.prefix,
|
||||
})
|
||||
return this.npm.output(`${prefix}${version}`)
|
||||
return output.standard(`${prefix}${version}`)
|
||||
}
|
||||
|
||||
async changeWorkspaces (args) {
|
||||
const updateWorkspaces = require('../utils/update-workspaces.js')
|
||||
const libnpmversion = require('libnpmversion')
|
||||
const prefix = this.npm.config.get('tag-version-prefix')
|
||||
const {
|
||||
config,
|
||||
flatOptions,
|
||||
localPrefix,
|
||||
} = this.npm
|
||||
await this.setWorkspaces()
|
||||
const updatedWorkspaces = []
|
||||
for (const [name, path] of this.workspaces) {
|
||||
this.npm.output(name)
|
||||
output.standard(name)
|
||||
const version = await libnpmversion(args[0], {
|
||||
...this.npm.flatOptions,
|
||||
...flatOptions,
|
||||
'git-tag-version': false,
|
||||
path,
|
||||
})
|
||||
updatedWorkspaces.push(name)
|
||||
this.npm.output(`${prefix}${version}`)
|
||||
output.standard(`${prefix}${version}`)
|
||||
}
|
||||
return this.update(updatedWorkspaces)
|
||||
return updateWorkspaces({
|
||||
config,
|
||||
flatOptions,
|
||||
localPrefix,
|
||||
npm: this.npm,
|
||||
workspaces: updatedWorkspaces,
|
||||
})
|
||||
}
|
||||
|
||||
async list (results = {}) {
|
||||
@@ -115,9 +126,9 @@ class Version extends BaseCommand {
|
||||
}
|
||||
|
||||
if (this.npm.config.get('json')) {
|
||||
this.npm.output(JSON.stringify(results, null, 2))
|
||||
output.standard(JSON.stringify(results, null, 2))
|
||||
} else {
|
||||
this.npm.output(results)
|
||||
output.standard(results)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,22 +146,6 @@ class Version extends BaseCommand {
|
||||
}
|
||||
return this.list(results)
|
||||
}
|
||||
|
||||
async update (workspaces) {
|
||||
const {
|
||||
config,
|
||||
flatOptions,
|
||||
localPrefix,
|
||||
} = this.npm
|
||||
|
||||
await updateWorkspaces({
|
||||
config,
|
||||
flatOptions,
|
||||
localPrefix,
|
||||
npm: this.npm,
|
||||
workspaces,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Version
|
||||
Vendored
+77
-116
@@ -1,20 +1,19 @@
|
||||
const columns = require('cli-columns')
|
||||
const fs = require('fs')
|
||||
const { readFile } = require('fs/promises')
|
||||
const jsonParse = require('json-parse-even-better-errors')
|
||||
const log = require('../utils/log-shim.js')
|
||||
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, promisify } = require('util')
|
||||
const { inspect } = require('util')
|
||||
const { packument } = require('pacote')
|
||||
const Queryable = require('../utils/queryable.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const readFile = promisify(fs.readFile)
|
||||
const readJson = async file => jsonParse(await readFile(file, 'utf8'))
|
||||
|
||||
const Queryable = require('../utils/queryable.js')
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class View extends BaseCommand {
|
||||
static description = 'View registry info'
|
||||
static name = 'view'
|
||||
@@ -115,13 +114,10 @@ class View extends BaseCommand {
|
||||
reducedData = cleanBlanks(reducedData)
|
||||
log.silly('view', reducedData)
|
||||
}
|
||||
// disable the progress bar entirely, as we can't meaningfully update it
|
||||
// if we may have partial lines printed.
|
||||
log.disableProgress()
|
||||
|
||||
const msg = await this.jsonData(reducedData, pckmnt._id)
|
||||
if (msg !== '') {
|
||||
this.npm.output(msg)
|
||||
output.standard(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -160,10 +156,10 @@ class View extends BaseCommand {
|
||||
if (wholePackument) {
|
||||
data.map((v) => this.prettyView(pckmnt, v[Object.keys(v)[0]]['']))
|
||||
} else {
|
||||
this.npm.output(`${name}:`)
|
||||
output.standard(`${name}:`)
|
||||
const msg = await this.jsonData(reducedData, pckmnt._id)
|
||||
if (msg !== '') {
|
||||
this.npm.output(msg)
|
||||
output.standard(msg)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -174,7 +170,7 @@ class View extends BaseCommand {
|
||||
}
|
||||
}
|
||||
if (Object.keys(results).length > 0) {
|
||||
this.npm.output(JSON.stringify(results, null, 2))
|
||||
output.standard(JSON.stringify(results, null, 2))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,131 +317,96 @@ class View extends BaseCommand {
|
||||
// More modern, pretty printing of default view
|
||||
const unicode = this.npm.config.get('unicode')
|
||||
const chalk = this.npm.chalk
|
||||
const tags = []
|
||||
|
||||
Object.keys(packu['dist-tags']).forEach((t) => {
|
||||
const version = packu['dist-tags'][t]
|
||||
tags.push(`${chalk.bold.green(t)}: ${version}`)
|
||||
})
|
||||
const unpackedSize = manifest.dist.unpackedSize &&
|
||||
formatBytes(manifest.dist.unpackedSize, true)
|
||||
const deps = Object.keys(manifest.dependencies || {}).map((dep) =>
|
||||
`${chalk.blue(dep)}: ${manifest.dependencies[dep]}`
|
||||
)
|
||||
const site = manifest.homepage?.url || manifest.homepage
|
||||
const bins = Object.keys(manifest.bin || {})
|
||||
const licenseField = manifest.license || 'Proprietary'
|
||||
const info = {
|
||||
name: chalk.green(manifest.name),
|
||||
version: chalk.green(manifest.version),
|
||||
bins: Object.keys(manifest.bin || {}),
|
||||
versions: chalk.yellow(packu.versions.length + ''),
|
||||
description: manifest.description,
|
||||
deprecated: manifest.deprecated,
|
||||
keywords: packu.keywords || [],
|
||||
license: typeof licenseField === 'string'
|
||||
? licenseField
|
||||
: (licenseField.type || 'Proprietary'),
|
||||
deps: Object.keys(manifest.dependencies || {}).map((dep) => {
|
||||
return `${chalk.yellow(dep)}: ${manifest.dependencies[dep]}`
|
||||
}),
|
||||
publisher: manifest._npmUser && unparsePerson({
|
||||
name: chalk.yellow(manifest._npmUser.name),
|
||||
email: chalk.cyan(manifest._npmUser.email),
|
||||
}),
|
||||
modified: !packu.time ? undefined
|
||||
: chalk.yellow(relativeDate(packu.time[manifest.version])),
|
||||
maintainers: (packu.maintainers || []).map((u) => unparsePerson({
|
||||
name: chalk.yellow(u.name),
|
||||
email: chalk.cyan(u.email),
|
||||
})),
|
||||
repo: (
|
||||
manifest.bugs && (manifest.bugs.url || manifest.bugs)
|
||||
) || (
|
||||
manifest.repository && (manifest.repository.url || manifest.repository)
|
||||
),
|
||||
site: (
|
||||
manifest.homepage && (manifest.homepage.url || manifest.homepage)
|
||||
),
|
||||
tags,
|
||||
tarball: chalk.cyan(manifest.dist.tarball),
|
||||
shasum: chalk.yellow(manifest.dist.shasum),
|
||||
integrity:
|
||||
manifest.dist.integrity && chalk.yellow(manifest.dist.integrity),
|
||||
fileCount:
|
||||
manifest.dist.fileCount && chalk.yellow(manifest.dist.fileCount),
|
||||
unpackedSize: unpackedSize && chalk.yellow(unpackedSize),
|
||||
}
|
||||
if (info.license.toLowerCase().trim() === 'proprietary') {
|
||||
info.license = chalk.bold.red(info.license)
|
||||
} else {
|
||||
info.license = chalk.green(info.license)
|
||||
const license = typeof licenseField === 'string'
|
||||
? licenseField
|
||||
: (licenseField.type || 'Proprietary')
|
||||
|
||||
output.standard('')
|
||||
output.standard([
|
||||
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 && output.standard(manifest.description)
|
||||
if (site) {
|
||||
output.standard(chalk.blue(site))
|
||||
}
|
||||
|
||||
this.npm.output('')
|
||||
this.npm.output(
|
||||
chalk.underline.bold(`${info.name}@${info.version}`) +
|
||||
' | ' + info.license +
|
||||
' | deps: ' + (info.deps.length ? chalk.cyan(info.deps.length) : chalk.green('none')) +
|
||||
' | versions: ' + info.versions
|
||||
)
|
||||
info.description && this.npm.output(info.description)
|
||||
if (info.repo || info.site) {
|
||||
info.site && this.npm.output(chalk.cyan(info.site))
|
||||
}
|
||||
|
||||
const warningSign = unicode ? ' ⚠️ ' : '!!'
|
||||
info.deprecated && this.npm.output(
|
||||
`\n${chalk.bold.red('DEPRECATED')}${
|
||||
warningSign
|
||||
} - ${info.deprecated}`
|
||||
manifest.deprecated && output.standard(
|
||||
`\n${chalk.redBright('DEPRECATED')}${unicode ? ' ⚠️ ' : '!!'} - ${manifest.deprecated}`
|
||||
)
|
||||
|
||||
if (info.keywords.length) {
|
||||
this.npm.output('')
|
||||
this.npm.output(`keywords: ${chalk.yellow(info.keywords.join(', '))}`)
|
||||
if (packu.keywords?.length) {
|
||||
output.standard(`\nkeywords: ${
|
||||
packu.keywords.map(k => chalk.cyan(k)).join(', ')
|
||||
}`)
|
||||
}
|
||||
|
||||
if (info.bins.length) {
|
||||
this.npm.output('')
|
||||
this.npm.output(`bin: ${chalk.yellow(info.bins.join(', '))}`)
|
||||
if (bins.length) {
|
||||
output.standard(`\nbin: ${chalk.cyan(bins.join(', '))}`)
|
||||
}
|
||||
|
||||
this.npm.output('')
|
||||
this.npm.output('dist')
|
||||
this.npm.output(`.tarball: ${info.tarball}`)
|
||||
this.npm.output(`.shasum: ${info.shasum}`)
|
||||
info.integrity && this.npm.output(`.integrity: ${info.integrity}`)
|
||||
info.unpackedSize && this.npm.output(`.unpackedSize: ${info.unpackedSize}`)
|
||||
output.standard('\ndist')
|
||||
output.standard(`.tarball: ${chalk.blue(manifest.dist.tarball)}`)
|
||||
output.standard(`.shasum: ${chalk.green(manifest.dist.shasum)}`)
|
||||
if (manifest.dist.integrity) {
|
||||
output.standard(`.integrity: ${chalk.green(manifest.dist.integrity)}`)
|
||||
}
|
||||
if (manifest.dist.unpackedSize) {
|
||||
output.standard(`.unpackedSize: ${chalk.blue(formatBytes(manifest.dist.unpackedSize, true))}`)
|
||||
}
|
||||
|
||||
const maxDeps = 24
|
||||
if (info.deps.length) {
|
||||
this.npm.output('')
|
||||
this.npm.output('dependencies:')
|
||||
this.npm.output(columns(info.deps.slice(0, maxDeps), { padding: 1 }))
|
||||
if (info.deps.length > maxDeps) {
|
||||
this.npm.output(`(...and ${info.deps.length - maxDeps} more.)`)
|
||||
if (deps.length) {
|
||||
const maxDeps = 24
|
||||
output.standard('\ndependencies:')
|
||||
output.standard(columns(deps.slice(0, maxDeps), { padding: 1 }))
|
||||
if (deps.length > maxDeps) {
|
||||
output.standard(chalk.dim(`(...and ${deps.length - maxDeps} more.)`))
|
||||
}
|
||||
}
|
||||
|
||||
if (info.maintainers && info.maintainers.length) {
|
||||
this.npm.output('')
|
||||
this.npm.output('maintainers:')
|
||||
info.maintainers.forEach((u) => this.npm.output(`- ${u}`))
|
||||
if (packu.maintainers?.length) {
|
||||
output.standard('\nmaintainers:')
|
||||
packu.maintainers.forEach(u =>
|
||||
output.standard(`- ${unparsePerson({
|
||||
name: chalk.blue(u.name),
|
||||
email: chalk.dim(u.email) })}`)
|
||||
)
|
||||
}
|
||||
|
||||
this.npm.output('')
|
||||
this.npm.output('dist-tags:')
|
||||
this.npm.output(columns(info.tags))
|
||||
output.standard('\ndist-tags:')
|
||||
output.standard(columns(Object.keys(packu['dist-tags']).map(t =>
|
||||
`${chalk.blue(t)}: ${packu['dist-tags'][t]}`
|
||||
)))
|
||||
|
||||
if (info.publisher || info.modified) {
|
||||
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 (info.modified) {
|
||||
publishInfo += ` ${info.modified}`
|
||||
if (packu.time) {
|
||||
publishInfo += ` ${chalk.cyan(relativeDate(packu.time[manifest.version]))}`
|
||||
}
|
||||
if (info.publisher) {
|
||||
publishInfo += ` by ${info.publisher}`
|
||||
if (publisher) {
|
||||
publishInfo += ` by ${publisher}`
|
||||
}
|
||||
this.npm.output('')
|
||||
this.npm.output(publishInfo)
|
||||
output.standard('')
|
||||
output.standard(publishInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = View
|
||||
|
||||
function cleanBlanks (obj) {
|
||||
|
||||
Vendored
+5
-3
@@ -1,16 +1,18 @@
|
||||
const { output } = require('proc-log')
|
||||
const getIdentity = require('../utils/get-identity.js')
|
||||
const BaseCommand = require('../base-cmd.js')
|
||||
|
||||
const BaseCommand = require('../base-command.js')
|
||||
class Whoami extends BaseCommand {
|
||||
static description = 'Display npm username'
|
||||
static name = 'whoami'
|
||||
static params = ['registry']
|
||||
|
||||
async exec (args) {
|
||||
async exec () {
|
||||
const username = await getIdentity(this.npm, { ...this.npm.flatOptions })
|
||||
this.npm.output(
|
||||
output.standard(
|
||||
this.npm.config.get('json') ? JSON.stringify(username) : username
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Whoami
|
||||
Vendored
+3
-2
@@ -1,7 +1,7 @@
|
||||
const BaseCommand = require('./base-cmd.js')
|
||||
|
||||
// The implementation of commands that are just "run a script"
|
||||
// restart, start, stop, test
|
||||
|
||||
const BaseCommand = require('./base-command.js')
|
||||
class LifecycleCmd extends BaseCommand {
|
||||
static usage = ['[-- <args>]']
|
||||
static isShellout = true
|
||||
@@ -16,4 +16,5 @@ class LifecycleCmd extends BaseCommand {
|
||||
return this.npm.exec('run-script', [this.constructor.name, ...args])
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = LifecycleCmd
|
||||
Vendored
+118
-215
@@ -1,19 +1,14 @@
|
||||
const { resolve, dirname, join } = require('path')
|
||||
const { resolve, dirname, join } = require('node:path')
|
||||
const Config = require('@npmcli/config')
|
||||
const which = require('which')
|
||||
const fs = require('fs/promises')
|
||||
|
||||
// Patch the global fs module here at the app level
|
||||
require('graceful-fs').gracefulify(require('fs'))
|
||||
|
||||
const fs = require('node:fs/promises')
|
||||
const { definitions, flatten, shorthands } = require('@npmcli/config/lib/definitions')
|
||||
const usage = require('./utils/npm-usage.js')
|
||||
const LogFile = require('./utils/log-file.js')
|
||||
const Timers = require('./utils/timers.js')
|
||||
const Display = require('./utils/display.js')
|
||||
const log = require('./utils/log-shim')
|
||||
const { log, time, output } = require('proc-log')
|
||||
const { redactLog: replaceInfo } = require('@npmcli/redact')
|
||||
const updateNotifier = require('./utils/update-notifier.js')
|
||||
const pkg = require('../package.json')
|
||||
const { deref } = require('./utils/cmd-list.js')
|
||||
|
||||
@@ -27,38 +22,25 @@ class Npm {
|
||||
if (!command) {
|
||||
throw Object.assign(new Error(`Unknown command ${c}`), {
|
||||
code: 'EUNKNOWNCOMMAND',
|
||||
command: c,
|
||||
})
|
||||
}
|
||||
return require(`./commands/${command}.js`)
|
||||
}
|
||||
|
||||
unrefPromises = []
|
||||
updateNotification = null
|
||||
loadErr = null
|
||||
argv = []
|
||||
|
||||
#command = null
|
||||
#runId = new Date().toISOString().replace(/[.:]/g, '_')
|
||||
#loadPromise = null
|
||||
#title = 'npm'
|
||||
#argvClean = []
|
||||
#npmRoot = null
|
||||
#warnedNonDashArg = false
|
||||
|
||||
#chalk = null
|
||||
#logChalk = null
|
||||
#noColorChalk = null
|
||||
|
||||
#outputBuffer = []
|
||||
#display = null
|
||||
#logFile = new LogFile()
|
||||
#display = new Display()
|
||||
#timers = new Timers({
|
||||
start: 'npm',
|
||||
listener: (name, ms) => {
|
||||
const args = ['timing', name, `Completed in ${ms}ms`]
|
||||
this.#logFile.log(...args)
|
||||
this.#display.log(...args)
|
||||
},
|
||||
})
|
||||
#timers = new Timers()
|
||||
|
||||
// all these options are only used by tests in order to make testing more
|
||||
// closely resemble real world usage. for now, npm has no programmatic API so
|
||||
@@ -72,7 +54,14 @@ class Npm {
|
||||
// allows tests created by tap inside this repo to not set the local
|
||||
// prefix to `npmRoot` since that is the first dir it would encounter when
|
||||
// doing implicit detection
|
||||
constructor ({ npmRoot = dirname(__dirname), argv = [], excludeNpmCwd = false } = {}) {
|
||||
constructor ({
|
||||
stdout = process.stdout,
|
||||
stderr = process.stderr,
|
||||
npmRoot = dirname(__dirname),
|
||||
argv = [],
|
||||
excludeNpmCwd = false,
|
||||
} = {}) {
|
||||
this.#display = new Display({ stdout, stderr })
|
||||
this.#npmRoot = npmRoot
|
||||
this.config = new Config({
|
||||
npmPath: this.#npmRoot,
|
||||
@@ -88,7 +77,8 @@ class Npm {
|
||||
return this.constructor.version
|
||||
}
|
||||
|
||||
setCmd (cmd) {
|
||||
// Call an npm command
|
||||
async exec (cmd, args = this.argv) {
|
||||
const Command = Npm.cmd(cmd)
|
||||
const command = new Command(this)
|
||||
|
||||
@@ -99,51 +89,11 @@ class Npm {
|
||||
process.env.npm_command = this.command
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
// Call an npm command
|
||||
// TODO: tests are currently the only time the second
|
||||
// parameter of args is used. When called via `lib/cli.js` the config is
|
||||
// loaded and this.argv is set to the remaining command line args. We should
|
||||
// consider testing the CLI the same way it is used and not allow args to be
|
||||
// passed in directly.
|
||||
async exec (cmd, args = this.argv) {
|
||||
const command = this.setCmd(cmd)
|
||||
|
||||
const timeEnd = this.time(`command:${cmd}`)
|
||||
|
||||
// this is async but we dont await it, since its ok if it doesnt
|
||||
// finish before the command finishes running. it uses command and argv
|
||||
// so it must be initiated here, after the command name is set
|
||||
// eslint-disable-next-line promise/catch-or-return
|
||||
updateNotifier(this).then((msg) => (this.updateNotification = msg))
|
||||
|
||||
// Options are prefixed by a hyphen-minus (-, \u2d).
|
||||
// Other dash-type chars look similar but are invalid.
|
||||
if (!this.#warnedNonDashArg) {
|
||||
const nonDashArgs = args.filter(a => /^[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]/.test(a))
|
||||
if (nonDashArgs.length) {
|
||||
this.#warnedNonDashArg = true
|
||||
log.error(
|
||||
'arg',
|
||||
'Argument starts with non-ascii dash, this is probably invalid:',
|
||||
nonDashArgs.join(', ')
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return command.cmdExec(args).finally(timeEnd)
|
||||
return time.start(`command:${cmd}`, () => command.cmdExec(args))
|
||||
}
|
||||
|
||||
async load () {
|
||||
if (!this.#loadPromise) {
|
||||
this.#loadPromise = this.time('npm:load', () => this.#load().catch((er) => {
|
||||
this.loadErr = er
|
||||
throw er
|
||||
}))
|
||||
}
|
||||
return this.#loadPromise
|
||||
return time.start('npm:load', () => this.#load())
|
||||
}
|
||||
|
||||
get loaded () {
|
||||
@@ -159,30 +109,44 @@ class Npm {
|
||||
this.#logFile.off()
|
||||
}
|
||||
|
||||
time (name, fn) {
|
||||
return this.#timers.time(name, fn)
|
||||
}
|
||||
|
||||
writeTimingFile () {
|
||||
this.#timers.writeFile({
|
||||
finish ({ showLogFileError } = {}) {
|
||||
this.#timers.finish({
|
||||
id: this.#runId,
|
||||
command: this.#argvClean,
|
||||
logfiles: this.logFiles,
|
||||
version: this.version,
|
||||
})
|
||||
|
||||
if (showLogFileError) {
|
||||
if (!this.silent) {
|
||||
// just a line break if not in silent mode
|
||||
output.error('')
|
||||
}
|
||||
|
||||
if (this.logFiles.length) {
|
||||
return log.error('', `A complete log of this run can be found in: ${this.logFiles}`)
|
||||
}
|
||||
|
||||
const logsMax = this.config.get('logs-max')
|
||||
if (logsMax <= 0) {
|
||||
// user specified no log file
|
||||
log.error('', `Log files were not written due to the config logs-max=${logsMax}`)
|
||||
} else {
|
||||
// could be an error writing to the directory
|
||||
log.error('',
|
||||
`Log files were not written due to an error writing to the directory: ${this.#logsDir}` +
|
||||
'\nYou can rerun the command with `--loglevel=verbose` to see the logs in your terminal'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get title () {
|
||||
return this.#title
|
||||
}
|
||||
|
||||
set title (t) {
|
||||
process.title = t
|
||||
this.#title = t
|
||||
}
|
||||
|
||||
async #load () {
|
||||
await this.time('npm:load:whichnode', async () => {
|
||||
await time.start('npm:load:whichnode', async () => {
|
||||
// TODO should we throw here?
|
||||
const node = await which(process.argv[0]).catch(() => {})
|
||||
if (node && node.toUpperCase() !== process.execPath.toUpperCase()) {
|
||||
@@ -192,46 +156,72 @@ class Npm {
|
||||
}
|
||||
})
|
||||
|
||||
await this.time('npm:load:configload', () => this.config.load())
|
||||
await time.start('npm:load:configload', () => this.config.load())
|
||||
|
||||
// get createSupportsColor from chalk directly if this lands
|
||||
// https://github.com/chalk/chalk/pull/600
|
||||
const [{ Chalk }, { createSupportsColor }] = await Promise.all([
|
||||
import('chalk'),
|
||||
import('supports-color'),
|
||||
])
|
||||
this.#noColorChalk = new Chalk({ level: 0 })
|
||||
// we get the chalk level based on a null stream meaning chalk will only use
|
||||
// what it knows about the environment to get color support since we already
|
||||
// determined in our definitions that we want to show colors.
|
||||
const level = Math.max(createSupportsColor(null).level, 1)
|
||||
this.#chalk = this.color ? new Chalk({ level }) : this.#noColorChalk
|
||||
this.#logChalk = this.logColor ? new Chalk({ level }) : this.#noColorChalk
|
||||
// npm --versions
|
||||
if (this.config.get('versions', 'cli')) {
|
||||
this.argv = ['version']
|
||||
this.config.set('usage', false, 'cli')
|
||||
} else {
|
||||
this.argv = [...this.config.parsedArgv.remain]
|
||||
}
|
||||
|
||||
// Remove first argv since that is our command as typed
|
||||
// Note that this might not be the actual name of the command
|
||||
// due to aliases, etc. But we use the raw form of it later
|
||||
// in user output so it must be preserved as is.
|
||||
const commandArg = this.argv.shift()
|
||||
|
||||
// This is the actual name of the command that will be run or
|
||||
// undefined if deref could not find a match
|
||||
const command = deref(commandArg)
|
||||
|
||||
await this.#display.load({
|
||||
command,
|
||||
loglevel: this.config.get('loglevel'),
|
||||
stdoutColor: this.color,
|
||||
stderrColor: this.logColor,
|
||||
timing: this.config.get('timing'),
|
||||
unicode: this.config.get('unicode'),
|
||||
progress: this.flatOptions.progress,
|
||||
json: this.config.get('json'),
|
||||
heading: this.config.get('heading'),
|
||||
})
|
||||
process.env.COLOR = this.color ? '1' : '0'
|
||||
|
||||
// npm -v
|
||||
// return from here early so we dont create any caches/logfiles/timers etc
|
||||
if (this.config.get('version', 'cli')) {
|
||||
output.standard(this.version)
|
||||
return { exec: false }
|
||||
}
|
||||
|
||||
// mkdir this separately since the logs dir can be set to
|
||||
// a different location. if this fails, then we don't have
|
||||
// a cache dir, but we don't want to fail immediately since
|
||||
// the command might not need a cache dir (like `npm --version`)
|
||||
await this.time('npm:load:mkdirpcache', () =>
|
||||
await time.start('npm:load:mkdirpcache', () =>
|
||||
fs.mkdir(this.cache, { recursive: true })
|
||||
.catch((e) => log.verbose('cache', `could not create cache: ${e}`)))
|
||||
|
||||
// it's ok if this fails. user might have specified an invalid dir
|
||||
// which we will tell them about at the end
|
||||
if (this.config.get('logs-max') > 0) {
|
||||
await this.time('npm:load:mkdirplogs', () =>
|
||||
fs.mkdir(this.logsDir, { recursive: true })
|
||||
await time.start('npm:load:mkdirplogs', () =>
|
||||
fs.mkdir(this.#logsDir, { recursive: true })
|
||||
.catch((e) => log.verbose('logfile', `could not create logs-dir: ${e}`)))
|
||||
}
|
||||
|
||||
// note: this MUST be shorter than the actual argv length, because it
|
||||
// uses the same memory, so node will truncate it if it's too long.
|
||||
this.time('npm:load:setTitle', () => {
|
||||
// We time this because setting process.title is slow sometimes but we
|
||||
// have to do it for security reasons. But still helpful to know how slow it is.
|
||||
time.start('npm:load:setTitle', () => {
|
||||
const { parsedArgv: { cooked, remain } } = this.config
|
||||
this.argv = remain
|
||||
// Secrets are mostly in configs, so title is set using only the positional args
|
||||
// to keep those from being leaked.
|
||||
this.title = ['npm'].concat(replaceInfo(remain)).join(' ').trim()
|
||||
// to keep those from being leaked. We still do a best effort replaceInfo.
|
||||
this.#title = ['npm'].concat(replaceInfo(remain)).join(' ').trim()
|
||||
process.title = this.#title
|
||||
// The cooked argv is also logged separately for debugging purposes. It is
|
||||
// cleaned as a best effort by replacing known secrets like basic auth
|
||||
// password and strings that look like npm tokens. XXX: for this to be
|
||||
@@ -242,45 +232,32 @@ class Npm {
|
||||
log.verbose('argv', this.#argvClean.map(JSON.stringify).join(' '))
|
||||
})
|
||||
|
||||
this.time('npm:load:display', () => {
|
||||
this.#display.load({
|
||||
// Use logColor since that is based on stderr
|
||||
color: this.logColor,
|
||||
chalk: this.logChalk,
|
||||
progress: this.flatOptions.progress,
|
||||
silent: this.silent,
|
||||
timing: this.config.get('timing'),
|
||||
loglevel: this.config.get('loglevel'),
|
||||
unicode: this.config.get('unicode'),
|
||||
heading: this.config.get('heading'),
|
||||
})
|
||||
process.env.COLOR = this.color ? '1' : '0'
|
||||
// logFile.load returns a promise that resolves when old logs are done being cleaned.
|
||||
// We save this promise to an array so that we can await it in tests to ensure more
|
||||
// deterministic logging behavior. The process will also hang open if this were to
|
||||
// take a long time to resolve, but that is why process.exit is called explicitly
|
||||
// in the exit-handler.
|
||||
this.unrefPromises.push(this.#logFile.load({
|
||||
path: this.logPath,
|
||||
logsMax: this.config.get('logs-max'),
|
||||
timing: this.config.get('timing'),
|
||||
}))
|
||||
|
||||
this.#timers.load({
|
||||
path: this.logPath,
|
||||
timing: this.config.get('timing'),
|
||||
})
|
||||
|
||||
this.time('npm:load:logFile', () => {
|
||||
this.#logFile.load({
|
||||
path: this.logPath,
|
||||
logsMax: this.config.get('logs-max'),
|
||||
})
|
||||
log.verbose('logfile', this.#logFile.files[0] || 'no logfile created')
|
||||
})
|
||||
|
||||
this.time('npm:load:timers', () =>
|
||||
this.#timers.load({
|
||||
path: this.config.get('timing') ? this.logPath : null,
|
||||
})
|
||||
)
|
||||
|
||||
this.time('npm:load:configScope', () => {
|
||||
const configScope = this.config.get('scope')
|
||||
if (configScope && !/^@/.test(configScope)) {
|
||||
this.config.set('scope', `@${configScope}`, this.config.find('scope'))
|
||||
}
|
||||
})
|
||||
const configScope = this.config.get('scope')
|
||||
if (configScope && !/^@/.test(configScope)) {
|
||||
this.config.set('scope', `@${configScope}`, this.config.find('scope'))
|
||||
}
|
||||
|
||||
if (this.config.get('force')) {
|
||||
log.warn('using --force', 'Recommended protections disabled.')
|
||||
}
|
||||
|
||||
return { exec: true, command: commandArg, args: this.argv }
|
||||
}
|
||||
|
||||
get isShellout () {
|
||||
@@ -313,15 +290,15 @@ class Npm {
|
||||
}
|
||||
|
||||
get noColorChalk () {
|
||||
return this.#noColorChalk
|
||||
return this.#display.chalk.noColor
|
||||
}
|
||||
|
||||
get chalk () {
|
||||
return this.#chalk
|
||||
return this.#display.chalk.stdout
|
||||
}
|
||||
|
||||
get logChalk () {
|
||||
return this.#logChalk
|
||||
return this.#display.chalk.stderr
|
||||
}
|
||||
|
||||
get global () {
|
||||
@@ -336,14 +313,6 @@ class Npm {
|
||||
return 2
|
||||
}
|
||||
|
||||
get unfinishedTimers () {
|
||||
return this.#timers.unfinished
|
||||
}
|
||||
|
||||
get finishedTimers () {
|
||||
return this.#timers.finished
|
||||
}
|
||||
|
||||
get started () {
|
||||
return this.#timers.started
|
||||
}
|
||||
@@ -352,16 +321,12 @@ class Npm {
|
||||
return this.#logFile.files
|
||||
}
|
||||
|
||||
get logsDir () {
|
||||
get #logsDir () {
|
||||
return this.config.get('logs-dir') || join(this.cache, '_logs')
|
||||
}
|
||||
|
||||
get logPath () {
|
||||
return resolve(this.logsDir, `${this.#runId}-`)
|
||||
}
|
||||
|
||||
get timingFile () {
|
||||
return this.#timers.file
|
||||
return resolve(this.#logsDir, `${this.#runId}-`)
|
||||
}
|
||||
|
||||
get npmRoot () {
|
||||
@@ -372,26 +337,14 @@ class Npm {
|
||||
return this.config.get('cache')
|
||||
}
|
||||
|
||||
set cache (r) {
|
||||
this.config.set('cache', r)
|
||||
}
|
||||
|
||||
get globalPrefix () {
|
||||
return this.config.globalPrefix
|
||||
}
|
||||
|
||||
set globalPrefix (r) {
|
||||
this.config.globalPrefix = r
|
||||
}
|
||||
|
||||
get localPrefix () {
|
||||
return this.config.localPrefix
|
||||
}
|
||||
|
||||
set localPrefix (r) {
|
||||
this.config.localPrefix = r
|
||||
}
|
||||
|
||||
get localPackage () {
|
||||
return this.config.localPackage
|
||||
}
|
||||
@@ -427,59 +380,9 @@ class Npm {
|
||||
return this.global ? this.globalPrefix : this.localPrefix
|
||||
}
|
||||
|
||||
set prefix (r) {
|
||||
const k = this.global ? 'globalPrefix' : 'localPrefix'
|
||||
this[k] = r
|
||||
}
|
||||
|
||||
get usage () {
|
||||
return usage(this)
|
||||
}
|
||||
|
||||
// output to stdout in a progress bar compatible way
|
||||
output (...msg) {
|
||||
log.clearProgress()
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(...msg.map(Display.clean))
|
||||
log.showProgress()
|
||||
}
|
||||
|
||||
outputBuffer (item) {
|
||||
this.#outputBuffer.push(item)
|
||||
}
|
||||
|
||||
flushOutput (jsonError) {
|
||||
if (!jsonError && !this.#outputBuffer.length) {
|
||||
return
|
||||
}
|
||||
|
||||
if (this.config.get('json')) {
|
||||
const jsonOutput = this.#outputBuffer.reduce((acc, item) => {
|
||||
if (typeof item === 'string') {
|
||||
// try to parse it as json in case its a string
|
||||
try {
|
||||
item = JSON.parse(item)
|
||||
} catch {
|
||||
return acc
|
||||
}
|
||||
}
|
||||
return { ...acc, ...item }
|
||||
}, {})
|
||||
this.output(JSON.stringify({ ...jsonOutput, ...jsonError }, null, 2))
|
||||
} else {
|
||||
for (const item of this.#outputBuffer) {
|
||||
this.output(item)
|
||||
}
|
||||
}
|
||||
|
||||
this.#outputBuffer.length = 0
|
||||
}
|
||||
|
||||
outputError (...msg) {
|
||||
log.clearProgress()
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(...msg.map(Display.clean))
|
||||
log.showProgress()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Npm
|
||||
Vendored
+5
-6
@@ -1,12 +1,9 @@
|
||||
// Base command for opening urls from a package manifest (bugs, docs, repo)
|
||||
|
||||
const pacote = require('pacote')
|
||||
const hostedGitInfo = require('hosted-git-info')
|
||||
|
||||
const openUrl = require('./utils/open-url.js')
|
||||
const log = require('./utils/log-shim')
|
||||
const { log } = require('proc-log')
|
||||
const BaseCommand = require('./base-cmd.js')
|
||||
|
||||
const BaseCommand = require('./base-command.js')
|
||||
// Base command for opening urls from a package manifest (bugs, docs, repo)
|
||||
class PackageUrlCommand extends BaseCommand {
|
||||
static params = [
|
||||
'browser',
|
||||
@@ -52,6 +49,7 @@ class PackageUrlCommand extends BaseCommand {
|
||||
// repository (if a string) or repository.url (if an object) returns null
|
||||
// if it's not a valid repo, or not a known hosted repo
|
||||
hostedFromMani (mani) {
|
||||
const hostedGitInfo = require('hosted-git-info')
|
||||
const r = mani.repository
|
||||
const rurl = !r ? null
|
||||
: typeof r === 'string' ? r
|
||||
@@ -62,4 +60,5 @@ class PackageUrlCommand extends BaseCommand {
|
||||
return (rurl && hostedGitInfo.fromUrl(rurl.replace(/^git\+/, ''))) || null
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PackageUrlCommand
|
||||
Vendored
+3
-3
@@ -1,4 +1,4 @@
|
||||
const log = require('./log-shim')
|
||||
const { log, output } = require('proc-log')
|
||||
const { redactLog: replaceInfo } = require('@npmcli/redact')
|
||||
|
||||
// print an error or just nothing if the audit report has an error
|
||||
@@ -22,7 +22,7 @@ const auditError = (npm, report) => {
|
||||
const { body: errBody } = error
|
||||
const body = Buffer.isBuffer(errBody) ? errBody.toString() : errBody
|
||||
if (npm.flatOptions.json) {
|
||||
npm.output(JSON.stringify({
|
||||
output.standard(JSON.stringify({
|
||||
message: error.message,
|
||||
method: error.method,
|
||||
uri: replaceInfo(error.uri),
|
||||
@@ -31,7 +31,7 @@ const auditError = (npm, report) => {
|
||||
body,
|
||||
}, null, 2))
|
||||
} else {
|
||||
npm.output(body)
|
||||
output.standard(body)
|
||||
}
|
||||
|
||||
throw 'audit endpoint returned an error'
|
||||
|
||||
Vendored
+2
-2
@@ -1,5 +1,5 @@
|
||||
const profile = require('npm-profile')
|
||||
const log = require('../utils/log-shim')
|
||||
const { log } = require('proc-log')
|
||||
const openUrlPrompt = require('../utils/open-url-prompt.js')
|
||||
const read = require('../utils/read-user-info.js')
|
||||
const otplease = require('../utils/otplease.js')
|
||||
@@ -36,7 +36,7 @@ const adduser = async (npm, { creds, ...opts }) => {
|
||||
// password, it's effectively a login, and if that account has otp you'll
|
||||
// be prompted for it.
|
||||
res = await otplease(npm, opts, (reqOpts) =>
|
||||
profile.adduserCouch(username, email, password, opts)
|
||||
profile.adduserCouch(username, email, password, reqOpts)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Vendored
+8
-9
@@ -8,7 +8,7 @@ const didYouMean = async (path, scmd) => {
|
||||
let best = []
|
||||
for (const str of close) {
|
||||
const cmd = Npm.cmd(str)
|
||||
best.push(` npm ${str} # ${cmd.description}`)
|
||||
best.push(` npm ${str} # ${cmd.description}`)
|
||||
}
|
||||
// We would already be suggesting this in `npm x` so omit them here
|
||||
const runScripts = ['stop', 'start', 'test', 'restart']
|
||||
@@ -17,13 +17,13 @@ const didYouMean = async (path, scmd) => {
|
||||
best = best.concat(
|
||||
Object.keys(scripts || {})
|
||||
.filter(cmd => distance(scmd, cmd) < scmd.length * 0.4 && !runScripts.includes(cmd))
|
||||
.map(str => ` npm run ${str} # run the "${str}" package script`),
|
||||
.map(str => ` npm run ${str} # run the "${str}" package script`),
|
||||
Object.keys(bin || {})
|
||||
.filter(cmd => distance(scmd, cmd) < scmd.length * 0.4)
|
||||
/* eslint-disable-next-line max-len */
|
||||
.map(str => ` npm exec ${str} # run the "${str}" command from either this or a remote npm package`)
|
||||
.map(str => ` npm exec ${str} # run the "${str}" command from either this or a remote npm package`)
|
||||
)
|
||||
} catch (_) {
|
||||
} catch {
|
||||
// gracefully ignore not being in a folder w/ a package.json
|
||||
}
|
||||
|
||||
@@ -31,10 +31,9 @@ const didYouMean = async (path, scmd) => {
|
||||
return ''
|
||||
}
|
||||
|
||||
const suggestion =
|
||||
best.length === 1
|
||||
? `\n\nDid you mean this?\n${best[0]}`
|
||||
: `\n\nDid you mean one of these?\n${best.slice(0, 3).join('\n')}`
|
||||
return suggestion
|
||||
return best.length === 1
|
||||
? `\n\nDid you mean this?\n${best[0]}`
|
||||
: `\n\nDid you mean one of these?\n${best.slice(0, 3).join('\n')}`
|
||||
}
|
||||
|
||||
module.exports = didYouMean
|
||||
Vendored
+445
-170
@@ -1,215 +1,490 @@
|
||||
const { inspect } = require('util')
|
||||
const npmlog = require('npmlog')
|
||||
const log = require('./log-shim.js')
|
||||
const { log, output, input, META } = require('proc-log')
|
||||
const { explain } = require('./explain-eresolve.js')
|
||||
const { formatWithOptions } = require('./format')
|
||||
|
||||
const originalCustomInspect = Symbol('npm.display.original.util.inspect.custom')
|
||||
// This is the general approach to color:
|
||||
// Eventually this will be exposed somewhere we can refer to these by name.
|
||||
// Foreground colors only. Never set the background color.
|
||||
/*
|
||||
* Black # (Don't use)
|
||||
* Red # Danger
|
||||
* Green # Success
|
||||
* Yellow # Warning
|
||||
* Blue # Accent
|
||||
* Magenta # Done
|
||||
* Cyan # Emphasis
|
||||
* White # (Don't use)
|
||||
*/
|
||||
|
||||
// These are most assuredly not a mistake
|
||||
// https://eslint.org/docs/latest/rules/no-control-regex
|
||||
/* eslint-disable no-control-regex */
|
||||
// \x00 through \x1f, \x7f through \x9f, not including \x09 \x0a \x0b \x0d
|
||||
const hasC01 = /[\x00-\x08\x0c\x0e-\x1f\x7f-\x9f]/
|
||||
// Allows everything up to '[38;5;255m' in 8 bit notation
|
||||
const allowedSGR = /^\[[0-9;]{0,8}m/
|
||||
// '[38;5;255m'.length
|
||||
const sgrMaxLen = 10
|
||||
// Translates log levels to chalk colors
|
||||
const COLOR_PALETTE = ({ chalk: c }) => ({
|
||||
heading: c.bold,
|
||||
title: c.blueBright,
|
||||
timing: c.magentaBright,
|
||||
// loglevels
|
||||
error: c.red,
|
||||
warn: c.yellow,
|
||||
notice: c.cyanBright,
|
||||
http: c.green,
|
||||
info: c.cyan,
|
||||
verbose: c.blue,
|
||||
silly: c.blue.dim,
|
||||
})
|
||||
|
||||
// Strips all ANSI C0 and C1 control characters (except for SGR up to 8 bit)
|
||||
function stripC01 (str) {
|
||||
if (!hasC01.test(str)) {
|
||||
return str
|
||||
}
|
||||
let result = ''
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str[i]
|
||||
const code = char.charCodeAt(0)
|
||||
if (!hasC01.test(char)) {
|
||||
// Most characters are in this set so continue early if we can
|
||||
result = `${result}${char}`
|
||||
} else if (code === 27 && allowedSGR.test(str.slice(i + 1, i + sgrMaxLen + 1))) {
|
||||
// \x1b with allowed SGR
|
||||
result = `${result}\x1b`
|
||||
} else if (code <= 31) {
|
||||
// escape all other C0 control characters besides \x7f
|
||||
result = `${result}^${String.fromCharCode(code + 64)}`
|
||||
} else {
|
||||
// hasC01 ensures this is now a C1 control character or \x7f
|
||||
result = `${result}^${String.fromCharCode(code - 64)}`
|
||||
const LEVEL_OPTIONS = {
|
||||
silent: {
|
||||
index: 0,
|
||||
},
|
||||
error: {
|
||||
index: 1,
|
||||
},
|
||||
warn: {
|
||||
index: 2,
|
||||
},
|
||||
notice: {
|
||||
index: 3,
|
||||
},
|
||||
http: {
|
||||
index: 4,
|
||||
},
|
||||
info: {
|
||||
index: 5,
|
||||
},
|
||||
verbose: {
|
||||
index: 6,
|
||||
},
|
||||
silly: {
|
||||
index: 7,
|
||||
},
|
||||
}
|
||||
|
||||
const LEVEL_METHODS = {
|
||||
...LEVEL_OPTIONS,
|
||||
[log.KEYS.timing]: {
|
||||
show: ({ timing, index }) => !!timing && index !== 0,
|
||||
},
|
||||
}
|
||||
|
||||
const tryJsonParse = (value) => {
|
||||
if (typeof value === 'string') {
|
||||
try {
|
||||
return JSON.parse(value)
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
return result
|
||||
return value
|
||||
}
|
||||
|
||||
const setBlocking = (stream) => {
|
||||
// Copied from https://github.com/yargs/set-blocking
|
||||
// https://raw.githubusercontent.com/yargs/set-blocking/master/LICENSE.txt
|
||||
/* istanbul ignore next - we trust that this works */
|
||||
if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') {
|
||||
stream._handle.setBlocking(true)
|
||||
}
|
||||
return stream
|
||||
}
|
||||
|
||||
const withMeta = (handler) => (level, ...args) => {
|
||||
let meta = {}
|
||||
const last = args.at(-1)
|
||||
if (last && typeof last === 'object' && Object.hasOwn(last, META)) {
|
||||
meta = args.pop()
|
||||
}
|
||||
return handler(level, meta, ...args)
|
||||
}
|
||||
|
||||
class Display {
|
||||
#chalk = null
|
||||
|
||||
constructor () {
|
||||
// pause by default until config is loaded
|
||||
this.on()
|
||||
log.pause()
|
||||
#logState = {
|
||||
buffering: true,
|
||||
buffer: [],
|
||||
}
|
||||
|
||||
static clean (output) {
|
||||
if (typeof output === 'string') {
|
||||
// Strings are cleaned inline
|
||||
return stripC01(output)
|
||||
}
|
||||
if (!output || typeof output !== 'object') {
|
||||
// Numbers, booleans, null all end up here and don't need cleaning
|
||||
return output
|
||||
}
|
||||
// output && typeof output === 'object'
|
||||
// We can't use hasOwn et al for detecting the original but we can use it
|
||||
// for detecting the properties we set via defineProperty
|
||||
if (
|
||||
output[inspect.custom] &&
|
||||
(!Object.hasOwn(output, originalCustomInspect))
|
||||
) {
|
||||
// Save the old one if we didn't already do it.
|
||||
Object.defineProperty(output, originalCustomInspect, {
|
||||
value: output[inspect.custom],
|
||||
writable: true,
|
||||
})
|
||||
}
|
||||
if (!Object.hasOwn(output, originalCustomInspect)) {
|
||||
// Put a dummy one in for when we run multiple times on the same object
|
||||
Object.defineProperty(output, originalCustomInspect, {
|
||||
value: function () {
|
||||
return this
|
||||
},
|
||||
writable: true,
|
||||
})
|
||||
}
|
||||
// Set the custom inspect to our own function
|
||||
Object.defineProperty(output, inspect.custom, {
|
||||
value: function () {
|
||||
const toClean = this[originalCustomInspect]()
|
||||
// Custom inspect can return things other than objects, check type again
|
||||
if (typeof toClean === 'string') {
|
||||
// Strings are cleaned inline
|
||||
return stripC01(toClean)
|
||||
}
|
||||
if (!toClean || typeof toClean !== 'object') {
|
||||
// Numbers, booleans, null all end up here and don't need cleaning
|
||||
return toClean
|
||||
}
|
||||
return stripC01(inspect(toClean, { customInspect: false }))
|
||||
},
|
||||
writable: true,
|
||||
})
|
||||
return output
|
||||
#outputState = {
|
||||
buffering: true,
|
||||
buffer: [],
|
||||
}
|
||||
|
||||
on () {
|
||||
// colors
|
||||
#noColorChalk
|
||||
#stdoutChalk
|
||||
#stdoutColor
|
||||
#stderrChalk
|
||||
#stderrColor
|
||||
#logColors
|
||||
|
||||
// progress
|
||||
#progress
|
||||
|
||||
// options
|
||||
#command
|
||||
#levelIndex
|
||||
#timing
|
||||
#json
|
||||
#heading
|
||||
#silent
|
||||
|
||||
// display streams
|
||||
#stdout
|
||||
#stderr
|
||||
|
||||
constructor ({ stdout, stderr }) {
|
||||
this.#stdout = setBlocking(stdout)
|
||||
this.#stderr = setBlocking(stderr)
|
||||
|
||||
// Handlers are set immediately so they can buffer all events
|
||||
process.on('log', this.#logHandler)
|
||||
process.on('output', this.#outputHandler)
|
||||
process.on('input', this.#inputHandler)
|
||||
this.#progress = new Progress({ stream: stderr })
|
||||
}
|
||||
|
||||
off () {
|
||||
process.off('log', this.#logHandler)
|
||||
// Unbalanced calls to enable/disable progress
|
||||
// will leave change listeners on the tracker
|
||||
// This pretty much only happens in tests but
|
||||
// this removes the event emitter listener warnings
|
||||
log.tracker.removeAllListeners()
|
||||
this.#logState.buffer.length = 0
|
||||
process.off('output', this.#outputHandler)
|
||||
this.#outputState.buffer.length = 0
|
||||
process.off('input', this.#inputHandler)
|
||||
this.#progress.off()
|
||||
}
|
||||
|
||||
load (config) {
|
||||
const {
|
||||
color,
|
||||
chalk,
|
||||
timing,
|
||||
loglevel,
|
||||
unicode,
|
||||
progress,
|
||||
silent,
|
||||
heading = 'npm',
|
||||
} = config
|
||||
|
||||
this.#chalk = chalk
|
||||
|
||||
// npmlog is still going away someday, so this is a hack to dynamically
|
||||
// set the loglevel of timing based on the timing flag, instead of making
|
||||
// a breaking change to npmlog. The result is that timing logs are never
|
||||
// shown except when the --timing flag is set. We also need to change
|
||||
// the index of the silly level since otherwise it is set to -Infinity
|
||||
// and we can't go any lower than that. silent is still set to Infinify
|
||||
// because we DO want silent to hide timing levels. This allows for the
|
||||
// special case of getting timing information while hiding all CLI output
|
||||
// in order to get perf information that might be affected by writing to
|
||||
// a terminal. XXX(npmlog): this will be removed along with npmlog
|
||||
log.levels.silly = -10000
|
||||
log.levels.timing = log.levels[loglevel] + (timing ? 1 : -1)
|
||||
|
||||
log.level = loglevel
|
||||
log.heading = heading
|
||||
|
||||
if (color) {
|
||||
log.enableColor()
|
||||
} else {
|
||||
log.disableColor()
|
||||
get chalk () {
|
||||
return {
|
||||
noColor: this.#noColorChalk,
|
||||
stdout: this.#stdoutChalk,
|
||||
stderr: this.#stderrChalk,
|
||||
}
|
||||
}
|
||||
|
||||
if (unicode) {
|
||||
log.enableUnicode()
|
||||
} else {
|
||||
log.disableUnicode()
|
||||
}
|
||||
async load ({
|
||||
command,
|
||||
heading,
|
||||
json,
|
||||
loglevel,
|
||||
progress,
|
||||
stderrColor,
|
||||
stdoutColor,
|
||||
timing,
|
||||
unicode,
|
||||
}) {
|
||||
// get createSupportsColor from chalk directly if this lands
|
||||
// https://github.com/chalk/chalk/pull/600
|
||||
const [{ Chalk }, { createSupportsColor }] = await Promise.all([
|
||||
import('chalk'),
|
||||
import('supports-color'),
|
||||
])
|
||||
// we get the chalk level based on a null stream meaning chalk will only use
|
||||
// what it knows about the environment to get color support since we already
|
||||
// determined in our definitions that we want to show colors.
|
||||
const level = Math.max(createSupportsColor(null).level, 1)
|
||||
this.#noColorChalk = new Chalk({ level: 0 })
|
||||
this.#stdoutColor = stdoutColor
|
||||
this.#stdoutChalk = stdoutColor ? new Chalk({ level }) : this.#noColorChalk
|
||||
this.#stderrColor = stderrColor
|
||||
this.#stderrChalk = stderrColor ? new Chalk({ level }) : this.#noColorChalk
|
||||
this.#logColors = COLOR_PALETTE({ chalk: this.#stderrChalk })
|
||||
|
||||
// if it's silent, don't show progress
|
||||
if (progress && !silent) {
|
||||
log.enableProgress()
|
||||
} else {
|
||||
log.disableProgress()
|
||||
}
|
||||
this.#command = command
|
||||
this.#levelIndex = LEVEL_OPTIONS[loglevel].index
|
||||
this.#timing = timing
|
||||
this.#json = json
|
||||
this.#heading = heading
|
||||
this.#silent = this.#levelIndex <= 0
|
||||
|
||||
// Resume displaying logs now that we have config
|
||||
// Emit resume event on the logs which will flush output
|
||||
log.resume()
|
||||
output.flush()
|
||||
this.#progress.load({
|
||||
unicode,
|
||||
enabled: !!progress && !this.#silent,
|
||||
})
|
||||
}
|
||||
|
||||
log (...args) {
|
||||
this.#logHandler(...args)
|
||||
// STREAM WRITES
|
||||
|
||||
// Write formatted and (non-)colorized output to streams
|
||||
#write (stream, options, ...args) {
|
||||
const colors = stream === this.#stdout ? this.#stdoutColor : this.#stderrColor
|
||||
const value = formatWithOptions({ colors, ...options }, ...args)
|
||||
this.#progress.write(() => stream.write(value))
|
||||
}
|
||||
|
||||
#logHandler = (level, ...args) => {
|
||||
// HANDLERS
|
||||
|
||||
// Arrow function assigned to a private class field so it can be passed
|
||||
// directly as a listener and still reference "this"
|
||||
#logHandler = withMeta((level, meta, ...args) => {
|
||||
switch (level) {
|
||||
case log.KEYS.resume:
|
||||
this.#logState.buffering = false
|
||||
this.#logState.buffer.forEach((item) => this.#tryWriteLog(...item))
|
||||
this.#logState.buffer.length = 0
|
||||
break
|
||||
|
||||
case log.KEYS.pause:
|
||||
this.#logState.buffering = true
|
||||
break
|
||||
|
||||
default:
|
||||
if (this.#logState.buffering) {
|
||||
this.#logState.buffer.push([level, meta, ...args])
|
||||
} else {
|
||||
this.#tryWriteLog(level, meta, ...args)
|
||||
}
|
||||
break
|
||||
}
|
||||
})
|
||||
|
||||
// Arrow function assigned to a private class field so it can be passed
|
||||
// directly as a listener and still reference "this"
|
||||
#outputHandler = withMeta((level, meta, ...args) => {
|
||||
switch (level) {
|
||||
case output.KEYS.flush:
|
||||
this.#outputState.buffering = false
|
||||
if (meta.jsonError && this.#json) {
|
||||
const json = {}
|
||||
for (const item of this.#outputState.buffer) {
|
||||
// index 2 skips the level and meta
|
||||
Object.assign(json, tryJsonParse(item[2]))
|
||||
}
|
||||
this.#writeOutput(
|
||||
output.KEYS.standard,
|
||||
meta,
|
||||
JSON.stringify({ ...json, error: meta.jsonError }, null, 2)
|
||||
)
|
||||
} else {
|
||||
this.#outputState.buffer.forEach((item) => this.#writeOutput(...item))
|
||||
}
|
||||
this.#outputState.buffer.length = 0
|
||||
break
|
||||
|
||||
case output.KEYS.buffer:
|
||||
this.#outputState.buffer.push([output.KEYS.standard, meta, ...args])
|
||||
break
|
||||
|
||||
default:
|
||||
if (this.#outputState.buffering) {
|
||||
this.#outputState.buffer.push([level, meta, ...args])
|
||||
} else {
|
||||
// HACK: Check if the argument looks like a run-script banner. This can be
|
||||
// replaced with proc-log.META in @npmcli/run-script
|
||||
if (typeof args[0] === 'string' && args[0].startsWith('\n> ') && args[0].endsWith('\n')) {
|
||||
if (this.#silent || ['exec', 'explore'].includes(this.#command)) {
|
||||
// Silent mode and some specific commands always hide run script banners
|
||||
break
|
||||
} else if (this.#json) {
|
||||
// In json mode, change output to stderr since we dont want to break json
|
||||
// parsing on stdout if the user is piping to jq or something.
|
||||
// XXX: in a future (breaking?) change it might make sense for run-script to
|
||||
// always output these banners with proc-log.output.error if we think they
|
||||
// align closer with "logging" instead of "output"
|
||||
level = output.KEYS.error
|
||||
}
|
||||
}
|
||||
this.#writeOutput(level, meta, ...args)
|
||||
}
|
||||
break
|
||||
}
|
||||
})
|
||||
|
||||
#inputHandler = withMeta((level, meta, ...args) => {
|
||||
switch (level) {
|
||||
case input.KEYS.start:
|
||||
log.pause()
|
||||
this.#outputState.buffering = true
|
||||
this.#progress.off()
|
||||
break
|
||||
|
||||
case input.KEYS.end:
|
||||
log.resume()
|
||||
output.flush()
|
||||
this.#progress.resume()
|
||||
break
|
||||
|
||||
case input.KEYS.read: {
|
||||
// The convention when calling input.read is to pass in a single fn that returns
|
||||
// the promise to await. resolve and reject are provided by proc-log
|
||||
const [res, rej, p] = args
|
||||
return input.start(() => p()
|
||||
.then(res)
|
||||
.catch(rej)
|
||||
// Any call to procLog.input.read will render a prompt to the user, so we always
|
||||
// add a single newline of output to stdout to move the cursor to the next line
|
||||
.finally(() => output.standard('')))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// OUTPUT
|
||||
|
||||
#writeOutput (level, meta, ...args) {
|
||||
switch (level) {
|
||||
case output.KEYS.standard:
|
||||
this.#write(this.#stdout, {}, ...args)
|
||||
break
|
||||
|
||||
case output.KEYS.error:
|
||||
this.#write(this.#stderr, {}, ...args)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// LOGS
|
||||
|
||||
#tryWriteLog (level, meta, ...args) {
|
||||
try {
|
||||
this.#log(level, ...args)
|
||||
// Also (and this is a really inexcusable kludge), we patch the
|
||||
// log.warn() method so that when we see a peerDep override
|
||||
// explanation from Arborist, we can replace the object with a
|
||||
// highly abbreviated explanation of what's being overridden.
|
||||
// TODO: this could probably be moved to arborist now that display is refactored
|
||||
const [heading, message, expl] = args
|
||||
if (level === log.KEYS.warn && heading === 'ERESOLVE' && expl && typeof expl === 'object') {
|
||||
this.#writeLog(level, meta, heading, message)
|
||||
this.#writeLog(level, meta, '', explain(expl, this.#stderrChalk, 2))
|
||||
return
|
||||
}
|
||||
this.#writeLog(level, meta, ...args)
|
||||
} catch (ex) {
|
||||
try {
|
||||
// if it crashed once, it might again!
|
||||
this.#npmlog('verbose', `attempt to log ${inspect(args)} crashed`, ex)
|
||||
this.#writeLog(log.KEYS.verbose, meta, '', `attempt to log crashed`, ...args, ex)
|
||||
} catch (ex2) {
|
||||
// This happens if the object has an inspect method that crashes so just console.error
|
||||
// with the errors but don't do anything else that might error again.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`attempt to log ${inspect(args)} crashed`, ex, ex2)
|
||||
console.error(`attempt to log crashed`, ex, ex2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#log (...args) {
|
||||
return this.#eresolveWarn(...args) || this.#npmlog(...args)
|
||||
}
|
||||
#writeLog (level, meta, ...args) {
|
||||
const levelOpts = LEVEL_METHODS[level]
|
||||
const show = levelOpts.show ?? (({ index }) => levelOpts.index <= index)
|
||||
const force = meta.force && !this.#silent
|
||||
|
||||
// Explicitly call these on npmlog and not log shim
|
||||
// This is the final place we should call npmlog before removing it.
|
||||
#npmlog (level, ...args) {
|
||||
npmlog[level](...args.map(Display.clean))
|
||||
}
|
||||
|
||||
// Also (and this is a really inexcusable kludge), we patch the
|
||||
// log.warn() method so that when we see a peerDep override
|
||||
// explanation from Arborist, we can replace the object with a
|
||||
// highly abbreviated explanation of what's being overridden.
|
||||
#eresolveWarn (level, heading, message, expl) {
|
||||
if (level === 'warn' &&
|
||||
heading === 'ERESOLVE' &&
|
||||
expl && typeof expl === 'object'
|
||||
) {
|
||||
this.#npmlog(level, heading, message)
|
||||
this.#npmlog(level, '', explain(expl, this.#chalk, 2))
|
||||
// Return true to short circuit other log in chain
|
||||
return true
|
||||
if (force || show({ index: this.#levelIndex, timing: this.#timing })) {
|
||||
// this mutates the array so we can pass args directly to format later
|
||||
const title = args.shift()
|
||||
const prefix = [
|
||||
this.#logColors.heading(this.#heading),
|
||||
this.#logColors[level](level),
|
||||
title ? this.#logColors.title(title) : null,
|
||||
]
|
||||
this.#write(this.#stderr, { prefix }, ...args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Progress {
|
||||
// Taken from https://github.com/sindresorhus/cli-spinners
|
||||
// MIT License
|
||||
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
static dots = { duration: 80, frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] }
|
||||
static lines = { duration: 130, frames: ['-', '\\', '|', '/'] }
|
||||
|
||||
#stream
|
||||
#spinner
|
||||
#enabled = false
|
||||
|
||||
#frameIndex = 0
|
||||
#lastUpdate = 0
|
||||
#interval
|
||||
#timeout
|
||||
|
||||
// We are rendering is enabled option is set and we are not waiting for the render timeout
|
||||
get #rendering () {
|
||||
return this.#enabled && !this.#timeout
|
||||
}
|
||||
|
||||
// We are spinning if enabled option is set and the render interval has been set
|
||||
get #spinning () {
|
||||
return this.#enabled && this.#interval
|
||||
}
|
||||
|
||||
constructor ({ stream }) {
|
||||
this.#stream = stream
|
||||
}
|
||||
|
||||
load ({ enabled, unicode }) {
|
||||
this.#enabled = enabled
|
||||
this.#spinner = unicode ? Progress.dots : Progress.lines
|
||||
// Dont render the spinner for short durations
|
||||
this.#render(200)
|
||||
}
|
||||
|
||||
off () {
|
||||
if (!this.#enabled) {
|
||||
return
|
||||
}
|
||||
clearTimeout(this.#timeout)
|
||||
this.#timeout = null
|
||||
clearInterval(this.#interval)
|
||||
this.#interval = null
|
||||
this.#frameIndex = 0
|
||||
this.#lastUpdate = 0
|
||||
this.#clearSpinner()
|
||||
}
|
||||
|
||||
resume () {
|
||||
this.#render()
|
||||
}
|
||||
|
||||
// If we are currenting rendering the spinner we clear it
|
||||
// before writing our line and then re-render the spinner after.
|
||||
// If not then all we need to do is write the line
|
||||
write (write) {
|
||||
if (this.#spinning) {
|
||||
this.#clearSpinner()
|
||||
}
|
||||
write()
|
||||
if (this.#spinning) {
|
||||
this.#render()
|
||||
}
|
||||
}
|
||||
|
||||
#render (ms) {
|
||||
if (ms) {
|
||||
this.#timeout = setTimeout(() => {
|
||||
this.#timeout = null
|
||||
this.#renderSpinner()
|
||||
}, ms)
|
||||
// Make sure this timeout does not keep the process open
|
||||
this.#timeout.unref()
|
||||
} else {
|
||||
this.#renderSpinner()
|
||||
}
|
||||
}
|
||||
|
||||
#renderSpinner () {
|
||||
if (!this.#rendering) {
|
||||
return
|
||||
}
|
||||
// We always attempt to render immediately but we only request to move to the next
|
||||
// frame if it has been longer than our spinner frame duration since our last update
|
||||
this.#renderFrame(Date.now() - this.#lastUpdate >= this.#spinner.duration)
|
||||
clearInterval(this.#interval)
|
||||
this.#interval = setInterval(() => this.#renderFrame(true), this.#spinner.duration)
|
||||
}
|
||||
|
||||
#renderFrame (next) {
|
||||
if (next) {
|
||||
this.#lastUpdate = Date.now()
|
||||
this.#frameIndex++
|
||||
if (this.#frameIndex >= this.#spinner.frames.length) {
|
||||
this.#frameIndex = 0
|
||||
}
|
||||
}
|
||||
this.#clearSpinner()
|
||||
this.#stream.write(this.#spinner.frames[this.#frameIndex])
|
||||
}
|
||||
|
||||
#clearSpinner () {
|
||||
// Move to the start of the line and clear the rest of the line
|
||||
this.#stream.cursorTo(0)
|
||||
this.#stream.clearLine(1)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Display
|
||||
Vendored
+9
-13
@@ -1,19 +1,16 @@
|
||||
const { format } = require('util')
|
||||
const { resolve } = require('path')
|
||||
const { format } = require('node:util')
|
||||
const { resolve } = require('node:path')
|
||||
const { redactLog: replaceInfo } = require('@npmcli/redact')
|
||||
const { report } = require('./explain-eresolve.js')
|
||||
const log = require('./log-shim')
|
||||
const { log } = require('proc-log')
|
||||
|
||||
const messageText = msg => msg.map(line => line.slice(1).join(' ')).join('\n')
|
||||
|
||||
const jsonError = (er, npm, { summary, detail }) => {
|
||||
if (npm?.config.loaded && npm.config.get('json')) {
|
||||
return {
|
||||
error: {
|
||||
code: er.code,
|
||||
summary: messageText(summary),
|
||||
detail: messageText(detail),
|
||||
},
|
||||
code: er.code,
|
||||
summary: messageText(summary),
|
||||
detail: messageText(detail),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +29,7 @@ const errorMessage = (er, npm) => {
|
||||
|
||||
switch (er.code) {
|
||||
case 'ERESOLVE': {
|
||||
const { report } = require('./explain-eresolve.js')
|
||||
short.push(['ERESOLVE', er.message])
|
||||
detail.push(['', ''])
|
||||
// XXX(display): error messages are logged so we use the logColor since that is based
|
||||
@@ -77,9 +75,7 @@ const errorMessage = (er, npm) => {
|
||||
npm.config.loaded &&
|
||||
er.dest.startsWith(npm.config.get('cache'))
|
||||
|
||||
const { isWindows } = require('./is-windows.js')
|
||||
|
||||
if (!isWindows && (isCachePath || isCacheDest)) {
|
||||
if (process.platform !== 'win32' && (isCachePath || isCacheDest)) {
|
||||
// user probably doesn't need this, but still add it to the debug log
|
||||
log.verbose(er.stack)
|
||||
short.push([
|
||||
@@ -101,7 +97,7 @@ const errorMessage = (er, npm) => {
|
||||
'',
|
||||
[
|
||||
'\nThe operation was rejected by your operating system.',
|
||||
isWindows
|
||||
process.platform === 'win32'
|
||||
/* eslint-disable-next-line max-len */
|
||||
? "It's possible that the file was already in use (by a text editor or antivirus),\n" +
|
||||
'or that you lack permissions to access it.'
|
||||
|
||||
Vendored
+20
-52
@@ -1,4 +1,4 @@
|
||||
const { relative } = require('path')
|
||||
const { relative } = require('node:path')
|
||||
|
||||
const explainNode = (node, depth, chalk) =>
|
||||
printNode(node, chalk) +
|
||||
@@ -6,63 +6,32 @@ const explainNode = (node, depth, chalk) =>
|
||||
explainLinksIn(node, depth, chalk)
|
||||
|
||||
const colorType = (type, chalk) => {
|
||||
const { red, yellow, cyan, magenta, blue, green, gray } = chalk
|
||||
const style = type === 'extraneous' ? red
|
||||
: type === 'dev' ? yellow
|
||||
: type === 'optional' ? cyan
|
||||
: type === 'peer' ? magenta
|
||||
: type === 'bundled' ? blue
|
||||
: type === 'workspace' ? green
|
||||
: type === 'overridden' ? gray
|
||||
const style = type === 'extraneous' ? chalk.red
|
||||
: type === 'dev' ? chalk.blue
|
||||
: type === 'optional' ? chalk.magenta
|
||||
: type === 'peer' ? chalk.magentaBright
|
||||
: type === 'bundled' ? chalk.underline.cyan
|
||||
: type === 'workspace' ? chalk.blueBright
|
||||
: type === 'overridden' ? chalk.dim
|
||||
: /* istanbul ignore next */ s => s
|
||||
return style(type)
|
||||
}
|
||||
|
||||
const printNode = (node, chalk) => {
|
||||
const {
|
||||
name,
|
||||
version,
|
||||
location,
|
||||
extraneous,
|
||||
dev,
|
||||
optional,
|
||||
peer,
|
||||
bundled,
|
||||
isWorkspace,
|
||||
overridden,
|
||||
} = node
|
||||
const { bold, dim, green } = chalk
|
||||
const extra = []
|
||||
if (extraneous) {
|
||||
extra.push(' ' + bold(colorType('extraneous', chalk)))
|
||||
|
||||
for (const meta of ['extraneous', 'dev', 'optional', 'peer', 'bundled', 'overridden']) {
|
||||
if (node[meta]) {
|
||||
extra.push(` ${colorType(meta, chalk)}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (dev) {
|
||||
extra.push(' ' + bold(colorType('dev', chalk)))
|
||||
}
|
||||
|
||||
if (optional) {
|
||||
extra.push(' ' + bold(colorType('optional', chalk)))
|
||||
}
|
||||
|
||||
if (peer) {
|
||||
extra.push(' ' + bold(colorType('peer', chalk)))
|
||||
}
|
||||
|
||||
if (bundled) {
|
||||
extra.push(' ' + bold(colorType('bundled', chalk)))
|
||||
}
|
||||
|
||||
if (overridden) {
|
||||
extra.push(' ' + bold(colorType('overridden', chalk)))
|
||||
}
|
||||
|
||||
const pkgid = isWorkspace
|
||||
? green(`${name}@${version}`)
|
||||
: `${bold(name)}@${bold(version)}`
|
||||
const pkgid = node.isWorkspace
|
||||
? chalk.blueBright(`${node.name}@${node.version}`)
|
||||
: `${node.name}@${node.version}`
|
||||
|
||||
return `${pkgid}${extra.join('')}` +
|
||||
(location ? dim(`\n${location}`) : '')
|
||||
(node.location ? chalk.dim(`\n${node.location}`) : '')
|
||||
}
|
||||
|
||||
const explainLinksIn = ({ linksIn }, depth, chalk) => {
|
||||
@@ -75,7 +44,7 @@ const explainLinksIn = ({ linksIn }, depth, chalk) => {
|
||||
return str.split('\n').join('\n ')
|
||||
}
|
||||
|
||||
const explainDependents = ({ name, dependents }, depth, chalk) => {
|
||||
const explainDependents = ({ dependents }, depth, chalk) => {
|
||||
if (!dependents || !dependents.length || depth <= 0) {
|
||||
return ''
|
||||
}
|
||||
@@ -107,10 +76,9 @@ const explainDependents = ({ name, dependents }, depth, chalk) => {
|
||||
}
|
||||
|
||||
const explainEdge = ({ name, type, bundled, from, spec, rawSpec, overridden }, depth, chalk) => {
|
||||
const { bold } = chalk
|
||||
let dep = type === 'workspace'
|
||||
? bold(relative(from.location, spec.slice('file:'.length)))
|
||||
: `${bold(name)}@"${bold(spec)}"`
|
||||
? chalk.bold(relative(from.location, spec.slice('file:'.length)))
|
||||
: `${name}@"${spec}"`
|
||||
if (overridden) {
|
||||
dep = `${colorType('overridden', chalk)} ${dep} (was "${rawSpec}")`
|
||||
}
|
||||
|
||||
+115
-75
@@ -1,6 +1,6 @@
|
||||
const { stripVTControlCharacters } = require('node:util')
|
||||
/* eslint-disable max-len */
|
||||
const { stripVTControlCharacters: strip } = require('node:util')
|
||||
const { Minipass } = require('minipass')
|
||||
const columnify = require('columnify')
|
||||
|
||||
// This module consumes package data in the following format:
|
||||
//
|
||||
@@ -16,14 +16,48 @@ const columnify = require('columnify')
|
||||
// The returned stream will format this package data
|
||||
// into a byte stream of formatted, displayable output.
|
||||
|
||||
module.exports = async (opts) => {
|
||||
return opts.json ? new JSONOutputStream() : new TextOutputStream(opts)
|
||||
function filter (data, exclude) {
|
||||
const words = [data.name]
|
||||
.concat(data.maintainers.map(m => m.username))
|
||||
.concat(data.keywords || [])
|
||||
.map(f => f?.trim?.())
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
|
||||
if (exclude.find(pattern => {
|
||||
// Treats both /foo and /foo/ as regex searches
|
||||
if (pattern.startsWith('/')) {
|
||||
if (pattern.endsWith('/')) {
|
||||
pattern = pattern.slice(0, -1)
|
||||
}
|
||||
return words.match(new RegExp(pattern.slice(1)))
|
||||
}
|
||||
return words.includes(pattern)
|
||||
})) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
module.exports = (opts) => {
|
||||
return opts.json ? new JSONOutputStream(opts) : new TextOutputStream(opts)
|
||||
}
|
||||
|
||||
class JSONOutputStream extends Minipass {
|
||||
#didFirst = false
|
||||
#exclude
|
||||
|
||||
constructor (opts) {
|
||||
super()
|
||||
this.#exclude = opts.exclude
|
||||
}
|
||||
|
||||
write (obj) {
|
||||
if (!filter(obj, this.#exclude)) {
|
||||
return
|
||||
}
|
||||
if (!this.#didFirst) {
|
||||
super.write('[\n')
|
||||
this.#didFirst = true
|
||||
@@ -41,94 +75,100 @@ class JSONOutputStream extends Minipass {
|
||||
}
|
||||
|
||||
class TextOutputStream extends Minipass {
|
||||
#opts
|
||||
#line = 0
|
||||
#args
|
||||
#chalk
|
||||
#exclude
|
||||
#parseable
|
||||
|
||||
constructor (opts) {
|
||||
super()
|
||||
this.#opts = opts
|
||||
this.#args = opts.args.map(s => s.toLowerCase()).filter(Boolean)
|
||||
this.#chalk = opts.npm.chalk
|
||||
this.#exclude = opts.exclude
|
||||
this.#parseable = opts.parseable
|
||||
}
|
||||
|
||||
write (pkg) {
|
||||
return super.write(this.#prettify(pkg))
|
||||
}
|
||||
|
||||
#prettify (data) {
|
||||
write (data) {
|
||||
if (!filter(data, this.#exclude)) {
|
||||
return
|
||||
}
|
||||
// Normalize
|
||||
const pkg = {
|
||||
author: data.maintainers.map((m) => `=${stripVTControlCharacters(m.username)}`).join(' '),
|
||||
date: 'prehistoric',
|
||||
description: stripVTControlCharacters(data.description ?? ''),
|
||||
keywords: '',
|
||||
name: stripVTControlCharacters(data.name),
|
||||
authors: data.maintainers.map((m) => `${strip(m.username)}`).join(' '),
|
||||
publisher: strip(data.publisher?.username || ''),
|
||||
date: data.date ? data.date.toISOString().slice(0, 10) : 'prehistoric',
|
||||
description: strip(data.description ?? ''),
|
||||
keywords: [],
|
||||
name: strip(data.name),
|
||||
version: data.version,
|
||||
}
|
||||
if (Array.isArray(data.keywords)) {
|
||||
pkg.keywords = data.keywords.map((k) => stripVTControlCharacters(k)).join(' ')
|
||||
pkg.keywords = data.keywords.map(strip)
|
||||
} else if (typeof data.keywords === 'string') {
|
||||
pkg.keywords = stripVTControlCharacters(data.keywords.replace(/[,\s]+/, ' '))
|
||||
}
|
||||
if (data.date) {
|
||||
pkg.date = data.date.toISOString().split('T')[0] // remove time
|
||||
pkg.keywords = strip(data.keywords.replace(/[,\s]+/, ' ')).split(' ')
|
||||
}
|
||||
|
||||
const columns = ['name', 'description', 'author', 'date', 'version', 'keywords']
|
||||
if (this.#opts.parseable) {
|
||||
return columns.map((col) => pkg[col] && ('' + pkg[col]).replace(/\t/g, ' ')).join('\t')
|
||||
let output
|
||||
if (this.#parseable) {
|
||||
output = [pkg.name, pkg.description, pkg.author, pkg.date, pkg.version, pkg.keywords]
|
||||
.filter(Boolean)
|
||||
.map(col => ('' + col).replace(/\t/g, ' ')).join('\t')
|
||||
return super.write(output)
|
||||
}
|
||||
|
||||
// stdout in tap is never a tty
|
||||
/* istanbul ignore next */
|
||||
const maxWidth = process.stdout.isTTY ? process.stdout.getWindowSize()[0] : Infinity
|
||||
let output = columnify(
|
||||
[pkg],
|
||||
{
|
||||
include: columns,
|
||||
showHeaders: ++this.#line <= 1,
|
||||
columnSplitter: ' | ',
|
||||
truncate: !this.#opts.long,
|
||||
config: {
|
||||
name: { minWidth: 25, maxWidth: 25, truncate: false, truncateMarker: '' },
|
||||
description: { minWidth: 20, maxWidth: 20 },
|
||||
author: { minWidth: 15, maxWidth: 15 },
|
||||
date: { maxWidth: 11 },
|
||||
version: { minWidth: 8, maxWidth: 8 },
|
||||
keywords: { maxWidth: Infinity },
|
||||
},
|
||||
}
|
||||
).split('\n').map(line => line.slice(0, maxWidth)).join('\n')
|
||||
|
||||
if (!this.#opts.color) {
|
||||
return output
|
||||
}
|
||||
|
||||
const colors = ['31m', '33m', '32m', '36m', '34m', '35m']
|
||||
|
||||
this.#opts.args.forEach((arg, i) => {
|
||||
const markStart = String.fromCharCode(i % colors.length + 1)
|
||||
const markEnd = String.fromCharCode(0)
|
||||
|
||||
if (arg.charAt(0) === '/') {
|
||||
output = output.replace(
|
||||
new RegExp(arg.slice(1, -1), 'gi'),
|
||||
bit => `${markStart}${bit}${markEnd}`
|
||||
)
|
||||
const keywords = pkg.keywords.map(k => {
|
||||
if (this.#args.includes(k)) {
|
||||
return this.#chalk.cyan(k)
|
||||
} else {
|
||||
// just a normal string, do the split/map thing
|
||||
let p = 0
|
||||
|
||||
output = output.toLowerCase().split(arg.toLowerCase()).map(piece => {
|
||||
piece = output.slice(p, p + piece.length)
|
||||
p += piece.length
|
||||
const mark = `${markStart}${output.slice(p, p + arg.length)}${markEnd}`
|
||||
p += arg.length
|
||||
return `${piece}${mark}`
|
||||
}).join('')
|
||||
return k
|
||||
}
|
||||
})
|
||||
}).join(' ')
|
||||
|
||||
for (let i = 1; i <= colors.length; i++) {
|
||||
output = output.split(String.fromCharCode(i)).join(`\u001B[${colors[i - 1]}`)
|
||||
let description = []
|
||||
for (const arg of this.#args) {
|
||||
const finder = pkg.description.toLowerCase().split(arg.toLowerCase())
|
||||
let p = 0
|
||||
for (const f of finder) {
|
||||
description.push(pkg.description.slice(p, p + f.length))
|
||||
const word = pkg.description.slice(p + f.length, p + f.length + arg.length)
|
||||
description.push(this.#chalk.cyan(word))
|
||||
p += f.length + arg.length
|
||||
}
|
||||
}
|
||||
return output.split('\u0000').join('\u001B[0m').trim()
|
||||
description = description.filter(Boolean)
|
||||
let name = pkg.name
|
||||
if (this.#args.includes(pkg.name)) {
|
||||
name = this.#chalk.cyan(pkg.name)
|
||||
} else {
|
||||
name = []
|
||||
for (const arg of this.#args) {
|
||||
const finder = pkg.name.toLowerCase().split(arg.toLowerCase())
|
||||
let p = 0
|
||||
for (const f of finder) {
|
||||
name.push(pkg.name.slice(p, p + f.length))
|
||||
const word = pkg.name.slice(p + f.length, p + f.length + arg.length)
|
||||
name.push(this.#chalk.cyan(word))
|
||||
p += f.length + arg.length
|
||||
}
|
||||
}
|
||||
name = this.#chalk.blue(name.join(''))
|
||||
}
|
||||
|
||||
if (description.length) {
|
||||
output = `${name}\n${description.join('')}\n`
|
||||
} else {
|
||||
output = `${name}\n`
|
||||
}
|
||||
if (pkg.publisher) {
|
||||
output += `Version ${this.#chalk.blue(pkg.version)} published ${this.#chalk.blue(pkg.date)} by ${this.#chalk.blue(pkg.publisher)}\n`
|
||||
} else {
|
||||
output += `Version ${this.#chalk.blue(pkg.version)} published ${this.#chalk.blue(pkg.date)} by ${this.#chalk.yellow('???')}\n`
|
||||
}
|
||||
output += `Maintainers: ${pkg.authors}\n`
|
||||
if (keywords) {
|
||||
output += `Keywords: ${keywords}\n`
|
||||
}
|
||||
output += `${this.#chalk.blue(`https://npm.im/${pkg.name}`)}\n`
|
||||
return super.write(output)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 418 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user