diff --git a/CHANGELOG.md b/CHANGELOG.md index 0922176c6bacd..923c565ab31fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,62 @@ +## 7.2.0 (2020-12-15) + +### FEATURES + +* [`a9c4b158c`](https://github.com/npm/cli/commit/a9c4b158c46dd0d0c8d8744a97750ffd0c30cc09) + [#2342](https://github.com/npm/cli/issues/2342) + allow npm rebuild to accept a path to a module + ([@nlf](https://github.com/nlf)) + +### DEPENDENCIES + +* [`beb371800`](https://github.com/npm/cli/commit/beb371800292140bf3882253c447168a378bc154) + [#2334](https://github.com/npm/cli/issues/2334) + remove unused top level dep tough-cookie + ([@darcyclarke](https://github.com/darcyclarke)) +* [`d45e181d1`](https://github.com/npm/cli/commit/d45e181d17dd88d82b3a97f8d9cd5fa5b6230e48) + [#2335](https://github.com/npm/cli/issues/2335) + `ini@2.0.0`, `@npmcli/config@1.2.7` + ([@isaacs](https://github.com/isaacs)) +* [`ef4b18b5a`](https://github.com/npm/cli/commit/ef4b18b5a70381b264d234817cff32eeb6848a73) + [#2309](https://github.com/npm/cli/issues/2309) + `@npmcli/arborist@2.0.2` + * properly remove deps when no lockfile and package.json is present +* [`c6c013e6e`](https://github.com/npm/cli/commit/c6c013e6ebc4fe036695db1fd491eb68f3b57c68) + `readdir-scoped-modules@1.1.0` +* [`a1a2134aa`](https://github.com/npm/cli/commit/a1a2134aa9a1092493db6d6c9a729ff5203f0dd4) + remove unused sorted-object dep + ([@nlf](https://github.com/nlf)) +* [`85c2a2d31`](https://github.com/npm/cli/commit/85c2a2d318ae066fb2c161174f5aea97e18bc9c5) + [#2344](https://github.com/npm/cli/issues/2344) + remove editor dependency + ([@nlf](https://github.com/nlf)) + +### TESTING + +* [`3a6dd511c`](https://github.com/npm/cli/commit/3a6dd511c944c5f2699825a99bba1dde333a45ef) + npm edit + ([@nlf](https://github.com/nlf)) +* [`3ba5de4e7`](https://github.com/npm/cli/commit/3ba5de4e7f6c5c0f995a29844926d6ed2833addd) + [#2347](https://github.com/npm/cli/issues/2347) + npm help-search + ([@nlf](https://github.com/nlf)) +* [`6caf19f49`](https://github.com/npm/cli/commit/6caf19f491e144be3e2a1a50f492dad48b01f361) + [#2348](https://github.com/npm/cli/issues/2348) + npm help + ([@nlf](https://github.com/nlf)) +* [`cb5847e32`](https://github.com/npm/cli/commit/cb5847e3203c52062485b5de68e4f6d29b33c361) + [#2349](https://github.com/npm/cli/issues/2349) + npm hook + ([@nlf](https://github.com/nlf)) +* [`996a2f6b1`](https://github.com/npm/cli/commit/996a2f6b130d6678998a2f6a5ec97d75534d5f66) + [#2353](https://github.com/npm/cli/issues/2353) + npm org + ([@nlf](https://github.com/nlf)) +* [`8c67c38a4`](https://github.com/npm/cli/commit/8c67c38a4f476ff5be938db6b6b3ee9ac6b44db5) + [#2354](https://github.com/npm/cli/issues/2354) + npm set + ([@nlf](https://github.com/nlf)) + ## 7.1.2 (2020-12-11) ### DEPENDENCIES diff --git a/lib/config.js b/lib/config.js index ad8db4ff53496..561c31e0b3ec5 100644 --- a/lib/config.js +++ b/lib/config.js @@ -9,7 +9,7 @@ const { promisify } = require('util') const fs = require('fs') const readFile = promisify(fs.readFile) const writeFile = promisify(fs.writeFile) -const editor = promisify(require('editor')) +const { spawn } = require('child_process') const { EOL } = require('os') const ini = require('ini') @@ -138,9 +138,6 @@ const del = async key => { const edit = async () => { const { editor: e, global } = npm.flatOptions - if (!e) - throw new Error('No `editor` config or EDITOR environment variable set') - const where = global ? 'global' : 'user' const file = npm.config.data.get(where).source @@ -183,7 +180,15 @@ ${defData} `.split('\n').join(EOL) await mkdirp(dirname(file)) await writeFile(file, tmpData, 'utf8') - await editor(file, { editor: e }) + await new Promise((resolve, reject) => { + const [bin, ...args] = e.split(/\s+/) + const editor = spawn(bin, [...args, file], { stdio: 'inherit' }) + editor.on('exit', (code) => { + if (code) + return reject(new Error(`editor process exited with code: ${code}`)) + return resolve() + }) + }) } const publicVar = k => !/^(\/\/[^:]+:)?_/.test(k) diff --git a/lib/edit.js b/lib/edit.js index 43f86dfe70ed6..9ae6349262c2d 100644 --- a/lib/edit.js +++ b/lib/edit.js @@ -1,52 +1,36 @@ // npm edit // open the package folder in the $EDITOR -module.exports = edit -edit.usage = 'npm edit [/...]' +const { resolve } = require('path') +const fs = require('graceful-fs') +const { spawn } = require('child_process') +const npm = require('./npm.js') +const usageUtil = require('./utils/usage.js') +const splitPackageNames = require('./utils/split-package-names.js') -edit.completion = require('./utils/completion/installed-shallow.js') - -var npm = require('./npm.js') -var path = require('path') -var fs = require('graceful-fs') -var editor = require('editor') -var noProgressTillDone = require('./utils/no-progress-while-running').tillDone +const usage = usageUtil('edit', 'npm edit [/...]') +const completion = require('./utils/completion/installed-shallow.js') function edit (args, cb) { - var p = args[0] - if (args.length !== 1 || !p) - return cb(edit.usage) - var e = npm.config.get('editor') - if (!e) { - return cb(new Error( - "No editor set. Set the 'editor' config, or $EDITOR environ." - )) - } - p = p.split('/') - // combine scoped parts - .reduce(function (parts, part) { - if (parts.length === 0) - return [part] - - var 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') - var f = path.resolve(npm.dir, p) - fs.lstat(f, function (er) { - if (er) - return cb(er) - editor(f, { editor: e }, noProgressTillDone(function (er) { - if (er) - return cb(er) - npm.commands.rebuild(args, cb) - })) + if (args.length !== 1) + return cb(usage) + + const path = splitPackageNames(args[0]) + const dir = resolve(npm.dir, path) + + fs.lstat(dir, (err) => { + if (err) + return cb(err) + + const [bin, ...args] = npm.config.get('editor').split(/\s+/) + const editor = spawn(bin, [...args, dir], { stdio: 'inherit' }) + editor.on('exit', (code) => { + if (code) + return cb(new Error(`editor process exited with code: ${code}`)) + + npm.commands.rebuild([dir], cb) + }) }) } + +module.exports = Object.assign(edit, { completion, usage }) diff --git a/lib/help-search.js b/lib/help-search.js index ae4302e8cc2f4..c1814b4e53fc3 100644 --- a/lib/help-search.js +++ b/lib/help-search.js @@ -1,11 +1,11 @@ const fs = require('fs') const path = require('path') const npm = require('./npm.js') -const glob = require('glob') const color = require('ansicolors') const output = require('./utils/output.js') const usageUtil = require('./utils/usage.js') const { promisify } = require('util') +const glob = promisify(require('glob')) const readFile = promisify(fs.readFile) const didYouMean = require('./utils/did-you-mean.js') const { cmdList } = require('./utils/cmd-list.js') @@ -23,12 +23,17 @@ const helpSearch = async args => { const docPath = path.resolve(__dirname, '..', 'docs/content') - // XXX: make glob return a promise and remove this wrapping - const files = await new Promise((res, rej) => - glob(`${docPath}/*/*.md`, (er, files) => er ? rej(er) : res(files))) - + const files = await glob(`${docPath}/*/*.md`) const data = await readFiles(files) const results = await searchFiles(args, data, files) + // if only one result, then just show that help section. + if (results.length === 1) { + return npm.commands.help([path.basename(results[0].file, '.md')], er => { + if (er) + throw er + }) + } + const formatted = formatResults(args, results) if (!formatted.trim()) npmUsage(false) @@ -125,15 +130,6 @@ const searchFiles = async (args, data, files) => { }) } - // if only one result, then just show that help section. - if (results.length === 1) { - npm.commands.help([results[0].file.replace(/\.md$/, '')], er => { - if (er) - throw er - }) - return [] - } - // sort results by number of results found, then by number of hits // then by number of matching lines return results.sort((a, b) => @@ -147,9 +143,6 @@ const searchFiles = async (args, data, files) => { } const formatResults = (args, results) => { - if (!results) - return 'No results for ' + args.map(JSON.stringify).join(' ') - const cols = Math.min(process.stdout.columns || Infinity, 80) + 1 const out = results.map(res => { diff --git a/lib/help.js b/lib/help.js index 5f9563e1cfe06..171c52704df6c 100644 --- a/lib/help.js +++ b/lib/help.js @@ -133,7 +133,12 @@ function viewMan (man, cb) { break case 'browser': - openUrl(htmlMan(man), 'help available at the following URL', cb) + try { + var url = htmlMan(man) + } catch (err) { + return cb(err) + } + openUrl(url, 'help available at the following URL', cb) break default: diff --git a/lib/org.js b/lib/org.js index d430131f83750..b7af3f3a3022a 100644 --- a/lib/org.js +++ b/lib/org.js @@ -73,9 +73,9 @@ function orgSet (org, user, role, opts) { memDeets.org.size, memDeets.user, memDeets.role, - ]) + ].join('\t')) } else if (!opts.silent && opts.loglevel !== 'silent') - output(`Added ${memDeets.user} as ${memDeets.role} to ${memDeets.org.name}. You now ${memDeets.org.size} member${memDeets.org.size === 1 ? '' : 's'} in this org.`) + output(`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.`) return memDeets }) diff --git a/lib/rebuild.js b/lib/rebuild.js index e02c89bd79f28..ab34b7f3dfb51 100644 --- a/lib/rebuild.js +++ b/lib/rebuild.js @@ -39,16 +39,25 @@ const getFilterFn = args => { const spec = npa(arg) if (spec.type === 'tag' && spec.rawSpec === '') return spec - if (spec.type !== 'range' && spec.type !== 'version') + + if (spec.type !== 'range' && spec.type !== 'version' && spec.type !== 'directory') throw new Error('`npm rebuild` only supports SemVer version/range specifiers') + return spec }) + return node => specs.some(spec => { - const { version } = node.package + if (spec.type === 'directory') + return node.path === spec.fetchSpec + if (spec.name !== node.name) return false + if (spec.rawSpec === '' || spec.rawSpec === '*') return true + + const { version } = node.package + // TODO: add tests for a package with missing version return semver.satisfies(version, spec.fetchSpec) }) } diff --git a/lib/utils/child-path.js b/lib/utils/child-path.js deleted file mode 100644 index 38b9df1380267..0000000000000 --- a/lib/utils/child-path.js +++ /dev/null @@ -1,9 +0,0 @@ -var path = require('path') -var validate = require('aproba') -var moduleName = require('../utils/module-name.js') - -module.exports = childPath -function childPath (parentPath, child) { - validate('SO', arguments) - return path.join(parentPath, 'node_modules', moduleName(child)) -} diff --git a/lib/utils/completion/file-completion.js b/lib/utils/completion/file-completion.js deleted file mode 100644 index b32eda52df93d..0000000000000 --- a/lib/utils/completion/file-completion.js +++ /dev/null @@ -1,23 +0,0 @@ -module.exports = fileCompletion - -const mkdir = require('mkdirp') -const glob = require('glob') - -function fileCompletion (root, req, depth, cb) { - if (typeof cb !== 'function') { - cb = depth - depth = Infinity - } - mkdir(root).catch(cb).then(() => { - // can be either exactly the req, or a descendent - var pattern = root + '/{' + req + ',' + req + '/**/*}' - var opts = { mark: true, dot: true, maxDepth: depth } - glob(pattern, opts, function (er, files) { - if (er) - return cb(er) - return cb(null, (files || []).map(function (f) { - return f.substr(root.length + 1).replace(/^\/|\/$/g, '') - })) - }) - }) -} diff --git a/lib/utils/deep-sort-object.js b/lib/utils/deep-sort-object.js deleted file mode 100644 index 56f1854f1e2f6..0000000000000 --- a/lib/utils/deep-sort-object.js +++ /dev/null @@ -1,14 +0,0 @@ -var sortedObject = require('sorted-object') - -module.exports = function deepSortObject (obj) { - if (obj == null || typeof obj !== 'object') - return obj - if (obj instanceof Array) - return obj.map(deepSortObject) - - obj = sortedObject(obj) - Object.keys(obj).forEach(function (key) { - obj[key] = deepSortObject(obj[key]) - }) - return obj -} diff --git a/lib/utils/git.js b/lib/utils/git.js deleted file mode 100644 index 299302b277eea..0000000000000 --- a/lib/utils/git.js +++ /dev/null @@ -1,55 +0,0 @@ -const exec = require('child_process').execFile -const spawn = require('./spawn') -const npm = require('../npm.js') -const which = require('which') -const git = npm.config.get('git') -const log = require('npmlog') -const noProgressTillDone = require('./no-progress-while-running.js').tillDone -const { promisify } = require('util') - -exports.spawn = spawnGit -exports.exec = promisify(execGit) -exports.chainableExec = chainableExec -exports.whichAndExec = whichAndExec - -function prefixGitArgs () { - return process.platform === 'win32' ? ['-c', 'core.longpaths=true'] : [] -} - -function execGit (args, options, cb) { - log.info('git', args) - const fullArgs = prefixGitArgs().concat(args || []) - return exec(git, fullArgs, options, noProgressTillDone(cb)) -} - -function spawnGit (args, options) { - log.info('git', args) - // If we're already in a git command (eg, running test as an exec - // line in an interactive rebase) then these environment variables - // will force git to operate on the current project, instead of - // checking out/fetching/etc. whatever the user actually intends. - options.env = options.env || Object.keys(process.env) - .filter(k => !/^GIT/.test(k)) - .reduce((set, k) => { - set[k] = process.env[k] - return set - }, {}) - return spawn(git, prefixGitArgs().concat(args || []), options) -} - -function chainableExec () { - var args = Array.prototype.slice.call(arguments) - return [execGit].concat(args) -} - -function whichAndExec (args, options, cb) { - // check for git - which(git, function (err) { - if (err) { - err.code = 'ENOGIT' - return cb(err) - } - - execGit(args, options, cb) - }) -} diff --git a/lib/utils/module-name.js b/lib/utils/module-name.js deleted file mode 100644 index c58050e55e574..0000000000000 --- a/lib/utils/module-name.js +++ /dev/null @@ -1,38 +0,0 @@ -var path = require('path') - -module.exports = moduleName -module.exports.test = {} - -module.exports.test.pathToPackageName = pathToPackageName -function pathToPackageName (dir) { - if (dir == null) - return '' - if (dir === '') - return '' - var name = path.relative(path.resolve(dir, '..'), dir) - var scoped = path.relative(path.resolve(dir, '../..'), dir) - if (scoped[0] === '@') - return scoped.replace(/\\/g, '/') - return name.trim() -} - -module.exports.test.isNotEmpty = isNotEmpty -function isNotEmpty (str) { - return str != null && str !== '' -} - -var unknown = 0 -function moduleName (tree) { - if (tree.name) - return tree.name - var pkg = tree.package || tree - if (isNotEmpty(pkg.name) && typeof pkg.name === 'string') - return pkg.name.trim() - var pkgName = pathToPackageName(tree.path) - if (pkgName !== '') - return pkgName - if (tree._invalidName != null) - return tree._invalidName - tree._invalidName = '!invalid#' + (++unknown) - return tree._invalidName -} diff --git a/lib/utils/split-package-names.js b/lib/utils/split-package-names.js new file mode 100644 index 0000000000000..bb6e449bac243 --- /dev/null +++ b/lib/utils/split-package-names.js @@ -0,0 +1,23 @@ +'use strict' + +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') +} + +module.exports = splitPackageNames diff --git a/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js b/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js index 731b78518775c..c1f18af7e43dc 100644 --- a/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js +++ b/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js @@ -312,8 +312,14 @@ module.exports = cls => class IdealTreeBuilder extends cls { // Load on a new Arborist object, so the Nodes aren't the same, // or else it'll get super confusing when we change them! .then(async root => { - if (!this[_updateAll] && !this[_global] && !root.meta.loadedFromDisk) + if (!this[_updateAll] && !this[_global] && !root.meta.loadedFromDisk) { await new this.constructor(this.options).loadActual({ root }) + // even though we didn't load it from a package-lock.json FILE, + // we still loaded it "from disk", meaning we have to reset + // dep flags before assuming that any mutations were reflected. + if (root.children.size) + root.meta.loadedFromDisk = true + } return root }) diff --git a/node_modules/@npmcli/arborist/package.json b/node_modules/@npmcli/arborist/package.json index 2f3ccb6131982..b8b27c29fdf3c 100644 --- a/node_modules/@npmcli/arborist/package.json +++ b/node_modules/@npmcli/arborist/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/arborist", - "version": "2.0.1", + "version": "2.0.2", "description": "Manage node_modules trees", "dependencies": { "@npmcli/installed-package-contents": "^1.0.5", diff --git a/node_modules/@npmcli/config/package.json b/node_modules/@npmcli/config/package.json index f8334ab51dbb5..26581f385c386 100644 --- a/node_modules/@npmcli/config/package.json +++ b/node_modules/@npmcli/config/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/config", - "version": "1.2.6", + "version": "1.2.7", "files": [ "lib" ], @@ -27,7 +27,7 @@ "tap": "^14.10.8" }, "dependencies": { - "ini": "^1.3.5", + "ini": "^2.0.0", "mkdirp-infer-owner": "^2.0.0", "nopt": "^5.0.0", "semver": "^7.3.4", diff --git a/node_modules/editor/LICENSE b/node_modules/editor/LICENSE deleted file mode 100644 index 8b856bc4a47f1..0000000000000 --- a/node_modules/editor/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2013 James Halliday (mail@substack.net) - -This project is free software released under the MIT license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/editor/README.markdown b/node_modules/editor/README.markdown deleted file mode 100644 index c1121cad2f9d2..0000000000000 --- a/node_modules/editor/README.markdown +++ /dev/null @@ -1,54 +0,0 @@ -editor -====== - -Launch $EDITOR in your program. - -example -======= - -``` js -var editor = require('editor'); -editor('beep.json', function (code, sig) { - console.log('finished editing with code ' + code); -}); -``` - -*** - -``` -$ node edit.js -``` - -![editor](http://substack.net/images/screenshots/editor.png) - -``` -finished editing with code 0 -``` - -methods -======= - -``` js -var editor = require('editor') -``` - -editor(file, opts={}, cb) -------------------------- - -Launch the `$EDITOR` (or `opts.editor`) for `file`. - -When the editor exits, `cb(code, sig)` fires. - -install -======= - -With [npm](http://npmjs.org) do: - -``` -npm install editor -``` - -license -======= - -MIT diff --git a/node_modules/editor/example/beep.json b/node_modules/editor/example/beep.json deleted file mode 100644 index ac07d2da8703a..0000000000000 --- a/node_modules/editor/example/beep.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "a" : 3, - "b" : 4, - "c" : 5 -} diff --git a/node_modules/editor/example/edit.js b/node_modules/editor/example/edit.js deleted file mode 100644 index ee11728710705..0000000000000 --- a/node_modules/editor/example/edit.js +++ /dev/null @@ -1,4 +0,0 @@ -var editor = require('../'); -editor(__dirname + '/beep.json', function (code, sig) { - console.log('finished editing with code ' + code); -}); diff --git a/node_modules/editor/index.js b/node_modules/editor/index.js deleted file mode 100644 index 3774edbe37b74..0000000000000 --- a/node_modules/editor/index.js +++ /dev/null @@ -1,20 +0,0 @@ -var spawn = require('child_process').spawn; - -module.exports = function (file, opts, cb) { - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - if (!opts) opts = {}; - - var ed = /^win/.test(process.platform) ? 'notepad' : 'vim'; - var editor = opts.editor || process.env.VISUAL || process.env.EDITOR || ed; - var args = editor.split(/\s+/); - var bin = args.shift(); - - var ps = spawn(bin, args.concat([ file ]), { stdio: 'inherit' }); - - ps.on('exit', function (code, sig) { - if (typeof cb === 'function') cb(code, sig) - }); -}; diff --git a/node_modules/editor/package.json b/node_modules/editor/package.json deleted file mode 100644 index d956a680247cc..0000000000000 --- a/node_modules/editor/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name" : "editor", - "version" : "1.0.0", - "description" : "launch $EDITOR in your program", - "main" : "index.js", - "directories" : { - "example" : "example", - "test" : "test" - }, - "dependencies" : {}, - "devDependencies" : { - "tap" : "~0.4.4" - }, - "scripts" : { - "test" : "tap test/*.js" - }, - "repository" : { - "type" : "git", - "url" : "git://github.com/substack/node-editor.git" - }, - "homepage" : "https://github.com/substack/node-editor", - "keywords" : [ - "text", - "edit", - "shell" - ], - "author" : { - "name" : "James Halliday", - "email" : "mail@substack.net", - "url" : "http://substack.net" - }, - "license" : "MIT", - "engine" : { "node" : ">=0.6" } -} diff --git a/node_modules/ini/ini.js b/node_modules/ini/ini.js index b576f08d7a6bb..7d05a719b066c 100644 --- a/node_modules/ini/ini.js +++ b/node_modules/ini/ini.js @@ -1,16 +1,11 @@ -exports.parse = exports.decode = decode +const { hasOwnProperty } = Object.prototype -exports.stringify = exports.encode = encode - -exports.safe = safe -exports.unsafe = unsafe - -var eol = typeof process !== 'undefined' && +const eol = typeof process !== 'undefined' && process.platform === 'win32' ? '\r\n' : '\n' -function encode (obj, opt) { - var children = [] - var out = '' +const encode = (obj, opt) => { + const children = [] + let out = '' if (typeof opt === 'string') { opt = { @@ -18,93 +13,90 @@ function encode (obj, opt) { whitespace: false, } } else { - opt = opt || {} + opt = opt || Object.create(null) opt.whitespace = opt.whitespace === true } - var separator = opt.whitespace ? ' = ' : '=' + const separator = opt.whitespace ? ' = ' : '=' - Object.keys(obj).forEach(function (k, _, __) { - var val = obj[k] + for (const k of Object.keys(obj)) { + const val = obj[k] if (val && Array.isArray(val)) { - val.forEach(function (item) { + for (const item of val) out += safe(k + '[]') + separator + safe(item) + '\n' - }) } else if (val && typeof val === 'object') children.push(k) else out += safe(k) + separator + safe(val) + eol - }) + } if (opt.section && out.length) out = '[' + safe(opt.section) + ']' + eol + out - children.forEach(function (k, _, __) { - var nk = dotSplit(k).join('\\.') - var section = (opt.section ? opt.section + '.' : '') + nk - var child = encode(obj[k], { - section: section, - whitespace: opt.whitespace, + for (const k of children) { + const nk = dotSplit(k).join('\\.') + const section = (opt.section ? opt.section + '.' : '') + nk + const { whitespace } = opt + const child = encode(obj[k], { + section, + whitespace, }) if (out.length && child.length) out += eol out += child - }) + } return out } -function dotSplit (str) { - return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') +const dotSplit = str => + str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') .replace(/\\\./g, '\u0001') - .split(/\./).map(function (part) { - return part.replace(/\1/g, '\\.') - .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001') - }) -} - -function decode (str) { - var out = {} - var p = out - var section = null + .split(/\./) + .map(part => + part.replace(/\1/g, '\\.') + .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001')) + +const decode = str => { + const out = Object.create(null) + let p = out + let section = null // section |key = value - var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i - var lines = str.split(/[\r\n]+/g) + const re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i + const lines = str.split(/[\r\n]+/g) - lines.forEach(function (line, _, __) { + for (const line of lines) { if (!line || line.match(/^\s*[;#]/)) - return - var match = line.match(re) + continue + const match = line.match(re) if (!match) - return + continue if (match[1] !== undefined) { section = unsafe(match[1]) if (section === '__proto__') { // not allowed // keep parsing the section, but don't attach it. - p = {} - return + p = Object.create(null) + continue } - p = out[section] = out[section] || {} - return + p = out[section] = out[section] || Object.create(null) + continue } - var key = unsafe(match[2]) + const keyRaw = unsafe(match[2]) + const isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]' + const key = isArray ? keyRaw.slice(0, -2) : keyRaw if (key === '__proto__') - return - var value = match[3] ? unsafe(match[4]) : true - switch (value) { - case 'true': - case 'false': - case 'null': value = JSON.parse(value) - } + continue + const valueRaw = match[3] ? unsafe(match[4]) : true + const value = valueRaw === 'true' || + valueRaw === 'false' || + valueRaw === 'null' ? JSON.parse(valueRaw) + : valueRaw // Convert keys with '[]' suffix to an array - if (key.length > 2 && key.slice(-2) === '[]') { - key = key.substring(0, key.length - 2) - if (key === '__proto__') - return - if (!p[key]) + if (isArray) { + if (!hasOwnProperty.call(p, key)) p[key] = [] else if (!Array.isArray(p[key])) p[key] = [p[key]] @@ -116,48 +108,48 @@ function decode (str) { p[key].push(value) else p[key] = value - }) + } // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} // use a filter to return the keys that have to be deleted. - Object.keys(out).filter(function (k, _, __) { - if (!out[k] || - typeof out[k] !== 'object' || - Array.isArray(out[k])) - return false + const remove = [] + for (const k of Object.keys(out)) { + if (!hasOwnProperty.call(out, k) || + typeof out[k] !== 'object' || + Array.isArray(out[k])) + continue // see if the parent section is also an object. // if so, add it to that, and mark this one for deletion - var parts = dotSplit(k) - var p = out - var l = parts.pop() - var nl = l.replace(/\\\./g, '.') - parts.forEach(function (part, _, __) { + const parts = dotSplit(k) + let p = out + const l = parts.pop() + const nl = l.replace(/\\\./g, '.') + for (const part of parts) { if (part === '__proto__') - return - if (!p[part] || typeof p[part] !== 'object') - p[part] = {} + continue + if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object') + p[part] = Object.create(null) p = p[part] - }) + } if (p === out && nl === l) - return false + continue p[nl] = out[k] - return true - }).forEach(function (del, _, __) { + remove.push(k) + } + for (const del of remove) delete out[del] - }) return out } -function isQuoted (val) { - return (val.charAt(0) === '"' && val.slice(-1) === '"') || +const isQuoted = val => + (val.charAt(0) === '"' && val.slice(-1) === '"') || (val.charAt(0) === "'" && val.slice(-1) === "'") -} -function safe (val) { - return (typeof val !== 'string' || +const safe = val => + (typeof val !== 'string' || val.match(/[=\r\n]/) || val.match(/^\[/) || (val.length > 1 && @@ -165,9 +157,8 @@ function safe (val) { val !== val.trim()) ? JSON.stringify(val) : val.replace(/;/g, '\\;').replace(/#/g, '\\#') -} -function unsafe (val, doUnesc) { +const unsafe = (val, doUnesc) => { val = (val || '').trim() if (isQuoted(val)) { // remove the single quotes before calling JSON.parse @@ -179,10 +170,10 @@ function unsafe (val, doUnesc) { } catch (_) {} } else { // walk the val to find the first not-escaped ; character - var esc = false - var unesc = '' - for (var i = 0, l = val.length; i < l; i++) { - var c = val.charAt(i) + let esc = false + let unesc = '' + for (let i = 0, l = val.length; i < l; i++) { + const c = val.charAt(i) if (esc) { if ('\\;#'.indexOf(c) !== -1) unesc += c @@ -204,3 +195,12 @@ function unsafe (val, doUnesc) { } return val } + +module.exports = { + parse: decode, + decode, + stringify: encode, + encode, + safe, + unsafe, +} diff --git a/node_modules/ini/package.json b/node_modules/ini/package.json index c830a3556ef82..59b7d5d0ad99b 100644 --- a/node_modules/ini/package.json +++ b/node_modules/ini/package.json @@ -2,7 +2,7 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "name": "ini", "description": "An ini encoder/decoder for node", - "version": "1.3.8", + "version": "2.0.0", "repository": { "type": "git", "url": "git://github.com/isaacs/ini.git" @@ -29,5 +29,8 @@ "license": "ISC", "files": [ "ini.js" - ] + ], + "engines": { + "node": ">=10" + } } diff --git a/node_modules/sorted-object/LICENSE.txt b/node_modules/sorted-object/LICENSE.txt deleted file mode 100644 index 2edd064bf5507..0000000000000 --- a/node_modules/sorted-object/LICENSE.txt +++ /dev/null @@ -1,47 +0,0 @@ -Dual licensed under WTFPL and MIT: - ---- - -Copyright © 2014–2016 Domenic Denicola - -This work is free. You can redistribute it and/or modify it under the -terms of the Do What The Fuck You Want To Public License, Version 2, -as published by Sam Hocevar. See below for more details. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2004 Sam Hocevar - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - ---- - -The MIT License (MIT) - -Copyright © 2014–2016 Domenic Denicola - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/node_modules/sorted-object/lib/sorted-object.js b/node_modules/sorted-object/lib/sorted-object.js deleted file mode 100644 index 1b3fe81a6be93..0000000000000 --- a/node_modules/sorted-object/lib/sorted-object.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; - -module.exports = function (input) { - var output = {}; - - Object.keys(input).sort().forEach(function (key) { - output[key] = input[key]; - }); - - return output; -}; diff --git a/node_modules/sorted-object/package.json b/node_modules/sorted-object/package.json deleted file mode 100644 index 2e81f36d6efc7..0000000000000 --- a/node_modules/sorted-object/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "sorted-object", - "description": "Returns a copy of an object with its keys sorted", - "keywords": [ - "sort", - "keys", - "object" - ], - "version": "2.0.1", - "author": "Domenic Denicola (https://domenic.me/)", - "license": "(WTFPL OR MIT)", - "repository": "domenic/sorted-object", - "main": "lib/sorted-object.js", - "files": [ - "lib/" - ], - "scripts": { - "test": "tape test/tests.js", - "lint": "eslint ." - }, - "devDependencies": { - "eslint": "^2.4.0", - "tape": "^4.5.1" - } -} diff --git a/node_modules/tough-cookie/LICENSE b/node_modules/tough-cookie/LICENSE deleted file mode 100644 index 22204e8758321..0000000000000 --- a/node_modules/tough-cookie/LICENSE +++ /dev/null @@ -1,12 +0,0 @@ -Copyright (c) 2015, Salesforce.com, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/tough-cookie/README.md b/node_modules/tough-cookie/README.md deleted file mode 100644 index 656a25556c3c5..0000000000000 --- a/node_modules/tough-cookie/README.md +++ /dev/null @@ -1,527 +0,0 @@ -[RFC6265](https://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js - -[![npm package](https://nodei.co/npm/tough-cookie.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/tough-cookie/) - -[![Build Status](https://travis-ci.org/salesforce/tough-cookie.png?branch=master)](https://travis-ci.org/salesforce/tough-cookie) - -# Synopsis - -``` javascript -var tough = require('tough-cookie'); -var Cookie = tough.Cookie; -var cookie = Cookie.parse(header); -cookie.value = 'somethingdifferent'; -header = cookie.toString(); - -var cookiejar = new tough.CookieJar(); -cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb); -// ... -cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) { - res.headers['cookie'] = cookies.join('; '); -}); -``` - -# Installation - -It's _so_ easy! - -`npm install tough-cookie` - -Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken. - -## Version Support - -Support for versions of node.js will follow that of the [request](https://www.npmjs.com/package/request) module. - -# API - -## tough - -Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound". - -**Note**: prior to 1.0.x, several of these functions took a `strict` parameter. This has since been removed from the API as it was no longer necessary. - -### `parseDate(string)` - -Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`. - -### `formatDate(date)` - -Format a Date into a RFC1123 string (the RFC6265-recommended format). - -### `canonicalDomain(str)` - -Transforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects). - -### `domainMatch(str,domStr[,canonicalize=true])` - -Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". - -The `canonicalize` parameter will run the other two parameters through `canonicalDomain` or not. - -### `defaultPath(path)` - -Given a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC. - -The `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output. - -### `pathMatch(reqPath,cookiePath)` - -Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean. - -This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`. - -### `parse(cookieString[, options])` - -alias for `Cookie.parse(cookieString[, options])` - -### `fromJSON(string)` - -alias for `Cookie.fromJSON(string)` - -### `getPublicSuffix(hostname)` - -Returns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it. - -For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`. - -For further information, see http://publicsuffix.org/. This module derives its list from that site. This call is currently a wrapper around [`psl`](https://www.npmjs.com/package/psl)'s [get() method](https://www.npmjs.com/package/psl#pslgetdomain). - -### `cookieCompare(a,b)` - -For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). The sort algorithm is, in order of precedence: - -* Longest `.path` -* oldest `.creation` (which has a 1ms precision, same as `Date`) -* lowest `.creationIndex` (to get beyond the 1ms precision) - -``` javascript -var cookies = [ /* unsorted array of Cookie objects */ ]; -cookies = cookies.sort(cookieCompare); -``` - -**Note**: Since JavaScript's `Date` is limited to a 1ms precision, cookies within the same milisecond are entirely possible. This is especially true when using the `now` option to `.setCookie()`. The `.creationIndex` property is a per-process global counter, assigned during construction with `new Cookie()`. This preserves the spirit of the RFC sorting: older cookies go first. This works great for `MemoryCookieStore`, since `Set-Cookie` headers are parsed in order, but may not be so great for distributed systems. Sophisticated `Store`s may wish to set this to some other _logical clock_ such that if cookies A and B are created in the same millisecond, but cookie A is created before cookie B, then `A.creationIndex < B.creationIndex`. If you want to alter the global counter, which you probably _shouldn't_ do, it's stored in `Cookie.cookiesCreated`. - -### `permuteDomain(domain)` - -Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores. - -### `permutePath(path)` - -Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores. - - -## Cookie - -Exported via `tough.Cookie`. - -### `Cookie.parse(cookieString[, options])` - -Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed. - -The options parameter is not required and currently has only one property: - - * _loose_ - boolean - if `true` enable parsing of key-less cookies like `=abc` and `=`, which are not RFC-compliant. - -If options is not an object, it is ignored, which means you can use `Array#map` with it. - -Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response: - -``` javascript -if (res.headers['set-cookie'] instanceof Array) - cookies = res.headers['set-cookie'].map(Cookie.parse); -else - cookies = [Cookie.parse(res.headers['set-cookie'])]; -``` - -_Note:_ in version 2.3.3, tough-cookie limited the number of spaces before the `=` to 256 characters. This limitation has since been removed. -See [Issue 92](https://github.com/salesforce/tough-cookie/issues/92) - -### Properties - -Cookie object properties: - - * _key_ - string - the name or key of the cookie (default "") - * _value_ - string - the value of the cookie (default "") - * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()` - * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()` - * _domain_ - string - the `Domain=` attribute of the cookie - * _path_ - string - the `Path=` of the cookie - * _secure_ - boolean - the `Secure` cookie flag - * _httpOnly_ - boolean - the `HttpOnly` cookie flag - * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside) - * _creation_ - `Date` - when this cookie was constructed - * _creationIndex_ - number - set at construction, used to provide greater sort precision (please see `cookieCompare(a,b)` for a full explanation) - -After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes: - - * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied) - * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one. - * _creation_ - `Date` - **modified** from construction to when the cookie was added to the jar - * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute. - -### `Cookie([{properties}])` - -Receives an options object that can contain any of the above Cookie properties, uses the default for unspecified properties. - -### `.toString()` - -encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`. - -### `.cookieString()` - -encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '='). - -### `.setExpires(String)` - -sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `"Infinity"` (a string) is set. - -### `.setMaxAge(number)` - -sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly. - -### `.expiryTime([now=Date.now()])` - -### `.expiryDate([now=Date.now()])` - -expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds. - -Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` parameter -- is used to offset the `.maxAge` attribute. - -If Expires (`.expires`) is set, that's returned. - -Otherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents). - -### `.TTL([now=Date.now()])` - -compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply. - -The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned. - -### `.canonicalizedDomain()` - -### `.cdomain()` - -return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters. - -### `.toJSON()` - -For convenience in using `JSON.serialize(cookie)`. Returns a plain-old `Object` that can be JSON-serialized. - -Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are exported in ISO format (`.toISOString()`). - -**NOTE**: Custom `Cookie` properties will be discarded. In tough-cookie 1.x, since there was no `.toJSON` method explicitly defined, all enumerable properties were captured. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. - -### `Cookie.fromJSON(strOrObj)` - -Does the reverse of `cookie.toJSON()`. If passed a string, will `JSON.parse()` that first. - -Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are parsed via `Date.parse()`, not the tough-cookie `parseDate`, since it's JavaScript/JSON-y timestamps being handled at this layer. - -Returns `null` upon JSON parsing error. - -### `.clone()` - -Does a deep clone of this cookie, exactly implemented as `Cookie.fromJSON(cookie.toJSON())`. - -### `.validate()` - -Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive. - -validates cookie attributes for semantic correctness. Useful for "lint" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string -- you can future-proof with this construct: - -``` javascript -if (cookie.validate() === true) { - // it's tasty -} else { - // yuck! -} -``` - - -## CookieJar - -Exported via `tough.CookieJar`. - -### `CookieJar([store],[options])` - -Simply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used. - -The `options` object can be omitted and can have the following properties: - - * _rejectPublicSuffixes_ - boolean - default `true` - reject cookies with domains like "com" and "co.uk" - * _looseMode_ - boolean - default `false` - accept malformed cookies like `bar` and `=bar`, which have an implied empty name. - This is not in the standard, but is used sometimes on the web and is accepted by (most) browsers. - -Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods. - -### `.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))` - -Attempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.creation`, `.lastAccessed` and `.hostOnly` properties. - -The `options` object can be omitted and can have the following properties: - - * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. - * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. - * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies - * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. `Store` errors aren't ignored by this option. - -As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual). - -### `.setCookieSync(cookieOrString, currentUrl, [{options}])` - -Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). - -### `.getCookies(currentUrl, [{options},] cb(err,cookies))` - -Retrieve the list of cookies that can be sent in a Cookie header for the current url. - -If an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given. - -The `options` object can be omitted and can have the following properties: - - * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. - * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. - * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies - * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially). - * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the underlying store (the default `MemoryCookieStore` supports it). - -The `.lastAccessed` property of the returned cookies will have been updated. - -### `.getCookiesSync(currentUrl, [{options}])` - -Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). - -### `.getCookieString(...)` - -Accepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`. - -### `.getCookieStringSync(...)` - -Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). - -### `.getSetCookieStrings(...)` - -Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`. - -### `.getSetCookieStringsSync(...)` - -Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). - -### `.serialize(cb(err,serializedObject))` - -Serialize the Jar if the underlying store supports `.getAllCookies`. - -**NOTE**: Custom `Cookie` properties will be discarded. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. - -See [Serialization Format]. - -### `.serializeSync()` - -Sync version of .serialize - -### `.toJSON()` - -Alias of .serializeSync() for the convenience of `JSON.stringify(cookiejar)`. - -### `CookieJar.deserialize(serialized, [store], cb(err,object))` - -A new Jar is created and the serialized Cookies are added to the underlying store. Each `Cookie` is added via `store.putCookie` in the order in which they appear in the serialization. - -The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. - -As a convenience, if `serialized` is a string, it is passed through `JSON.parse` first. If that throws an error, this is passed to the callback. - -### `CookieJar.deserializeSync(serialized, [store])` - -Sync version of `.deserialize`. _Note_ that the `store` must be synchronous for this to work. - -### `CookieJar.fromJSON(string)` - -Alias of `.deserializeSync` to provide consistency with `Cookie.fromJSON()`. - -### `.clone([store,]cb(err,newJar))` - -Produces a deep clone of this jar. Modifications to the original won't affect the clone, and vice versa. - -The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. Transferring between store types is supported so long as the source implements `.getAllCookies()` and the destination implements `.putCookie()`. - -### `.cloneSync([store])` - -Synchronous version of `.clone`, returning a new `CookieJar` instance. - -The `store` argument is optional, but must be a _synchronous_ `Store` instance if specified. If not passed, a new instance of `MemoryCookieStore` is used. - -The _source_ and _destination_ must both be synchronous `Store`s. If one or both stores are asynchronous, use `.clone` instead. Recall that `MemoryCookieStore` supports both synchronous and asynchronous API calls. - -### `.removeAllCookies(cb(err))` - -Removes all cookies from the jar. - -This is a new backwards-compatible feature of `tough-cookie` version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement `removeAllCookies`, the fallback is to call `removeCookie` after `getAllCookies`. If `getAllCookies` fails or isn't implemented in the Store, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned. - -### `.removeAllCookiesSync()` - -Sync version of `.removeAllCookies()` - -## Store - -Base class for CookieJar stores. Available as `tough.Store`. - -## Store API - -The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores. - -Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. - -Stores are asynchronous by default, but if `store.synchronous` is set to `true`, then the `*Sync` methods on the of the containing `CookieJar` can be used (however, the continuation-passing style - -All `domain` parameters will have been normalized before calling. - -The Cookie store must have all of the following methods. - -### `store.findCookie(domain, path, key, cb(err,cookie))` - -Retrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned. - -Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error). - -### `store.findCookies(domain, path, cb(err,cookies))` - -Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above. - -If no cookies are found, the callback MUST be passed an empty array. - -The resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done. - -As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only). - -### `store.putCookie(cookie, cb(err))` - -Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur. - -The `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties. - -Pass an error if the cookie cannot be stored. - -### `store.updateCookie(oldCookie, newCookie, cb(err))` - -Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store. - -The `.lastAccessed` property will always be different between the two objects (to the precision possible via JavaScript's clock). Both `.creation` and `.creationIndex` are guaranteed to be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are selected for automatic deletion (e.g., least-recently-used, which is up to the store to implement). - -Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object. - -The `newCookie` and `oldCookie` objects MUST NOT be modified. - -Pass an error if the newCookie cannot be stored. - -### `store.removeCookie(domain, path, key, cb(err))` - -Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint). - -The implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie. - -### `store.removeCookies(domain, path, cb(err))` - -Removes matching cookies from the store. The `path` parameter is optional, and if missing means all paths in a domain should be removed. - -Pass an error ONLY if removing any existing cookies failed. - -### `store.removeAllCookies(cb(err))` - -_Optional_. Removes all cookies from the store. - -Pass an error if one or more cookies can't be removed. - -**Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this. - -### `store.getAllCookies(cb(err, cookies))` - -_Optional_. Produces an `Array` of all cookies during `jar.serialize()`. The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format] data structure. - -Cookies SHOULD be returned in creation order to preserve sorting via `compareCookies()`. For reference, `MemoryCookieStore` will sort by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1ms. See `compareCookies` for more detail. - -Pass an error if retrieval fails. - -**Note**: not all Stores can implement this due to technical limitations, so it is optional. - -## MemoryCookieStore - -Inherits from `Store`. - -A just-in-memory CookieJar synchronous store implementation, used by default. Despite being a synchronous implementation, it's usable with both the synchronous and asynchronous forms of the `CookieJar` API. Supports serialization, `getAllCookies`, and `removeAllCookies`. - -## Community Cookie Stores - -These are some Store implementations authored and maintained by the community. They aren't official and we don't vouch for them but you may be interested to have a look: - -- [`db-cookie-store`](https://github.com/JSBizon/db-cookie-store): SQL including SQLite-based databases -- [`file-cookie-store`](https://github.com/JSBizon/file-cookie-store): Netscape cookie file format on disk -- [`redis-cookie-store`](https://github.com/benkroeger/redis-cookie-store): Redis -- [`tough-cookie-filestore`](https://github.com/mitsuru/tough-cookie-filestore): JSON on disk -- [`tough-cookie-web-storage-store`](https://github.com/exponentjs/tough-cookie-web-storage-store): DOM localStorage and sessionStorage - - -# Serialization Format - -**NOTE**: if you want to have custom `Cookie` properties serialized, add the property name to `Cookie.serializableProperties`. - -```js - { - // The version of tough-cookie that serialized this jar. - version: 'tough-cookie@1.x.y', - - // add the store type, to make humans happy: - storeType: 'MemoryCookieStore', - - // CookieJar configuration: - rejectPublicSuffixes: true, - // ... future items go here - - // Gets filled from jar.store.getAllCookies(): - cookies: [ - { - key: 'string', - value: 'string', - // ... - /* other Cookie.serializableProperties go here */ - } - ] - } -``` - -# Copyright and License - -BSD-3-Clause: - -```text - Copyright (c) 2015, Salesforce.com, Inc. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. Neither the name of Salesforce.com nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. -``` diff --git a/node_modules/tough-cookie/lib/cookie.js b/node_modules/tough-cookie/lib/cookie.js deleted file mode 100644 index 2ab6f092d1f31..0000000000000 --- a/node_modules/tough-cookie/lib/cookie.js +++ /dev/null @@ -1,1488 +0,0 @@ -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -'use strict'; -var urlParse = require('url').parse; -var util = require('util'); -var ipRegex = require('ip-regex')({ exact: true }); -var pubsuffix = require('./pubsuffix-psl'); -var Store = require('./store').Store; -var MemoryCookieStore = require('./memstore').MemoryCookieStore; -var pathMatch = require('./pathMatch').pathMatch; -var VERSION = require('./version'); - -var punycode; -try { - punycode = require('punycode'); -} catch(e) { - console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization"); -} - -// From RFC6265 S4.1.1 -// note that it excludes \x3B ";" -var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; - -var CONTROL_CHARS = /[\x00-\x1F]/; - -// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in -// the "relaxed" mode, see: -// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 -var TERMINATORS = ['\n', '\r', '\0']; - -// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' -// Note ';' is \x3B -var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; - -// date-time parsing constants (RFC6265 S5.1.1) - -var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; - -var MONTH_TO_NUM = { - jan:0, feb:1, mar:2, apr:3, may:4, jun:5, - jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 -}; -var NUM_TO_MONTH = [ - 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' -]; -var NUM_TO_DAY = [ - 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' -]; - -var MAX_TIME = 2147483647000; // 31-bit max -var MIN_TIME = 0; // 31-bit min - -/* - * Parses a Natural number (i.e., non-negative integer) with either the - * *DIGIT ( non-digit *OCTET ) - * or - * *DIGIT - * grammar (RFC6265 S5.1.1). - * - * The "trailingOK" boolean controls if the grammar accepts a - * "( non-digit *OCTET )" trailer. - */ -function parseDigits(token, minDigits, maxDigits, trailingOK) { - var count = 0; - while (count < token.length) { - var c = token.charCodeAt(count); - // "non-digit = %x00-2F / %x3A-FF" - if (c <= 0x2F || c >= 0x3A) { - break; - } - count++; - } - - // constrain to a minimum and maximum number of digits. - if (count < minDigits || count > maxDigits) { - return null; - } - - if (!trailingOK && count != token.length) { - return null; - } - - return parseInt(token.substr(0,count), 10); -} - -function parseTime(token) { - var parts = token.split(':'); - var result = [0,0,0]; - - /* RF6256 S5.1.1: - * time = hms-time ( non-digit *OCTET ) - * hms-time = time-field ":" time-field ":" time-field - * time-field = 1*2DIGIT - */ - - if (parts.length !== 3) { - return null; - } - - for (var i = 0; i < 3; i++) { - // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be - // followed by "( non-digit *OCTET )" so therefore the last time-field can - // have a trailer - var trailingOK = (i == 2); - var num = parseDigits(parts[i], 1, 2, trailingOK); - if (num === null) { - return null; - } - result[i] = num; - } - - return result; -} - -function parseMonth(token) { - token = String(token).substr(0,3).toLowerCase(); - var num = MONTH_TO_NUM[token]; - return num >= 0 ? num : null; -} - -/* - * RFC6265 S5.1.1 date parser (see RFC for full grammar) - */ -function parseDate(str) { - if (!str) { - return; - } - - /* RFC6265 S5.1.1: - * 2. Process each date-token sequentially in the order the date-tokens - * appear in the cookie-date - */ - var tokens = str.split(DATE_DELIM); - if (!tokens) { - return; - } - - var hour = null; - var minute = null; - var second = null; - var dayOfMonth = null; - var month = null; - var year = null; - - for (var i=0; i= 70 && year <= 99) { - year += 1900; - } else if (year >= 0 && year <= 69) { - year += 2000; - } - } - } - } - - /* RFC 6265 S5.1.1 - * "5. Abort these steps and fail to parse the cookie-date if: - * * at least one of the found-day-of-month, found-month, found- - * year, or found-time flags is not set, - * * the day-of-month-value is less than 1 or greater than 31, - * * the year-value is less than 1601, - * * the hour-value is greater than 23, - * * the minute-value is greater than 59, or - * * the second-value is greater than 59. - * (Note that leap seconds cannot be represented in this syntax.)" - * - * So, in order as above: - */ - if ( - dayOfMonth === null || month === null || year === null || second === null || - dayOfMonth < 1 || dayOfMonth > 31 || - year < 1601 || - hour > 23 || - minute > 59 || - second > 59 - ) { - return; - } - - return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); -} - -function formatDate(date) { - var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d; - var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; - var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; - var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; - return NUM_TO_DAY[date.getUTCDay()] + ', ' + - d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ - h+':'+m+':'+s+' GMT'; -} - -// S5.1.2 Canonicalized Host Names -function canonicalDomain(str) { - if (str == null) { - return null; - } - str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . - - // convert to IDN if any non-ASCII characters - if (punycode && /[^\u0001-\u007f]/.test(str)) { - str = punycode.toASCII(str); - } - - return str.toLowerCase(); -} - -// S5.1.3 Domain Matching -function domainMatch(str, domStr, canonicalize) { - if (str == null || domStr == null) { - return null; - } - if (canonicalize !== false) { - str = canonicalDomain(str); - domStr = canonicalDomain(domStr); - } - - /* - * "The domain string and the string are identical. (Note that both the - * domain string and the string will have been canonicalized to lower case at - * this point)" - */ - if (str == domStr) { - return true; - } - - /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ - - /* "* The string is a host name (i.e., not an IP address)." */ - if (ipRegex.test(str)) { - return false; - } - - /* "* The domain string is a suffix of the string" */ - var idx = str.indexOf(domStr); - if (idx <= 0) { - return false; // it's a non-match (-1) or prefix (0) - } - - // e.g "a.b.c".indexOf("b.c") === 2 - // 5 === 3+2 - if (str.length !== domStr.length + idx) { // it's not a suffix - return false; - } - - /* "* The last character of the string that is not included in the domain - * string is a %x2E (".") character." */ - if (str.substr(idx-1,1) !== '.') { - return false; - } - - return true; -} - - -// RFC6265 S5.1.4 Paths and Path-Match - -/* - * "The user agent MUST use an algorithm equivalent to the following algorithm - * to compute the default-path of a cookie:" - * - * Assumption: the path (and not query part or absolute uri) is passed in. - */ -function defaultPath(path) { - // "2. If the uri-path is empty or if the first character of the uri-path is not - // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. - if (!path || path.substr(0,1) !== "/") { - return "/"; - } - - // "3. If the uri-path contains no more than one %x2F ("/") character, output - // %x2F ("/") and skip the remaining step." - if (path === "/") { - return path; - } - - var rightSlash = path.lastIndexOf("/"); - if (rightSlash === 0) { - return "/"; - } - - // "4. Output the characters of the uri-path from the first character up to, - // but not including, the right-most %x2F ("/")." - return path.slice(0, rightSlash); -} - -function trimTerminator(str) { - for (var t = 0; t < TERMINATORS.length; t++) { - var terminatorIdx = str.indexOf(TERMINATORS[t]); - if (terminatorIdx !== -1) { - str = str.substr(0,terminatorIdx); - } - } - - return str; -} - -function parseCookiePair(cookiePair, looseMode) { - cookiePair = trimTerminator(cookiePair); - - var firstEq = cookiePair.indexOf('='); - if (looseMode) { - if (firstEq === 0) { // '=' is immediately at start - cookiePair = cookiePair.substr(1); - firstEq = cookiePair.indexOf('='); // might still need to split on '=' - } - } else { // non-loose mode - if (firstEq <= 0) { // no '=' or is at start - return; // needs to have non-empty "cookie-name" - } - } - - var cookieName, cookieValue; - if (firstEq <= 0) { - cookieName = ""; - cookieValue = cookiePair.trim(); - } else { - cookieName = cookiePair.substr(0, firstEq).trim(); - cookieValue = cookiePair.substr(firstEq+1).trim(); - } - - if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { - return; - } - - var c = new Cookie(); - c.key = cookieName; - c.value = cookieValue; - return c; -} - -function parse(str, options) { - if (!options || typeof options !== 'object') { - options = {}; - } - str = str.trim(); - - // We use a regex to parse the "name-value-pair" part of S5.2 - var firstSemi = str.indexOf(';'); // S5.2 step 1 - var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi); - var c = parseCookiePair(cookiePair, !!options.loose); - if (!c) { - return; - } - - if (firstSemi === -1) { - return c; - } - - // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string - // (including the %x3B (";") in question)." plus later on in the same section - // "discard the first ";" and trim". - var unparsed = str.slice(firstSemi + 1).trim(); - - // "If the unparsed-attributes string is empty, skip the rest of these - // steps." - if (unparsed.length === 0) { - return c; - } - - /* - * S5.2 says that when looping over the items "[p]rocess the attribute-name - * and attribute-value according to the requirements in the following - * subsections" for every item. Plus, for many of the individual attributes - * in S5.3 it says to use the "attribute-value of the last attribute in the - * cookie-attribute-list". Therefore, in this implementation, we overwrite - * the previous value. - */ - var cookie_avs = unparsed.split(';'); - while (cookie_avs.length) { - var av = cookie_avs.shift().trim(); - if (av.length === 0) { // happens if ";;" appears - continue; - } - var av_sep = av.indexOf('='); - var av_key, av_value; - - if (av_sep === -1) { - av_key = av; - av_value = null; - } else { - av_key = av.substr(0,av_sep); - av_value = av.substr(av_sep+1); - } - - av_key = av_key.trim().toLowerCase(); - - if (av_value) { - av_value = av_value.trim(); - } - - switch(av_key) { - case 'expires': // S5.2.1 - if (av_value) { - var exp = parseDate(av_value); - // "If the attribute-value failed to parse as a cookie date, ignore the - // cookie-av." - if (exp) { - // over and underflow not realistically a concern: V8's getTime() seems to - // store something larger than a 32-bit time_t (even with 32-bit node) - c.expires = exp; - } - } - break; - - case 'max-age': // S5.2.2 - if (av_value) { - // "If the first character of the attribute-value is not a DIGIT or a "-" - // character ...[or]... If the remainder of attribute-value contains a - // non-DIGIT character, ignore the cookie-av." - if (/^-?[0-9]+$/.test(av_value)) { - var delta = parseInt(av_value, 10); - // "If delta-seconds is less than or equal to zero (0), let expiry-time - // be the earliest representable date and time." - c.setMaxAge(delta); - } - } - break; - - case 'domain': // S5.2.3 - // "If the attribute-value is empty, the behavior is undefined. However, - // the user agent SHOULD ignore the cookie-av entirely." - if (av_value) { - // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E - // (".") character." - var domain = av_value.trim().replace(/^\./, ''); - if (domain) { - // "Convert the cookie-domain to lower case." - c.domain = domain.toLowerCase(); - } - } - break; - - case 'path': // S5.2.4 - /* - * "If the attribute-value is empty or if the first character of the - * attribute-value is not %x2F ("/"): - * Let cookie-path be the default-path. - * Otherwise: - * Let cookie-path be the attribute-value." - * - * We'll represent the default-path as null since it depends on the - * context of the parsing. - */ - c.path = av_value && av_value[0] === "/" ? av_value : null; - break; - - case 'secure': // S5.2.5 - /* - * "If the attribute-name case-insensitively matches the string "Secure", - * the user agent MUST append an attribute to the cookie-attribute-list - * with an attribute-name of Secure and an empty attribute-value." - */ - c.secure = true; - break; - - case 'httponly': // S5.2.6 -- effectively the same as 'secure' - c.httpOnly = true; - break; - - default: - c.extensions = c.extensions || []; - c.extensions.push(av); - break; - } - } - - return c; -} - -// avoid the V8 deoptimization monster! -function jsonParse(str) { - var obj; - try { - obj = JSON.parse(str); - } catch (e) { - return e; - } - return obj; -} - -function fromJSON(str) { - if (!str) { - return null; - } - - var obj; - if (typeof str === 'string') { - obj = jsonParse(str); - if (obj instanceof Error) { - return null; - } - } else { - // assume it's an Object - obj = str; - } - - var c = new Cookie(); - for (var i=0; i 1) { - var lindex = path.lastIndexOf('/'); - if (lindex === 0) { - break; - } - path = path.substr(0,lindex); - permutations.push(path); - } - permutations.push('/'); - return permutations; -} - -function getCookieContext(url) { - if (url instanceof Object) { - return url; - } - // NOTE: decodeURI will throw on malformed URIs (see GH-32). - // Therefore, we will just skip decoding for such URIs. - try { - url = decodeURI(url); - } - catch(err) { - // Silently swallow error - } - - return urlParse(url); -} - -function Cookie(options) { - options = options || {}; - - Object.keys(options).forEach(function(prop) { - if (Cookie.prototype.hasOwnProperty(prop) && - Cookie.prototype[prop] !== options[prop] && - prop.substr(0,1) !== '_') - { - this[prop] = options[prop]; - } - }, this); - - this.creation = this.creation || new Date(); - - // used to break creation ties in cookieCompare(): - Object.defineProperty(this, 'creationIndex', { - configurable: false, - enumerable: false, // important for assert.deepEqual checks - writable: true, - value: ++Cookie.cookiesCreated - }); -} - -Cookie.cookiesCreated = 0; // incremented each time a cookie is created - -Cookie.parse = parse; -Cookie.fromJSON = fromJSON; - -Cookie.prototype.key = ""; -Cookie.prototype.value = ""; - -// the order in which the RFC has them: -Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity -Cookie.prototype.maxAge = null; // takes precedence over expires for TTL -Cookie.prototype.domain = null; -Cookie.prototype.path = null; -Cookie.prototype.secure = false; -Cookie.prototype.httpOnly = false; -Cookie.prototype.extensions = null; - -// set by the CookieJar: -Cookie.prototype.hostOnly = null; // boolean when set -Cookie.prototype.pathIsDefault = null; // boolean when set -Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse -Cookie.prototype.lastAccessed = null; // Date when set -Object.defineProperty(Cookie.prototype, 'creationIndex', { - configurable: true, - enumerable: false, - writable: true, - value: 0 -}); - -Cookie.serializableProperties = Object.keys(Cookie.prototype) - .filter(function(prop) { - return !( - Cookie.prototype[prop] instanceof Function || - prop === 'creationIndex' || - prop.substr(0,1) === '_' - ); - }); - -Cookie.prototype.inspect = function inspect() { - var now = Date.now(); - return 'Cookie="'+this.toString() + - '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + - '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + - '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + - '"'; -}; - -// Use the new custom inspection symbol to add the custom inspect function if -// available. -if (util.inspect.custom) { - Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect; -} - -Cookie.prototype.toJSON = function() { - var obj = {}; - - var props = Cookie.serializableProperties; - for (var i=0; i=6" - }, - "devDependencies": { - "async": "^1.4.2", - "genversion": "^2.1.0", - "nyc": "^11.6.0", - "string.prototype.repeat": "^0.2.0", - "vows": "^0.8.2" - }, - "dependencies": { - "ip-regex": "^2.1.0", - "psl": "^1.1.28", - "punycode": "^2.1.1" - } -} diff --git a/package-lock.json b/package-lock.json index 4564ba22fdc65..a1efbf45f7aaf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "npm", - "version": "7.1.2", + "version": "7.2.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "npm", - "version": "7.1.2", + "version": "7.2.0", "bundleDependencies": [ "@npmcli/arborist", "@npmcli/ci-detect", @@ -24,7 +24,6 @@ "cli-columns", "cli-table3", "columnify", - "editor", "glob", "graceful-fs", "hosted-git-info", @@ -64,9 +63,9 @@ "read", "read-package-json", "read-package-json-fast", + "readdir-scoped-modules", "rimraf", "semver", - "sorted-object", "ssri", "tar", "text-table", @@ -302,7 +301,6 @@ "read-pkg", "read-pkg-up", "readable-stream", - "readdir-scoped-modules", "regexpp", "request", "resolve", @@ -356,9 +354,9 @@ ], "license": "Artistic-2.0", "dependencies": { - "@npmcli/arborist": "^2.0.1", + "@npmcli/arborist": "^2.0.2", "@npmcli/ci-detect": "^1.2.0", - "@npmcli/config": "^1.2.6", + "@npmcli/config": "^1.2.7", "@npmcli/run-script": "^1.8.1", "abbrev": "~1.1.1", "ansicolors": "~0.3.2", @@ -372,11 +370,10 @@ "cli-columns": "^3.1.2", "cli-table3": "^0.6.0", "columnify": "~1.5.4", - "editor": "~1.0.0", "glob": "^7.1.4", "graceful-fs": "^4.2.3", "hosted-git-info": "^3.0.6", - "ini": "^1.3.8", + "ini": "^2.0.0", "init-package-json": "^2.0.1", "is-cidr": "^4.0.2", "leven": "^3.1.0", @@ -411,9 +408,9 @@ "read": "~1.0.7", "read-package-json": "^3.0.0", "read-package-json-fast": "^1.2.1", + "readdir-scoped-modules": "^1.1.0", "rimraf": "^3.0.2", "semver": "^7.3.4", - "sorted-object": "~2.0.1", "ssri": "^8.0.0", "tar": "^6.0.5", "text-table": "~0.2.0", @@ -685,9 +682,9 @@ } }, "node_modules/@npmcli/arborist": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@npmcli/arborist/-/arborist-2.0.1.tgz", - "integrity": "sha512-xUH2aggJhPTrKu94sAQxwyPLr/LHFLYTEzd+tQ/Ubgrs6H1UQSdQKrq/U+mlx74ypxw7Ee/blPJBed8SnMqXpA==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/arborist/-/arborist-2.0.2.tgz", + "integrity": "sha512-QMMUSeGW6u9/T8zH0zCGSRtOqCMmv8LnRNjZFX+zv4u1dauIx5iJ4i8e7EJbvXkKEZyGjK8sJ45NIoF+umMgIQ==", "inBundle": true, "dependencies": { "@npmcli/installed-package-contents": "^1.0.5", @@ -724,12 +721,12 @@ "inBundle": true }, "node_modules/@npmcli/config": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@npmcli/config/-/config-1.2.6.tgz", - "integrity": "sha512-qCH3njpc4El2l92BS1oa47wy1SRyWuQGC0RqiP2n/wbS7tdbQenwbuPIUxgQ9FY4sq2uMVrNQFIgdhMNM+OYKg==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@npmcli/config/-/config-1.2.7.tgz", + "integrity": "sha512-zV1xhCK91UegZO03G7BdNSRMCTDVMB1UI31XDbZ8bjUB/8rUuFvbYoIRzZDMyUPT24ltzLQC15Ub2bzgg0ORSg==", "inBundle": true, "dependencies": { - "ini": "^1.3.5", + "ini": "^2.0.0", "mkdirp-infer-owner": "^2.0.0", "nopt": "^5.0.0", "semver": "^7.3.4", @@ -2110,12 +2107,6 @@ "safer-buffer": "^2.1.0" } }, - "node_modules/editor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/editor/-/editor-1.0.0.tgz", - "integrity": "sha1-YMf4e9YrzGqJT6jM1q+3gjok90I=", - "inBundle": true - }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -3548,10 +3539,13 @@ "inBundle": true }, "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "inBundle": true + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-2.0.0.tgz", + "integrity": "sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==", + "inBundle": true, + "engines": { + "node": ">=10" + } }, "node_modules/init-package-json": { "version": "2.0.1", @@ -5699,6 +5693,12 @@ "rc": "cli.js" } }, + "node_modules/rc/node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true + }, "node_modules/rc/node_modules/strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", @@ -6253,12 +6253,6 @@ "node": ">= 6" } }, - "node_modules/sorted-object": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/sorted-object/-/sorted-object-2.0.1.tgz", - "integrity": "sha1-fWMfS9OnmKJK8d/8+/6DM3pd9fw=", - "inBundle": true - }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -9861,9 +9855,9 @@ } }, "@npmcli/arborist": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@npmcli/arborist/-/arborist-2.0.1.tgz", - "integrity": "sha512-xUH2aggJhPTrKu94sAQxwyPLr/LHFLYTEzd+tQ/Ubgrs6H1UQSdQKrq/U+mlx74ypxw7Ee/blPJBed8SnMqXpA==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/arborist/-/arborist-2.0.2.tgz", + "integrity": "sha512-QMMUSeGW6u9/T8zH0zCGSRtOqCMmv8LnRNjZFX+zv4u1dauIx5iJ4i8e7EJbvXkKEZyGjK8sJ45NIoF+umMgIQ==", "requires": { "@npmcli/installed-package-contents": "^1.0.5", "@npmcli/map-workspaces": "^1.0.1", @@ -9898,11 +9892,11 @@ "integrity": "sha512-oN3y7FAROHhrAt7Rr7PnTSwrHrZVRTS2ZbyxeQwSSYD0ifwM3YNgQqbaRmjcWoPyq77MjchusjJDspbzMmip1Q==" }, "@npmcli/config": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@npmcli/config/-/config-1.2.6.tgz", - "integrity": "sha512-qCH3njpc4El2l92BS1oa47wy1SRyWuQGC0RqiP2n/wbS7tdbQenwbuPIUxgQ9FY4sq2uMVrNQFIgdhMNM+OYKg==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@npmcli/config/-/config-1.2.7.tgz", + "integrity": "sha512-zV1xhCK91UegZO03G7BdNSRMCTDVMB1UI31XDbZ8bjUB/8rUuFvbYoIRzZDMyUPT24ltzLQC15Ub2bzgg0ORSg==", "requires": { - "ini": "^1.3.5", + "ini": "^2.0.0", "mkdirp-infer-owner": "^2.0.0", "nopt": "^5.0.0", "semver": "^7.3.4", @@ -10924,11 +10918,6 @@ "safer-buffer": "^2.1.0" } }, - "editor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/editor/-/editor-1.0.0.tgz", - "integrity": "sha1-YMf4e9YrzGqJT6jM1q+3gjok90I=" - }, "emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -11976,9 +11965,9 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-2.0.0.tgz", + "integrity": "sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==" }, "init-package-json": { "version": "2.0.1", @@ -13545,6 +13534,12 @@ "strip-json-comments": "~2.0.1" }, "dependencies": { + "ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true + }, "strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", @@ -13953,11 +13948,6 @@ "socks": "^2.3.3" } }, - "sorted-object": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/sorted-object/-/sorted-object-2.0.1.tgz", - "integrity": "sha1-fWMfS9OnmKJK8d/8+/6DM3pd9fw=" - }, "source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", diff --git a/package.json b/package.json index 89cb0e6aad7f0..8e2917c5edca2 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "7.1.2", + "version": "7.2.0", "name": "npm", "description": "a package manager for JavaScript", "keywords": [ @@ -42,9 +42,9 @@ "./package.json": "./package.json" }, "dependencies": { - "@npmcli/arborist": "^2.0.1", + "@npmcli/arborist": "^2.0.2", "@npmcli/ci-detect": "^1.2.0", - "@npmcli/config": "^1.2.6", + "@npmcli/config": "^1.2.7", "@npmcli/run-script": "^1.8.1", "abbrev": "~1.1.1", "ansicolors": "~0.3.2", @@ -58,11 +58,10 @@ "cli-columns": "^3.1.2", "cli-table3": "^0.6.0", "columnify": "~1.5.4", - "editor": "~1.0.0", "glob": "^7.1.4", "graceful-fs": "^4.2.3", "hosted-git-info": "^3.0.6", - "ini": "^1.3.8", + "ini": "^2.0.0", "init-package-json": "^2.0.1", "is-cidr": "^4.0.2", "leven": "^3.1.0", @@ -97,9 +96,9 @@ "read": "~1.0.7", "read-package-json": "^3.0.0", "read-package-json-fast": "^1.2.1", + "readdir-scoped-modules": "^1.1.0", "rimraf": "^3.0.2", "semver": "^7.3.4", - "sorted-object": "~2.0.1", "ssri": "^8.0.0", "tar": "^6.0.5", "text-table": "~0.2.0", @@ -127,7 +126,6 @@ "cli-columns", "cli-table3", "columnify", - "editor", "glob", "graceful-fs", "hosted-git-info", @@ -167,9 +165,9 @@ "read", "read-package-json", "read-package-json-fast", + "readdir-scoped-modules", "rimraf", "semver", - "sorted-object", "ssri", "tar", "text-table", diff --git a/test/lib/config.js b/test/lib/config.js index 8a11a40c81337..74cd530c68270 100644 --- a/test/lib/config.js +++ b/test/lib/config.js @@ -1,5 +1,6 @@ const t = require('tap') const requireInject = require('require-inject') +const { EventEmitter } = require('events') const redactCwd = (path) => { const normalizePath = p => p @@ -437,10 +438,16 @@ sign-git-commit=true` cb() }, }, - editor: (file, { editor }, cb) => { - t.equal(file, '~/.npmrc', 'should match user source data') - t.equal(editor, 'vi', 'should use default editor') - cb() + child_process: { + spawn: (bin, args) => { + t.equal(bin, 'vi', 'should use default editor') + t.strictSame(args, ['~/.npmrc'], 'should match user source data') + const ee = new EventEmitter() + process.nextTick(() => { + ee.emit('exit', 0) + }) + return ee + }, }, } const config = requireInject('../../lib/config.js', editMocks) @@ -487,15 +494,21 @@ t.test('config edit --global', t => { cb() }, }, - editor: (file, { editor }, cb) => { - t.equal(file, '/etc/npmrc', 'should match global source data') - t.equal(editor, 'vi', 'should use default editor') - cb() + child_process: { + spawn: (bin, args, cb) => { + t.equal(bin, 'vi', 'should use default editor') + t.strictSame(args, ['/etc/npmrc'], 'should match global source data') + const ee = new EventEmitter() + process.nextTick(() => { + ee.emit('exit', 137) + }) + return ee + }, }, } const config = requireInject('../../lib/config.js', editMocks) config(['edit'], (err) => { - t.ifError(err, 'npm config edit --global') + t.match(err, /exited with code: 137/, 'propagated exit code from editor') }) t.teardown(() => { @@ -505,19 +518,6 @@ t.test('config edit --global', t => { }) }) -t.test('config edit no editor set', t => { - flatOptions.editor = undefined - config(['edit'], (err) => { - t.match( - err, - /No `editor` config or EDITOR environment variable set/, - 'should throw no available editor error' - ) - flatOptions.editor = 'vi' - t.end() - }) -}) - t.test('completion', t => { const { completion } = config diff --git a/test/lib/edit.js b/test/lib/edit.js new file mode 100644 index 0000000000000..0d3bbb4c57e71 --- /dev/null +++ b/test/lib/edit.js @@ -0,0 +1,123 @@ +const { test } = require('tap') +const { resolve } = require('path') +const requireInject = require('require-inject') +const { EventEmitter } = require('events') + +let editorBin = null +let editorArgs = null +let editorOpts = null +let EDITOR_CODE = 0 +const childProcess = { + spawn: (bin, args, opts) => { + // save for assertions + editorBin = bin + editorArgs = args + editorOpts = opts + + const editorEvents = new EventEmitter() + process.nextTick(() => { + editorEvents.emit('exit', EDITOR_CODE) + }) + return editorEvents + }, +} + +let rebuildArgs = null +let EDITOR = 'vim' +const npm = { + config: { + get: () => EDITOR, + }, + dir: resolve(__dirname, '../../node_modules'), + commands: { + rebuild: (args, cb) => { + rebuildArgs = args + return cb() + }, + }, +} + +const gracefulFs = require('graceful-fs') +const edit = requireInject('../../lib/edit.js', { + '../../lib/npm.js': npm, + child_process: childProcess, + 'graceful-fs': gracefulFs, +}) + +test('npm edit', t => { + t.teardown(() => { + rebuildArgs = null + editorBin = null + editorArgs = null + editorOpts = null + }) + + return edit(['semver'], (err) => { + if (err) + throw err + + const path = resolve(__dirname, '../../node_modules/semver') + t.strictSame(editorBin, EDITOR, 'used the correct editor') + t.strictSame(editorArgs, [path], 'edited the correct directory') + t.strictSame(editorOpts, { stdio: 'inherit' }, 'passed the correct opts') + t.strictSame(rebuildArgs, [path], 'passed the correct path to rebuild') + t.end() + }) +}) + +test('npm edit editor has flags', t => { + EDITOR = 'code -w' + t.teardown(() => { + rebuildArgs = null + editorBin = null + editorArgs = null + editorOpts = null + EDITOR = 'vim' + }) + + return edit(['semver'], (err) => { + if (err) + throw err + + const path = resolve(__dirname, '../../node_modules/semver') + t.strictSame(editorBin, 'code', 'used the correct editor') + t.strictSame(editorArgs, ['-w', path], 'edited the correct directory, keeping flags') + t.strictSame(editorOpts, { stdio: 'inherit' }, 'passed the correct opts') + t.strictSame(rebuildArgs, [path], 'passed the correct path to rebuild') + t.end() + }) +}) + +test('npm edit no args', t => { + return edit([], (err) => { + t.match(err, /npm edit/, 'throws usage error') + t.end() + }) +}) + +test('npm edit lstat error propagates', t => { + const _lstat = gracefulFs.lstat + gracefulFs.lstat = (dir, cb) => { + return cb(new Error('lstat failed')) + } + t.teardown(() => { + gracefulFs.lstat = _lstat + }) + + return edit(['semver'], (err) => { + t.match(err, /lstat failed/, 'user received correct error') + t.end() + }) +}) + +test('npm edit editor exit code error propagates', t => { + EDITOR_CODE = 137 + t.teardown(() => { + EDITOR_CODE = 0 + }) + + return edit(['semver'], (err) => { + t.match(err, /exited with code: 137/, 'user received correct error') + t.end() + }) +}) diff --git a/test/lib/help-search.js b/test/lib/help-search.js new file mode 100644 index 0000000000000..5ecf5db0614ac --- /dev/null +++ b/test/lib/help-search.js @@ -0,0 +1,181 @@ +const { test } = require('tap') +const { join } = require('path') +const requireInject = require('require-inject') +const ansicolors = require('ansicolors') + +const OUTPUT = [] +const output = (msg) => { + OUTPUT.push(msg) +} + +let npmHelpArgs = null +let npmHelpErr = null +const npm = { + color: false, + flatOptions: { + long: false, + }, + commands: { + help: (args, cb) => { + npmHelpArgs = args + return cb(npmHelpErr) + }, + }, +} + +let npmUsageArg = null +const npmUsage = (arg) => { + npmUsageArg = arg +} + +let globRoot = null +const globDir = { + 'npm-exec.md': 'the exec command\nhelp has multiple lines of exec help\none of them references exec', + 'npm-something.md': 'another\ncommand you run\nthat\nreferences exec\nand has multiple lines\nwith no matches\nthat will be ignored\nand another line\nthat does have exec as well', + 'npm-run-script.md': 'the scripted run-script command runs scripts\nand has lines\nsome of which dont match the string run\nor script\nscript', + 'npm-install.md': 'does a thing in a script\nif a thing does not exist in a thing you run\nto install it and run it maybe in a script', + 'npm-help.md': 'will run the `help-search` command if you need to run it to help you search', + 'npm-help-search.md': 'is the help search command\nthat you get if you run help-search', + 'npm-useless.md': 'exec\nexec', + 'npm-more-useless.md': 'exec exec', + 'npm-extra-useless.md': 'exec\nexec\nexec', +} +const glob = (p, cb) => cb(null, Object.keys(globDir).map((file) => join(globRoot, file))) + +const helpSearch = requireInject('../../lib/help-search.js', { + '../../lib/npm.js': npm, + '../../lib/utils/npm-usage.js': npmUsage, + '../../lib/utils/output.js': output, + glob, +}) + +test('npm help-search', t => { + globRoot = t.testdir(globDir) + t.teardown(() => { + OUTPUT.length = 0 + globRoot = null + }) + + return helpSearch(['exec'], (err) => { + if (err) + throw err + + t.match(OUTPUT, /Top hits for/, 'outputs results') + t.match(OUTPUT, /Did you mean this\?\n\s+exec/, 'matched command, so suggest it') + t.end() + }) +}) + +test('npm help-search multiple terms', t => { + globRoot = t.testdir(globDir) + t.teardown(() => { + OUTPUT.length = 0 + globRoot = null + }) + + return helpSearch(['run', 'script'], (err) => { + if (err) + throw err + + t.match(OUTPUT, /Top hits for/, 'outputs results') + t.match(OUTPUT, /run:\d+ script:\d+/, 'shows hit counts for both terms') + t.end() + }) +}) + +test('npm help-search single result prints full section', t => { + globRoot = t.testdir(globDir) + t.teardown(() => { + OUTPUT.length = 0 + npmHelpArgs = null + globRoot = null + }) + + return helpSearch(['does not exist in'], (err) => { + if (err) + throw err + + t.strictSame(npmHelpArgs, ['npm-install'], 'identified the correct man page and called help with it') + t.end() + }) +}) + +test('npm help-search single result propagates error', t => { + globRoot = t.testdir(globDir) + npmHelpErr = new Error('help broke') + t.teardown(() => { + OUTPUT.length = 0 + npmHelpArgs = null + npmHelpErr = null + globRoot = null + }) + + return helpSearch(['does not exist in'], (err) => { + t.strictSame(npmHelpArgs, ['npm-install'], 'identified the correct man page and called help with it') + t.match(err, /help broke/, 'propagated the error from help') + t.end() + }) +}) + +test('npm help-search long output', t => { + globRoot = t.testdir(globDir) + npm.flatOptions.long = true + t.teardown(() => { + OUTPUT.length = 0 + npm.flatOptions.long = false + globRoot = null + }) + + return helpSearch(['exec'], (err) => { + if (err) + throw err + + t.match(OUTPUT, /has multiple lines of exec help/, 'outputs detailed results') + t.end() + }) +}) + +test('npm help-search long output with color', t => { + globRoot = t.testdir(globDir) + npm.flatOptions.long = true + npm.color = true + t.teardown(() => { + OUTPUT.length = 0 + npm.flatOptions.long = false + npm.color = false + globRoot = null + }) + + return helpSearch(['help-search'], (err) => { + if (err) + throw err + + const highlightedText = ansicolors.bgBlack(ansicolors.red('help-search')) + t.equal(OUTPUT.some((line) => line.includes(highlightedText)), true, 'returned highlighted search terms') + t.end() + }) +}) + +test('npm help-search no args', t => { + return helpSearch([], (err) => { + t.match(err, /npm help-search/, 'throws usage') + t.end() + }) +}) + +test('npm help-search no matches', t => { + globRoot = t.testdir(globDir) + t.teardown(() => { + OUTPUT.length = 0 + npmUsageArg = null + globRoot = null + }) + + return helpSearch(['asdfasdf'], (err) => { + if (err) + throw err + + t.equal(npmUsageArg, false, 'called npmUsage for no matches') + t.end() + }) +}) diff --git a/test/lib/help.js b/test/lib/help.js new file mode 100644 index 0000000000000..17018acc61620 --- /dev/null +++ b/test/lib/help.js @@ -0,0 +1,362 @@ +const { test } = require('tap') +const requireInject = require('require-inject') +const { EventEmitter } = require('events') + +let npmUsageArg = null +const npmUsage = (arg) => { + npmUsageArg = arg +} + +const npmConfig = { + usage: false, + viewer: undefined, + loglevel: undefined, +} + +let helpSearchArgs = null +const npm = { + config: { + get: (key) => npmConfig[key], + set: (key, value) => { + npmConfig[key] = value + }, + parsedArgv: { + cooked: [], + }, + }, + commands: { + 'help-search': (args, cb) => { + helpSearchArgs = args + return cb() + }, + help: { + usage: 'npm help ', + }, + }, + deref: (cmd) => {}, +} + +const OUTPUT = [] +const output = (msg) => { + OUTPUT.push(msg) +} + +const globDefaults = [ + '/root/man/man1/npm-whoami.1', + '/root/man/man5/npmrc.5', + '/root/man/man7/disputes.7', +] + +let globErr = null +let globResult = globDefaults +const glob = (p, cb) => { + return cb(globErr, globResult) +} + +let spawnBin = null +let spawnArgs = null +const spawn = (bin, args) => { + spawnBin = bin + spawnArgs = args + const spawnEmitter = new EventEmitter() + process.nextTick(() => { + spawnEmitter.emit('close', 0) + }) + return spawnEmitter +} + +let openUrlArg = null +const openUrl = (url, msg, cb) => { + openUrlArg = url + return cb() +} + +const help = requireInject('../../lib/help.js', { + '../../lib/npm.js': npm, + '../../lib/utils/npm-usage.js': npmUsage, + '../../lib/utils/open-url.js': openUrl, + '../../lib/utils/output.js': output, + '../../lib/utils/spawn.js': spawn, + glob, +}) + +test('npm help', t => { + t.teardown(() => { + npmUsageArg = null + }) + + return help([], (err) => { + if (err) + throw err + + t.equal(npmUsageArg, false, 'called npmUsage') + t.end() + }) +}) + +test('npm help completion', async t => { + t.teardown(() => { + globErr = null + }) + const completion = (opts) => new Promise((resolve, reject) => { + help.completion(opts, (err, res) => { + if (err) + return reject(err) + return resolve(res) + }) + }) + + const noArgs = await completion({ conf: { argv: { remain: [] } } }) + t.strictSame(noArgs, ['help', 'whoami', 'npmrc', 'disputes'], 'outputs available help pages') + const threeArgs = await completion({ conf: { argv: { remain: ['one', 'two', 'three'] } } }) + t.strictSame(threeArgs, [], 'outputs no results when more than 2 args are provided') + globErr = new Error('glob failed') + t.rejects(completion({ conf: { argv: { remain: [] } } }), /glob failed/, 'glob errors propagate') +}) + +test('npm help -h', t => { + npmConfig.usage = true + t.teardown(() => { + npmConfig.usage = false + OUTPUT.length = 0 + }) + + return help(['help'], (err) => { + if (err) + throw err + + t.strictSame(OUTPUT, ['npm help '], 'outputs usage information for command') + t.end() + }) +}) + +test('npm help multiple args calls search', t => { + t.teardown(() => { + helpSearchArgs = null + }) + + return help(['run', 'script'], (err) => { + if (err) + throw err + + t.strictSame(helpSearchArgs, ['run', 'script'], 'passed the args to help-search') + t.end() + }) +}) + +test('npm help no matches calls search', t => { + globResult = [] + t.teardown(() => { + helpSearchArgs = null + globResult = globDefaults + }) + + return help(['asdfasdf'], (err) => { + if (err) + throw err + + t.strictSame(helpSearchArgs, ['asdfasdf'], 'passed the args to help-search') + t.end() + }) +}) + +test('npm help glob errors propagate', t => { + globErr = new Error('glob failed') + t.teardown(() => { + globErr = null + spawnBin = null + spawnArgs = null + }) + + return help(['whoami'], (err) => { + t.match(err, /glob failed/, 'glob error propagates') + t.end() + }) +}) + +test('npm help whoami', t => { + globResult = ['/root/man/man1/npm-whoami.1.xz'] + t.teardown(() => { + globResult = globDefaults + spawnBin = null + spawnArgs = null + }) + + return help(['whoami'], (err) => { + if (err) + throw err + + t.equal(spawnBin, 'man', 'calls man by default') + t.strictSame(spawnArgs, ['1', 'npm-whoami'], 'passes the correct arguments') + t.end() + }) +}) + +test('npm help 1 install', t => { + npmConfig.viewer = 'browser' + globResult = [ + '/root/man/man5/install.5', + '/root/man/man1/npm-install.1', + ] + + t.teardown(() => { + npmConfig.viewer = undefined + globResult = globDefaults + spawnBin = null + spawnArgs = null + }) + + return help(['1', 'install'], (err) => { + if (err) + throw err + + t.match(openUrlArg, /commands(\/|\\)npm-install.html$/, 'attempts to open the correct url') + t.end() + }) +}) + +test('npm help 5 install', t => { + npmConfig.viewer = 'browser' + globResult = [ + '/root/man/man5/install.5', + '/root/man/man1/npm-install.1', + ] + + t.teardown(() => { + npmConfig.viewer = undefined + globResult = globDefaults + spawnBin = null + spawnArgs = null + }) + + return help(['5', 'install'], (err) => { + if (err) + throw err + + t.match(openUrlArg, /configuring-npm(\/|\\)install.html$/, 'attempts to open the correct url') + t.end() + }) +}) + +test('npm help 7 config', t => { + npmConfig.viewer = 'browser' + globResult = [ + '/root/man/man1/npm-config.1', + '/root/man/man7/config.7', + ] + t.teardown(() => { + npmConfig.viewer = undefined + globResult = globDefaults + spawnBin = null + spawnArgs = null + }) + + return help(['7', 'config'], (err) => { + if (err) + throw err + + t.match(openUrlArg, /using-npm(\/|\\)config.html$/, 'attempts to open the correct url') + t.end() + }) +}) + +test('npm help with browser viewer and invalid section throws', t => { + npmConfig.viewer = 'browser' + globResult = [ + '/root/man/man1/npm-config.1', + '/root/man/man7/config.7', + '/root/man/man9/config.9', + ] + t.teardown(() => { + npmConfig.viewer = undefined + globResult = globDefaults + spawnBin = null + spawnArgs = null + }) + + return help(['9', 'config'], (err) => { + t.match(err, /invalid man section: 9/, 'throws appropriate error') + t.end() + }) +}) + +test('npm help global redirects to folders', t => { + globResult = ['/root/man/man5/folders.5'] + t.teardown(() => { + globResult = globDefaults + spawnBin = null + spawnArgs = null + }) + + return help(['global'], (err) => { + if (err) + throw err + + t.equal(spawnBin, 'man', 'calls man by default') + t.strictSame(spawnArgs, ['5', 'folders'], 'passes the correct arguments') + t.end() + }) +}) + +test('npm help package.json redirects to package-json', t => { + globResult = ['/root/man/man5/package-json.5'] + t.teardown(() => { + globResult = globDefaults + spawnBin = null + spawnArgs = null + }) + + return help(['package.json'], (err) => { + if (err) + throw err + + t.equal(spawnBin, 'man', 'calls man by default') + t.strictSame(spawnArgs, ['5', 'package-json'], 'passes the correct arguments') + t.end() + }) +}) + +test('npm help ?(un)star', t => { + npmConfig.viewer = 'woman' + globResult = [ + '/root/man/man1/npm-star.1', + '/root/man/man1/npm-unstar.1', + ] + t.teardown(() => { + npmConfig.viewer = undefined + globResult = globDefaults + spawnBin = null + spawnArgs = null + }) + + return help(['?(un)star'], (err) => { + if (err) + throw err + + t.equal(spawnBin, 'emacsclient', 'maps woman to emacs correctly') + t.strictSame(spawnArgs, ['-e', `(woman-find-file '/root/man/man1/npm-unstar.1')`], 'passes the correct arguments') + t.end() + }) +}) + +test('npm help un*', t => { + globResult = [ + '/root/man/man1/npm-unstar.1', + '/root/man/man1/npm-uninstall.1', + '/root/man/man1/npm-unpublish.1', + ] + t.teardown(() => { + globResult = globDefaults + spawnBin = null + spawnArgs = null + }) + + return help(['un*'], (err) => { + if (err) + throw err + + t.equal(spawnBin, 'man', 'calls man by default') + t.strictSame(spawnArgs, ['1', 'npm-unstar'], 'passes the correct arguments') + t.end() + }) +}) diff --git a/test/lib/hook.js b/test/lib/hook.js new file mode 100644 index 0000000000000..3599042021f38 --- /dev/null +++ b/test/lib/hook.js @@ -0,0 +1,589 @@ +const { test } = require('tap') +const requireInject = require('require-inject') + +const npm = { + flatOptions: { + json: false, + parseable: false, + silent: false, + loglevel: 'info', + unicode: false, + }, +} + +const pkgTypes = { + semver: 'package', + '@npmcli': 'scope', + npm: 'owner', +} + +const now = Date.now() +let hookResponse = null +let hookArgs = null +const libnpmhook = { + add: async (pkg, uri, secret, opts) => { + hookArgs = { pkg, uri, secret, opts } + return { id: 1, name: pkg.replace(/^@/, ''), type: pkgTypes[pkg], endpoint: uri } + }, + ls: async (opts) => { + hookArgs = opts + let id = 0 + if (hookResponse) + return hookResponse + + return Object.keys(pkgTypes).map((name) => ({ + id: ++id, + name: name.replace(/^@/, ''), + type: pkgTypes[name], + endpoint: 'https://google.com', + last_delivery: id % 2 === 0 ? now : undefined, + })) + }, + rm: async (id, opts) => { + hookArgs = { id, opts } + const pkg = Object.keys(pkgTypes)[0] + return { id: 1, name: pkg.replace(/^@/, ''), type: pkgTypes[pkg], endpoint: 'https://google.com' } + }, + update: async (id, uri, secret, opts) => { + hookArgs = { id, uri, secret, opts } + const pkg = Object.keys(pkgTypes)[0] + return { id, name: pkg.replace(/^@/, ''), type: pkgTypes[pkg], endpoint: uri } + }, +} + +const output = [] +const hook = requireInject('../../lib/hook.js', { + '../../lib/npm.js': npm, + '../../lib/utils/otplease.js': async (opts, fn) => fn(opts), + '../../lib/utils/output.js': (msg) => { + output.push(msg) + }, + libnpmhook, +}) + +test('npm hook no args', t => { + return hook([], (err) => { + t.match(err, /npm hook add/, 'throws usage with no arguments') + t.end() + }) +}) + +test('npm hook add', t => { + t.teardown(() => { + hookArgs = null + output.length = 0 + }) + + return hook(['add', 'semver', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + pkg: 'semver', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'provided the correct arguments to libnpmhook') + t.strictSame(output, ['+ semver -> https://google.com'], 'prints the correct output') + t.end() + }) +}) + +test('npm hook add - unicode output', t => { + npm.flatOptions.unicode = true + t.teardown(() => { + npm.flatOptions.unicode = false + hookArgs = null + output.length = 0 + }) + + return hook(['add', 'semver', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + pkg: 'semver', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'provided the correct arguments to libnpmhook') + t.strictSame(output, ['+ semver ➜ https://google.com'], 'prints the correct output') + t.end() + }) +}) + +test('npm hook add - json output', t => { + npm.flatOptions.json = true + t.teardown(() => { + npm.flatOptions.json = false + hookArgs = null + output.length = 0 + }) + + return hook(['add', '@npmcli', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + pkg: '@npmcli', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'provided the correct arguments to libnpmhook') + t.strictSame(JSON.parse(output[0]), { + id: 1, + name: 'npmcli', + endpoint: 'https://google.com', + type: 'scope', + }, 'prints the correct json output') + t.end() + }) +}) + +test('npm hook add - parseable output', t => { + npm.flatOptions.parseable = true + t.teardown(() => { + npm.flatOptions.parseable = false + hookArgs = null + output.length = 0 + }) + + return hook(['add', '@npmcli', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + pkg: '@npmcli', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'provided the correct arguments to libnpmhook') + t.strictSame(output[0].split(/\t/), [ + 'id', 'name', 'type', 'endpoint', + ], 'prints the correct parseable output headers') + t.strictSame(output[1].split(/\t/), [ + '1', 'npmcli', 'scope', 'https://google.com', + ], 'prints the correct parseable values') + t.end() + }) +}) + +test('npm hook add - silent output', t => { + npm.flatOptions.silent = true + t.teardown(() => { + npm.flatOptions.silent = false + hookArgs = null + output.length = 0 + }) + + return hook(['add', '@npmcli', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + pkg: '@npmcli', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'provided the correct arguments to libnpmhook') + t.strictSame(output, [], 'printed no output') + t.end() + }) +}) + +test('npm hook ls', t => { + t.teardown(() => { + hookArgs = null + output.length = 0 + }) + + return hook(['ls'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + ...npm.flatOptions, + package: undefined, + }, 'received the correct arguments') + t.equal(output[0], 'You have 3 hooks configured.', 'prints the correct header') + const out = require('../../lib/utils/ansi-trim')(output[1]) + t.match(out, /semver.*https:\/\/google.com.*\n.*\n.*never triggered/, 'prints package hook') + t.match(out, /@npmcli.*https:\/\/google.com.*\n.*\n.*triggered just now/, 'prints scope hook') + t.match(out, /~npm.*https:\/\/google.com.*\n.*\n.*never triggered/, 'prints owner hook') + t.end() + }) +}) + +test('npm hook ls, no results', t => { + hookResponse = [] + t.teardown(() => { + hookResponse = null + hookArgs = null + output.length = 0 + }) + + return hook(['ls'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + ...npm.flatOptions, + package: undefined, + }, 'received the correct arguments') + t.equal(output[0], 'You don\'t have any hooks configured yet.', 'prints the correct result') + t.end() + }) +}) + +test('npm hook ls, single result', t => { + hookResponse = [{ + id: 1, + name: 'semver', + type: 'package', + endpoint: 'https://google.com', + }] + + t.teardown(() => { + hookResponse = null + hookArgs = null + output.length = 0 + }) + + return hook(['ls'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + ...npm.flatOptions, + package: undefined, + }, 'received the correct arguments') + t.equal(output[0], 'You have one hook configured.', 'prints the correct header') + const out = require('../../lib/utils/ansi-trim')(output[1]) + t.match(out, /semver.*https:\/\/google.com.*\n.*\n.*never triggered/, 'prints package hook') + t.end() + }) +}) + +test('npm hook ls - json output', t => { + npm.flatOptions.json = true + t.teardown(() => { + npm.flatOptions.json = false + hookArgs = null + output.length = 0 + }) + + return hook(['ls'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + ...npm.flatOptions, + package: undefined, + }, 'received the correct arguments') + const out = JSON.parse(output[0]) + t.match(out, [{ + id: 1, + name: 'semver', + type: 'package', + endpoint: 'https://google.com', + }, { + id: 2, + name: 'npmcli', + type: 'scope', + endpoint: 'https://google.com', + }, { + id: 3, + name: 'npm', + type: 'owner', + endpoint: 'https://google.com', + }], 'prints the correct output') + t.end() + }) +}) + +test('npm hook ls - parseable output', t => { + npm.flatOptions.parseable = true + t.teardown(() => { + npm.flatOptions.parseable = false + hookArgs = null + output.length = 0 + }) + + return hook(['ls'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + ...npm.flatOptions, + package: undefined, + }, 'received the correct arguments') + t.strictSame(output.map(line => line.split(/\t/)), [ + ['id', 'name', 'type', 'endpoint', 'last_delivery'], + ['1', 'semver', 'package', 'https://google.com', ''], + ['2', 'npmcli', 'scope', 'https://google.com', `${now}`], + ['3', 'npm', 'owner', 'https://google.com', ''], + ], 'prints the correct result') + t.end() + }) +}) + +test('npm hook ls - silent output', t => { + npm.flatOptions.silent = true + t.teardown(() => { + npm.flatOptions.silent = false + hookArgs = null + output.length = 0 + }) + + return hook(['ls'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + ...npm.flatOptions, + package: undefined, + }, 'received the correct arguments') + t.strictSame(output, [], 'printed no output') + t.end() + }) +}) + +test('npm hook rm', t => { + t.teardown(() => { + hookArgs = null + output.length = 0 + }) + + return hook(['rm', '1'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output, [ + '- semver X https://google.com', + ], 'printed the correct output') + t.end() + }) +}) + +test('npm hook rm - unicode output', t => { + npm.flatOptions.unicode = true + t.teardown(() => { + npm.flatOptions.unicode = false + hookArgs = null + output.length = 0 + }) + + return hook(['rm', '1'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output, [ + '- semver ✘ https://google.com', + ], 'printed the correct output') + t.end() + }) +}) + +test('npm hook rm - silent output', t => { + npm.flatOptions.silent = true + t.teardown(() => { + npm.flatOptions.silent = false + hookArgs = null + output.length = 0 + }) + + return hook(['rm', '1'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output, [], 'printed no output') + t.end() + }) +}) + +test('npm hook rm - json output', t => { + npm.flatOptions.json = true + t.teardown(() => { + npm.flatOptions.json = false + hookArgs = null + output.length = 0 + }) + + return hook(['rm', '1'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(JSON.parse(output[0]), { + id: 1, + name: 'semver', + type: 'package', + endpoint: 'https://google.com', + }, 'printed correct output') + t.end() + }) +}) + +test('npm hook rm - parseable output', t => { + npm.flatOptions.parseable = true + t.teardown(() => { + npm.flatOptions.parseable = false + hookArgs = null + output.length = 0 + }) + + return hook(['rm', '1'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output.map(line => line.split(/\t/)), [ + ['id', 'name', 'type', 'endpoint'], + ['1', 'semver', 'package', 'https://google.com'], + ], 'printed correct output') + t.end() + }) +}) + +test('npm hook update', t => { + t.teardown(() => { + hookArgs = null + output.length = 0 + }) + + return hook(['update', '1', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output, [ + '+ semver -> https://google.com', + ], 'printed the correct output') + t.end() + }) +}) + +test('npm hook update - unicode', t => { + npm.flatOptions.unicode = true + t.teardown(() => { + npm.flatOptions.unicode = false + hookArgs = null + output.length = 0 + }) + + return hook(['update', '1', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output, [ + '+ semver ➜ https://google.com', + ], 'printed the correct output') + t.end() + }) +}) + +test('npm hook update - json output', t => { + npm.flatOptions.json = true + t.teardown(() => { + npm.flatOptions.json = false + hookArgs = null + output.length = 0 + }) + + return hook(['update', '1', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(JSON.parse(output[0]), { + id: '1', + name: 'semver', + type: 'package', + endpoint: 'https://google.com', + }, 'printed the correct output') + t.end() + }) +}) + +test('npm hook update - parseable output', t => { + npm.flatOptions.parseable = true + t.teardown(() => { + npm.flatOptions.parseable = false + hookArgs = null + output.length = 0 + }) + + return hook(['update', '1', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output.map(line => line.split(/\t/)), [ + ['id', 'name', 'type', 'endpoint'], + ['1', 'semver', 'package', 'https://google.com'], + ], 'printed the correct output') + t.end() + }) +}) + +test('npm hook update - silent output', t => { + npm.flatOptions.silent = true + t.teardown(() => { + npm.flatOptions.silent = false + hookArgs = null + output.length = 0 + }) + + return hook(['update', '1', 'https://google.com', 'some-secret'], (err) => { + if (err) + throw err + + t.strictSame(hookArgs, { + id: '1', + uri: 'https://google.com', + secret: 'some-secret', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output, [], 'printed no output') + t.end() + }) +}) diff --git a/test/lib/org.js b/test/lib/org.js new file mode 100644 index 0000000000000..68e3c9f0d6c8b --- /dev/null +++ b/test/lib/org.js @@ -0,0 +1,585 @@ +const { test } = require('tap') +const requireInject = require('require-inject') +const ansiTrim = require('../../lib/utils/ansi-trim.js') + +const npm = { + flatOptions: { + json: false, + parseable: false, + silent: false, + loglevel: 'info', + }, +} + +const output = [] + +let orgSize = 1 +let orgSetArgs = null +let orgRmArgs = null +let orgLsArgs = null +let orgList = {} +const libnpmorg = { + set: async (org, user, role, opts) => { + orgSetArgs = { org, user, role, opts } + return { + org: { + name: org, + size: orgSize, + }, + user, + role, + } + }, + rm: async (org, user, opts) => { + orgRmArgs = { org, user, opts } + }, + ls: async (org, opts) => { + orgLsArgs = { org, opts } + return orgList + }, +} + +const org = requireInject('../../lib/org.js', { + '../../lib/npm.js': npm, + '../../lib/utils/otplease.js': async (opts, fn) => fn(opts), + '../../lib/utils/output.js': (msg) => { + output.push(msg) + }, + libnpmorg, +}) + +test('completion', async t => { + const completion = (argv) => new Promise((resolve, reject) => { + org.completion({ conf: { argv: { remain: argv } } }, (err, res) => { + if (err) + return reject(err) + return resolve(res) + }) + }) + + const assertions = [ + [['npm', 'org'], ['set', 'rm', 'ls']], + [['npm', 'org', 'ls'], []], + [['npm', 'org', 'add'], []], + [['npm', 'org', 'rm'], []], + [['npm', 'org', 'set'], []], + ] + + for (const [argv, expected] of assertions) + t.strictSame(await completion(argv), expected, `completion for: ${argv.join(', ')}`) + + t.rejects(completion(['npm', 'org', 'flurb']), /flurb not recognized/, 'errors for unknown subcommand') +}) + +test('npm org - invalid subcommand', t => { + return org(['foo'], (err) => { + t.match(err, /npm org set/, 'prints usage information') + t.end() + }) +}) + +test('npm org add', t => { + t.teardown(() => { + orgSetArgs = null + output.length = 0 + }) + + return org(['add', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgSetArgs, { + org: 'orgname', + user: 'username', + role: 'developer', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.equal(output[0], 'Added username as developer to orgname. You now have 1 member in this org.', 'printed the correct output') + t.end() + }) +}) + +test('npm org add - no org', t => { + t.teardown(() => { + orgSetArgs = null + output.length = 0 + }) + + return org(['add', '', 'username'], (err) => { + t.match(err, /`orgname` is required/, 'returns the correct error') + t.end() + }) +}) + +test('npm org add - no user', t => { + t.teardown(() => { + orgSetArgs = null + output.length = 0 + }) + + return org(['add', 'orgname', ''], (err) => { + t.match(err, /`username` is required/, 'returns the correct error') + t.end() + }) +}) + +test('npm org add - invalid role', t => { + t.teardown(() => { + orgSetArgs = null + output.length = 0 + }) + + return org(['add', 'orgname', 'username', 'person'], (err) => { + t.match(err, /`role` must be one of/, 'returns the correct error') + t.end() + }) +}) + +test('npm org add - more users', t => { + orgSize = 5 + t.teardown(() => { + orgSize = 1 + orgSetArgs = null + output.length = 0 + }) + + return org(['add', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgSetArgs, { + org: 'orgname', + user: 'username', + role: 'developer', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.equal(output[0], 'Added username as developer to orgname. You now have 5 members in this org.', 'printed the correct output') + t.end() + }) +}) + +test('npm org add - json output', t => { + npm.flatOptions.json = true + t.teardown(() => { + npm.flatOptions.json = false + orgSetArgs = null + output.length = 0 + }) + + return org(['add', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgSetArgs, { + org: 'orgname', + user: 'username', + role: 'developer', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(JSON.parse(output[0]), { + org: { + name: 'orgname', + size: 1, + }, + user: 'username', + role: 'developer', + }, 'printed the correct output') + t.end() + }) +}) + +test('npm org add - parseable output', t => { + npm.flatOptions.parseable = true + t.teardown(() => { + npm.flatOptions.parseable = false + orgSetArgs = null + output.length = 0 + }) + + return org(['add', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgSetArgs, { + org: 'orgname', + user: 'username', + role: 'developer', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output.map(line => line.split(/\t/)), [ + ['org', 'orgsize', 'user', 'role'], + ['orgname', '1', 'username', 'developer'], + ], 'printed the correct output') + t.end() + }) +}) + +test('npm org add - silent output', t => { + npm.flatOptions.silent = true + t.teardown(() => { + npm.flatOptions.silent = false + orgSetArgs = null + output.length = 0 + }) + + return org(['add', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgSetArgs, { + org: 'orgname', + user: 'username', + role: 'developer', + opts: npm.flatOptions, + }, 'received the correct arguments') + t.strictSame(output, [], 'prints no output') + t.end() + }) +}) + +test('npm org rm', t => { + t.teardown(() => { + orgRmArgs = null + orgLsArgs = null + output.length = 0 + }) + + return org(['rm', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgRmArgs, { + org: 'orgname', + user: 'username', + opts: npm.flatOptions, + }, 'libnpmorg.rm received the correct args') + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'libnpmorg.ls received the correct args') + t.equal(output[0], 'Successfully removed username from orgname. You now have 0 members in this org.', 'printed the correct output') + t.end() + }) +}) + +test('npm org rm - no org', t => { + t.teardown(() => { + orgRmArgs = null + orgLsArgs = null + output.length = 0 + }) + + return org(['rm', '', 'username'], (err) => { + t.match(err, /`orgname` is required/, 'threw the correct error') + t.end() + }) +}) + +test('npm org rm - no user', t => { + t.teardown(() => { + orgRmArgs = null + orgLsArgs = null + output.length = 0 + }) + + return org(['rm', 'orgname'], (err) => { + t.match(err, /`username` is required/, 'threw the correct error') + t.end() + }) +}) + +test('npm org rm - one user left', t => { + orgList = { + one: 'developer', + } + + t.teardown(() => { + orgList = {} + orgRmArgs = null + orgLsArgs = null + output.length = 0 + }) + + return org(['rm', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgRmArgs, { + org: 'orgname', + user: 'username', + opts: npm.flatOptions, + }, 'libnpmorg.rm received the correct args') + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'libnpmorg.ls received the correct args') + t.equal(output[0], 'Successfully removed username from orgname. You now have 1 member in this org.', 'printed the correct output') + t.end() + }) +}) + +test('npm org rm - json output', t => { + npm.flatOptions.json = true + t.teardown(() => { + npm.flatOptions.json = false + orgRmArgs = null + orgLsArgs = null + output.length = 0 + }) + + return org(['rm', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgRmArgs, { + org: 'orgname', + user: 'username', + opts: npm.flatOptions, + }, 'libnpmorg.rm received the correct args') + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'libnpmorg.ls received the correct args') + t.strictSame(JSON.parse(output[0]), { + user: 'username', + org: 'orgname', + userCount: 0, + deleted: true, + }, 'printed the correct output') + t.end() + }) +}) + +test('npm org rm - parseable output', t => { + npm.flatOptions.parseable = true + t.teardown(() => { + npm.flatOptions.parseable = false + orgRmArgs = null + orgLsArgs = null + output.length = 0 + }) + + return org(['rm', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgRmArgs, { + org: 'orgname', + user: 'username', + opts: npm.flatOptions, + }, 'libnpmorg.rm received the correct args') + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'libnpmorg.ls received the correct args') + t.strictSame(output.map(line => line.split(/\t/)), [ + ['user', 'org', 'userCount', 'deleted'], + ['username', 'orgname', '0', 'true'], + ], 'printed the correct output') + t.end() + }) +}) + +test('npm org rm - silent output', t => { + npm.flatOptions.silent = true + t.teardown(() => { + npm.flatOptions.silent = false + orgRmArgs = null + orgLsArgs = null + output.length = 0 + }) + + return org(['rm', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgRmArgs, { + org: 'orgname', + user: 'username', + opts: npm.flatOptions, + }, 'libnpmorg.rm received the correct args') + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'libnpmorg.ls received the correct args') + t.strictSame(output, [], 'printed no output') + t.end() + }) +}) + +test('npm org ls', t => { + orgList = { + one: 'developer', + two: 'admin', + three: 'owner', + } + t.teardown(() => { + orgList = {} + orgLsArgs = null + output.length = 0 + }) + + return org(['ls', 'orgname'], (err) => { + if (err) + throw err + + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'receieved the correct args') + const out = ansiTrim(output[0]) + t.match(out, /one.*developer/, 'contains the developer member') + t.match(out, /two.*admin/, 'contains the admin member') + t.match(out, /three.*owner/, 'contains the owner member') + t.end() + }) +}) + +test('npm org ls - user filter', t => { + orgList = { + username: 'admin', + missing: 'admin', + } + t.teardown(() => { + orgList = {} + orgLsArgs = null + output.length = 0 + }) + + return org(['ls', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'receieved the correct args') + const out = ansiTrim(output[0]) + t.match(out, /username.*admin/, 'contains the filtered member') + t.notMatch(out, /missing.*admin/, 'does not contain other members') + t.end() + }) +}) + +test('npm org ls - user filter, missing user', t => { + orgList = { + missing: 'admin', + } + t.teardown(() => { + orgList = {} + orgLsArgs = null + output.length = 0 + }) + + return org(['ls', 'orgname', 'username'], (err) => { + if (err) + throw err + + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'receieved the correct args') + const out = ansiTrim(output[0]) + t.notMatch(out, /username/, 'does not contain the requested member') + t.notMatch(out, /missing.*admin/, 'does not contain other members') + t.end() + }) +}) + +test('npm org ls - no org', t => { + t.teardown(() => { + orgLsArgs = null + output.length = 0 + }) + + return org(['ls'], (err) => { + t.match(err, /`orgname` is required/, 'throws the correct error') + t.end() + }) +}) + +test('npm org ls - json output', t => { + npm.flatOptions.json = true + orgList = { + one: 'developer', + two: 'admin', + three: 'owner', + } + t.teardown(() => { + npm.flatOptions.json = false + orgList = {} + orgLsArgs = null + output.length = 0 + }) + + return org(['ls', 'orgname'], (err) => { + if (err) + throw err + + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'receieved the correct args') + t.strictSame(JSON.parse(output[0]), orgList, 'prints the correct output') + t.end() + }) +}) + +test('npm org ls - parseable output', t => { + npm.flatOptions.parseable = true + orgList = { + one: 'developer', + two: 'admin', + three: 'owner', + } + t.teardown(() => { + npm.flatOptions.parseable = false + orgList = {} + orgLsArgs = null + output.length = 0 + }) + + return org(['ls', 'orgname'], (err) => { + if (err) + throw err + + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'receieved the correct args') + t.strictSame(output.map(line => line.split(/\t/)), [ + ['user', 'role'], + ['one', 'developer'], + ['two', 'admin'], + ['three', 'owner'], + ], 'printed the correct output') + t.end() + }) +}) + +test('npm org ls - silent output', t => { + npm.flatOptions.silent = true + orgList = { + one: 'developer', + two: 'admin', + three: 'owner', + } + t.teardown(() => { + npm.flatOptions.silent = false + orgList = {} + orgLsArgs = null + output.length = 0 + }) + + return org(['ls', 'orgname'], (err) => { + if (err) + throw err + + t.strictSame(orgLsArgs, { + org: 'orgname', + opts: npm.flatOptions, + }, 'receieved the correct args') + t.strictSame(output, [], 'printed no output') + t.end() + }) +}) diff --git a/test/lib/rebuild.js b/test/lib/rebuild.js index dbc37d57af566..d9df048d9057e 100644 --- a/test/lib/rebuild.js +++ b/test/lib/rebuild.js @@ -174,8 +174,48 @@ t.test('filter by pkg@', t => { }) }) -t.test('filter must be a semver version/range', t => { - rebuild(['b:git+ssh://github.com/npm/arborist'], err => { +t.test('filter by directory', t => { + const path = t.testdir({ + node_modules: { + a: { + 'index.js': '', + 'package.json': JSON.stringify({ + name: 'a', + version: '1.0.0', + bin: 'index.js', + }), + }, + b: { + 'index.js': '', + 'package.json': JSON.stringify({ + name: 'b', + version: '1.0.0', + bin: 'index.js', + }), + }, + }, + }) + + npm.prefix = path + + const aBinFile = resolve(path, 'node_modules/.bin/a') + const bBinFile = resolve(path, 'node_modules/.bin/b') + t.throws(() => fs.statSync(aBinFile)) + t.throws(() => fs.statSync(bBinFile)) + + rebuild(['file:node_modules/b'], err => { + if (err) + throw err + + t.throws(() => fs.statSync(aBinFile), 'should not link a bin') + t.ok(() => fs.statSync(bBinFile), 'should link filtered pkg bin') + + t.end() + }) +}) + +t.test('filter must be a semver version/range, or directory', t => { + rebuild(['git+ssh://github.com/npm/arborist'], err => { t.match( err, /Error: `npm rebuild` only supports SemVer version\/range specifiers/, diff --git a/test/lib/set.js b/test/lib/set.js new file mode 100644 index 0000000000000..aeb239e9c4e39 --- /dev/null +++ b/test/lib/set.js @@ -0,0 +1,33 @@ +const { test } = require('tap') +const requireInject = require('require-inject') + +let configArgs = null +const npm = { + commands: { + config: (args, cb) => { + configArgs = args + return cb() + }, + }, +} + +const set = requireInject('../../lib/set.js', { + '../../lib/npm.js': npm, +}) + +test('npm set - no args', t => { + return set([], (err) => { + t.match(err, /npm set/, 'prints usage') + t.end() + }) +}) + +test('npm set', t => { + return set(['email', 'me@me.me'], (err) => { + if (err) + throw err + + t.strictSame(configArgs, ['set', 'email', 'me@me.me'], 'passed the correct arguments to config') + t.end() + }) +}) diff --git a/test/lib/utils/split-package-names.js b/test/lib/utils/split-package-names.js new file mode 100644 index 0000000000000..c69bb2a3dab8c --- /dev/null +++ b/test/lib/utils/split-package-names.js @@ -0,0 +1,17 @@ +'use strict' + +const { test } = require('tap') +const splitPackageNames = require('../../../lib/utils/split-package-names.js') + +test('splitPackageNames', t => { + const assertions = [ + ['semver', 'semver'], + ['read-pkg/semver', 'read-pkg/node_modules/semver'], + ['@npmcli/one/@npmcli/two', '@npmcli/one/node_modules/@npmcli/two'], + ['@npmcli/one/semver', '@npmcli/one/node_modules/semver'], + ] + + for (const [input, expected] of assertions) + t.equal(splitPackageNames(input), expected, `split ${input} correctly`) + t.end() +})