deps: upgrade npm to 8.2.0

PR-URL: https://github.com/nodejs/node/pull/41065
Reviewed-By: Myles Borins <myles.borins@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
npm team authored and Danielle Adams committed 2022-01-31 23:08:41 -05:00
1 parent 25d3103f38
commit 3c13bbd8aa
287 files changed
+5139 -5638

No files matched your search

+3 -3
View File
@@ -1014,8 +1014,8 @@ Ideal if all users are on npm version 7 and higher.
* Type: "silent", "error", "warn", "notice", "http", "timing", "info",
"verbose", or "silly"
What level of logs to report. On failure, *all* logs are written to
`npm-debug.log` in the current working directory.
What level of logs to report. All logs are written to a debug log, with the
path to that file printed if the execution of a command fails.
Any logs of a higher level than the setting are shown. The default is
"notice".
@@ -1387,7 +1387,7 @@ Save installed packages to a package.json file as `optionalDependencies`.
* Default: false
* Type: Boolean
Save installed packages. to a package.json file as `peerDependencies`
Save installed packages to a package.json file as `peerDependencies`
<!-- automatically generated, do not edit manually -->
<!-- see lib/utils/config/definitions.js -->
+60
View File
@@ -0,0 +1,60 @@
---
title: Logging
section: 7
description: Why, What & How we Log
---
### Description
The `npm` CLI has various mechanisms for showing different levels of information back to end-users for certain commands, configurations & environments.
### Setting Log Levels
#### `loglevel`
`loglevel` is a global argument/config that can be set to determine the type of information to be displayed.
The default value of `loglevel` is `"notice"` but there are several levels/types of logs available, including:
- `"silent"`
- `"error"`
- `"warn"`
- `"notice"`
- `"http"`
- `"timing"`
- `"info"`
- `"verbose"`
- `"silly"`
All logs pertaining to a level proceeding the current setting will be shown.
All logs are written to a debug log, with the path to that file printed if the execution of a command fails.
##### Aliases
The log levels listed above have various corresponding aliases, including:
- `-d`: `--loglevel info`
- `--dd`: `--loglevel verbose`
- `--verbose`: `--loglevel verbose`
- `--ddd`: `--loglevel silly`
- `-q`: `--loglevel warn`
- `--quiet`: `--loglevel warn`
- `-s`: `--loglevel silent`
- `--silent`: `--loglevel silent`
#### `foreground-scripts`
The `npm` CLI began hiding the output of lifecycle scripts for `npm install` as of `v7`. Notably, this means you will not see logs/output from packages that may be using "install scripts" to display information back to you or from your own project's scripts defined in `package.json`. If you'd like to change this behavior & log this output you can set `foreground-scripts` to `true`.
### Registry Response Headers
#### `npm-notice`
The `npm` CLI reads from & logs any `npm-notice` headers that are returned from the configured registry. This mechanism can be used by third-party registries to provide useful information when network-dependent requests occur.
This header is not cached, and will not be logged if the request is served from the cache.
### See also
* [config](/using-npm/config)
+1 -1
View File
@@ -259,7 +259,7 @@ package.json file, then your package scripts would have the
in your code with `process.env.npm_package_name` and
`process.env.npm_package_version`, and so on for other fields.
See [`package-json.md`](/configuring-npm/package-json) for more on package configs.
See [`package.json`](/configuring-npm/package-json) for more on package configs.
#### current lifecycle event
+1 -1
View File
@@ -8,7 +8,7 @@ description: Working with workspaces
**Workspaces** is a generic term that refers to the set of features in the
npm cli that provides support to managing multiple packages from your local
files system from within a singular top-level, root package.
file system from within a singular top-level, root package.
This set of features makes up for a much more streamlined workflow handling
linked packages from the local file system. Automating the linking process
+1 -1
View File
@@ -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 lang="bash"><code>npm@8.1.4 /path/to/npm
<pre lang="bash"><code>npm@8.2.0 /path/to/npm
└─┬ init-package-json@0.0.4
└── promzard@0.1.5
</code></pre>
+1 -1
View File
@@ -149,7 +149,7 @@ npm command-line interface
<pre lang="bash"><code>npm &lt;command&gt; [args]
</code></pre>
<h3 id="version">Version</h3>
<p>8.1.4</p>
<p>8.2.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
+3 -3
View File
@@ -962,8 +962,8 @@ Ideal if all users are on npm version 7 and higher.</p>
<li>Type: "silent", "error", "warn", "notice", "http", "timing", "info",
"verbose", or "silly"</li>
</ul>
<p>What level of logs to report. On failure, <em>all</em> logs are written to
<code>npm-debug.log</code> in the current working directory.</p>
<p>What level of logs to report. All logs are written to a debug log, with the
path to that file printed if the execution of a command fails.</p>
<p>Any logs of a higher level than the setting are shown. The default is
"notice".</p>
<p>See also the <code>foreground-scripts</code> config.</p>
@@ -1259,7 +1259,7 @@ rather than using npm's default semver range operator.</p>
<li>Default: false</li>
<li>Type: Boolean</li>
</ul>
<p>Save installed packages. to a package.json file as <code>peerDependencies</code></p>
<p>Save installed packages to a package.json file as <code>peerDependencies</code></p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<h4 id="save-prefix"><code>save-prefix</code></h4>
+203
View File
@@ -0,0 +1,203 @@
<!DOCTYPE html><html><head>
<meta charset="utf-8">
<title>Logging</title>
<style>
body {
background-color: #ffffff;
color: #24292e;
margin: 0;
line-height: 1.5;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
}
#rainbar {
height: 10px;
background-image: linear-gradient(139deg, #fb8817, #ff4b01, #c12127, #e02aff);
}
a {
text-decoration: none;
color: #0366d6;
}
a:hover {
text-decoration: underline;
}
pre {
margin: 1em 0px;
padding: 1em;
border: solid 1px #e1e4e8;
border-radius: 6px;
display: block;
overflow: auto;
white-space: pre;
background-color: #f6f8fa;
color: #393a34;
}
code {
font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace;
font-size: 85%;
padding: 0.2em 0.4em;
background-color: #f6f8fa;
color: #393a34;
}
pre > code {
padding: 0;
background-color: inherit;
color: inherit;
}
h1, h2, h3 {
font-weight: 600;
}
#logobar {
background-color: #333333;
margin: 0 auto;
padding: 1em 4em;
}
#logobar .logo {
float: left;
}
#logobar .title {
font-weight: 600;
color: #dddddd;
float: left;
margin: 5px 0 0 1em;
}
#logobar:after {
content: "";
display: block;
clear: both;
}
#content {
margin: 0 auto;
padding: 0 4em;
}
#table_of_contents > h2 {
font-size: 1.17em;
}
#table_of_contents ul:first-child {
border: solid 1px #e1e4e8;
border-radius: 6px;
padding: 1em;
background-color: #f6f8fa;
color: #393a34;
}
#table_of_contents ul {
list-style-type: none;
padding-left: 1.5em;
}
#table_of_contents li {
font-size: 0.9em;
}
#table_of_contents li a {
color: #000000;
}
header.title {
border-bottom: solid 1px #e1e4e8;
}
header.title > h1 {
margin-bottom: 0.25em;
}
header.title > .description {
display: block;
margin-bottom: 0.5em;
line-height: 1;
}
footer#edit {
border-top: solid 1px #e1e4e8;
margin: 3em 0 4em 0;
padding-top: 2em;
}
</style>
</head>
<body>
<div id="banner">
<div id="rainbar"></div>
<div id="logobar">
<svg class="logo" role="img" height="32" width="32" viewBox="0 0 700 700">
<polygon fill="#cb0000" points="0,700 700,700 700,0 0,0"></polygon>
<polygon fill="#ffffff" points="150,550 350,550 350,250 450,250 450,550 550,550 550,150 150,150"></polygon>
</svg>
<div class="title">
npm command-line interface
</div>
</div>
</div>
<section id="content">
<header class="title">
<h1 id="logging">Logging</h1>
<span class="description">Why, What &amp; How we Log</span>
</header>
<section id="table_of_contents">
<h2 id="table-of-contents">Table of contents</h2>
<div id="_table_of_contents"><ul><li><a href="#description">Description</a></li><li><a href="#setting-log-levels">Setting Log Levels</a></li><ul><li><a href="#loglevel"><code>loglevel</code></a></li><ul><li><a href="#aliases">Aliases</a></li></ul><li><a href="#foreground-scripts"><code>foreground-scripts</code></a></li></ul><li><a href="#registry-response-headers">Registry Response Headers</a></li><ul><li><a href="#npm-notice"><code>npm-notice</code></a></li></ul><li><a href="#see-also">See also</a></li></ul></div>
</section>
<div id="_content"><h3 id="description">Description</h3>
<p>The <code>npm</code> CLI has various mechanisms for showing different levels of information back to end-users for certain commands, configurations &amp; environments.</p>
<h3 id="setting-log-levels">Setting Log Levels</h3>
<h4 id="loglevel"><code>loglevel</code></h4>
<p><code>loglevel</code> is a global argument/config that can be set to determine the type of information to be displayed.</p>
<p>The default value of <code>loglevel</code> is <code>"notice"</code> but there are several levels/types of logs available, including:</p>
<ul>
<li><code>"silent"</code></li>
<li><code>"error"</code></li>
<li><code>"warn"</code></li>
<li><code>"notice"</code></li>
<li><code>"http"</code></li>
<li><code>"timing"</code></li>
<li><code>"info"</code></li>
<li><code>"verbose"</code></li>
<li><code>"silly"</code></li>
</ul>
<p>All logs pertaining to a level proceeding the current setting will be shown.</p>
<p>All logs are written to a debug log, with the path to that file printed if the execution of a command fails.</p>
<h5 id="aliases">Aliases</h5>
<p>The log levels listed above have various corresponding aliases, including:</p>
<ul>
<li><code>-d</code>: <code>--loglevel info</code></li>
<li><code>--dd</code>: <code>--loglevel verbose</code></li>
<li><code>--verbose</code>: <code>--loglevel verbose</code></li>
<li><code>--ddd</code>: <code>--loglevel silly</code></li>
<li><code>-q</code>: <code>--loglevel warn</code></li>
<li><code>--quiet</code>: <code>--loglevel warn</code></li>
<li><code>-s</code>: <code>--loglevel silent</code></li>
<li><code>--silent</code>: <code>--loglevel silent</code></li>
</ul>
<h4 id="foreground-scripts"><code>foreground-scripts</code></h4>
<p>The <code>npm</code> CLI began hiding the output of lifecycle scripts for <code>npm install</code> as of <code>v7</code>. Notably, this means you will not see logs/output from packages that may be using "install scripts" to display information back to you or from your own project's scripts defined in <code>package.json</code>. If you'd like to change this behavior &amp; log this output you can set <code>foreground-scripts</code> to <code>true</code>.</p>
<h3 id="registry-response-headers">Registry Response Headers</h3>
<h4 id="npm-notice"><code>npm-notice</code></h4>
<p>The <code>npm</code> CLI reads from &amp; logs any <code>npm-notice</code> headers that are returned from the configured registry. This mechanism can be used by third-party registries to provide useful information when network-dependent requests occur.</p>
<p>This header is not cached, and will not be logged if the request is served from the cache.</p>
<h3 id="see-also">See also</h3>
<ul>
<li><a href="../using-npm/config.html">config</a></li>
</ul>
</div>
<footer id="edit">
<a href="https://github.com/npm/cli/edit/latest/docs/content/using-npm/logging.md">
<svg role="img" viewBox="0 0 16 16" width="16" height="16" fill="currentcolor" style="vertical-align: text-bottom; margin-right: 0.3em;">
<path fill-rule="evenodd" d="M11.013 1.427a1.75 1.75 0 012.474 0l1.086 1.086a1.75 1.75 0 010 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 01-.927-.928l.929-3.25a1.75 1.75 0 01.445-.758l8.61-8.61zm1.414 1.06a.25.25 0 00-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 000-.354l-1.086-1.086zM11.189 6.25L9.75 4.81l-6.286 6.287a.25.25 0 00-.064.108l-.558 1.953 1.953-.558a.249.249 0 00.108-.064l6.286-6.286z"></path>
</svg>
Edit this page on GitHub
</a>
</footer>
</section>
</body></html>
+1 -1
View File
@@ -380,7 +380,7 @@ package.json file, then your package scripts would have the
<code>npm_package_version</code> set to "1.2.5". You can access these variables
in your code with <code>process.env.npm_package_name</code> and
<code>process.env.npm_package_version</code>, and so on for other fields.</p>
<p>See <a href="../configuring-npm/package-json.html"><code>package-json.md</code></a> for more on package configs.</p>
<p>See <a href="../configuring-npm/package-json.html"><code>package.json</code></a> for more on package configs.</p>
<h4 id="current-lifecycle-event">current lifecycle event</h4>
<p>Lastly, the <code>npm_lifecycle_event</code> environment variable is set to
whichever stage of the cycle is being executed. So, you could have a
+1 -1
View File
@@ -148,7 +148,7 @@ npm command-line interface
<div id="_content"><h3 id="description">Description</h3>
<p><strong>Workspaces</strong> is a generic term that refers to the set of features in the
npm cli that provides support to managing multiple packages from your local
files system from within a singular top-level, root package.</p>
file system from within a singular top-level, root package.</p>
<p>This set of features makes up for a much more streamlined workflow handling
linked packages from the local file system. Automating the linking process
as part of <code>npm install</code> and avoiding manually having to use <code>npm link</code> in
+4 -7
View File
@@ -1,15 +1,12 @@
const log = require('npmlog')
const profile = require('npm-profile')
const log = require('../utils/log-shim')
const openUrl = require('../utils/open-url.js')
const read = require('../utils/read-user-info.js')
const loginPrompter = async (creds) => {
const opts = { log: log }
creds.username = await read.username('Username:', creds.username, opts)
creds.username = await read.username('Username:', creds.username)
creds.password = await read.password('Password:', creds.password)
creds.email = await read.email('Email: (this IS public) ', creds.email, opts)
creds.email = await read.email('Email: (this IS public) ', creds.email)
return creds
}
@@ -19,7 +16,7 @@ const login = async (npm, opts) => {
const requestOTP = async () => {
const otp = await read.otp(
'Enter one-time password from your authenticator app: '
'Enter one-time password: '
)
return profile.loginCouch(
+1 -2
View File
@@ -7,10 +7,9 @@
// CLI, we can remove this, and fold the lib/auth/legacy.js back into
// lib/adduser.js
const log = require('npmlog')
const profile = require('npm-profile')
const npmFetch = require('npm-registry-fetch')
const log = require('../utils/log-shim')
const openUrl = require('../utils/open-url.js')
const otplease = require('../utils/otplease.js')
+17 -16
View File
@@ -4,20 +4,23 @@ module.exports = async process => {
// leak any private CLI configs to other programs
process.title = 'npm'
const { checkForBrokenNode, checkForUnsupportedNode } = require('../lib/utils/unsupported.js')
// We used to differentiate between known broken and unsupported
// versions of node and attempt to only log unsupported but still run.
// After we dropped node 10 support, we can use new features
// (like static, private, etc) which will only give vague syntax errors,
// so now both broken and unsupported use console, but only broken
// will process.exit. It is important to now perform *both* of these
// checks as early as possible so the user gets the error message.
const { checkForBrokenNode, checkForUnsupportedNode } = require('./utils/unsupported.js')
checkForBrokenNode()
const log = require('npmlog')
// pause it here so it can unpause when we've loaded the configs
// and know what loglevel we should be printing.
log.pause()
checkForUnsupportedNode()
const Npm = require('../lib/npm.js')
const exitHandler = require('./utils/exit-handler.js')
process.on('uncaughtException', exitHandler)
process.on('unhandledRejection', exitHandler)
const Npm = require('./npm.js')
const npm = new Npm()
const exitHandler = require('../lib/utils/exit-handler.js')
exitHandler.setNpm(npm)
// if npm is called as "npmg" or "npm_g", then
@@ -26,16 +29,14 @@ module.exports = async process => {
process.argv.splice(1, 1, 'npm', '-g')
}
const replaceInfo = require('../lib/utils/replace-info.js')
const log = require('./utils/log-shim.js')
const replaceInfo = require('./utils/replace-info.js')
log.verbose('cli', replaceInfo(process.argv))
log.info('using', 'npm@%s', npm.version)
log.info('using', 'node@%s', process.version)
process.on('uncaughtException', exitHandler)
process.on('unhandledRejection', exitHandler)
const updateNotifier = require('../lib/utils/update-notifier.js')
const updateNotifier = require('./utils/update-notifier.js')
let cmd
// now actually fire up npm and run the command.
@@ -63,7 +64,7 @@ module.exports = async process => {
}
await npm.exec(cmd, npm.argv)
exitHandler()
return exitHandler()
} catch (err) {
if (err.code === 'EUNKNOWNCOMMAND') {
const didYouMean = require('./utils/did-you-mean.js')
+2 -1
View File
@@ -1,4 +1,4 @@
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const replaceInfo = require('../utils/replace-info.js')
const BaseCommand = require('../base-command.js')
const authTypes = {
@@ -31,6 +31,7 @@ class AddUser extends BaseCommand {
creds,
registry,
scope,
log,
})
await this.updateConfig({
+1
View File
@@ -10,6 +10,7 @@ class Bin extends BaseCommand {
const b = this.npm.bin
this.npm.output(b)
if (this.npm.config.get('global') && !envPath.includes(b)) {
// XXX: does this need to be console?
console.error('(not in PATH env variable)')
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
const log = require('npmlog')
const pacote = require('pacote')
const log = require('../utils/log-shim')
const openUrl = require('../utils/open-url.js')
const hostedFromMani = require('../utils/hosted-git-info-from-manifest.js')
const BaseCommand = require('../base-command.js')
+2 -2
View File
@@ -1,6 +1,5 @@
const cacache = require('cacache')
const { promisify } = require('util')
const log = require('npmlog')
const pacote = require('pacote')
const path = require('path')
const rimraf = promisify(require('rimraf'))
@@ -9,6 +8,7 @@ const BaseCommand = require('../base-command.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 searchCachePackage = async (path, spec, cacheKeys) => {
const parsed = npa(spec)
@@ -141,7 +141,7 @@ class Cache extends BaseCommand {
try {
entry = await cacache.get(cachePath, key)
} catch (err) {
this.npm.log.warn(`Not Found: ${key}`)
log.warn(`Not Found: ${key}`)
break
}
this.npm.output(`Deleted: ${key}`)
+2 -3
View File
@@ -5,8 +5,7 @@ const reifyFinish = require('../utils/reify-finish.js')
const runScript = require('@npmcli/run-script')
const fs = require('fs')
const readdir = util.promisify(fs.readdir)
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const removeNodeModules = async where => {
const rimrafOpts = { glob: false }
@@ -39,7 +38,7 @@ class CI extends ArboristWorkspaceCmd {
const opts = {
...this.npm.flatOptions,
path: where,
log: this.npm.log,
log,
save: false, // npm ci should never modify the lockfile or package.json
workspaces: this.workspaceNames,
}
+6 -5
View File
@@ -11,6 +11,7 @@ const { spawn } = require('child_process')
const { EOL } = require('os')
const ini = require('ini')
const localeCompare = require('@isaacs/string-locale-compare')('en')
const log = require('../utils/log-shim.js')
// take an array of `[key, value, k2=v2, k3, v3, ...]` and turn into
// { key: value, k2: v2, k3: v3 }
@@ -87,12 +88,12 @@ class Config extends BaseCommand {
}
async execWorkspaces (args, filters) {
this.npm.log.warn('config', 'This command does not support workspaces.')
log.warn('config', 'This command does not support workspaces.')
return this.exec(args)
}
async exec ([action, ...args]) {
this.npm.log.disableProgress()
log.disableProgress()
try {
switch (action) {
case 'set':
@@ -117,7 +118,7 @@ class Config extends BaseCommand {
throw this.usageError()
}
} finally {
this.npm.log.enableProgress()
log.enableProgress()
}
}
@@ -128,10 +129,10 @@ class Config extends BaseCommand {
const where = this.npm.flatOptions.location
for (const [key, val] of Object.entries(keyValues(args))) {
this.npm.log.info('config', 'set %j %j', key, val)
log.info('config', 'set %j %j', key, val)
this.npm.config.set(key, val || '', where)
if (!this.npm.config.validate(where)) {
this.npm.log.warn('config', 'omitting invalid config values')
log.warn('config', 'omitting invalid config values')
}
}
+2 -1
View File
@@ -1,6 +1,7 @@
// dedupe duplicated packages, or find them in the tree
const Arborist = require('@npmcli/arborist')
const reifyFinish = require('../utils/reify-finish.js')
const log = require('../utils/log-shim.js')
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
@@ -32,7 +33,7 @@ class Dedupe extends ArboristWorkspaceCmd {
const where = this.npm.prefix
const opts = {
...this.npm.flatOptions,
log: this.npm.log,
log,
path: where,
dryRun,
workspaces: this.workspaceNames,
+7 -9
View File
@@ -1,13 +1,11 @@
const { resolve } = require('path')
const semver = require('semver')
const libnpmdiff = require('libnpmdiff')
const npa = require('npm-package-arg')
const Arborist = require('@npmcli/arborist')
const npmlog = require('npmlog')
const pacote = require('pacote')
const pickManifest = require('npm-pick-manifest')
const log = require('../utils/log-shim')
const readPackageName = require('../utils/read-package-name.js')
const BaseCommand = require('../base-command.js')
@@ -57,7 +55,7 @@ class Diff extends BaseCommand {
}
const [a, b] = await this.retrieveSpecs(specs)
npmlog.info('diff', { src: a, dst: b })
log.info('diff', { src: a, dst: b })
const res = await libnpmdiff([a, b], {
...this.npm.flatOptions,
@@ -83,7 +81,7 @@ class Diff extends BaseCommand {
try {
name = await readPackageName(this.prefix)
} catch (e) {
npmlog.verbose('diff', 'could not read project dir package.json')
log.verbose('diff', 'could not read project dir package.json')
}
if (!name) {
@@ -116,7 +114,7 @@ class Diff extends BaseCommand {
try {
pkgName = await readPackageName(this.prefix)
} catch (e) {
npmlog.verbose('diff', 'could not read project dir package.json')
log.verbose('diff', 'could not read project dir package.json')
noPackageJson = true
}
@@ -154,7 +152,7 @@ class Diff extends BaseCommand {
actualTree.inventory.query('name', spec.name)
.values().next().value
} catch (e) {
npmlog.verbose('diff', 'failed to load actual install tree')
log.verbose('diff', 'failed to load actual install tree')
}
if (!node || !node.name || !node.package || !node.package.version) {
@@ -227,7 +225,7 @@ class Diff extends BaseCommand {
try {
pkgName = await readPackageName(this.prefix)
} catch (e) {
npmlog.verbose('diff', 'could not read project dir package.json')
log.verbose('diff', 'could not read project dir package.json')
}
if (!pkgName) {
@@ -261,7 +259,7 @@ class Diff extends BaseCommand {
const arb = new Arborist(opts)
actualTree = await arb.loadActual(opts)
} catch (e) {
npmlog.verbose('diff', 'failed to load actual install tree')
log.verbose('diff', 'failed to load actual install tree')
}
return specs.map(i => {
+1 -2
View File
@@ -1,8 +1,7 @@
const log = require('npmlog')
const npa = require('npm-package-arg')
const regFetch = require('npm-registry-fetch')
const semver = require('semver')
const log = require('../utils/log-shim')
const otplease = require('../utils/otplease.js')
const readPackageName = require('../utils/read-package-name.js')
const BaseCommand = require('../base-command.js')
+1 -2
View File
@@ -1,8 +1,7 @@
const log = require('npmlog')
const pacote = require('pacote')
const openUrl = require('../utils/open-url.js')
const hostedFromMani = require('../utils/hosted-git-info-from-manifest.js')
const log = require('../utils/log-shim')
const BaseCommand = require('../base-command.js')
class Docs extends BaseCommand {
static description = 'Open documentation for a package in a web browser'
+9 -8
View File
@@ -8,6 +8,7 @@ const pacote = require('pacote')
const { resolve } = require('path')
const semver = require('semver')
const { promisify } = require('util')
const log = require('../utils/log-shim.js')
const ansiTrim = require('../utils/ansi-trim.js')
const isWindows = require('../utils/is-windows.js')
const ping = require('../utils/ping.js')
@@ -42,7 +43,7 @@ class Doctor extends BaseCommand {
static params = ['registry']
async exec (args) {
this.npm.log.info('Running checkup')
log.info('Running checkup')
// each message is [title, ok, message]
const messages = []
@@ -124,7 +125,7 @@ class Doctor extends BaseCommand {
stringLength: s => ansiTrim(s).length,
}
const silent = this.npm.log.levels[this.npm.log.level] > this.npm.log.levels.error
const silent = log.levels[log.level] > log.levels.error
if (!silent) {
this.npm.output(table(outTable, tableOpts))
if (!allOk) {
@@ -137,7 +138,7 @@ class Doctor extends BaseCommand {
}
async checkPing () {
const tracker = this.npm.log.newItem('checkPing', 1)
const tracker = log.newItem('checkPing', 1)
tracker.info('checkPing', 'Pinging registry')
try {
await ping(this.npm.flatOptions)
@@ -154,7 +155,7 @@ class Doctor extends BaseCommand {
}
async getLatestNpmVersion () {
const tracker = this.npm.log.newItem('getLatestNpmVersion', 1)
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
@@ -173,7 +174,7 @@ class Doctor extends BaseCommand {
const current = process.version
const currentRange = `^${current}`
const url = 'https://nodejs.org/dist/index.json'
const tracker = this.npm.log.newItem('getLatestNodejsVersion', 1)
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 })
@@ -207,7 +208,7 @@ class Doctor extends BaseCommand {
let ok = true
const tracker = this.npm.log.newItem(root, 1)
const tracker = log.newItem(root, 1)
try {
const uid = process.getuid()
@@ -269,7 +270,7 @@ class Doctor extends BaseCommand {
}
async getGitPath () {
const tracker = this.npm.log.newItem('getGitPath', 1)
const tracker = log.newItem('getGitPath', 1)
tracker.info('getGitPath', 'Finding git in your PATH')
try {
return await which('git').catch(er => {
@@ -282,7 +283,7 @@ class Doctor extends BaseCommand {
}
async verifyCachedFiles () {
const tracker = this.npm.log.newItem('verifyCachedFiles', 1)
const tracker = log.newItem('verifyCachedFiles', 1)
tracker.info('verifyCachedFiles', 'Verifying the npm cache')
try {
const stats = await cacache.verify(this.npm.flatOptions.cache)
+1 -1
View File
@@ -1,6 +1,7 @@
const libexec = require('libnpmexec')
const BaseCommand = require('../base-command.js')
const getLocationMsg = require('../exec/get-workspace-location-msg.js')
const log = require('../utils/log-shim')
// it's like this:
//
@@ -59,7 +60,6 @@ class Exec extends BaseCommand {
const {
flatOptions,
localBin,
log,
globalBin,
} = this.npm
const output = (...outputArgs) => this.npm.output(...outputArgs)
+4 -3
View File
@@ -4,6 +4,7 @@
const rpj = require('read-package-json-fast')
const runScript = require('@npmcli/run-script')
const { join, resolve, relative } = require('path')
const log = require('../utils/log-shim.js')
const completion = require('../utils/completion/installed-shallow.js')
const BaseCommand = require('../base-command.js')
@@ -37,7 +38,7 @@ class Explore extends BaseCommand {
// handle all the escaping and PATH setup stuff.
const pkg = await rpj(resolve(path, 'package.json')).catch(er => {
this.npm.log.error('explore', `It doesn't look like ${pkgname} is installed.`)
log.error('explore', `It doesn't look like ${pkgname} is installed.`)
throw er
})
@@ -50,7 +51,7 @@ class Explore extends BaseCommand {
if (!args.length) {
this.npm.output(`\nExploring ${path}\nType 'exit' or ^D when finished\n`)
}
this.npm.log.disableProgress()
log.disableProgress()
try {
return await runScript({
...this.npm.flatOptions,
@@ -71,7 +72,7 @@ class Explore extends BaseCommand {
}
})
} finally {
this.npm.log.enableProgress()
log.enableProgress()
}
}
}
+2 -1
View File
@@ -5,6 +5,7 @@ const pacote = require('pacote')
const semver = require('semver')
const npa = require('npm-package-arg')
const { depth } = require('treeverse')
const log = require('../utils/log-shim.js')
const { readTree: getFundingInfo, normalizeFunding, isValidFunding } = require('libnpmfund')
const completion = require('../utils/completion/installed-deep.js')
@@ -68,7 +69,7 @@ class Fund extends ArboristWorkspaceCmd {
// TODO: add !workspacesEnabled option handling to libnpmfund
const fundingInfo = getFundingInfo(tree, {
...this.flatOptions,
log: this.npm.log,
log,
workspaces: this.workspaceNames,
})
+8 -8
View File
@@ -7,6 +7,7 @@ const rpj = require('read-package-json-fast')
const libexec = require('libnpmexec')
const mapWorkspaces = require('@npmcli/map-workspaces')
const PackageJson = require('@npmcli/package-json')
const log = require('../utils/log-shim.js')
const getLocationMsg = require('../exec/get-workspace-location-msg.js')
const BaseCommand = require('../base-command.js')
@@ -94,7 +95,6 @@ class Init extends BaseCommand {
const {
flatOptions,
localBin,
log,
globalBin,
} = this.npm
// this function is definitely called. But because of coverage map stuff
@@ -125,8 +125,8 @@ class Init extends BaseCommand {
}
async template (path = process.cwd()) {
this.npm.log.pause()
this.npm.log.disableProgress()
log.pause()
log.disableProgress()
const initFile = this.npm.config.get('init-module')
if (!this.npm.config.get('yes') && !this.npm.config.get('force')) {
@@ -147,17 +147,17 @@ class Init extends BaseCommand {
// XXX promisify init-package-json
await new Promise((res, rej) => {
initJson(path, initFile, this.npm.config, (er, data) => {
this.npm.log.resume()
this.npm.log.enableProgress()
this.npm.log.silly('package data', data)
log.resume()
log.enableProgress()
log.silly('package data', data)
if (er && er.message === 'canceled') {
this.npm.log.warn('init', 'canceled')
log.warn('init', 'canceled')
return res()
}
if (er) {
rej(er)
} else {
this.npm.log.info('init', 'written successfully')
log.info('init', 'written successfully')
res(data)
}
})
+3 -3
View File
@@ -3,7 +3,7 @@ const fs = require('fs')
const util = require('util')
const readdir = util.promisify(fs.readdir)
const reifyFinish = require('../utils/reify-finish.js')
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const { resolve, join } = require('path')
const Arborist = require('@npmcli/arborist')
const runScript = require('@npmcli/run-script')
@@ -118,7 +118,7 @@ class Install extends ArboristWorkspaceCmd {
checks.checkEngine(npmManifest, npmManifest.version, process.version)
} catch (e) {
if (forced) {
this.npm.log.warn(
log.warn(
'install',
/* eslint-disable-next-line max-len */
`Forcing global npm install with incompatible version ${npmManifest.version} into node ${process.version}`
@@ -147,7 +147,7 @@ class Install extends ArboristWorkspaceCmd {
const opts = {
...this.npm.flatOptions,
log: this.npm.log,
log,
auditLevel: null,
path: where,
add: args,
+6 -5
View File
@@ -7,6 +7,7 @@ const Arborist = require('@npmcli/arborist')
const npa = require('npm-package-arg')
const rpj = require('read-package-json-fast')
const semver = require('semver')
const log = require('../utils/log-shim.js')
const reifyFinish = require('../utils/reify-finish.js')
@@ -68,7 +69,7 @@ class Link extends ArboristWorkspaceCmd {
const globalOpts = {
...this.npm.flatOptions,
path: globalTop,
log: this.npm.log,
log,
global: true,
prune: false,
}
@@ -117,7 +118,7 @@ class Link extends ArboristWorkspaceCmd {
const localArb = new Arborist({
...this.npm.flatOptions,
prune: false,
log: this.npm.log,
log,
path: this.npm.prefix,
save,
})
@@ -125,7 +126,7 @@ class Link extends ArboristWorkspaceCmd {
...this.npm.flatOptions,
prune: false,
path: this.npm.prefix,
log: this.npm.log,
log,
add: names.map(l => `file:${resolve(globalTop, 'node_modules', l)}`),
save,
workspaces: this.workspaceNames,
@@ -142,12 +143,12 @@ class Link extends ArboristWorkspaceCmd {
const arb = new Arborist({
...this.npm.flatOptions,
path: globalTop,
log: this.npm.log,
log,
global: true,
})
await arb.reify({
add,
log: this.npm.log,
log,
})
await reifyFinish(this.npm, arb)
}
+1 -1
View File
@@ -1,6 +1,6 @@
const log = require('npmlog')
const getAuth = require('npm-registry-fetch/auth.js')
const npmFetch = require('npm-registry-fetch')
const log = require('../utils/log-shim')
const BaseCommand = require('../base-command.js')
class Logout extends BaseCommand {
+1 -2
View File
@@ -1,8 +1,7 @@
const log = require('npmlog')
const npa = require('npm-package-arg')
const npmFetch = require('npm-registry-fetch')
const pacote = require('pacote')
const log = require('../utils/log-shim')
const otplease = require('../utils/otplease.js')
const readLocalPkgName = require('../utils/read-package-name.js')
const BaseCommand = require('../base-command.js')
+3 -6
View File
@@ -1,14 +1,11 @@
const util = require('util')
const log = require('npmlog')
const pacote = require('pacote')
const libpack = require('libnpmpack')
const npa = require('npm-package-arg')
const path = require('path')
const log = require('../utils/log-shim')
const { getContents, logTar } = require('../utils/tar.js')
const writeFile = util.promisify(require('fs').writeFile)
const BaseCommand = require('../base-command.js')
class Pack extends BaseCommand {
@@ -70,7 +67,7 @@ class Pack extends BaseCommand {
}
for (const tar of tarballs) {
logTar(tar, { log, unicode })
logTar(tar, { unicode })
this.npm.output(tar.filename.replace(/^@/, '').replace(/\//, '-'))
}
}
@@ -82,7 +79,7 @@ class Pack extends BaseCommand {
const useWorkspaces = args.length === 0 || args.includes('.')
if (!useWorkspaces) {
this.npm.log.warn('Ignoring workspaces for specified package(s)')
log.warn('Ignoring workspaces for specified package(s)')
return this.exec(args)
}
+1 -1
View File
@@ -1,4 +1,4 @@
const log = require('npmlog')
const log = require('../utils/log-shim')
const pingUtil = require('../utils/ping.js')
const BaseCommand = require('../base-command.js')
+3 -3
View File
@@ -1,7 +1,7 @@
const inspect = require('util').inspect
const { URL } = require('url')
const ansistyles = require('ansistyles')
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const npmProfile = require('npm-profile')
const qrcodeTerminal = require('qrcode-terminal')
const Table = require('cli-table3')
@@ -321,7 +321,7 @@ class Profile extends BaseCommand {
} else if (userInfo && userInfo.tfa) {
if (!conf.otp) {
conf.otp = await readUserInfo.otp(
'Enter one-time password from your authenticator app: '
'Enter one-time password: '
)
}
}
@@ -386,7 +386,7 @@ class Profile extends BaseCommand {
const password = await readUserInfo.password()
if (!conf.otp) {
const msg = 'Enter one-time password from your authenticator app: '
const msg = 'Enter one-time password: '
conf.otp = await readUserInfo.otp(msg)
}
+2 -1
View File
@@ -1,5 +1,6 @@
// prune extraneous packages
const Arborist = require('@npmcli/arborist')
const log = require('../utils/log-shim.js')
const reifyFinish = require('../utils/reify-finish.js')
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
@@ -14,7 +15,7 @@ class Prune extends ArboristWorkspaceCmd {
const opts = {
...this.npm.flatOptions,
path: where,
log: this.npm.log,
log,
workspaces: this.workspaceNames,
}
const arb = new Arborist(opts)
+3 -3
View File
@@ -1,5 +1,5 @@
const util = require('util')
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const semver = require('semver')
const pack = require('libnpmpack')
const libpub = require('libnpmpublish').publish
@@ -94,10 +94,10 @@ class Publish extends BaseCommand {
flatten(manifest.publishConfig, opts)
}
// note that logTar calls npmlog.notice(), so if we ARE in silent mode,
// note that logTar calls log.notice(), so if we ARE in silent mode,
// this will do nothing, but we still want it in the debuglog if it fails.
if (!json) {
logTar(pkgContents, { log, unicode })
logTar(pkgContents, { unicode })
}
if (!dryRun) {
+1 -2
View File
@@ -1,7 +1,6 @@
const log = require('npmlog')
const pacote = require('pacote')
const { URL } = require('url')
const log = require('../utils/log-shim')
const hostedFromMani = require('../utils/hosted-git-info-from-manifest.js')
const openUrl = require('../utils/open-url.js')
+1 -1
View File
@@ -3,7 +3,7 @@ const chalk = require('chalk')
const runScript = require('@npmcli/run-script')
const { isServerPackage } = runScript
const rpj = require('read-package-json-fast')
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const didYouMean = require('../utils/did-you-mean.js')
const isWindowsShell = require('../utils/is-windows-shell.js')
+1 -1
View File
@@ -1,7 +1,7 @@
const Minipass = require('minipass')
const Pipeline = require('minipass-pipeline')
const libSearch = require('libnpmsearch')
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const formatPackageStream = require('../search/format-package-stream.js')
const packageFilter = require('../search/package-filter.js')
+1 -1
View File
@@ -1,7 +1,7 @@
const { resolve } = require('path')
const log = require('npmlog')
const rpj = require('read-package-json-fast')
const PackageJson = require('@npmcli/package-json')
const log = require('../utils/log-shim')
const BaseCommand = require('../base-command.js')
class SetScript extends BaseCommand {
+1 -2
View File
@@ -1,8 +1,7 @@
const { resolve, basename } = require('path')
const { unlink } = require('fs').promises
const Arborist = require('@npmcli/arborist')
const log = require('npmlog')
const log = require('../utils/log-shim')
const BaseCommand = require('../base-command.js')
class Shrinkwrap extends BaseCommand {
static description = 'Lock down dependency versions for publication'
+1 -2
View File
@@ -1,7 +1,6 @@
const fetch = require('npm-registry-fetch')
const log = require('npmlog')
const npa = require('npm-package-arg')
const log = require('../utils/log-shim')
const getIdentity = require('../utils/get-identity')
const BaseCommand = require('../base-command.js')
+1 -2
View File
@@ -1,6 +1,5 @@
const log = require('npmlog')
const fetch = require('npm-registry-fetch')
const log = require('../utils/log-shim')
const getIdentity = require('../utils/get-identity.js')
const BaseCommand = require('../base-command.js')
+1 -1
View File
@@ -1,7 +1,7 @@
const Table = require('cli-table3')
const ansistyles = require('ansistyles')
const { v4: isCidrV4, v6: isCidrV6 } = require('is-cidr')
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const profile = require('npm-profile')
const otplease = require('../utils/otplease.js')
+2 -1
View File
@@ -1,4 +1,5 @@
const { resolve } = require('path')
const log = require('../utils/log-shim.js')
const Arborist = require('@npmcli/arborist')
const rpj = require('read-package-json-fast')
@@ -48,7 +49,7 @@ class Uninstall extends ArboristWorkspaceCmd {
const opts = {
...this.npm.flatOptions,
path,
log: this.npm.log,
log,
rm: args,
workspaces: this.workspaceNames,
}
+4 -4
View File
@@ -5,7 +5,7 @@ const libaccess = require('libnpmaccess')
const npmFetch = require('npm-registry-fetch')
const libunpub = require('libnpmpublish').unpublish
const readJson = util.promisify(require('read-package-json'))
const log = require('../utils/log-shim')
const otplease = require('../utils/otplease.js')
const getIdentity = require('../utils/get-identity.js')
@@ -66,8 +66,8 @@ class Unpublish extends BaseCommand {
let pkgName
let pkgVersion
this.npm.log.silly('unpublish', 'args[0]', args[0])
this.npm.log.silly('unpublish', 'spec', spec)
log.silly('unpublish', 'args[0]', args[0])
log.silly('unpublish', 'spec', spec)
if ((!spec || !spec.rawSpec) && !force) {
throw this.usageError(
@@ -92,7 +92,7 @@ class Unpublish extends BaseCommand {
}
}
this.npm.log.verbose('unpublish', manifest)
log.verbose('unpublish', manifest)
const { name, version, publishConfig } = manifest
const pkgJsonSpec = npa.resolve(name, version)
+2 -2
View File
@@ -1,7 +1,7 @@
const path = require('path')
const Arborist = require('@npmcli/arborist')
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const reifyFinish = require('../utils/reify-finish.js')
const completion = require('../utils/completion/installed-deep.js')
@@ -47,7 +47,7 @@ class Update extends ArboristWorkspaceCmd {
const arb = new Arborist({
...this.npm.flatOptions,
log: this.npm.log,
log,
path: where,
workspaces: this.workspaceNames,
})
+2 -2
View File
@@ -4,7 +4,7 @@ const color = require('ansicolors')
const columns = require('cli-columns')
const fs = require('fs')
const jsonParse = require('json-parse-even-better-errors')
const log = require('npmlog')
const log = require('../utils/log-shim.js')
const npa = require('npm-package-arg')
const { resolve } = require('path')
const formatBytes = require('../utils/format-bytes.js')
@@ -139,7 +139,7 @@ class View extends BaseCommand {
const local = /^\.@/.test(pkg) || pkg === '.'
if (!local) {
this.npm.log.warn('Ignoring workspaces for specified package(s)')
log.warn('Ignoring workspaces for specified package(s)')
return this.exec([pkg, ...args])
}
let wholePackument = false
+101 -57
View File
@@ -1,34 +1,10 @@
const EventEmitter = require('events')
const { resolve, dirname } = require('path')
const Config = require('@npmcli/config')
const log = require('npmlog')
// Patch the global fs module here at the app level
require('graceful-fs').gracefulify(require('fs'))
// TODO make this only ever load once (or unload) in tests
const procLogListener = require('./utils/proc-log-listener.js')
// Timers in progress
const timers = new Map()
// Finished timers
const timings = {}
const processOnTimeHandler = name => {
timers.set(name, Date.now())
}
const processOnTimeEndHandler = name => {
if (timers.has(name)) {
const ms = Date.now() - timers.get(name)
log.timing(name, `Completed in ${ms}ms`)
timings[name] = ms
timers.delete(name)
} else {
log.silly('timing', "Tried to end timer that doesn't exist:", name)
}
}
const { definitions, flatten, shorthands } = require('./utils/config/index.js')
const { shellouts } = require('./utils/cmd-list.js')
const usage = require('./utils/npm-usage.js')
@@ -36,9 +12,11 @@ const usage = require('./utils/npm-usage.js')
const which = require('which')
const deref = require('./utils/deref-command.js')
const setupLog = require('./utils/setup-log.js')
const cleanUpLogFiles = require('./utils/cleanup-log-files.js')
const getProjectScope = require('./utils/get-project-scope.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 replaceInfo = require('./utils/replace-info.js')
let warnedNonDashArg = false
const _load = Symbol('_load')
@@ -51,21 +29,30 @@ class Npm extends EventEmitter {
return pkg.version
}
#unloaded = false
#timers = null
#logFile = null
#display = null
constructor () {
super()
this.started = Date.now()
this.command = null
this.timings = timings
this.timers = timers
process.on('time', processOnTimeHandler)
process.on('timeEnd', processOnTimeEndHandler)
procLogListener()
process.emit('time', 'npm')
this.#logFile = new LogFile()
this.#display = new Display()
this.#timers = new Timers({
start: 'npm',
listener: (name, ms) => {
const args = ['timing', name, `Completed in ${ms}ms`]
this.#logFile.log(...args)
this.#display.log(...args)
},
})
this.config = new Config({
npmPath: dirname(__dirname),
definitions,
flatten,
shorthands,
log,
})
this[_title] = process.title
this.updateNotification = null
@@ -118,7 +105,7 @@ class Npm extends EventEmitter {
.filter(arg => /^[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]/.test(arg))
.forEach(arg => {
warnedNonDashArg = true
this.log.error(
log.error(
'arg',
'Argument starts with non-ascii dash, this is probably invalid:',
arg
@@ -165,14 +152,13 @@ class Npm extends EventEmitter {
async load () {
if (!this.loadPromise) {
process.emit('time', 'npm:load')
this.log.pause()
this.loadPromise = new Promise((resolve, reject) => {
this[_load]()
.catch(er => er)
.then(er => {
this.loadErr = er
if (!er && this.config.get('force')) {
this.log.warn('using --force', 'Recommended protections disabled.')
log.warn('using --force', 'Recommended protections disabled.')
}
process.emit('timeEnd', 'npm:load')
@@ -190,6 +176,34 @@ class Npm extends EventEmitter {
return this.config.loaded
}
// This gets called at the end of the exit handler and
// during any tests to cleanup all of our listeners
// Everything in here should be synchronous
unload () {
// Track if we've already unloaded so we dont
// write multiple timing files. This is only an
// issue in tests right now since we unload
// in both tap teardowns and the exit handler
if (this.#unloaded) {
return
}
this.#timers.off()
this.#display.off()
this.#logFile.off()
if (this.loaded && this.config.get('timing')) {
this.#timers.writeFile({
command: process.argv.slice(2),
// We used to only ever report a single log file
// so to be backwards compatible report the last logfile
// XXX: remove this in npm 9 or just keep it forever
logfile: this.logFiles[this.logFiles.length - 1],
logfiles: this.logFiles,
version: this.version,
})
}
this.#unloaded = true
}
get title () {
return this[_title]
}
@@ -204,12 +218,12 @@ class Npm extends EventEmitter {
let node
try {
node = which.sync(process.argv[0])
} catch (_) {
} catch {
// TODO should we throw here?
}
process.emit('timeEnd', 'npm:load:whichnode')
if (node && node.toUpperCase() !== process.execPath.toUpperCase()) {
this.log.verbose('node symlink', node)
log.verbose('node symlink', node)
process.execPath = node
this.config.execPath = node
}
@@ -229,19 +243,35 @@ class Npm extends EventEmitter {
const tokrev = deref(this.argv[0]) === 'token' && this.argv[1] === 'revoke'
this.title = tokrev
? 'npm token revoke' + (this.argv[2] ? ' ***' : '')
: ['npm', ...this.argv].join(' ')
: replaceInfo(['npm', ...this.argv].join(' '))
process.emit('timeEnd', 'npm:load:setTitle')
process.emit('time', 'npm:load:setupLog')
setupLog(this.config)
process.emit('timeEnd', 'npm:load:setupLog')
process.emit('time', 'npm:load:display')
this.#display.load({
// Use logColor since that is based on stderr
color: this.logColor,
progress: this.flatOptions.progress,
timing: this.config.get('timing'),
loglevel: this.config.get('loglevel'),
unicode: this.config.get('unicode'),
heading: this.config.get('heading'),
})
process.emit('timeEnd', 'npm:load:display')
process.env.COLOR = this.color ? '1' : '0'
process.emit('time', 'npm:load:cleanupLog')
cleanUpLogFiles(this.cache, this.config.get('logs-max'), this.log.warn)
process.emit('timeEnd', 'npm:load:cleanupLog')
process.emit('time', 'npm:load:logFile')
this.#logFile.load({
dir: resolve(this.cache, '_logs'),
logsMax: this.config.get('logs-max'),
})
log.verbose('logfile', this.#logFile.files[0])
process.emit('timeEnd', 'npm:load:logFile')
this.log.resume()
process.emit('time', 'npm:load:timers')
this.#timers.load({
dir: this.cache,
})
process.emit('timeEnd', 'npm:load:timers')
process.emit('time', 'npm:load:configScope')
const configScope = this.config.get('scope')
@@ -249,10 +279,6 @@ class Npm extends EventEmitter {
this.config.set('scope', `@${configScope}`, this.config.find('scope'))
}
process.emit('timeEnd', 'npm:load:configScope')
process.emit('time', 'npm:load:projectScope')
this.projectScope = this.config.get('scope') || getProjectScope(this.prefix)
process.emit('timeEnd', 'npm:load:projectScope')
}
get flatOptions () {
@@ -263,18 +289,35 @@ class Npm extends EventEmitter {
return flat
}
// color and logColor are a special derived values that takes into
// consideration not only the config, but whether or not we are operating
// in a tty with the associated output (stdout/stderr)
get color () {
// This is a special derived value that takes into consideration not only
// the config, but whether or not we are operating in a tty.
return this.flatOptions.color
}
get logColor () {
return this.flatOptions.logColor
}
get lockfileVersion () {
return 2
}
get log () {
return log
get unfinishedTimers () {
return this.#timers.unfinished
}
get finishedTimers () {
return this.#timers.finished
}
get started () {
return this.#timers.started
}
get logFiles () {
return this.#logFile.files
}
get cache () {
@@ -352,9 +395,10 @@ class Npm extends EventEmitter {
// output to stdout in a progress bar compatible way
output (...msg) {
this.log.clearProgress()
log.clearProgress()
// eslint-disable-next-line no-console
console.log(...msg)
this.log.showProgress()
log.showProgress()
}
}
module.exports = Npm
+3 -1
View File
@@ -1,3 +1,5 @@
const log = require('./log-shim')
// print an error or just nothing if the audit report has an error
// this is called by the audit command, and by the reify-output util
// prints a JSON version of the error if it's --json
@@ -15,7 +17,7 @@ const auditError = (npm, report) => {
const { error } = report
// ok, we care about it, then
npm.log.warn('audit', error.message)
log.warn('audit', error.message)
const { body: errBody } = error
const body = Buffer.isBuffer(errBody) ? errBody.toString() : errBody
if (npm.flatOptions.json) {
-35
View File
@@ -1,35 +0,0 @@
// module to clean out the old log files in cache/_logs
// this is a best-effort attempt. if a rm fails, we just
// log a message about it and move on. We do return a
// Promise that succeeds when we've tried to delete everything,
// just for the benefit of testing this function properly.
const { resolve } = require('path')
const rimraf = require('rimraf')
const glob = require('glob')
module.exports = (cache, max, warn) => {
return new Promise(done => {
glob(resolve(cache, '_logs', '*-debug.log'), (er, files) => {
if (er) {
return done()
}
let pending = files.length - max
if (pending <= 0) {
return done()
}
for (let i = 0; i < files.length - max; i++) {
rimraf(files[i], er => {
if (er) {
warn('log', 'failed to remove log file', files[i])
}
if (--pending === 0) {
done()
}
})
}
})
})
}
+15 -5
View File
@@ -472,7 +472,10 @@ define('color', {
flatten (key, obj, flatOptions) {
flatOptions.color = !obj.color ? false
: obj.color === 'always' ? true
: process.stdout.isTTY
: !!process.stdout.isTTY
flatOptions.logColor = !obj.color ? false
: obj.color === 'always' ? true
: !!process.stderr.isTTY
},
})
@@ -1211,8 +1214,8 @@ define('loglevel', {
'silly',
],
description: `
What level of logs to report. On failure, *all* logs are written to
\`npm-debug.log\` in the current working directory.
What level of logs to report. All logs are written to a debug log,
with the path to that file printed if the execution of a command fails.
Any logs of a higher level than the setting are shown. The default is
"notice".
@@ -1533,6 +1536,10 @@ define('progress', {
Set to \`false\` to suppress the progress bar.
`,
flatten (key, obj, flatOptions) {
flatOptions.progress = !obj.progress ? false
: !!process.stderr.isTTY && process.env.TERM !== 'dumb'
},
})
define('proxy', {
@@ -1681,7 +1688,7 @@ define('save-peer', {
default: false,
type: Boolean,
description: `
Save installed packages. to a package.json file as \`peerDependencies\`
Save installed packages to a package.json file as \`peerDependencies\`
`,
flatten (key, obj, flatOptions) {
if (!obj[key]) {
@@ -1782,7 +1789,10 @@ define('scope', {
`,
flatten (key, obj, flatOptions) {
const value = obj[key]
flatOptions.projectScope = value && !/^@/.test(value) ? `@${value}` : value
const scope = value && !/^@/.test(value) ? `@${value}` : value
flatOptions.scope = scope
// projectScope is kept for compatibility with npm-registry-fetch
flatOptions.projectScope = scope
},
})
+1 -1
View File
@@ -1,6 +1,6 @@
// de-reference abbreviations and shorthands into canonical command name
const { aliases, cmdList, plumbing } = require('../utils/cmd-list.js')
const { aliases, cmdList, plumbing } = require('./cmd-list.js')
const aliasNames = Object.keys(aliases)
const fullList = cmdList.concat(aliasNames).filter(c => !plumbing.includes(c))
const abbrev = require('abbrev')
+119
View File
@@ -0,0 +1,119 @@
const { inspect } = require('util')
const npmlog = require('npmlog')
const log = require('./log-shim.js')
const { explain } = require('./explain-eresolve.js')
const _logHandler = Symbol('logHandler')
const _eresolveWarn = Symbol('eresolveWarn')
const _log = Symbol('log')
const _npmlog = Symbol('npmlog')
class Display {
constructor () {
// pause by default until config is loaded
this.on()
log.pause()
}
on () {
process.on('log', this[_logHandler])
}
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()
}
load (config) {
const {
color,
timing,
loglevel,
unicode,
progress,
heading = 'npm',
} = config
// XXX: decouple timing from loglevel
if (timing && loglevel === 'notice') {
log.level = 'timing'
} else {
log.level = loglevel
}
log.heading = heading
if (color) {
log.enableColor()
} else {
log.disableColor()
}
if (unicode) {
log.enableUnicode()
} else {
log.disableUnicode()
}
// if it's more than error, don't show progress
const silent = log.levels[log.level] > log.levels.error
if (progress && !silent) {
log.enableProgress()
} else {
log.disableProgress()
}
// Resume displaying logs now that we have config
log.resume()
}
log (...args) {
this[_logHandler](...args)
}
[_logHandler] = (level, ...args) => {
try {
this[_log](level, ...args)
} catch (ex) {
try {
// if it crashed once, it might again!
this[_npmlog]('verbose', `attempt to log ${inspect(args)} crashed`, ex)
} catch (ex2) {
// eslint-disable-next-line no-console
console.error(`attempt to log ${inspect(args)} crashed`, ex, ex2)
}
}
}
[_log] (...args) {
return this[_eresolveWarn](...args) || this[_npmlog](...args)
}
// 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)
}
// 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, log.useColor(), 2))
// Return true to short circuit other log in chain
return true
}
}
}
module.exports = Display
+6 -3
View File
@@ -1,9 +1,9 @@
const { format } = require('util')
const { resolve } = require('path')
const nameValidator = require('validate-npm-package-name')
const npmlog = require('npmlog')
const replaceInfo = require('./replace-info.js')
const { report } = require('./explain-eresolve.js')
const log = require('./log-shim')
module.exports = (er, npm) => {
const short = []
@@ -20,7 +20,10 @@ module.exports = (er, npm) => {
case 'ERESOLVE':
short.push(['ERESOLVE', er.message])
detail.push(['', ''])
detail.push(['', report(er, npm.color, resolve(npm.cache, 'eresolve-report.txt'))])
// XXX(display): error messages are logged so we use the logColor since that is based
// on stderr. This should be handled solely by the display layer so it could also be
// printed to stdout if necessary.
detail.push(['', report(er, !!npm.logColor, resolve(npm.cache, 'eresolve-report.txt'))])
break
case 'ENOLOCK': {
@@ -61,7 +64,7 @@ module.exports = (er, npm) => {
if (!isWindows && (isCachePath || isCacheDest)) {
// user probably doesn't need this, but still add it to the debug log
npmlog.verbose(er.stack)
log.verbose(er.stack)
short.push([
'',
[
+76 -129
View File
@@ -1,119 +1,108 @@
const os = require('os')
const path = require('path')
const writeFileAtomic = require('write-file-atomic')
const mkdirp = require('mkdirp-infer-owner')
const fs = require('graceful-fs')
const log = require('./log-shim.js')
const errorMessage = require('./error-message.js')
const replaceInfo = require('./replace-info.js')
const messageText = msg => msg.map(line => line.slice(1).join(' ')).join('\n')
let npm = null // set by the cli
let exitHandlerCalled = false
let logFileName
let npm // set by the cli
let wroteLogFile = false
const getLogFile = () => {
// we call this multiple times, so we need to treat it as a singleton because
// the date is part of the name
if (!logFileName) {
logFileName = path.resolve(
npm.config.get('cache'),
'_logs',
new Date().toISOString().replace(/[.:]/g, '_') + '-debug.log'
)
}
return logFileName
}
let showLogFileMessage = 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')
npm.log.disableProgress()
for (const [name, timers] of npm.timers) {
npm.log.verbose('unfinished npm timer', name, timers)
}
if (npm.config.loaded && npm.config.get('timing')) {
try {
const file = path.resolve(npm.config.get('cache'), '_timing.json')
const dir = path.dirname(npm.config.get('cache'))
mkdirp.sync(dir)
const hasNpm = !!npm
const hasLoadedNpm = hasNpm && npm.config.loaded
fs.appendFileSync(
file,
JSON.stringify({
command: process.argv.slice(2),
logfile: getLogFile(),
version: npm.version,
...npm.timings,
}) + '\n'
)
const st = fs.lstatSync(path.dirname(npm.config.get('cache')))
fs.chownSync(dir, st.uid, st.gid)
fs.chownSync(file, st.uid, st.gid)
} catch (ex) {
// ignore
// Unfinished timers can be read before config load
if (hasNpm) {
for (const [name, timer] of npm.unfinishedTimers) {
log.verbose('unfinished npm timer', name, timer)
}
}
if (!code) {
npm.log.info('ok')
log.info('ok')
} else {
npm.log.verbose('code', code)
log.verbose('code', code)
}
if (!exitHandlerCalled) {
process.exitCode = code || 1
npm.log.error('', 'Exit handler never called!')
log.error('', 'Exit handler never called!')
console.error('')
npm.log.error('', 'This is an error with npm itself. Please report this error at:')
npm.log.error('', ' <https://github.com/npm/cli/issues>')
// TODO this doesn't have an npm.config.loaded guard
writeLogFile()
log.error('', 'This is an error with npm itself. Please report this error at:')
log.error('', ' <https://github.com/npm/cli/issues>')
showLogFileMessage = true
}
// In timing mode we always write the log file
if (npm.config.loaded && npm.config.get('timing') && !wroteLogFile) {
writeLogFile()
// In timing mode we always show the log file message
if (hasLoadedNpm && npm.config.get('timing')) {
showLogFileMessage = true
}
if (wroteLogFile) {
// npm must be loaded to know where the log file was written
if (showLogFileMessage && hasLoadedNpm) {
// just a line break
if (npm.log.levels[npm.log.level] <= npm.log.levels.error) {
if (log.levels[log.level] <= log.levels.error) {
console.error('')
}
npm.log.error(
log.error(
'',
['A complete log of this run can be found in:', ' ' + getLogFile()].join('\n')
[
'A complete log of this run can be found in:',
...npm.logFiles.map(f => ' ' + f),
].join('\n')
)
}
// This removes any listeners npm setup and writes files if necessary
// This is mostly used for tests to avoid max listener warnings
if (hasLoadedNpm) {
npm.unload()
}
// these are needed for the tests to have a clean slate in each test case
exitHandlerCalled = false
wroteLogFile = false
showLogFileMessage = false
})
const exitHandler = err => {
npm.log.disableProgress()
if (!npm.config.loaded) {
exitHandlerCalled = true
log.disableProgress()
const hasNpm = !!npm
const hasLoadedNpm = hasNpm && npm.config.loaded
if (!hasNpm) {
err = err || new Error('Exit prior to setting npm in exit handler')
console.error(err.stack || err.message)
return process.exit(1)
}
if (!hasLoadedNpm) {
err = err || new Error('Exit prior to config file resolving.')
console.error(err.stack || err.message)
}
// only show the notification if it finished.
if (typeof npm.updateNotification === 'string') {
const { level } = npm.log
npm.log.level = 'notice'
npm.log.notice('', npm.updateNotification)
npm.log.level = level
const { level } = log
log.level = 'notice'
log.notice('', npm.updateNotification)
log.level = level
}
exitHandlerCalled = true
let exitCode
let noLog
let noLogMessage
if (err) {
exitCode = 1
@@ -125,13 +114,13 @@ const exitHandler = err => {
const quietShellout = isShellout && typeof err.code === 'number' && err.code
if (quietShellout) {
exitCode = err.code
noLog = true
noLogMessage = true
} else if (typeof err === 'string') {
noLog = true
npm.log.error('', err)
log.error('', err)
noLogMessage = true
} else if (!(err instanceof Error)) {
noLog = true
npm.log.error('weird error', err)
log.error('weird error', err)
noLogMessage = true
} else {
if (!err.code) {
const matchErrorCode = err.message.match(/^(?:Error: )?(E[A-Z]+)/)
@@ -141,31 +130,30 @@ const exitHandler = err => {
for (const k of ['type', 'stack', 'statusCode', 'pkgid']) {
const v = err[k]
if (v) {
npm.log.verbose(k, replaceInfo(v))
log.verbose(k, replaceInfo(v))
}
}
npm.log.verbose('cwd', process.cwd())
const args = replaceInfo(process.argv)
npm.log.verbose('', os.type() + ' ' + os.release())
npm.log.verbose('argv', args.map(JSON.stringify).join(' '))
npm.log.verbose('node', process.version)
npm.log.verbose('npm ', 'v' + npm.version)
log.verbose('cwd', process.cwd())
log.verbose('', os.type() + ' ' + os.release())
log.verbose('argv', args.map(JSON.stringify).join(' '))
log.verbose('node', process.version)
log.verbose('npm ', 'v' + npm.version)
for (const k of ['code', 'syscall', 'file', 'path', 'dest', 'errno']) {
const v = err[k]
if (v) {
npm.log.error(k, v)
log.error(k, v)
}
}
const msg = errorMessage(err, npm)
for (const errline of [...msg.summary, ...msg.detail]) {
npm.log.error(...errline)
log.error(...errline)
}
if (npm.config.loaded && npm.config.get('json')) {
if (hasLoadedNpm && npm.config.get('json')) {
const error = {
error: {
code: err.code,
@@ -183,17 +171,12 @@ const exitHandler = err => {
}
}
}
npm.log.verbose('exit', exitCode || 0)
if (npm.log.level === 'silent') {
noLog = true
}
log.verbose('exit', exitCode || 0)
// noLog is true if there was an error, including if config wasn't loaded, so
// this doesn't need a config.loaded guard
if (exitCode && !noLog) {
writeLogFile()
}
showLogFileMessage = log.level === 'silent' || noLogMessage
? false
: !!exitCode
// explicitly call process.exit now so we don't hang on things like the
// update notifier, also flush stdout beforehand because process.exit doesn't
@@ -201,42 +184,6 @@ const exitHandler = err => {
process.stdout.write('', () => process.exit(exitCode))
}
const messageText = msg => msg.map(line => line.slice(1).join(' ')).join('\n')
const writeLogFile = () => {
try {
let logOutput = ''
npm.log.record.forEach(m => {
const p = [m.id, m.level]
if (m.prefix) {
p.push(m.prefix)
}
const pref = p.join(' ')
m.message
.trim()
.split(/\r?\n/)
.map(line => (pref + ' ' + line).trim())
.forEach(line => {
logOutput += line + os.EOL
})
})
const file = getLogFile()
const dir = path.dirname(file)
mkdirp.sync(dir)
writeFileAtomic.sync(file, logOutput)
const st = fs.lstatSync(path.dirname(npm.config.get('cache')))
fs.chownSync(dir, st.uid, st.gid)
fs.chownSync(file, st.uid, st.gid)
// truncate once it's been written.
npm.log.record.length = 0
wroteLogFile = true
} catch (ex) {}
}
module.exports = exitHandler
module.exports.setNpm = n => {
npm = n
-19
View File
@@ -1,19 +0,0 @@
const { resolve } = require('path')
module.exports = prefix => {
try {
const { name } = require(resolve(prefix, 'package.json'))
if (!name || typeof name !== 'string') {
return ''
}
const split = name.split('/')
if (split.length < 2) {
return ''
}
const scope = split[0]
return /^@/.test(scope) ? scope : ''
} catch (er) {
return ''
}
}
+245
View File
@@ -0,0 +1,245 @@
const os = require('os')
const path = require('path')
const { format, promisify } = require('util')
const rimraf = promisify(require('rimraf'))
const glob = promisify(require('glob'))
const MiniPass = require('minipass')
const fsMiniPass = require('fs-minipass')
const log = require('./log-shim')
const withChownSync = require('./with-chown-sync')
const _logHandler = Symbol('logHandler')
const _formatLogItem = Symbol('formatLogItem')
const _getLogFilePath = Symbol('getLogFilePath')
const _openLogFile = Symbol('openLogFile')
const _cleanLogs = Symbol('cleanlogs')
const _endStream = Symbol('endStream')
const _isBuffered = Symbol('isBuffered')
class LogFiles {
// If we write multiple log files we want them all to have the same
// identifier for sorting and matching purposes
#logId = null
// Default to a plain minipass stream so we can buffer
// initial writes before we know the cache location
#logStream = null
// We cap log files at a certain number of log events per file.
// Note that each log event can write more than one line to the
// file. Then we rotate log files once this number of events is reached
#MAX_LOGS_PER_FILE = null
// Now that we write logs continuously we need to have a backstop
// here for infinite loops that still log. This is also partially handled
// by the config.get('max-files') option, but this is a failsafe to
// prevent runaway log file creation
#MAX_LOG_FILES_PER_PROCESS = null
#fileLogCount = 0
#totalLogCount = 0
#dir = null
#logsMax = null
#files = []
constructor ({
maxLogsPerFile = 50_000,
maxFilesPerProcess = 5,
} = {}) {
this.#logId = LogFiles.logId(new Date())
this.#MAX_LOGS_PER_FILE = maxLogsPerFile
this.#MAX_LOG_FILES_PER_PROCESS = maxFilesPerProcess
this.on()
}
static logId (d) {
return d.toISOString().replace(/[.:]/g, '_')
}
static fileName (prefix, suffix) {
return `${prefix}-debug-${suffix}.log`
}
static format (count, level, title, ...args) {
let prefix = `${count} ${level}`
if (title) {
prefix += ` ${title}`
}
return format(...args)
.split(/\r?\n/)
.reduce((lines, line) =>
lines += prefix + (line ? ' ' : '') + line + os.EOL,
''
)
}
on () {
this.#logStream = new MiniPass()
process.on('log', this[_logHandler])
}
off () {
process.off('log', this[_logHandler])
this[_endStream]()
}
load ({ dir, logsMax } = {}) {
this.#dir = dir
this.#logsMax = logsMax
// Log stream has already ended
if (!this.#logStream) {
return
}
// Pipe our initial stream to our new file stream and
// set that as the new log logstream for future writes
const initialFile = this[_openLogFile]()
if (initialFile) {
this.#logStream = this.#logStream.pipe(initialFile)
}
// Kickoff cleaning process. This is async but it wont delete
// our next log file since it deletes oldest first. Return the
// result so it can be awaited in tests
return this[_cleanLogs]()
}
log (...args) {
this[_logHandler](...args)
}
get files () {
return this.#files
}
get [_isBuffered] () {
return this.#logStream instanceof MiniPass
}
[_endStream] (output) {
if (this.#logStream) {
this.#logStream.end(output)
this.#logStream = null
}
}
[_logHandler] = (level, ...args) => {
// Ignore pause and resume events since we
// write everything to the log file
if (level === 'pause' || level === 'resume') {
return
}
// If the stream is ended then do nothing
if (!this.#logStream) {
return
}
const logOutput = this[_formatLogItem](level, ...args)
if (this[_isBuffered]) {
// Cant do anything but buffer the output if we dont
// have a file stream yet
this.#logStream.write(logOutput)
return
}
// Open a new log file if we've written too many logs to this one
if (this.#fileLogCount >= this.#MAX_LOGS_PER_FILE) {
// Write last chunk to the file and close it
this[_endStream](logOutput)
if (this.#files.length >= this.#MAX_LOG_FILES_PER_PROCESS) {
// but if its way too many then we just stop listening
this.off()
} else {
// otherwise we are ready for a new file for the next event
this.#logStream = this[_openLogFile]()
}
} else {
this.#logStream.write(logOutput)
}
}
[_formatLogItem] (...args) {
this.#fileLogCount += 1
return LogFiles.format(this.#totalLogCount++, ...args)
}
[_getLogFilePath] (prefix, suffix) {
return path.resolve(this.#dir, LogFiles.fileName(prefix, suffix))
}
[_openLogFile] () {
// Count in filename will be 0 indexed
const count = this.#files.length
// Pad with zeros so that our log files are always sorted properly
// We never want to write files ending in `-9.log` and `-10.log` because
// log file cleaning is done by deleting the oldest so in this example
// `-10.log` would be deleted next
const countDigits = this.#MAX_LOG_FILES_PER_PROCESS.toString().length
try {
const logStream = withChownSync(
this[_getLogFilePath](this.#logId, count.toString().padStart(countDigits, '0')),
// Some effort was made to make the async, but we need to write logs
// during process.on('exit') which has to be synchronous. So in order
// to never drop log messages, it is easiest to make it sync all the time
// and this was measured to be about 1.5% slower for 40k lines of output
(f) => new fsMiniPass.WriteStreamSync(f, { flags: 'a' })
)
if (count > 0) {
// Reset file log count if we are opening
// after our first file
this.#fileLogCount = 0
}
this.#files.push(logStream.path)
return logStream
} catch (e) {
// XXX: do something here for errors?
// log to display only?
return null
}
}
async [_cleanLogs] () {
// module to clean out the old log files
// this is a best-effort attempt. if a rm fails, we just
// log a message about it and move on. We do return a
// Promise that succeeds when we've tried to delete everything,
// just for the benefit of testing this function properly.
if (typeof this.#logsMax !== 'number') {
return
}
// Add 1 to account for the current log file and make
// minimum config 0 so current log file is never deleted
// XXX: we should make a separate documented option to
// disable log file writing
const max = Math.max(this.#logsMax, 0) + 1
try {
const files = await glob(this[_getLogFilePath]('*', '*'))
const toDelete = files.length - max
if (toDelete <= 0) {
return
}
log.silly('logfile', `start cleaning logs, removing ${toDelete} files`)
for (const file of files.slice(0, toDelete)) {
try {
await rimraf(file)
} catch (e) {
log.warn('logfile', 'error removing log file', file, e)
}
}
} catch (e) {
log.warn('logfile', 'error cleaning log files', e)
}
}
}
module.exports = LogFiles
+59
View File
@@ -0,0 +1,59 @@
const NPMLOG = require('npmlog')
const PROCLOG = require('proc-log')
// Sets getter and optionally a setter
// otherwise setting should throw
const accessors = (obj, set) => (k) => ({
get: () => obj[k],
set: set ? (v) => (obj[k] = v) : () => {
throw new Error(`Cant set ${k}`)
},
})
// Set the value to a bound function on the object
const value = (obj) => (k) => ({
value: (...args) => obj[k].apply(obj, args),
})
const properties = {
// npmlog getters/setters
level: accessors(NPMLOG, true),
heading: accessors(NPMLOG, true),
levels: accessors(NPMLOG),
gauge: accessors(NPMLOG),
stream: accessors(NPMLOG),
tracker: accessors(NPMLOG),
progressEnabled: accessors(NPMLOG),
// npmlog methods
useColor: value(NPMLOG),
enableColor: value(NPMLOG),
disableColor: value(NPMLOG),
enableUnicode: value(NPMLOG),
disableUnicode: value(NPMLOG),
enableProgress: value(NPMLOG),
disableProgress: value(NPMLOG),
clearProgress: value(NPMLOG),
showProgress: value(NPMLOG),
newItem: value(NPMLOG),
newGroup: value(NPMLOG),
// proclog methods
notice: value(PROCLOG),
error: value(PROCLOG),
warn: value(PROCLOG),
info: value(PROCLOG),
verbose: value(PROCLOG),
http: value(PROCLOG),
silly: value(PROCLOG),
pause: value(PROCLOG),
resume: value(PROCLOG),
}
const descriptors = Object.entries(properties).reduce((acc, [k, v]) => {
acc[k] = { enumerable: true, ...v(k) }
return acc
}, {})
// Create an object with the allowed properties rom npm log and all
// the logging methods from proc log
// XXX: this should go away and requires of this should be replaced with proc-log + new display
module.exports = Object.freeze(Object.defineProperties({}, descriptors))
-22
View File
@@ -1,22 +0,0 @@
const log = require('npmlog')
const { inspect } = require('util')
module.exports = () => {
process.on('log', (level, ...args) => {
try {
log[level](...args)
} catch (ex) {
try {
// if it crashed once, it might again!
log.verbose(`attempt to log ${inspect([level, ...args])} crashed`, ex)
} catch (ex2) {
console.error(`attempt to log ${inspect([level, ...args])} crashed`, ex)
}
}
})
}
// for tests
/* istanbul ignore next */
module.exports.reset = () => {
process.removeAllListeners('log')
}
+1 -1
View File
@@ -1,4 +1,4 @@
const log = require('npmlog')
const log = require('./log-shim.js')
let pulseTimer = null
const withPromise = async (promise) => {
+7 -7
View File
@@ -1,7 +1,7 @@
const { promisify } = require('util')
const readAsync = promisify(require('read'))
const userValidate = require('npm-user-validate')
const log = require('npmlog')
const log = require('./log-shim.js')
exports.otp = readOTP
exports.password = readPassword
@@ -40,30 +40,30 @@ function readPassword (msg = passwordPrompt, password, isRetry) {
.then((password) => readPassword(msg, password, true))
}
function readUsername (msg = usernamePrompt, username, opts = {}, isRetry) {
function readUsername (msg = usernamePrompt, username, isRetry) {
if (isRetry && username) {
const error = userValidate.username(username)
if (error) {
opts.log && opts.log.warn(error.message)
log.warn(error.message)
} else {
return Promise.resolve(username.trim())
}
}
return read({ prompt: msg, default: username || '' })
.then((username) => readUsername(msg, username, opts, true))
.then((username) => readUsername(msg, username, true))
}
function readEmail (msg = emailPrompt, email, opts = {}, isRetry) {
function readEmail (msg = emailPrompt, email, isRetry) {
if (isRetry && email) {
const error = userValidate.email(email)
if (error) {
opts.log && opts.log.warn(error.message)
log.warn(error.message)
} else {
return email.trim()
}
}
return read({ prompt: msg, default: email || '' })
.then((username) => readEmail(msg, username, opts, true))
.then((username) => readEmail(msg, username, true))
}
+1 -1
View File
@@ -9,7 +9,7 @@
// found 37 vulnerabilities (5 low, 7 moderate, 25 high)
// run `npm audit fix` to fix them, or `npm audit` for details
const log = require('npmlog')
const log = require('./log-shim.js')
const { depth } = require('treeverse')
const ms = require('ms')
const auditReport = require('npm-audit-report')
-66
View File
@@ -1,66 +0,0 @@
// module to set the appropriate log settings based on configs
// returns a boolean to say whether we should enable color on
// stdout or not.
//
// 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.
const log = require('npmlog')
const { explain } = require('./explain-eresolve.js')
module.exports = (config) => {
const color = config.get('color')
const { warn } = log
const stdoutTTY = process.stdout.isTTY
const stderrTTY = process.stderr.isTTY
const dumbTerm = process.env.TERM === 'dumb'
const stderrNotDumb = stderrTTY && !dumbTerm
// this logic is duplicated in the config 'color' flattener
const enableColorStderr = color === 'always' ? true
: color === false ? false
: stderrTTY
const enableColorStdout = color === 'always' ? true
: color === false ? false
: stdoutTTY
log.warn = (heading, ...args) => {
if (heading === 'ERESOLVE' && args[1] && typeof args[1] === 'object') {
warn(heading, args[0])
return warn('', explain(args[1], enableColorStdout, 2))
}
return warn(heading, ...args)
}
if (config.get('timing') && config.get('loglevel') === 'notice') {
log.level = 'timing'
} else {
log.level = config.get('loglevel')
}
log.heading = config.get('heading') || 'npm'
if (enableColorStderr) {
log.enableColor()
} else {
log.disableColor()
}
if (config.get('unicode')) {
log.enableUnicode()
} else {
log.disableUnicode()
}
// if it's more than error, don't show progress
const quiet = log.levels[log.level] > log.levels.error
if (config.get('progress') && stderrNotDumb && !quiet) {
log.enableProgress()
} else {
log.disableProgress()
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
const tar = require('tar')
const ssri = require('ssri')
const npmlog = require('npmlog')
const log = require('./log-shim')
const formatBytes = require('./format-bytes.js')
const columnify = require('columnify')
const localeCompare = require('@isaacs/string-locale-compare')('en', {
@@ -9,7 +9,7 @@ const localeCompare = require('@isaacs/string-locale-compare')('en', {
})
const logTar = (tarball, opts = {}) => {
const { unicode = false, log = npmlog } = opts
const { unicode = false } = opts
log.notice('')
log.notice('', `${unicode ? '📦 ' : 'package:'} ${tarball.name}@${tarball.version}`)
log.notice('=== Tarball Contents ===')
+111
View File
@@ -0,0 +1,111 @@
const EE = require('events')
const path = require('path')
const fs = require('graceful-fs')
const log = require('./log-shim')
const withChownSync = require('./with-chown-sync.js')
const _timeListener = Symbol('timeListener')
const _timeEndListener = Symbol('timeEndListener')
const _init = Symbol('init')
// This is an event emiiter but on/off
// only listen on a single internal event that gets
// emitted whenever a timer ends
class Timers extends EE {
#unfinished = new Map()
#finished = {}
#onTimeEnd = Symbol('onTimeEnd')
#dir = null
#initialListener = null
#initialTimer = null
constructor ({ listener = null, start = 'npm' } = {}) {
super()
this.#initialListener = listener
this.#initialTimer = start
this[_init]()
}
get unfinished () {
return this.#unfinished
}
get finished () {
return this.#finished
}
[_init] () {
this.on()
if (this.#initialListener) {
this.on(this.#initialListener)
}
process.emit('time', this.#initialTimer)
this.started = this.#unfinished.get(this.#initialTimer)
}
on (listener) {
if (listener) {
super.on(this.#onTimeEnd, listener)
} else {
process.on('time', this[_timeListener])
process.on('timeEnd', this[_timeEndListener])
}
}
off (listener) {
if (listener) {
super.off(this.#onTimeEnd, listener)
} else {
this.removeAllListeners(this.#onTimeEnd)
process.off('time', this[_timeListener])
process.off('timeEnd', this[_timeEndListener])
}
}
load ({ dir }) {
this.#dir = dir
}
writeFile (fileData) {
try {
const globalStart = this.started
const globalEnd = this.#finished.npm || Date.now()
const content = {
...fileData,
...this.#finished,
// add any unfinished timers with their relative start/end
unfinished: [...this.#unfinished.entries()].reduce((acc, [name, start]) => {
acc[name] = [start - globalStart, globalEnd - globalStart]
return acc
}, {}),
}
withChownSync(
path.resolve(this.#dir, '_timing.json'),
(f) =>
// we append line delimited json to this file...forever
// XXX: should we also write a process specific timing file?
// with similar rules to the debug log (max files, etc)
fs.appendFileSync(f, JSON.stringify(content) + '\n')
)
} catch (e) {
log.warn('timing', 'could not write timing file', e)
}
}
[_timeListener] = (name) => {
this.#unfinished.set(name, Date.now())
}
[_timeEndListener] = (name) => {
if (this.#unfinished.has(name)) {
const ms = Date.now() - this.#unfinished.get(name)
this.#finished[name] = ms
this.#unfinished.delete(name)
this.emit(this.#onTimeEnd, name, ms)
} else {
log.silly('timing', "Tried to end timer that doesn't exist:", name)
}
}
}
module.exports = Timers
+11 -5
View File
@@ -1,7 +1,14 @@
/* eslint-disable no-console */
const semver = require('semver')
const supported = require('../../package.json').engines.node
const knownBroken = '<6.2.0 || 9 <9.3.0'
// Keep this file compatible with all practical versions of node
// so we dont get syntax errors when trying to give the users
// a nice error message. Don't use our log handler because
// if we encounter a syntax error early on, that will never
// get displayed to the user.
const checkVersion = exports.checkVersion = version => {
const versionNoPrerelease = version.replace(/-.*$/, '')
return {
@@ -24,10 +31,9 @@ exports.checkForBrokenNode = () => {
exports.checkForUnsupportedNode = () => {
const nodejs = checkVersion(process.version)
if (nodejs.unsupported) {
const log = require('npmlog')
log.warn('npm', 'npm does not support Node.js ' + process.version)
log.warn('npm', 'You should probably upgrade to a newer version of node as we')
log.warn('npm', "can't make any promises that npm will work with this version.")
log.warn('npm', 'You can find the latest version at https://nodejs.org/')
console.error('npm does not support Node.js ' + process.version)
console.error('You should probably upgrade to a newer version of node as we')
console.error("can't make any promises that npm will work with this version.")
console.error('You can find the latest version at https://nodejs.org/')
}
}
+2 -1
View File
@@ -10,6 +10,7 @@ const { promisify } = require('util')
const stat = promisify(require('fs').stat)
const writeFile = promisify(require('fs').writeFile)
const { resolve } = require('path')
const log = require('./log-shim.js')
const isGlobalNpmUpdate = npm => {
return npm.flatOptions.global &&
@@ -61,7 +62,7 @@ const updateNotifier = async (npm, spec = 'latest') => {
// if they're currently using a prerelease, nudge to the next prerelease
// otherwise, nudge to latest.
const useColor = npm.log.useColor()
const useColor = log.useColor()
const mani = await pacote.manifest(`npm@${spec}`, {
// always prefer latest, even if doing --tag=whatever on the cmd
+1 -1
View File
@@ -1,4 +1,4 @@
const aliases = require('../utils/cmd-list').aliases
const aliases = require('./cmd-list').aliases
module.exports = function usage (cmd, txt, opt) {
const post = Object.keys(aliases).reduce(function (p, c) {
+13
View File
@@ -0,0 +1,13 @@
const mkdirp = require('mkdirp-infer-owner')
const fs = require('graceful-fs')
const path = require('path')
module.exports = (file, method) => {
const dir = path.dirname(file)
mkdirp.sync(dir)
const result = method(file)
const st = fs.lstatSync(dir)
fs.chownSync(dir, st.uid, st.gid)
fs.chownSync(file, st.uid, st.gid)
return result
}
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-ACCESS" "1" "November 2021" "" ""
.TH "NPM\-ACCESS" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-access\fR \- Set access level on published packages
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-ADDUSER" "1" "November 2021" "" ""
.TH "NPM\-ADDUSER" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-adduser\fR \- Add a registry user account
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-AUDIT" "1" "November 2021" "" ""
.TH "NPM\-AUDIT" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-audit\fR \- Run a security audit
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-BIN" "1" "November 2021" "" ""
.TH "NPM\-BIN" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-bin\fR \- Display npm bin folder
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-BUGS" "1" "November 2021" "" ""
.TH "NPM\-BUGS" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-bugs\fR \- Report bugs for a package in a web browser
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-CACHE" "1" "November 2021" "" ""
.TH "NPM\-CACHE" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-cache\fR \- Manipulates packages cache
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-CI" "1" "November 2021" "" ""
.TH "NPM\-CI" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-ci\fR \- Install a project with a clean slate
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-COMPLETION" "1" "November 2021" "" ""
.TH "NPM\-COMPLETION" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-completion\fR \- Tab Completion for npm
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-CONFIG" "1" "November 2021" "" ""
.TH "NPM\-CONFIG" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-config\fR \- Manage the npm configuration files
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-DEDUPE" "1" "November 2021" "" ""
.TH "NPM\-DEDUPE" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-dedupe\fR \- Reduce duplication in the package tree
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-DEPRECATE" "1" "November 2021" "" ""
.TH "NPM\-DEPRECATE" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-deprecate\fR \- Deprecate a version of a package
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-DIFF" "1" "November 2021" "" ""
.TH "NPM\-DIFF" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-diff\fR \- The registry diff command
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-DIST\-TAG" "1" "November 2021" "" ""
.TH "NPM\-DIST\-TAG" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-dist-tag\fR \- Modify package distribution tags
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-DOCS" "1" "November 2021" "" ""
.TH "NPM\-DOCS" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-docs\fR \- Open documentation for a package in a web browser
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-DOCTOR" "1" "November 2021" "" ""
.TH "NPM\-DOCTOR" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-doctor\fR \- Check your npm environment
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-EDIT" "1" "November 2021" "" ""
.TH "NPM\-EDIT" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-edit\fR \- Edit an installed package
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-EXEC" "1" "November 2021" "" ""
.TH "NPM\-EXEC" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-exec\fR \- Run a command from a local or remote npm package
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-EXPLAIN" "1" "November 2021" "" ""
.TH "NPM\-EXPLAIN" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-explain\fR \- Explain installed packages
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-EXPLORE" "1" "November 2021" "" ""
.TH "NPM\-EXPLORE" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-explore\fR \- Browse an installed package
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-FIND\-DUPES" "1" "November 2021" "" ""
.TH "NPM\-FIND\-DUPES" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-find-dupes\fR \- Find duplication in the package tree
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-FUND" "1" "November 2021" "" ""
.TH "NPM\-FUND" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-fund\fR \- Retrieve funding information
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-HELP\-SEARCH" "1" "November 2021" "" ""
.TH "NPM\-HELP\-SEARCH" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-help-search\fR \- Search npm help documentation
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-HELP" "1" "November 2021" "" ""
.TH "NPM\-HELP" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-help\fR \- Get help on npm
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-HOOK" "1" "November 2021" "" ""
.TH "NPM\-HOOK" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-hook\fR \- Manage registry hooks
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-INIT" "1" "November 2021" "" ""
.TH "NPM\-INIT" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-init\fR \- Create a package\.json file
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-INSTALL\-CI\-TEST" "1" "November 2021" "" ""
.TH "NPM\-INSTALL\-CI\-TEST" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-install-ci-test\fR \- Install a project with a clean slate and run tests
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-INSTALL\-TEST" "1" "November 2021" "" ""
.TH "NPM\-INSTALL\-TEST" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-install-test\fR \- Install package(s) and run tests
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-INSTALL" "1" "November 2021" "" ""
.TH "NPM\-INSTALL" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-install\fR \- Install a package
.SS Synopsis
+1 -1
View File
@@ -1,4 +1,4 @@
.TH "NPM\-LINK" "1" "November 2021" "" ""
.TH "NPM\-LINK" "1" "December 2021" "" ""
.SH "NAME"
\fBnpm-link\fR \- Symlink a package folder
.SS Synopsis
Loaded 100 of 287 files, more files were not shown because too many files have changed in this diff. Show more