diff --git a/DEPENDENCIES.md b/DEPENDENCIES.md index ff979b48e92ed..7d13fb772b1b6 100644 --- a/DEPENDENCIES.md +++ b/DEPENDENCIES.md @@ -319,6 +319,7 @@ graph LR; isaacs-cliui-->strip-ansi; isaacs-cliui-->wrap-ansi-cjs; isaacs-cliui-->wrap-ansi; + isaacs-fs-minipass-->minipass; jackspeak-->isaacs-cliui["@isaacs/cliui"]; jackspeak-->pkgjs-parseargs["@pkgjs/parseargs"]; libnpmaccess-->nock; @@ -440,6 +441,7 @@ graph LR; minipass-pipeline-->minipass; minipass-sized-->minipass; minizlib-->minipass; + minizlib-->rimraf; minizlib-->yallist; node-gyp-->env-paths; node-gyp-->exponential-backoff; @@ -763,6 +765,7 @@ graph LR; strip-ansi-->ansi-regex; tar-->chownr; tar-->fs-minipass; + tar-->isaacs-fs-minipass["@isaacs/fs-minipass"]; tar-->minipass; tar-->minizlib; tar-->mkdirp; diff --git a/node_modules/.gitignore b/node_modules/.gitignore index b17cf5a8b16a8..7ce7e967ccd1a 100644 --- a/node_modules/.gitignore +++ b/node_modules/.gitignore @@ -30,37 +30,6 @@ /@npmcli/map-workspaces/node_modules/@npmcli/* !/@npmcli/map-workspaces/node_modules/@npmcli/name-from-folder !/@npmcli/metavuln-calculator -!/@npmcli/metavuln-calculator/node_modules/ -/@npmcli/metavuln-calculator/node_modules/* -!/@npmcli/metavuln-calculator/node_modules/@npmcli/ -/@npmcli/metavuln-calculator/node_modules/@npmcli/* -!/@npmcli/metavuln-calculator/node_modules/@npmcli/agent -!/@npmcli/metavuln-calculator/node_modules/@npmcli/fs -!/@npmcli/metavuln-calculator/node_modules/@npmcli/git -!/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents -!/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json -!/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn -!/@npmcli/metavuln-calculator/node_modules/@npmcli/redact -!/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script -!/@npmcli/metavuln-calculator/node_modules/cacache -!/@npmcli/metavuln-calculator/node_modules/hosted-git-info -!/@npmcli/metavuln-calculator/node_modules/ini -!/@npmcli/metavuln-calculator/node_modules/isexe -!/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors -!/@npmcli/metavuln-calculator/node_modules/make-fetch-happen -!/@npmcli/metavuln-calculator/node_modules/normalize-package-data -!/@npmcli/metavuln-calculator/node_modules/npm-bundled -!/@npmcli/metavuln-calculator/node_modules/npm-install-checks -!/@npmcli/metavuln-calculator/node_modules/npm-package-arg -!/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest -!/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch -!/@npmcli/metavuln-calculator/node_modules/pacote -!/@npmcli/metavuln-calculator/node_modules/proc-log -!/@npmcli/metavuln-calculator/node_modules/ssri -!/@npmcli/metavuln-calculator/node_modules/unique-filename -!/@npmcli/metavuln-calculator/node_modules/unique-slug -!/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name -!/@npmcli/metavuln-calculator/node_modules/which !/@npmcli/name-from-folder !/@npmcli/node-gyp !/@npmcli/package-json @@ -159,7 +128,6 @@ !/http-proxy-agent !/https-proxy-agent !/iconv-lite -!/ignore-walk !/imurmurhash !/indent-string !/ini @@ -237,7 +205,6 @@ !/npm-install-checks !/npm-normalize-package-bin !/npm-package-arg -!/npm-packlist !/npm-pick-manifest !/npm-pick-manifest/node_modules/ /npm-pick-manifest/node_modules/* diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/agents.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/agents.js deleted file mode 100644 index c541b93001517..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/agents.js +++ /dev/null @@ -1,206 +0,0 @@ -'use strict' - -const net = require('net') -const tls = require('tls') -const { once } = require('events') -const timers = require('timers/promises') -const { normalizeOptions, cacheOptions } = require('./options') -const { getProxy, getProxyAgent, proxyCache } = require('./proxy.js') -const Errors = require('./errors.js') -const { Agent: AgentBase } = require('agent-base') - -module.exports = class Agent extends AgentBase { - #options - #timeouts - #proxy - #noProxy - #ProxyAgent - - constructor (options = {}) { - const { timeouts, proxy, noProxy, ...normalizedOptions } = normalizeOptions(options) - - super(normalizedOptions) - - this.#options = normalizedOptions - this.#timeouts = timeouts - - if (proxy) { - this.#proxy = new URL(proxy) - this.#noProxy = noProxy - this.#ProxyAgent = getProxyAgent(proxy) - } - } - - get proxy () { - return this.#proxy ? { url: this.#proxy } : {} - } - - #getProxy (options) { - if (!this.#proxy) { - return - } - - const proxy = getProxy(`${options.protocol}//${options.host}:${options.port}`, { - proxy: this.#proxy, - noProxy: this.#noProxy, - }) - - if (!proxy) { - return - } - - const cacheKey = cacheOptions({ - ...options, - ...this.#options, - timeouts: this.#timeouts, - proxy, - }) - - if (proxyCache.has(cacheKey)) { - return proxyCache.get(cacheKey) - } - - let ProxyAgent = this.#ProxyAgent - if (Array.isArray(ProxyAgent)) { - ProxyAgent = this.isSecureEndpoint(options) ? ProxyAgent[1] : ProxyAgent[0] - } - - const proxyAgent = new ProxyAgent(proxy, { - ...this.#options, - socketOptions: { family: this.#options.family }, - }) - proxyCache.set(cacheKey, proxyAgent) - - return proxyAgent - } - - // takes an array of promises and races them against the connection timeout - // which will throw the necessary error if it is hit. This will return the - // result of the promise race. - async #timeoutConnection ({ promises, options, timeout }, ac = new AbortController()) { - if (timeout) { - const connectionTimeout = timers.setTimeout(timeout, null, { signal: ac.signal }) - .then(() => { - throw new Errors.ConnectionTimeoutError(`${options.host}:${options.port}`) - }).catch((err) => { - if (err.name === 'AbortError') { - return - } - throw err - }) - promises.push(connectionTimeout) - } - - let result - try { - result = await Promise.race(promises) - ac.abort() - } catch (err) { - ac.abort() - throw err - } - return result - } - - async connect (request, options) { - // if the connection does not have its own lookup function - // set, then use the one from our options - options.lookup ??= this.#options.lookup - - let socket - let timeout = this.#timeouts.connection - const isSecureEndpoint = this.isSecureEndpoint(options) - - const proxy = this.#getProxy(options) - if (proxy) { - // some of the proxies will wait for the socket to fully connect before - // returning so we have to await this while also racing it against the - // connection timeout. - const start = Date.now() - socket = await this.#timeoutConnection({ - options, - timeout, - promises: [proxy.connect(request, options)], - }) - // see how much time proxy.connect took and subtract it from - // the timeout - if (timeout) { - timeout = timeout - (Date.now() - start) - } - } else { - socket = (isSecureEndpoint ? tls : net).connect(options) - } - - socket.setKeepAlive(this.keepAlive, this.keepAliveMsecs) - socket.setNoDelay(this.keepAlive) - - const abortController = new AbortController() - const { signal } = abortController - - const connectPromise = socket[isSecureEndpoint ? 'secureConnecting' : 'connecting'] - ? once(socket, isSecureEndpoint ? 'secureConnect' : 'connect', { signal }) - : Promise.resolve() - - await this.#timeoutConnection({ - options, - timeout, - promises: [ - connectPromise, - once(socket, 'error', { signal }).then((err) => { - throw err[0] - }), - ], - }, abortController) - - if (this.#timeouts.idle) { - socket.setTimeout(this.#timeouts.idle, () => { - socket.destroy(new Errors.IdleTimeoutError(`${options.host}:${options.port}`)) - }) - } - - return socket - } - - addRequest (request, options) { - const proxy = this.#getProxy(options) - // it would be better to call proxy.addRequest here but this causes the - // http-proxy-agent to call its super.addRequest which causes the request - // to be added to the agent twice. since we only support 3 agents - // currently (see the required agents in proxy.js) we have manually - // checked that the only public methods we need to call are called in the - // next block. this could change in the future and presumably we would get - // failing tests until we have properly called the necessary methods on - // each of our proxy agents - if (proxy?.setRequestProps) { - proxy.setRequestProps(request, options) - } - - request.setHeader('connection', this.keepAlive ? 'keep-alive' : 'close') - - if (this.#timeouts.response) { - let responseTimeout - request.once('finish', () => { - setTimeout(() => { - request.destroy(new Errors.ResponseTimeoutError(request, this.#proxy)) - }, this.#timeouts.response) - }) - request.once('response', () => { - clearTimeout(responseTimeout) - }) - } - - if (this.#timeouts.transfer) { - let transferTimeout - request.once('response', (res) => { - setTimeout(() => { - res.destroy(new Errors.TransferTimeoutError(request, this.#proxy)) - }, this.#timeouts.transfer) - res.once('close', () => { - clearTimeout(transferTimeout) - }) - }) - } - - return super.addRequest(request, options) - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/dns.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/dns.js deleted file mode 100644 index 3c6946c566d73..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/dns.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict' - -const { LRUCache } = require('lru-cache') -const dns = require('dns') - -// this is a factory so that each request can have its own opts (i.e. ttl) -// while still sharing the cache across all requests -const cache = new LRUCache({ max: 50 }) - -const getOptions = ({ - family = 0, - hints = dns.ADDRCONFIG, - all = false, - verbatim = undefined, - ttl = 5 * 60 * 1000, - lookup = dns.lookup, -}) => ({ - // hints and lookup are returned since both are top level properties to (net|tls).connect - hints, - lookup: (hostname, ...args) => { - const callback = args.pop() // callback is always last arg - const lookupOptions = args[0] ?? {} - - const options = { - family, - hints, - all, - verbatim, - ...(typeof lookupOptions === 'number' ? { family: lookupOptions } : lookupOptions), - } - - const key = JSON.stringify({ hostname, ...options }) - - if (cache.has(key)) { - const cached = cache.get(key) - return process.nextTick(callback, null, ...cached) - } - - lookup(hostname, options, (err, ...result) => { - if (err) { - return callback(err) - } - - cache.set(key, result, { ttl }) - return callback(null, ...result) - }) - }, -}) - -module.exports = { - cache, - getOptions, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/errors.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/errors.js deleted file mode 100644 index 70475aec8eb35..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/errors.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict' - -class InvalidProxyProtocolError extends Error { - constructor (url) { - super(`Invalid protocol \`${url.protocol}\` connecting to proxy \`${url.host}\``) - this.code = 'EINVALIDPROXY' - this.proxy = url - } -} - -class ConnectionTimeoutError extends Error { - constructor (host) { - super(`Timeout connecting to host \`${host}\``) - this.code = 'ECONNECTIONTIMEOUT' - this.host = host - } -} - -class IdleTimeoutError extends Error { - constructor (host) { - super(`Idle timeout reached for host \`${host}\``) - this.code = 'EIDLETIMEOUT' - this.host = host - } -} - -class ResponseTimeoutError extends Error { - constructor (request, proxy) { - let msg = 'Response timeout ' - if (proxy) { - msg += `from proxy \`${proxy.host}\` ` - } - msg += `connecting to host \`${request.host}\`` - super(msg) - this.code = 'ERESPONSETIMEOUT' - this.proxy = proxy - this.request = request - } -} - -class TransferTimeoutError extends Error { - constructor (request, proxy) { - let msg = 'Transfer timeout ' - if (proxy) { - msg += `from proxy \`${proxy.host}\` ` - } - msg += `for \`${request.host}\`` - super(msg) - this.code = 'ETRANSFERTIMEOUT' - this.proxy = proxy - this.request = request - } -} - -module.exports = { - InvalidProxyProtocolError, - ConnectionTimeoutError, - IdleTimeoutError, - ResponseTimeoutError, - TransferTimeoutError, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/index.js deleted file mode 100644 index b33d6eaef07a2..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/index.js +++ /dev/null @@ -1,56 +0,0 @@ -'use strict' - -const { LRUCache } = require('lru-cache') -const { normalizeOptions, cacheOptions } = require('./options') -const { getProxy, proxyCache } = require('./proxy.js') -const dns = require('./dns.js') -const Agent = require('./agents.js') - -const agentCache = new LRUCache({ max: 20 }) - -const getAgent = (url, { agent, proxy, noProxy, ...options } = {}) => { - // false has meaning so this can't be a simple truthiness check - if (agent != null) { - return agent - } - - url = new URL(url) - - const proxyForUrl = getProxy(url, { proxy, noProxy }) - const normalizedOptions = { - ...normalizeOptions(options), - proxy: proxyForUrl, - } - - const cacheKey = cacheOptions({ - ...normalizedOptions, - secureEndpoint: url.protocol === 'https:', - }) - - if (agentCache.has(cacheKey)) { - return agentCache.get(cacheKey) - } - - const newAgent = new Agent(normalizedOptions) - agentCache.set(cacheKey, newAgent) - - return newAgent -} - -module.exports = { - getAgent, - Agent, - // these are exported for backwards compatability - HttpAgent: Agent, - HttpsAgent: Agent, - cache: { - proxy: proxyCache, - agent: agentCache, - dns: dns.cache, - clear: () => { - proxyCache.clear() - agentCache.clear() - dns.cache.clear() - }, - }, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/options.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/options.js deleted file mode 100644 index 0bf53f725f084..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/options.js +++ /dev/null @@ -1,86 +0,0 @@ -'use strict' - -const dns = require('./dns') - -const normalizeOptions = (opts) => { - const family = parseInt(opts.family ?? '0', 10) - const keepAlive = opts.keepAlive ?? true - - const normalized = { - // nodejs http agent options. these are all the defaults - // but kept here to increase the likelihood of cache hits - // https://nodejs.org/api/http.html#new-agentoptions - keepAliveMsecs: keepAlive ? 1000 : undefined, - maxSockets: opts.maxSockets ?? 15, - maxTotalSockets: Infinity, - maxFreeSockets: keepAlive ? 256 : undefined, - scheduling: 'fifo', - // then spread the rest of the options - ...opts, - // we already set these to their defaults that we want - family, - keepAlive, - // our custom timeout options - timeouts: { - // the standard timeout option is mapped to our idle timeout - // and then deleted below - idle: opts.timeout ?? 0, - connection: 0, - response: 0, - transfer: 0, - ...opts.timeouts, - }, - // get the dns options that go at the top level of socket connection - ...dns.getOptions({ family, ...opts.dns }), - } - - // remove timeout since we already used it to set our own idle timeout - delete normalized.timeout - - return normalized -} - -const createKey = (obj) => { - let key = '' - const sorted = Object.entries(obj).sort((a, b) => a[0] - b[0]) - for (let [k, v] of sorted) { - if (v == null) { - v = 'null' - } else if (v instanceof URL) { - v = v.toString() - } else if (typeof v === 'object') { - v = createKey(v) - } - key += `${k}:${v}:` - } - return key -} - -const cacheOptions = ({ secureEndpoint, ...options }) => createKey({ - secureEndpoint: !!secureEndpoint, - // socket connect options - family: options.family, - hints: options.hints, - localAddress: options.localAddress, - // tls specific connect options - strictSsl: secureEndpoint ? !!options.rejectUnauthorized : false, - ca: secureEndpoint ? options.ca : null, - cert: secureEndpoint ? options.cert : null, - key: secureEndpoint ? options.key : null, - // http agent options - keepAlive: options.keepAlive, - keepAliveMsecs: options.keepAliveMsecs, - maxSockets: options.maxSockets, - maxTotalSockets: options.maxTotalSockets, - maxFreeSockets: options.maxFreeSockets, - scheduling: options.scheduling, - // timeout options - timeouts: options.timeouts, - // proxy - proxy: options.proxy, -}) - -module.exports = { - normalizeOptions, - cacheOptions, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/proxy.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/proxy.js deleted file mode 100644 index 6272e929e57bc..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/lib/proxy.js +++ /dev/null @@ -1,88 +0,0 @@ -'use strict' - -const { HttpProxyAgent } = require('http-proxy-agent') -const { HttpsProxyAgent } = require('https-proxy-agent') -const { SocksProxyAgent } = require('socks-proxy-agent') -const { LRUCache } = require('lru-cache') -const { InvalidProxyProtocolError } = require('./errors.js') - -const PROXY_CACHE = new LRUCache({ max: 20 }) - -const SOCKS_PROTOCOLS = new Set(SocksProxyAgent.protocols) - -const PROXY_ENV_KEYS = new Set(['https_proxy', 'http_proxy', 'proxy', 'no_proxy']) - -const PROXY_ENV = Object.entries(process.env).reduce((acc, [key, value]) => { - key = key.toLowerCase() - if (PROXY_ENV_KEYS.has(key)) { - acc[key] = value - } - return acc -}, {}) - -const getProxyAgent = (url) => { - url = new URL(url) - - const protocol = url.protocol.slice(0, -1) - if (SOCKS_PROTOCOLS.has(protocol)) { - return SocksProxyAgent - } - if (protocol === 'https' || protocol === 'http') { - return [HttpProxyAgent, HttpsProxyAgent] - } - - throw new InvalidProxyProtocolError(url) -} - -const isNoProxy = (url, noProxy) => { - if (typeof noProxy === 'string') { - noProxy = noProxy.split(',').map((p) => p.trim()).filter(Boolean) - } - - if (!noProxy || !noProxy.length) { - return false - } - - const hostSegments = url.hostname.split('.').reverse() - - return noProxy.some((no) => { - const noSegments = no.split('.').filter(Boolean).reverse() - if (!noSegments.length) { - return false - } - - for (let i = 0; i < noSegments.length; i++) { - if (hostSegments[i] !== noSegments[i]) { - return false - } - } - - return true - }) -} - -const getProxy = (url, { proxy, noProxy }) => { - url = new URL(url) - - if (!proxy) { - proxy = url.protocol === 'https:' - ? PROXY_ENV.https_proxy - : PROXY_ENV.https_proxy || PROXY_ENV.http_proxy || PROXY_ENV.proxy - } - - if (!noProxy) { - noProxy = PROXY_ENV.no_proxy - } - - if (!proxy || isNoProxy(url, noProxy)) { - return null - } - - return new URL(proxy) -} - -module.exports = { - getProxyAgent, - getProxy, - proxyCache: PROXY_CACHE, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/package.json deleted file mode 100644 index ef5b4e3228cc4..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "name": "@npmcli/agent", - "version": "2.2.2", - "description": "the http/https agent used by the npm cli", - "main": "lib/index.js", - "scripts": { - "gencerts": "bash scripts/create-cert.sh", - "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" - }, - "author": "GitHub Inc.", - "license": "ISC", - "bugs": { - "url": "https://github.com/npm/agent/issues" - }, - "homepage": "https://github.com/npm/agent#readme", - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.3", - "publish": "true" - }, - "dependencies": { - "agent-base": "^7.1.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.1", - "lru-cache": "^10.0.1", - "socks-proxy-agent": "^8.0.3" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.3", - "minipass-fetch": "^3.0.3", - "nock": "^13.2.7", - "semver": "^7.5.4", - "simple-socks": "^3.1.0", - "tap": "^16.3.0" - }, - "repository": { - "type": "git", - "url": "https://github.com/npm/agent.git" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/LICENSE.md b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/LICENSE.md deleted file mode 100644 index 5fc208ff122e0..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ - - -ISC License - -Copyright npm, Inc. - -Permission to use, copy, modify, and/or distribute this -software for any purpose with or without fee is hereby -granted, provided that the above copyright notice and this -permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL -WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO -EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE -USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/common/get-options.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/common/get-options.js deleted file mode 100644 index cb5982f79077a..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/common/get-options.js +++ /dev/null @@ -1,20 +0,0 @@ -// given an input that may or may not be an object, return an object that has -// a copy of every defined property listed in 'copy'. if the input is not an -// object, assign it to the property named by 'wrap' -const getOptions = (input, { copy, wrap }) => { - const result = {} - - if (input && typeof input === 'object') { - for (const prop of copy) { - if (input[prop] !== undefined) { - result[prop] = input[prop] - } - } - } else { - result[wrap] = input - } - - return result -} - -module.exports = getOptions diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/common/node.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/common/node.js deleted file mode 100644 index 4d13bc037359d..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/common/node.js +++ /dev/null @@ -1,9 +0,0 @@ -const semver = require('semver') - -const satisfies = (range) => { - return semver.satisfies(process.version, range, { includePrerelease: true }) -} - -module.exports = { - satisfies, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/LICENSE deleted file mode 100644 index 93546dfb7655b..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -(The MIT License) - -Copyright (c) 2011-2017 JP Richardson - -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/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/errors.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/errors.js deleted file mode 100644 index 1cd1e05d0c533..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/errors.js +++ /dev/null @@ -1,129 +0,0 @@ -'use strict' -const { inspect } = require('util') - -// adapted from node's internal/errors -// https://github.com/nodejs/node/blob/c8a04049/lib/internal/errors.js - -// close copy of node's internal SystemError class. -class SystemError { - constructor (code, prefix, context) { - // XXX context.code is undefined in all constructors used in cp/polyfill - // that may be a bug copied from node, maybe the constructor should use - // `code` not `errno`? nodejs/node#41104 - let message = `${prefix}: ${context.syscall} returned ` + - `${context.code} (${context.message})` - - if (context.path !== undefined) { - message += ` ${context.path}` - } - if (context.dest !== undefined) { - message += ` => ${context.dest}` - } - - this.code = code - Object.defineProperties(this, { - name: { - value: 'SystemError', - enumerable: false, - writable: true, - configurable: true, - }, - message: { - value: message, - enumerable: false, - writable: true, - configurable: true, - }, - info: { - value: context, - enumerable: true, - configurable: true, - writable: false, - }, - errno: { - get () { - return context.errno - }, - set (value) { - context.errno = value - }, - enumerable: true, - configurable: true, - }, - syscall: { - get () { - return context.syscall - }, - set (value) { - context.syscall = value - }, - enumerable: true, - configurable: true, - }, - }) - - if (context.path !== undefined) { - Object.defineProperty(this, 'path', { - get () { - return context.path - }, - set (value) { - context.path = value - }, - enumerable: true, - configurable: true, - }) - } - - if (context.dest !== undefined) { - Object.defineProperty(this, 'dest', { - get () { - return context.dest - }, - set (value) { - context.dest = value - }, - enumerable: true, - configurable: true, - }) - } - } - - toString () { - return `${this.name} [${this.code}]: ${this.message}` - } - - [Symbol.for('nodejs.util.inspect.custom')] (_recurseTimes, ctx) { - return inspect(this, { - ...ctx, - getters: true, - customInspect: false, - }) - } -} - -function E (code, message) { - module.exports[code] = class NodeError extends SystemError { - constructor (ctx) { - super(code, message, ctx) - } - } -} - -E('ERR_FS_CP_DIR_TO_NON_DIR', 'Cannot overwrite directory with non-directory') -E('ERR_FS_CP_EEXIST', 'Target already exists') -E('ERR_FS_CP_EINVAL', 'Invalid src or dest') -E('ERR_FS_CP_FIFO_PIPE', 'Cannot copy a FIFO pipe') -E('ERR_FS_CP_NON_DIR_TO_DIR', 'Cannot overwrite non-directory with directory') -E('ERR_FS_CP_SOCKET', 'Cannot copy a socket file') -E('ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY', 'Cannot overwrite symlink in subdirectory of self') -E('ERR_FS_CP_UNKNOWN', 'Cannot copy an unknown file type') -E('ERR_FS_EISDIR', 'Path is a directory') - -module.exports.ERR_INVALID_ARG_TYPE = class ERR_INVALID_ARG_TYPE extends Error { - constructor (name, expected, actual) { - super() - this.code = 'ERR_INVALID_ARG_TYPE' - this.message = `The ${name} argument must be ${expected}. Received ${typeof actual}` - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/index.js deleted file mode 100644 index 972ce7aa12abe..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/index.js +++ /dev/null @@ -1,22 +0,0 @@ -const fs = require('fs/promises') -const getOptions = require('../common/get-options.js') -const node = require('../common/node.js') -const polyfill = require('./polyfill.js') - -// node 16.7.0 added fs.cp -const useNative = node.satisfies('>=16.7.0') - -const cp = async (src, dest, opts) => { - const options = getOptions(opts, { - copy: ['dereference', 'errorOnExist', 'filter', 'force', 'preserveTimestamps', 'recursive'], - }) - - // the polyfill is tested separately from this module, no need to hack - // process.version to try to trigger it just for coverage - // istanbul ignore next - return useNative - ? fs.cp(src, dest, options) - : polyfill(src, dest, options) -} - -module.exports = cp diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/polyfill.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/polyfill.js deleted file mode 100644 index 80eb10de97191..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/cp/polyfill.js +++ /dev/null @@ -1,428 +0,0 @@ -// this file is a modified version of the code in node 17.2.0 -// which is, in turn, a modified version of the fs-extra module on npm -// node core changes: -// - Use of the assert module has been replaced with core's error system. -// - All code related to the glob dependency has been removed. -// - Bring your own custom fs module is not currently supported. -// - Some basic code cleanup. -// changes here: -// - remove all callback related code -// - drop sync support -// - change assertions back to non-internal methods (see options.js) -// - throws ENOTDIR when rmdir gets an ENOENT for a path that exists in Windows -'use strict' - -const { - ERR_FS_CP_DIR_TO_NON_DIR, - ERR_FS_CP_EEXIST, - ERR_FS_CP_EINVAL, - ERR_FS_CP_FIFO_PIPE, - ERR_FS_CP_NON_DIR_TO_DIR, - ERR_FS_CP_SOCKET, - ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY, - ERR_FS_CP_UNKNOWN, - ERR_FS_EISDIR, - ERR_INVALID_ARG_TYPE, -} = require('./errors.js') -const { - constants: { - errno: { - EEXIST, - EISDIR, - EINVAL, - ENOTDIR, - }, - }, -} = require('os') -const { - chmod, - copyFile, - lstat, - mkdir, - readdir, - readlink, - stat, - symlink, - unlink, - utimes, -} = require('fs/promises') -const { - dirname, - isAbsolute, - join, - parse, - resolve, - sep, - toNamespacedPath, -} = require('path') -const { fileURLToPath } = require('url') - -const defaultOptions = { - dereference: false, - errorOnExist: false, - filter: undefined, - force: true, - preserveTimestamps: false, - recursive: false, -} - -async function cp (src, dest, opts) { - if (opts != null && typeof opts !== 'object') { - throw new ERR_INVALID_ARG_TYPE('options', ['Object'], opts) - } - return cpFn( - toNamespacedPath(getValidatedPath(src)), - toNamespacedPath(getValidatedPath(dest)), - { ...defaultOptions, ...opts }) -} - -function getValidatedPath (fileURLOrPath) { - const path = fileURLOrPath != null && fileURLOrPath.href - && fileURLOrPath.origin - ? fileURLToPath(fileURLOrPath) - : fileURLOrPath - return path -} - -async function cpFn (src, dest, opts) { - // Warn about using preserveTimestamps on 32-bit node - // istanbul ignore next - if (opts.preserveTimestamps && process.arch === 'ia32') { - const warning = 'Using the preserveTimestamps option in 32-bit ' + - 'node is not recommended' - process.emitWarning(warning, 'TimestampPrecisionWarning') - } - const stats = await checkPaths(src, dest, opts) - const { srcStat, destStat } = stats - await checkParentPaths(src, srcStat, dest) - if (opts.filter) { - return handleFilter(checkParentDir, destStat, src, dest, opts) - } - return checkParentDir(destStat, src, dest, opts) -} - -async function checkPaths (src, dest, opts) { - const { 0: srcStat, 1: destStat } = await getStats(src, dest, opts) - if (destStat) { - if (areIdentical(srcStat, destStat)) { - throw new ERR_FS_CP_EINVAL({ - message: 'src and dest cannot be the same', - path: dest, - syscall: 'cp', - errno: EINVAL, - }) - } - if (srcStat.isDirectory() && !destStat.isDirectory()) { - throw new ERR_FS_CP_DIR_TO_NON_DIR({ - message: `cannot overwrite directory ${src} ` + - `with non-directory ${dest}`, - path: dest, - syscall: 'cp', - errno: EISDIR, - }) - } - if (!srcStat.isDirectory() && destStat.isDirectory()) { - throw new ERR_FS_CP_NON_DIR_TO_DIR({ - message: `cannot overwrite non-directory ${src} ` + - `with directory ${dest}`, - path: dest, - syscall: 'cp', - errno: ENOTDIR, - }) - } - } - - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new ERR_FS_CP_EINVAL({ - message: `cannot copy ${src} to a subdirectory of self ${dest}`, - path: dest, - syscall: 'cp', - errno: EINVAL, - }) - } - return { srcStat, destStat } -} - -function areIdentical (srcStat, destStat) { - return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && - destStat.dev === srcStat.dev -} - -function getStats (src, dest, opts) { - const statFunc = opts.dereference ? - (file) => stat(file, { bigint: true }) : - (file) => lstat(file, { bigint: true }) - return Promise.all([ - statFunc(src), - statFunc(dest).catch((err) => { - // istanbul ignore next: unsure how to cover. - if (err.code === 'ENOENT') { - return null - } - // istanbul ignore next: unsure how to cover. - throw err - }), - ]) -} - -async function checkParentDir (destStat, src, dest, opts) { - const destParent = dirname(dest) - const dirExists = await pathExists(destParent) - if (dirExists) { - return getStatsForCopy(destStat, src, dest, opts) - } - await mkdir(destParent, { recursive: true }) - return getStatsForCopy(destStat, src, dest, opts) -} - -function pathExists (dest) { - return stat(dest).then( - () => true, - // istanbul ignore next: not sure when this would occur - (err) => (err.code === 'ENOENT' ? false : Promise.reject(err))) -} - -// Recursively check if dest parent is a subdirectory of src. -// It works for all file types including symlinks since it -// checks the src and dest inodes. It starts from the deepest -// parent and stops once it reaches the src parent or the root path. -async function checkParentPaths (src, srcStat, dest) { - const srcParent = resolve(dirname(src)) - const destParent = resolve(dirname(dest)) - if (destParent === srcParent || destParent === parse(destParent).root) { - return - } - let destStat - try { - destStat = await stat(destParent, { bigint: true }) - } catch (err) { - // istanbul ignore else: not sure when this would occur - if (err.code === 'ENOENT') { - return - } - // istanbul ignore next: not sure when this would occur - throw err - } - if (areIdentical(srcStat, destStat)) { - throw new ERR_FS_CP_EINVAL({ - message: `cannot copy ${src} to a subdirectory of self ${dest}`, - path: dest, - syscall: 'cp', - errno: EINVAL, - }) - } - return checkParentPaths(src, srcStat, destParent) -} - -const normalizePathToArray = (path) => - resolve(path).split(sep).filter(Boolean) - -// Return true if dest is a subdir of src, otherwise false. -// It only checks the path strings. -function isSrcSubdir (src, dest) { - const srcArr = normalizePathToArray(src) - const destArr = normalizePathToArray(dest) - return srcArr.every((cur, i) => destArr[i] === cur) -} - -async function handleFilter (onInclude, destStat, src, dest, opts, cb) { - const include = await opts.filter(src, dest) - if (include) { - return onInclude(destStat, src, dest, opts, cb) - } -} - -function startCopy (destStat, src, dest, opts) { - if (opts.filter) { - return handleFilter(getStatsForCopy, destStat, src, dest, opts) - } - return getStatsForCopy(destStat, src, dest, opts) -} - -async function getStatsForCopy (destStat, src, dest, opts) { - const statFn = opts.dereference ? stat : lstat - const srcStat = await statFn(src) - // istanbul ignore else: can't portably test FIFO - if (srcStat.isDirectory() && opts.recursive) { - return onDir(srcStat, destStat, src, dest, opts) - } else if (srcStat.isDirectory()) { - throw new ERR_FS_EISDIR({ - message: `${src} is a directory (not copied)`, - path: src, - syscall: 'cp', - errno: EINVAL, - }) - } else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) { - return onFile(srcStat, destStat, src, dest, opts) - } else if (srcStat.isSymbolicLink()) { - return onLink(destStat, src, dest) - } else if (srcStat.isSocket()) { - throw new ERR_FS_CP_SOCKET({ - message: `cannot copy a socket file: ${dest}`, - path: dest, - syscall: 'cp', - errno: EINVAL, - }) - } else if (srcStat.isFIFO()) { - throw new ERR_FS_CP_FIFO_PIPE({ - message: `cannot copy a FIFO pipe: ${dest}`, - path: dest, - syscall: 'cp', - errno: EINVAL, - }) - } - // istanbul ignore next: should be unreachable - throw new ERR_FS_CP_UNKNOWN({ - message: `cannot copy an unknown file type: ${dest}`, - path: dest, - syscall: 'cp', - errno: EINVAL, - }) -} - -function onFile (srcStat, destStat, src, dest, opts) { - if (!destStat) { - return _copyFile(srcStat, src, dest, opts) - } - return mayCopyFile(srcStat, src, dest, opts) -} - -async function mayCopyFile (srcStat, src, dest, opts) { - if (opts.force) { - await unlink(dest) - return _copyFile(srcStat, src, dest, opts) - } else if (opts.errorOnExist) { - throw new ERR_FS_CP_EEXIST({ - message: `${dest} already exists`, - path: dest, - syscall: 'cp', - errno: EEXIST, - }) - } -} - -async function _copyFile (srcStat, src, dest, opts) { - await copyFile(src, dest) - if (opts.preserveTimestamps) { - return handleTimestampsAndMode(srcStat.mode, src, dest) - } - return setDestMode(dest, srcStat.mode) -} - -async function handleTimestampsAndMode (srcMode, src, dest) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable(srcMode)) { - await makeFileWritable(dest, srcMode) - return setDestTimestampsAndMode(srcMode, src, dest) - } - return setDestTimestampsAndMode(srcMode, src, dest) -} - -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} - -function makeFileWritable (dest, srcMode) { - return setDestMode(dest, srcMode | 0o200) -} - -async function setDestTimestampsAndMode (srcMode, src, dest) { - await setDestTimestamps(src, dest) - return setDestMode(dest, srcMode) -} - -function setDestMode (dest, srcMode) { - return chmod(dest, srcMode) -} - -async function setDestTimestamps (src, dest) { - // The initial srcStat.atime cannot be trusted - // because it is modified by the read(2) system call - // (See https://nodejs.org/api/fs.html#fs_stat_time_values) - const updatedSrcStat = await stat(src) - return utimes(dest, updatedSrcStat.atime, updatedSrcStat.mtime) -} - -function onDir (srcStat, destStat, src, dest, opts) { - if (!destStat) { - return mkDirAndCopy(srcStat.mode, src, dest, opts) - } - return copyDir(src, dest, opts) -} - -async function mkDirAndCopy (srcMode, src, dest, opts) { - await mkdir(dest) - await copyDir(src, dest, opts) - return setDestMode(dest, srcMode) -} - -async function copyDir (src, dest, opts) { - const dir = await readdir(src) - for (let i = 0; i < dir.length; i++) { - const item = dir[i] - const srcItem = join(src, item) - const destItem = join(dest, item) - const { destStat } = await checkPaths(srcItem, destItem, opts) - await startCopy(destStat, srcItem, destItem, opts) - } -} - -async function onLink (destStat, src, dest) { - let resolvedSrc = await readlink(src) - if (!isAbsolute(resolvedSrc)) { - resolvedSrc = resolve(dirname(src), resolvedSrc) - } - if (!destStat) { - return symlink(resolvedSrc, dest) - } - let resolvedDest - try { - resolvedDest = await readlink(dest) - } catch (err) { - // Dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - // istanbul ignore next: can only test on windows - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') { - return symlink(resolvedSrc, dest) - } - // istanbul ignore next: should not be possible - throw err - } - if (!isAbsolute(resolvedDest)) { - resolvedDest = resolve(dirname(dest), resolvedDest) - } - if (isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new ERR_FS_CP_EINVAL({ - message: `cannot copy ${resolvedSrc} to a subdirectory of self ` + - `${resolvedDest}`, - path: dest, - syscall: 'cp', - errno: EINVAL, - }) - } - // Do not copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - const srcStat = await stat(src) - if (srcStat.isDirectory() && isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY({ - message: `cannot overwrite ${resolvedDest} with ${resolvedSrc}`, - path: dest, - syscall: 'cp', - errno: EINVAL, - }) - } - return copyLink(resolvedSrc, dest) -} - -async function copyLink (resolvedSrc, dest) { - await unlink(dest) - return symlink(resolvedSrc, dest) -} - -module.exports = cp diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/index.js deleted file mode 100644 index 81c746304cc42..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict' - -const cp = require('./cp/index.js') -const withTempDir = require('./with-temp-dir.js') -const readdirScoped = require('./readdir-scoped.js') -const moveFile = require('./move-file.js') - -module.exports = { - cp, - withTempDir, - readdirScoped, - moveFile, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/move-file.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/move-file.js deleted file mode 100644 index d56e06d384659..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/move-file.js +++ /dev/null @@ -1,78 +0,0 @@ -const { dirname, join, resolve, relative, isAbsolute } = require('path') -const fs = require('fs/promises') - -const pathExists = async path => { - try { - await fs.access(path) - return true - } catch (er) { - return er.code !== 'ENOENT' - } -} - -const moveFile = async (source, destination, options = {}, root = true, symlinks = []) => { - if (!source || !destination) { - throw new TypeError('`source` and `destination` file required') - } - - options = { - overwrite: true, - ...options, - } - - if (!options.overwrite && await pathExists(destination)) { - throw new Error(`The destination file exists: ${destination}`) - } - - await fs.mkdir(dirname(destination), { recursive: true }) - - try { - await fs.rename(source, destination) - } catch (error) { - if (error.code === 'EXDEV' || error.code === 'EPERM') { - const sourceStat = await fs.lstat(source) - if (sourceStat.isDirectory()) { - const files = await fs.readdir(source) - await Promise.all(files.map((file) => - moveFile(join(source, file), join(destination, file), options, false, symlinks) - )) - } else if (sourceStat.isSymbolicLink()) { - symlinks.push({ source, destination }) - } else { - await fs.copyFile(source, destination) - } - } else { - throw error - } - } - - if (root) { - await Promise.all(symlinks.map(async ({ source: symSource, destination: symDestination }) => { - let target = await fs.readlink(symSource) - // junction symlinks in windows will be absolute paths, so we need to - // make sure they point to the symlink destination - if (isAbsolute(target)) { - target = resolve(symDestination, relative(symSource, target)) - } - // try to determine what the actual file is so we can create the correct - // type of symlink in windows - let targetStat = 'file' - try { - targetStat = await fs.stat(resolve(dirname(symSource), target)) - if (targetStat.isDirectory()) { - targetStat = 'junction' - } - } catch { - // targetStat remains 'file' - } - await fs.symlink( - target, - symDestination, - targetStat - ) - })) - await fs.rm(source, { recursive: true, force: true }) - } -} - -module.exports = moveFile diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/readdir-scoped.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/readdir-scoped.js deleted file mode 100644 index cd601dfbe7486..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/readdir-scoped.js +++ /dev/null @@ -1,20 +0,0 @@ -const { readdir } = require('fs/promises') -const { join } = require('path') - -const readdirScoped = async (dir) => { - const results = [] - - for (const item of await readdir(dir)) { - if (item.startsWith('@')) { - for (const scopedItem of await readdir(join(dir, item))) { - results.push(join(item, scopedItem)) - } - } else { - results.push(item) - } - } - - return results -} - -module.exports = readdirScoped diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/with-temp-dir.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/with-temp-dir.js deleted file mode 100644 index 0738ac4f29e1b..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/lib/with-temp-dir.js +++ /dev/null @@ -1,39 +0,0 @@ -const { join, sep } = require('path') - -const getOptions = require('./common/get-options.js') -const { mkdir, mkdtemp, rm } = require('fs/promises') - -// create a temp directory, ensure its permissions match its parent, then call -// the supplied function passing it the path to the directory. clean up after -// the function finishes, whether it throws or not -const withTempDir = async (root, fn, opts) => { - const options = getOptions(opts, { - copy: ['tmpPrefix'], - }) - // create the directory - await mkdir(root, { recursive: true }) - - const target = await mkdtemp(join(`${root}${sep}`, options.tmpPrefix || '')) - let err - let result - - try { - result = await fn(target) - } catch (_err) { - err = _err - } - - try { - await rm(target, { force: true, recursive: true }) - } catch { - // ignore errors - } - - if (err) { - throw err - } - - return result -} - -module.exports = withTempDir diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/package.json deleted file mode 100644 index 5261a11b78000..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "@npmcli/fs", - "version": "3.1.1", - "description": "filesystem utilities for the npm cli", - "main": "lib/index.js", - "files": [ - "bin/", - "lib/" - ], - "scripts": { - "snap": "tap", - "test": "tap", - "npmclilint": "npmcli-lint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint", - "postsnap": "npm run lintfix --", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/fs.git" - }, - "keywords": [ - "npm", - "oss" - ], - "author": "GitHub Inc.", - "license": "ISC", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" - }, - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/LICENSE deleted file mode 100644 index 8f90f96f4c6c5..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) npm, Inc. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE NPM DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, -OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, -DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS -ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS -SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/clone.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/clone.js deleted file mode 100644 index e25a4d1426821..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/clone.js +++ /dev/null @@ -1,172 +0,0 @@ -// The goal here is to minimize both git workload and -// the number of refs we download over the network. -// -// Every method ends up with the checked out working dir -// at the specified ref, and resolves with the git sha. - -// Only certain whitelisted hosts get shallow cloning. -// Many hosts (including GHE) don't always support it. -// A failed shallow fetch takes a LOT longer than a full -// fetch in most cases, so we skip it entirely. -// Set opts.gitShallow = true/false to force this behavior -// one way or the other. -const shallowHosts = new Set([ - 'github.com', - 'gist.github.com', - 'gitlab.com', - 'bitbucket.com', - 'bitbucket.org', -]) -// we have to use url.parse until we add the same shim that hosted-git-info has -// to handle scp:// urls -const { parse } = require('url') // eslint-disable-line node/no-deprecated-api -const path = require('path') - -const getRevs = require('./revs.js') -const spawn = require('./spawn.js') -const { isWindows } = require('./utils.js') - -const pickManifest = require('npm-pick-manifest') -const fs = require('fs/promises') - -module.exports = (repo, ref = 'HEAD', target = null, opts = {}) => - getRevs(repo, opts).then(revs => clone( - repo, - revs, - ref, - resolveRef(revs, ref, opts), - target || defaultTarget(repo, opts.cwd), - opts - )) - -const maybeShallow = (repo, opts) => { - if (opts.gitShallow === false || opts.gitShallow) { - return opts.gitShallow - } - return shallowHosts.has(parse(repo).host) -} - -const defaultTarget = (repo, /* istanbul ignore next */ cwd = process.cwd()) => - path.resolve(cwd, path.basename(repo.replace(/[/\\]?\.git$/, ''))) - -const clone = (repo, revs, ref, revDoc, target, opts) => { - if (!revDoc) { - return unresolved(repo, ref, target, opts) - } - if (revDoc.sha === revs.refs.HEAD.sha) { - return plain(repo, revDoc, target, opts) - } - if (revDoc.type === 'tag' || revDoc.type === 'branch') { - return branch(repo, revDoc, target, opts) - } - return other(repo, revDoc, target, opts) -} - -const resolveRef = (revs, ref, opts) => { - const { spec = {} } = opts - ref = spec.gitCommittish || ref - /* istanbul ignore next - will fail anyway, can't pull */ - if (!revs) { - return null - } - if (spec.gitRange) { - return pickManifest(revs, spec.gitRange, opts) - } - if (!ref) { - return revs.refs.HEAD - } - if (revs.refs[ref]) { - return revs.refs[ref] - } - if (revs.shas[ref]) { - return revs.refs[revs.shas[ref][0]] - } - return null -} - -// pull request or some other kind of advertised ref -const other = (repo, revDoc, target, opts) => { - const shallow = maybeShallow(repo, opts) - - const fetchOrigin = ['fetch', 'origin', revDoc.rawRef] - .concat(shallow ? ['--depth=1'] : []) - - const git = (args) => spawn(args, { ...opts, cwd: target }) - return fs.mkdir(target, { recursive: true }) - .then(() => git(['init'])) - .then(() => isWindows(opts) - ? git(['config', '--local', '--add', 'core.longpaths', 'true']) - : null) - .then(() => git(['remote', 'add', 'origin', repo])) - .then(() => git(fetchOrigin)) - .then(() => git(['checkout', revDoc.sha])) - .then(() => updateSubmodules(target, opts)) - .then(() => revDoc.sha) -} - -// tag or branches. use -b -const branch = (repo, revDoc, target, opts) => { - const args = [ - 'clone', - '-b', - revDoc.ref, - repo, - target, - '--recurse-submodules', - ] - if (maybeShallow(repo, opts)) { - args.push('--depth=1') - } - if (isWindows(opts)) { - args.push('--config', 'core.longpaths=true') - } - return spawn(args, opts).then(() => revDoc.sha) -} - -// just the head. clone it -const plain = (repo, revDoc, target, opts) => { - const args = [ - 'clone', - repo, - target, - '--recurse-submodules', - ] - if (maybeShallow(repo, opts)) { - args.push('--depth=1') - } - if (isWindows(opts)) { - args.push('--config', 'core.longpaths=true') - } - return spawn(args, opts).then(() => revDoc.sha) -} - -const updateSubmodules = async (target, opts) => { - const hasSubmodules = await fs.stat(`${target}/.gitmodules`) - .then(() => true) - .catch(() => false) - if (!hasSubmodules) { - return null - } - return spawn([ - 'submodule', - 'update', - '-q', - '--init', - '--recursive', - ], { ...opts, cwd: target }) -} - -const unresolved = (repo, ref, target, opts) => { - // can't do this one shallowly, because the ref isn't advertised - // but we can avoid checking out the working dir twice, at least - const lp = isWindows(opts) ? ['--config', 'core.longpaths=true'] : [] - const cloneArgs = ['clone', '--mirror', '-q', repo, target + '/.git'] - const git = (args) => spawn(args, { ...opts, cwd: target }) - return fs.mkdir(target, { recursive: true }) - .then(() => git(cloneArgs.concat(lp))) - .then(() => git(['init'])) - .then(() => git(['checkout', ref])) - .then(() => updateSubmodules(target, opts)) - .then(() => git(['rev-parse', '--revs-only', 'HEAD'])) - .then(({ stdout }) => stdout.trim()) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/errors.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/errors.js deleted file mode 100644 index 3ceaa45811669..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/errors.js +++ /dev/null @@ -1,36 +0,0 @@ - -const maxRetry = 3 - -class GitError extends Error { - shouldRetry () { - return false - } -} - -class GitConnectionError extends GitError { - constructor () { - super('A git connection error occurred') - } - - shouldRetry (number) { - return number < maxRetry - } -} - -class GitPathspecError extends GitError { - constructor () { - super('The git reference could not be found') - } -} - -class GitUnknownError extends GitError { - constructor () { - super('An unknown git error occurred') - } -} - -module.exports = { - GitConnectionError, - GitPathspecError, - GitUnknownError, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/find.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/find.js deleted file mode 100644 index 34bd310b88e5d..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/find.js +++ /dev/null @@ -1,15 +0,0 @@ -const is = require('./is.js') -const { dirname } = require('path') - -module.exports = async ({ cwd = process.cwd(), root } = {}) => { - while (true) { - if (await is({ cwd })) { - return cwd - } - const next = dirname(cwd) - if (cwd === root || cwd === next) { - return null - } - cwd = next - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/index.js deleted file mode 100644 index 10a65f782e6da..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/index.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports = { - clone: require('./clone.js'), - revs: require('./revs.js'), - spawn: require('./spawn.js'), - is: require('./is.js'), - find: require('./find.js'), - isClean: require('./is-clean.js'), - errors: require('./errors.js'), -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/is-clean.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/is-clean.js deleted file mode 100644 index 182373be94193..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/is-clean.js +++ /dev/null @@ -1,6 +0,0 @@ -const spawn = require('./spawn.js') - -module.exports = (opts = {}) => - spawn(['status', '--porcelain=v1', '-uno'], opts) - .then(res => !res.stdout.trim().split(/\r?\n+/) - .map(l => l.trim()).filter(l => l).length) diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/is.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/is.js deleted file mode 100644 index f5a0e8754f10d..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/is.js +++ /dev/null @@ -1,4 +0,0 @@ -// not an airtight indicator, but a good gut-check to even bother trying -const { stat } = require('fs/promises') -module.exports = ({ cwd = process.cwd() } = {}) => - stat(cwd + '/.git').then(() => true, () => false) diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/lines-to-revs.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/lines-to-revs.js deleted file mode 100644 index 6bd7e7a4c1531..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/lines-to-revs.js +++ /dev/null @@ -1,147 +0,0 @@ -// turn an array of lines from `git ls-remote` into a thing -// vaguely resembling a packument, where docs are a resolved ref - -const semver = require('semver') - -module.exports = lines => finish(lines.reduce(linesToRevsReducer, { - versions: {}, - 'dist-tags': {}, - refs: {}, - shas: {}, -})) - -const finish = revs => distTags(shaList(peelTags(revs))) - -// We can check out shallow clones on specific SHAs if we have a ref -const shaList = revs => { - Object.keys(revs.refs).forEach(ref => { - const doc = revs.refs[ref] - if (!revs.shas[doc.sha]) { - revs.shas[doc.sha] = [ref] - } else { - revs.shas[doc.sha].push(ref) - } - }) - return revs -} - -// Replace any tags with their ^{} counterparts, if those exist -const peelTags = revs => { - Object.keys(revs.refs).filter(ref => ref.endsWith('^{}')).forEach(ref => { - const peeled = revs.refs[ref] - const unpeeled = revs.refs[ref.replace(/\^\{\}$/, '')] - if (unpeeled) { - unpeeled.sha = peeled.sha - delete revs.refs[ref] - } - }) - return revs -} - -const distTags = revs => { - // not entirely sure what situations would result in an - // ichabod repo, but best to be careful in Sleepy Hollow anyway - const HEAD = revs.refs.HEAD || /* istanbul ignore next */ {} - const versions = Object.keys(revs.versions) - versions.forEach(v => { - // simulate a dist-tags with latest pointing at the - // 'latest' branch if one exists and is a version, - // or HEAD if not. - const ver = revs.versions[v] - if (revs.refs.latest && ver.sha === revs.refs.latest.sha) { - revs['dist-tags'].latest = v - } else if (ver.sha === HEAD.sha) { - revs['dist-tags'].HEAD = v - if (!revs.refs.latest) { - revs['dist-tags'].latest = v - } - } - }) - return revs -} - -const refType = ref => { - if (ref.startsWith('refs/tags/')) { - return 'tag' - } - if (ref.startsWith('refs/heads/')) { - return 'branch' - } - if (ref.startsWith('refs/pull/')) { - return 'pull' - } - if (ref === 'HEAD') { - return 'head' - } - // Could be anything, ignore for now - /* istanbul ignore next */ - return 'other' -} - -// return the doc, or null if we should ignore it. -const lineToRevDoc = line => { - const split = line.trim().split(/\s+/, 2) - if (split.length < 2) { - return null - } - - const sha = split[0].trim() - const rawRef = split[1].trim() - const type = refType(rawRef) - - if (type === 'tag') { - // refs/tags/foo^{} is the 'peeled tag', ie the commit - // that is tagged by refs/tags/foo they resolve to the same - // content, just different objects in git's data structure. - // But, we care about the thing the tag POINTS to, not the tag - // object itself, so we only look at the peeled tag refs, and - // ignore the pointer. - // For now, though, we have to save both, because some tags - // don't have peels, if they were not annotated. - const ref = rawRef.slice('refs/tags/'.length) - return { sha, ref, rawRef, type } - } - - if (type === 'branch') { - const ref = rawRef.slice('refs/heads/'.length) - return { sha, ref, rawRef, type } - } - - if (type === 'pull') { - // NB: merged pull requests installable with #pull/123/merge - // for the merged pr, or #pull/123 for the PR head - const ref = rawRef.slice('refs/'.length).replace(/\/head$/, '') - return { sha, ref, rawRef, type } - } - - if (type === 'head') { - const ref = 'HEAD' - return { sha, ref, rawRef, type } - } - - // at this point, all we can do is leave the ref un-munged - return { sha, ref: rawRef, rawRef, type } -} - -const linesToRevsReducer = (revs, line) => { - const doc = lineToRevDoc(line) - - if (!doc) { - return revs - } - - revs.refs[doc.ref] = doc - revs.refs[doc.rawRef] = doc - - if (doc.type === 'tag') { - // try to pull a semver value out of tags like `release-v1.2.3` - // which is a pretty common pattern. - const match = !doc.ref.endsWith('^{}') && - doc.ref.match(/v?(\d+\.\d+\.\d+(?:[-+].+)?)$/) - if (match && semver.valid(match[1], true)) { - revs.versions[semver.clean(match[1], true)] = doc - } - } - - return revs -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/make-error.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/make-error.js deleted file mode 100644 index 7540ec7c8b9f7..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/make-error.js +++ /dev/null @@ -1,33 +0,0 @@ -const { - GitConnectionError, - GitPathspecError, - GitUnknownError, -} = require('./errors.js') - -const connectionErrorRe = new RegExp([ - 'remote error: Internal Server Error', - 'The remote end hung up unexpectedly', - 'Connection timed out', - 'Operation timed out', - 'Failed to connect to .* Timed out', - 'Connection reset by peer', - 'SSL_ERROR_SYSCALL', - 'The requested URL returned error: 503', -].join('|')) - -const missingPathspecRe = /pathspec .* did not match any file\(s\) known to git/ - -function makeError (er) { - const message = er.stderr - let gitEr - if (connectionErrorRe.test(message)) { - gitEr = new GitConnectionError(message) - } else if (missingPathspecRe.test(message)) { - gitEr = new GitPathspecError(message) - } else { - gitEr = new GitUnknownError(message) - } - return Object.assign(gitEr, er) -} - -module.exports = makeError diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/opts.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/opts.js deleted file mode 100644 index 1e80e9efe4989..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/opts.js +++ /dev/null @@ -1,57 +0,0 @@ -const fs = require('node:fs') -const os = require('node:os') -const path = require('node:path') -const ini = require('ini') - -const gitConfigPath = path.join(os.homedir(), '.gitconfig') - -let cachedConfig = null - -// Function to load and cache the git config -const loadGitConfig = () => { - if (cachedConfig === null) { - try { - cachedConfig = {} - if (fs.existsSync(gitConfigPath)) { - const configContent = fs.readFileSync(gitConfigPath, 'utf-8') - cachedConfig = ini.parse(configContent) - } - } catch (error) { - cachedConfig = {} - } - } - return cachedConfig -} - -const checkGitConfigs = () => { - const config = loadGitConfig() - return { - sshCommandSetInConfig: config?.core?.sshCommand !== undefined, - askPassSetInConfig: config?.core?.askpass !== undefined, - } -} - -const sshCommandSetInEnv = process.env.GIT_SSH_COMMAND !== undefined -const askPassSetInEnv = process.env.GIT_ASKPASS !== undefined -const { sshCommandSetInConfig, askPassSetInConfig } = checkGitConfigs() - -// Values we want to set if they're not already defined by the end user -// This defaults to accepting new ssh host key fingerprints -const finalGitEnv = { - ...(askPassSetInEnv || askPassSetInConfig ? {} : { - GIT_ASKPASS: 'echo', - }), - ...(sshCommandSetInEnv || sshCommandSetInConfig ? {} : { - GIT_SSH_COMMAND: 'ssh -oStrictHostKeyChecking=accept-new', - }), -} - -module.exports = (opts = {}) => ({ - stdioString: true, - ...opts, - shell: false, - env: opts.env || { ...finalGitEnv, ...process.env }, -}) - -// Export the loadGitConfig function for testing -module.exports.loadGitConfig = loadGitConfig diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/revs.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/revs.js deleted file mode 100644 index ca14837de1b87..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/revs.js +++ /dev/null @@ -1,28 +0,0 @@ -const pinflight = require('promise-inflight') -const spawn = require('./spawn.js') -const { LRUCache } = require('lru-cache') - -const revsCache = new LRUCache({ - max: 100, - ttl: 5 * 60 * 1000, -}) - -const linesToRevs = require('./lines-to-revs.js') - -module.exports = async (repo, opts = {}) => { - if (!opts.noGitRevCache) { - const cached = revsCache.get(repo) - if (cached) { - return cached - } - } - - return pinflight(`ls-remote:${repo}`, () => - spawn(['ls-remote', repo], opts) - .then(({ stdout }) => linesToRevs(stdout.trim().split('\n'))) - .then(revs => { - revsCache.set(repo, revs) - return revs - }) - ) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/spawn.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/spawn.js deleted file mode 100644 index 03c1cbde21547..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/spawn.js +++ /dev/null @@ -1,44 +0,0 @@ -const spawn = require('@npmcli/promise-spawn') -const promiseRetry = require('promise-retry') -const { log } = require('proc-log') -const makeError = require('./make-error.js') -const makeOpts = require('./opts.js') - -module.exports = (gitArgs, opts = {}) => { - const whichGit = require('./which.js') - const gitPath = whichGit(opts) - - if (gitPath instanceof Error) { - return Promise.reject(gitPath) - } - - // undocumented option, mostly only here for tests - const args = opts.allowReplace || gitArgs[0] === '--no-replace-objects' - ? gitArgs - : ['--no-replace-objects', ...gitArgs] - - let retryOpts = opts.retry - if (retryOpts === null || retryOpts === undefined) { - retryOpts = { - retries: opts.fetchRetries || 2, - factor: opts.fetchRetryFactor || 10, - maxTimeout: opts.fetchRetryMaxtimeout || 60000, - minTimeout: opts.fetchRetryMintimeout || 1000, - } - } - return promiseRetry((retryFn, number) => { - if (number !== 1) { - log.silly('git', `Retrying git command: ${ - args.join(' ')} attempt # ${number}`) - } - - return spawn(gitPath, args, makeOpts(opts)) - .catch(er => { - const gitError = makeError(er) - if (!gitError.shouldRetry(number)) { - throw gitError - } - retryFn(gitError) - }) - }, retryOpts) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/utils.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/utils.js deleted file mode 100644 index fcd9578a19597..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/utils.js +++ /dev/null @@ -1,3 +0,0 @@ -const isWindows = opts => (opts.fakePlatform || process.platform) === 'win32' - -exports.isWindows = isWindows diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/which.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/which.js deleted file mode 100644 index dc2a1ad212166..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/lib/which.js +++ /dev/null @@ -1,18 +0,0 @@ -const which = require('which') - -let gitPath -try { - gitPath = which.sync('git') -} catch { - // ignore errors -} - -module.exports = (opts = {}) => { - if (opts.git) { - return opts.git - } - if (!gitPath || opts.git === false) { - return Object.assign(new Error('No git binary found in $PATH'), { code: 'ENOGIT' }) - } - return gitPath -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/package.json deleted file mode 100644 index b6aa4a282cc0f..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@npmcli/git", - "version": "5.0.8", - "main": "lib/index.js", - "files": [ - "bin/", - "lib/" - ], - "description": "a util for spawning git from npm CLI contexts", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/git.git" - }, - "author": "GitHub Inc.", - "license": "ISC", - "scripts": { - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "snap": "tap", - "test": "tap", - "posttest": "npm run lint", - "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" - }, - "tap": { - "timeout": 600, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "npm-package-arg": "^11.0.0", - "slash": "^3.0.0", - "tap": "^16.0.1" - }, - "dependencies": { - "@npmcli/promise-spawn": "^7.0.0", - "ini": "^4.1.3", - "lru-cache": "^10.0.1", - "npm-pick-manifest": "^9.0.0", - "proc-log": "^4.0.0", - "promise-inflight": "^1.0.1", - "promise-retry": "^2.0.1", - "semver": "^7.3.5", - "which": "^4.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/LICENSE deleted file mode 100644 index 19cec97b18468..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) npm, Inc. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/bin/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/bin/index.js deleted file mode 100755 index 7b83b23bf168c..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/bin/index.js +++ /dev/null @@ -1,44 +0,0 @@ -#! /usr/bin/env node - -const { relative } = require('path') -const pkgContents = require('../') - -const usage = `Usage: - installed-package-contents [-d --depth=] - -Lists the files installed for a package specified by . - -Options: - -d --depth= Provide a numeric value ("Infinity" is allowed) - to specify how deep in the file tree to traverse. - Default=1 - -h --help Show this usage information` - -const options = {} - -process.argv.slice(2).forEach(arg => { - let match - if ((match = arg.match(/^(?:--depth=|-d)([0-9]+|Infinity)/))) { - options.depth = +match[1] - } else if (arg === '-h' || arg === '--help') { - console.log(usage) - process.exit(0) - } else { - options.path = arg - } -}) - -if (!options.path) { - console.error('ERROR: no path provided') - console.error(usage) - process.exit(1) -} - -const cwd = process.cwd() - -pkgContents(options) - .then(list => list.sort().forEach(p => console.log(relative(cwd, p)))) - .catch(/* istanbul ignore next - pretty unusual */ er => { - console.error(er) - process.exit(1) - }) diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/lib/index.js deleted file mode 100644 index ab1486cd01d00..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/lib/index.js +++ /dev/null @@ -1,181 +0,0 @@ -// to GET CONTENTS for folder at PATH (which may be a PACKAGE): -// - if PACKAGE, read path/package.json -// - if bins in ../node_modules/.bin, add those to result -// - if depth >= maxDepth, add PATH to result, and finish -// - readdir(PATH, with file types) -// - add all FILEs in PATH to result -// - if PARENT: -// - if depth < maxDepth, add GET CONTENTS of all DIRs in PATH -// - else, add all DIRs in PATH -// - if no parent -// - if no bundled deps, -// - if depth < maxDepth, add GET CONTENTS of DIRs in path except -// node_modules -// - else, add all DIRs in path other than node_modules -// - if has bundled deps, -// - get list of bundled deps -// - add GET CONTENTS of bundled deps, PACKAGE=true, depth + 1 - -const bundled = require('npm-bundled') -const { readFile, readdir, stat } = require('fs/promises') -const { resolve, basename, dirname } = require('path') -const normalizePackageBin = require('npm-normalize-package-bin') - -const readPackage = ({ path, packageJsonCache }) => packageJsonCache.has(path) - ? Promise.resolve(packageJsonCache.get(path)) - : readFile(path).then(json => { - const pkg = normalizePackageBin(JSON.parse(json)) - packageJsonCache.set(path, pkg) - return pkg - }).catch(() => null) - -// just normalize bundle deps and bin, that's all we care about here. -const normalized = Symbol('package data has been normalized') -const rpj = ({ path, packageJsonCache }) => readPackage({ path, packageJsonCache }) - .then(pkg => { - if (!pkg || pkg[normalized]) { - return pkg - } - if (pkg.bundledDependencies && !pkg.bundleDependencies) { - pkg.bundleDependencies = pkg.bundledDependencies - delete pkg.bundledDependencies - } - const bd = pkg.bundleDependencies - if (bd === true) { - pkg.bundleDependencies = [ - ...Object.keys(pkg.dependencies || {}), - ...Object.keys(pkg.optionalDependencies || {}), - ] - } - if (typeof bd === 'object' && !Array.isArray(bd)) { - pkg.bundleDependencies = Object.keys(bd) - } - pkg[normalized] = true - return pkg - }) - -const pkgContents = async ({ - path, - depth = 1, - currentDepth = 0, - pkg = null, - result = null, - packageJsonCache = null, -}) => { - if (!result) { - result = new Set() - } - - if (!packageJsonCache) { - packageJsonCache = new Map() - } - - if (pkg === true) { - return rpj({ path: path + '/package.json', packageJsonCache }) - .then(p => pkgContents({ - path, - depth, - currentDepth, - pkg: p, - result, - packageJsonCache, - })) - } - - if (pkg) { - // add all bins to result if they exist - if (pkg.bin) { - const dir = dirname(path) - const scope = basename(dir) - const nm = /^@.+/.test(scope) ? dirname(dir) : dir - - const binFiles = [] - Object.keys(pkg.bin).forEach(b => { - const base = resolve(nm, '.bin', b) - binFiles.push(base, base + '.cmd', base + '.ps1') - }) - - const bins = await Promise.all( - binFiles.map(b => stat(b).then(() => b).catch(() => null)) - ) - bins.filter(b => b).forEach(b => result.add(b)) - } - } - - if (currentDepth >= depth) { - result.add(path) - return result - } - - // we'll need bundle list later, so get that now in parallel - const [dirEntries, bundleDeps] = await Promise.all([ - readdir(path, { withFileTypes: true }), - currentDepth === 0 && pkg && pkg.bundleDependencies - ? bundled({ path, packageJsonCache }) : null, - ]).catch(() => []) - - // not a thing, probably a missing folder - if (!dirEntries) { - return result - } - - // empty folder, just add the folder itself to the result - if (!dirEntries.length && !bundleDeps && currentDepth !== 0) { - result.add(path) - return result - } - - const recursePromises = [] - - for (const entry of dirEntries) { - const p = resolve(path, entry.name) - if (entry.isDirectory() === false) { - result.add(p) - continue - } - - if (currentDepth !== 0 || entry.name !== 'node_modules') { - if (currentDepth < depth - 1) { - recursePromises.push(pkgContents({ - path: p, - packageJsonCache, - depth, - currentDepth: currentDepth + 1, - result, - })) - } else { - result.add(p) - } - continue - } - } - - if (bundleDeps) { - // bundle deps are all folders - // we always recurse to get pkg bins, but if currentDepth is too high, - // it'll return early before walking their contents. - recursePromises.push(...bundleDeps.map(dep => { - const p = resolve(path, 'node_modules', dep) - return pkgContents({ - path: p, - packageJsonCache, - pkg: true, - depth, - currentDepth: currentDepth + 1, - result, - }) - })) - } - - if (recursePromises.length) { - await Promise.all(recursePromises) - } - - return result -} - -module.exports = ({ path, ...opts }) => pkgContents({ - path: resolve(path), - ...opts, - pkg: true, -}).then(results => [...results]) diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/package.json deleted file mode 100644 index 132256430a6c1..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "@npmcli/installed-package-contents", - "version": "2.1.0", - "description": "Get the list of files installed in a package in node_modules, including bundled dependencies", - "author": "GitHub Inc.", - "main": "lib/index.js", - "bin": { - "installed-package-contents": "bin/index.js" - }, - "license": "ISC", - "scripts": { - "test": "tap", - "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.4", - "tap": "^16.3.0" - }, - "dependencies": { - "npm-bundled": "^3.0.0", - "npm-normalize-package-bin": "^3.0.0" - }, - "repository": { - "type": "git", - "url": "https://github.com/npm/installed-package-contents.git" - }, - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.4", - "publish": true - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/LICENSE deleted file mode 100644 index 6a1f3708f6d70..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -ISC License - -Copyright GitHub Inc. - -Permission to use, copy, modify, and/or distribute this -software for any purpose with or without fee is hereby -granted, provided that the above copyright notice and this -permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL -WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO -EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE -USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/index.js deleted file mode 100644 index f165ee23b75ab..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/index.js +++ /dev/null @@ -1,278 +0,0 @@ -const { readFile, writeFile } = require('node:fs/promises') -const { resolve } = require('node:path') -const parseJSON = require('json-parse-even-better-errors') - -const updateDeps = require('./update-dependencies.js') -const updateScripts = require('./update-scripts.js') -const updateWorkspaces = require('./update-workspaces.js') -const normalize = require('./normalize.js') -const { read, parse } = require('./read-package.js') - -// a list of handy specialized helper functions that take -// care of special cases that are handled by the npm cli -const knownSteps = new Set([ - updateDeps, - updateScripts, - updateWorkspaces, -]) - -// list of all keys that are handled by "knownSteps" helpers -const knownKeys = new Set([ - ...updateDeps.knownKeys, - 'scripts', - 'workspaces', -]) - -class PackageJson { - static normalizeSteps = Object.freeze([ - '_id', - '_attributes', - 'bundledDependencies', - 'bundleDependencies', - 'optionalDedupe', - 'scripts', - 'funding', - 'bin', - ]) - - // npm pkg fix - static fixSteps = Object.freeze([ - 'binRefs', - 'bundleDependencies', - 'bundleDependenciesFalse', - 'fixNameField', - 'fixVersionField', - 'fixRepositoryField', - 'fixDependencies', - 'devDependencies', - 'scriptpath', - ]) - - static prepareSteps = Object.freeze([ - '_id', - '_attributes', - 'bundledDependencies', - 'bundleDependencies', - 'bundleDependenciesDeleteFalse', - 'gypfile', - 'serverjs', - 'scriptpath', - 'authors', - 'readme', - 'mans', - 'binDir', - 'gitHead', - 'fillTypes', - 'normalizeData', - 'binRefs', - ]) - - // create a new empty package.json, so we can save at the given path even - // though we didn't start from a parsed file - static async create (path, opts = {}) { - const p = new PackageJson() - await p.create(path) - if (opts.data) { - return p.update(opts.data) - } - return p - } - - // Loads a package.json at given path and JSON parses - static async load (path, opts = {}) { - const p = new PackageJson() - // Avoid try/catch if we aren't going to create - if (!opts.create) { - return p.load(path) - } - - try { - return await p.load(path) - } catch (err) { - if (!err.message.startsWith('Could not read package.json')) { - throw err - } - return await p.create(path) - } - } - - // npm pkg fix - static async fix (path, opts) { - const p = new PackageJson() - await p.load(path, true) - return p.fix(opts) - } - - // read-package-json compatible behavior - static async prepare (path, opts) { - const p = new PackageJson() - await p.load(path, true) - return p.prepare(opts) - } - - // read-package-json-fast compatible behavior - static async normalize (path, opts) { - const p = new PackageJson() - await p.load(path) - return p.normalize(opts) - } - - #path - #manifest - #readFileContent = '' - #canSave = true - - // Load content from given path - async load (path, parseIndex) { - this.#path = path - let parseErr - try { - this.#readFileContent = await read(this.filename) - } catch (err) { - if (!parseIndex) { - throw err - } - parseErr = err - } - - if (parseErr) { - const indexFile = resolve(this.path, 'index.js') - let indexFileContent - try { - indexFileContent = await readFile(indexFile, 'utf8') - } catch (err) { - throw parseErr - } - try { - this.fromComment(indexFileContent) - } catch (err) { - throw parseErr - } - // This wasn't a package.json so prevent saving - this.#canSave = false - return this - } - - return this.fromJSON(this.#readFileContent) - } - - // Load data from a JSON string/buffer - fromJSON (data) { - this.#manifest = parse(data) - return this - } - - fromContent (data) { - this.#manifest = data - this.#canSave = false - return this - } - - // Load data from a comment - // /**package { "name": "foo", "version": "1.2.3", ... } **/ - fromComment (data) { - data = data.split(/^\/\*\*package(?:\s|$)/m) - - if (data.length < 2) { - throw new Error('File has no package in comments') - } - data = data[1] - data = data.split(/\*\*\/$/m) - - if (data.length < 2) { - throw new Error('File has no package in comments') - } - data = data[0] - data = data.replace(/^\s*\*/mg, '') - - this.#manifest = parseJSON(data) - return this - } - - get content () { - return this.#manifest - } - - get path () { - return this.#path - } - - get filename () { - if (this.path) { - return resolve(this.path, 'package.json') - } - return undefined - } - - create (path) { - this.#path = path - this.#manifest = {} - return this - } - - // This should be the ONLY way to set content in the manifest - update (content) { - if (!this.content) { - throw new Error('Can not update without content. Please `load` or `create`') - } - - for (const step of knownSteps) { - this.#manifest = step({ content, originalContent: this.content }) - } - - // unknown properties will just be overwitten - for (const [key, value] of Object.entries(content)) { - if (!knownKeys.has(key)) { - this.content[key] = value - } - } - - return this - } - - async save () { - if (!this.#canSave) { - throw new Error('No package.json to save to') - } - const { - [Symbol.for('indent')]: indent, - [Symbol.for('newline')]: newline, - } = this.content - - const format = indent === undefined ? ' ' : indent - const eol = newline === undefined ? '\n' : newline - const fileContent = `${ - JSON.stringify(this.content, null, format) - }\n` - .replace(/\n/g, eol) - - if (fileContent.trim() !== this.#readFileContent.trim()) { - return await writeFile(this.filename, fileContent) - } - } - - async normalize (opts = {}) { - if (!opts.steps) { - opts.steps = this.constructor.normalizeSteps - } - await normalize(this, opts) - return this - } - - async prepare (opts = {}) { - if (!opts.steps) { - opts.steps = this.constructor.prepareSteps - } - await normalize(this, opts) - return this - } - - async fix (opts = {}) { - // This one is not overridable - opts.steps = this.constructor.fixSteps - await normalize(this, opts) - return this - } -} - -module.exports = PackageJson diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/normalize.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/normalize.js deleted file mode 100644 index 3adec0143f445..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/normalize.js +++ /dev/null @@ -1,615 +0,0 @@ -const valid = require('semver/functions/valid') -const clean = require('semver/functions/clean') -const fs = require('node:fs/promises') -const path = require('node:path') -const { log } = require('proc-log') - -/** - * @type {import('hosted-git-info')} - */ -let _hostedGitInfo -function lazyHostedGitInfo () { - if (!_hostedGitInfo) { - _hostedGitInfo = require('hosted-git-info') - } - return _hostedGitInfo -} - -/** - * @type {import('glob').glob} - */ -let _glob -function lazyLoadGlob () { - if (!_glob) { - _glob = require('glob').glob - } - return _glob -} - -// used to be npm-normalize-package-bin -function normalizePackageBin (pkg, changes) { - if (pkg.bin) { - if (typeof pkg.bin === 'string' && pkg.name) { - changes?.push('"bin" was converted to an object') - pkg.bin = { [pkg.name]: pkg.bin } - } else if (Array.isArray(pkg.bin)) { - changes?.push('"bin" was converted to an object') - pkg.bin = pkg.bin.reduce((acc, k) => { - acc[path.basename(k)] = k - return acc - }, {}) - } - if (typeof pkg.bin === 'object') { - for (const binKey in pkg.bin) { - if (typeof pkg.bin[binKey] !== 'string') { - delete pkg.bin[binKey] - changes?.push(`removed invalid "bin[${binKey}]"`) - continue - } - const base = path.basename(secureAndUnixifyPath(binKey)) - if (!base) { - delete pkg.bin[binKey] - changes?.push(`removed invalid "bin[${binKey}]"`) - continue - } - - const binTarget = secureAndUnixifyPath(pkg.bin[binKey]) - - if (!binTarget) { - delete pkg.bin[binKey] - changes?.push(`removed invalid "bin[${binKey}]"`) - continue - } - - if (base !== binKey) { - delete pkg.bin[binKey] - changes?.push(`"bin[${binKey}]" was renamed to "bin[${base}]"`) - } - if (binTarget !== pkg.bin[binKey]) { - changes?.push(`"bin[${base}]" script name was cleaned`) - } - pkg.bin[base] = binTarget - } - - if (Object.keys(pkg.bin).length === 0) { - changes?.push('empty "bin" was removed') - delete pkg.bin - } - - return pkg - } - } - delete pkg.bin -} - -function normalizePackageMan (pkg, changes) { - if (pkg.man) { - const mans = [] - for (const man of (Array.isArray(pkg.man) ? pkg.man : [pkg.man])) { - if (typeof man !== 'string') { - changes?.push(`removed invalid "man [${man}]"`) - } else { - mans.push(secureAndUnixifyPath(man)) - } - } - - if (!mans.length) { - changes?.push('empty "man" was removed') - } else { - pkg.man = mans - return pkg - } - } - delete pkg.man -} - -function isCorrectlyEncodedName (spec) { - return !spec.match(/[/@\s+%:]/) && - spec === encodeURIComponent(spec) -} - -function isValidScopedPackageName (spec) { - if (spec.charAt(0) !== '@') { - return false - } - - const rest = spec.slice(1).split('/') - if (rest.length !== 2) { - return false - } - - return rest[0] && rest[1] && - rest[0] === encodeURIComponent(rest[0]) && - rest[1] === encodeURIComponent(rest[1]) -} - -function unixifyPath (ref) { - return ref.replace(/\\|:/g, '/') -} - -function secureAndUnixifyPath (ref) { - const secured = unixifyPath(path.join('.', path.join('/', unixifyPath(ref)))) - return secured.startsWith('./') ? '' : secured -} - -// We don't want the `changes` array in here by default because this is a hot -// path for parsing packuments during install. So the calling method passes it -// in if it wants to track changes. -const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) => { - if (!pkg.content) { - throw new Error('Can not normalize without content') - } - const data = pkg.content - const scripts = data.scripts || {} - const pkgId = `${data.name ?? ''}@${data.version ?? ''}` - - // name and version are load bearing so we have to clean them up first - if (steps.includes('fixNameField') || steps.includes('normalizeData')) { - if (!data.name && !strict) { - changes?.push('Missing "name" field was set to an empty string') - data.name = '' - } else { - if (typeof data.name !== 'string') { - throw new Error('name field must be a string.') - } - if (!strict) { - const name = data.name.trim() - if (data.name !== name) { - changes?.push(`Whitespace was trimmed from "name"`) - data.name = name - } - } - - if (data.name.startsWith('.') || - !(isValidScopedPackageName(data.name) || isCorrectlyEncodedName(data.name)) || - (strict && (!allowLegacyCase) && data.name !== data.name.toLowerCase()) || - data.name.toLowerCase() === 'node_modules' || - data.name.toLowerCase() === 'favicon.ico') { - throw new Error('Invalid name: ' + JSON.stringify(data.name)) - } - } - } - - if (steps.includes('fixVersionField') || steps.includes('normalizeData')) { - // allow "loose" semver 1.0 versions in non-strict mode - // enforce strict semver 2.0 compliance in strict mode - const loose = !strict - if (!data.version) { - data.version = '' - } else { - if (!valid(data.version, loose)) { - throw new Error(`Invalid version: "${data.version}"`) - } - const version = clean(data.version, loose) - if (version !== data.version) { - changes?.push(`"version" was cleaned and set to "${version}"`) - data.version = version - } - } - } - // remove attributes that start with "_" - if (steps.includes('_attributes')) { - for (const key in data) { - if (key.startsWith('_')) { - changes?.push(`"${key}" was removed`) - delete pkg.content[key] - } - } - } - - // build the "_id" attribute - if (steps.includes('_id')) { - if (data.name && data.version) { - changes?.push(`"_id" was set to ${pkgId}`) - data._id = pkgId - } - } - - // fix bundledDependencies typo - // normalize bundleDependencies - if (steps.includes('bundledDependencies')) { - if (data.bundleDependencies === undefined && data.bundledDependencies !== undefined) { - data.bundleDependencies = data.bundledDependencies - } - changes?.push(`Deleted incorrect "bundledDependencies"`) - delete data.bundledDependencies - } - // expand "bundleDependencies: true or translate from object" - if (steps.includes('bundleDependencies')) { - const bd = data.bundleDependencies - if (bd === false && !steps.includes('bundleDependenciesDeleteFalse')) { - changes?.push(`"bundleDependencies" was changed from "false" to "[]"`) - data.bundleDependencies = [] - } else if (bd === true) { - changes?.push(`"bundleDependencies" was auto-populated from "dependencies"`) - data.bundleDependencies = Object.keys(data.dependencies || {}) - } else if (bd && typeof bd === 'object') { - if (!Array.isArray(bd)) { - changes?.push(`"bundleDependencies" was changed from an object to an array`) - data.bundleDependencies = Object.keys(bd) - } - } else if ('bundleDependencies' in data) { - changes?.push(`"bundleDependencies" was removed`) - delete data.bundleDependencies - } - } - - // it was once common practice to list deps both in optionalDependencies and - // in dependencies, to support npm versions that did not know about - // optionalDependencies. This is no longer a relevant need, so duplicating - // the deps in two places is unnecessary and excessive. - if (steps.includes('optionalDedupe')) { - if (data.dependencies && - data.optionalDependencies && typeof data.optionalDependencies === 'object') { - for (const name in data.optionalDependencies) { - changes?.push(`optionalDependencies."${name}" was removed`) - delete data.dependencies[name] - } - if (!Object.keys(data.dependencies).length) { - changes?.push(`Empty "optionalDependencies" was removed`) - delete data.dependencies - } - } - } - - // add "install" attribute if any "*.gyp" files exist - if (steps.includes('gypfile')) { - if (!scripts.install && !scripts.preinstall && data.gypfile !== false) { - const files = await lazyLoadGlob()('*.gyp', { cwd: pkg.path }) - if (files.length) { - scripts.install = 'node-gyp rebuild' - data.scripts = scripts - data.gypfile = true - changes?.push(`"scripts.install" was set to "node-gyp rebuild"`) - changes?.push(`"gypfile" was set to "true"`) - } - } - } - - // add "start" attribute if "server.js" exists - if (steps.includes('serverjs') && !scripts.start) { - try { - await fs.access(path.join(pkg.path, 'server.js')) - scripts.start = 'node server.js' - data.scripts = scripts - changes?.push('"scripts.start" was set to "node server.js"') - } catch { - // do nothing - } - } - - // strip "node_modules/.bin" from scripts entries - // remove invalid scripts entries (non-strings) - if ((steps.includes('scripts') || steps.includes('scriptpath')) && data.scripts !== undefined) { - const spre = /^(\.[/\\])?node_modules[/\\].bin[\\/]/ - if (typeof data.scripts === 'object') { - for (const name in data.scripts) { - if (typeof data.scripts[name] !== 'string') { - delete data.scripts[name] - changes?.push(`Invalid scripts."${name}" was removed`) - } else if (steps.includes('scriptpath') && spre.test(data.scripts[name])) { - data.scripts[name] = data.scripts[name].replace(spre, '') - changes?.push(`scripts entry "${name}" was fixed to remove node_modules/.bin reference`) - } - } - } else { - changes?.push(`Removed invalid "scripts"`) - delete data.scripts - } - } - - if (steps.includes('funding')) { - if (data.funding && typeof data.funding === 'string') { - data.funding = { url: data.funding } - changes?.push(`"funding" was changed to an object with a url attribute`) - } - } - - // populate "authors" attribute - if (steps.includes('authors') && !data.contributors) { - try { - const authorData = await fs.readFile(path.join(pkg.path, 'AUTHORS'), 'utf8') - const authors = authorData.split(/\r?\n/g) - .map(line => line.replace(/^\s*#.*$/, '').trim()) - .filter(line => line) - data.contributors = authors - changes?.push('"contributors" was auto-populated with the contents of the "AUTHORS" file') - } catch { - // do nothing - } - } - - // populate "readme" attribute - if (steps.includes('readme') && !data.readme) { - const mdre = /\.m?a?r?k?d?o?w?n?$/i - const files = await lazyLoadGlob()('{README,README.*}', { - cwd: pkg.path, - nocase: true, - mark: true, - }) - let readmeFile - for (const file of files) { - // don't accept directories. - if (!file.endsWith(path.sep)) { - if (file.match(mdre)) { - readmeFile = file - break - } - if (file.endsWith('README')) { - readmeFile = file - } - } - } - if (readmeFile) { - const readmeData = await fs.readFile(path.join(pkg.path, readmeFile), 'utf8') - data.readme = readmeData - data.readmeFilename = readmeFile - changes?.push(`"readme" was set to the contents of ${readmeFile}`) - changes?.push(`"readmeFilename" was set to ${readmeFile}`) - } - if (!data.readme) { - // this.warn('missingReadme') - data.readme = 'ERROR: No README data found!' - } - } - - // expand directories.man - if (steps.includes('mans')) { - if (data.directories?.man && !data.man) { - const manDir = secureAndUnixifyPath(data.directories.man) - const cwd = path.resolve(pkg.path, manDir) - const files = await lazyLoadGlob()('**/*.[0-9]', { cwd }) - data.man = files.map(man => - path.relative(pkg.path, path.join(cwd, man)).split(path.sep).join('/') - ) - } - normalizePackageMan(data, changes) - } - - if (steps.includes('bin') || steps.includes('binDir') || steps.includes('binRefs')) { - normalizePackageBin(data, changes) - } - - // expand "directories.bin" - if (steps.includes('binDir') && data.directories?.bin && !data.bin) { - const binsDir = path.resolve(pkg.path, secureAndUnixifyPath(data.directories.bin)) - const bins = await lazyLoadGlob()('**', { cwd: binsDir }) - data.bin = bins.reduce((acc, binFile) => { - if (binFile && !binFile.startsWith('.')) { - const binName = path.basename(binFile) - acc[binName] = path.join(data.directories.bin, binFile) - } - return acc - }, {}) - // *sigh* - normalizePackageBin(data, changes) - } - - // populate "gitHead" attribute - if (steps.includes('gitHead') && !data.gitHead) { - const git = require('@npmcli/git') - const gitRoot = await git.find({ cwd: pkg.path, root }) - let head - if (gitRoot) { - try { - head = await fs.readFile(path.resolve(gitRoot, '.git/HEAD'), 'utf8') - } catch (err) { - // do nothing - } - } - let headData - if (head) { - if (head.startsWith('ref: ')) { - const headRef = head.replace(/^ref: /, '').trim() - const headFile = path.resolve(gitRoot, '.git', headRef) - try { - headData = await fs.readFile(headFile, 'utf8') - headData = headData.replace(/^ref: /, '').trim() - } catch (err) { - // do nothing - } - if (!headData) { - const packFile = path.resolve(gitRoot, '.git/packed-refs') - try { - let refs = await fs.readFile(packFile, 'utf8') - if (refs) { - refs = refs.split('\n') - for (let i = 0; i < refs.length; i++) { - const match = refs[i].match(/^([0-9a-f]{40}) (.+)$/) - if (match && match[2].trim() === headRef) { - headData = match[1] - break - } - } - } - } catch { - // do nothing - } - } - } else { - headData = head.trim() - } - } - if (headData) { - data.gitHead = headData - } - } - - // populate "types" attribute - if (steps.includes('fillTypes')) { - const index = data.main || 'index.js' - - if (typeof index !== 'string') { - throw new TypeError('The "main" attribute must be of type string.') - } - - // TODO exports is much more complicated than this in verbose format - // We need to support for instance - - // "exports": { - // ".": [ - // { - // "default": "./lib/npm.js" - // }, - // "./lib/npm.js" - // ], - // "./package.json": "./package.json" - // }, - // as well as conditional exports - - // if (data.exports && typeof data.exports === 'string') { - // index = data.exports - // } - - // if (data.exports && data.exports['.']) { - // index = data.exports['.'] - // if (typeof index !== 'string') { - // } - // } - const extless = path.join(path.dirname(index), path.basename(index, path.extname(index))) - const dts = `./${extless}.d.ts` - const hasDTSFields = 'types' in data || 'typings' in data - if (!hasDTSFields) { - try { - await fs.access(path.join(pkg.path, dts)) - data.types = dts.split(path.sep).join('/') - } catch { - // do nothing - } - } - } - - // "normalizeData" from "read-package-json", which was just a call through to - // "normalize-package-data". We only call the "fixer" functions because - // outside of that it was also clobbering _id (which we already conditionally - // do) and also adding the gypfile script (which we also already - // conditionally do) - - // Some steps are isolated so we can do a limited subset of these in `fix` - if (steps.includes('fixRepositoryField') || steps.includes('normalizeData')) { - if (data.repositories) { - /* eslint-disable-next-line max-len */ - changes?.push(`"repository" was set to the first entry in "repositories" (${data.repository})`) - data.repository = data.repositories[0] - } - if (data.repository) { - if (typeof data.repository === 'string') { - changes?.push('"repository" was changed from a string to an object') - data.repository = { - type: 'git', - url: data.repository, - } - } - if (data.repository.url) { - const hosted = lazyHostedGitInfo().fromUrl(data.repository.url) - let r - if (hosted) { - if (hosted.getDefaultRepresentation() === 'shortcut') { - r = hosted.https() - } else { - r = hosted.toString() - } - if (r !== data.repository.url) { - changes?.push(`"repository.url" was normalized to "${r}"`) - data.repository.url = r - } - } - } - } - } - - if (steps.includes('fixDependencies') || steps.includes('normalizeData')) { - // peerDependencies? - // devDependencies is meaningless here, it's ignored on an installed package - for (const type of ['dependencies', 'devDependencies', 'optionalDependencies']) { - if (data[type]) { - let secondWarning = true - if (typeof data[type] === 'string') { - changes?.push(`"${type}" was converted from a string into an object`) - data[type] = data[type].trim().split(/[\n\r\s\t ,]+/) - secondWarning = false - } - if (Array.isArray(data[type])) { - if (secondWarning) { - changes?.push(`"${type}" was converted from an array into an object`) - } - const o = {} - for (const d of data[type]) { - if (typeof d === 'string') { - const dep = d.trim().split(/(:?[@\s><=])/) - const dn = dep.shift() - const dv = dep.join('').replace(/^@/, '').trim() - o[dn] = dv - } - } - data[type] = o - } - } - } - // normalize-package-data used to put optional dependencies BACK into - // dependencies here, we no longer do this - - for (const deps of ['dependencies', 'devDependencies']) { - if (deps in data) { - if (!data[deps] || typeof data[deps] !== 'object') { - changes?.push(`Removed invalid "${deps}"`) - delete data[deps] - } else { - for (const d in data[deps]) { - const r = data[deps][d] - if (typeof r !== 'string') { - changes?.push(`Removed invalid "${deps}.${d}"`) - delete data[deps][d] - } - const hosted = lazyHostedGitInfo().fromUrl(data[deps][d])?.toString() - if (hosted && hosted !== data[deps][d]) { - changes?.push(`Normalized git reference to "${deps}.${d}"`) - data[deps][d] = hosted.toString() - } - } - } - } - } - } - - if (steps.includes('normalizeData')) { - const legacyFixer = require('normalize-package-data/lib/fixer.js') - const legacyMakeWarning = require('normalize-package-data/lib/make_warning.js') - legacyFixer.warn = function () { - changes?.push(legacyMakeWarning.apply(null, arguments)) - } - - const legacySteps = [ - 'fixDescriptionField', - 'fixModulesField', - 'fixFilesField', - 'fixManField', - 'fixBugsField', - 'fixKeywordsField', - 'fixBundleDependenciesField', - 'fixHomepageField', - 'fixReadmeField', - 'fixLicenseField', - 'fixPeople', - 'fixTypos', - ] - for (const legacyStep of legacySteps) { - legacyFixer[legacyStep](data) - } - } - - // Warn if the bin references don't point to anything. This might be better - // in normalize-package-data if it had access to the file path. - if (steps.includes('binRefs') && data.bin instanceof Object) { - for (const key in data.bin) { - try { - await fs.access(path.resolve(pkg.path, data.bin[key])) - } catch { - log.warn('package-json', pkgId, `No bin file found at ${data.bin[key]}`) - // XXX: should a future breaking change delete bin entries that cannot be accessed? - } - } - } -} - -module.exports = normalize diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/read-package.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/read-package.js deleted file mode 100644 index d6c86ce388e6c..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/read-package.js +++ /dev/null @@ -1,39 +0,0 @@ -// This is JUST the code needed to open a package.json file and parse it. -// It's isolated out so that code needing to parse a package.json file can do so in the same way as this module does, without needing to require the whole module, or needing to require the underlying parsing library. - -const { readFile } = require('fs/promises') -const parseJSON = require('json-parse-even-better-errors') - -async function read (filename) { - try { - const data = await readFile(filename, 'utf8') - return data - } catch (err) { - err.message = `Could not read package.json: ${err}` - throw err - } -} - -function parse (data) { - try { - const content = parseJSON(data) - return content - } catch (err) { - err.message = `Invalid package.json: ${err}` - throw err - } -} - -// This is what most external libs will use. -// PackageJson will call read and parse separately -async function readPackage (filename) { - const data = await read(filename) - const content = parse(data) - return content -} - -module.exports = { - read, - parse, - readPackage, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/update-dependencies.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/update-dependencies.js deleted file mode 100644 index 7259949ab661d..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/update-dependencies.js +++ /dev/null @@ -1,75 +0,0 @@ -const depTypes = new Set([ - 'dependencies', - 'optionalDependencies', - 'devDependencies', - 'peerDependencies', -]) - -// sort alphabetically all types of deps for a given package -const orderDeps = (content) => { - for (const type of depTypes) { - if (content && content[type]) { - content[type] = Object.keys(content[type]) - .sort((a, b) => a.localeCompare(b, 'en')) - .reduce((res, key) => { - res[key] = content[type][key] - return res - }, {}) - } - } - return content -} - -const updateDependencies = ({ content, originalContent }) => { - const pkg = orderDeps({ - ...content, - }) - - // optionalDependencies don't need to be repeated in two places - if (pkg.dependencies) { - if (pkg.optionalDependencies) { - for (const name of Object.keys(pkg.optionalDependencies)) { - delete pkg.dependencies[name] - } - } - } - - const result = { ...originalContent } - - // loop through all types of dependencies and update package json pkg - for (const type of depTypes) { - if (pkg[type]) { - result[type] = pkg[type] - } - - // prune empty type props from resulting object - const emptyDepType = - pkg[type] - && typeof pkg === 'object' - && Object.keys(pkg[type]).length === 0 - if (emptyDepType) { - delete result[type] - } - } - - // if original package.json had dep in peerDeps AND deps, preserve that. - const { dependencies: origProd, peerDependencies: origPeer } = - originalContent || {} - const { peerDependencies: newPeer } = result - if (origProd && origPeer && newPeer) { - // we have original prod/peer deps, and new peer deps - // copy over any that were in both in the original - for (const name of Object.keys(origPeer)) { - if (origProd[name] !== undefined && newPeer[name] !== undefined) { - result.dependencies = result.dependencies || {} - result.dependencies[name] = newPeer[name] - } - } - } - - return result -} - -updateDependencies.knownKeys = depTypes - -module.exports = updateDependencies diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/update-scripts.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/update-scripts.js deleted file mode 100644 index 30495e54cc3c7..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/update-scripts.js +++ /dev/null @@ -1,29 +0,0 @@ -const updateScripts = ({ content, originalContent = {} }) => { - const newScripts = content.scripts - - if (!newScripts) { - return originalContent - } - - // validate scripts content being appended - const hasInvalidScripts = () => - Object.entries(newScripts) - .some(([key, value]) => - typeof key !== 'string' || typeof value !== 'string') - if (hasInvalidScripts()) { - throw Object.assign( - new TypeError( - 'package.json scripts should be a key-value pair of strings.'), - { code: 'ESCRIPTSINVALID' } - ) - } - - return { - ...originalContent, - scripts: { - ...newScripts, - }, - } -} - -module.exports = updateScripts diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/update-workspaces.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/update-workspaces.js deleted file mode 100644 index 04bf63230636f..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/lib/update-workspaces.js +++ /dev/null @@ -1,26 +0,0 @@ -const updateWorkspaces = ({ content, originalContent = {} }) => { - const newWorkspaces = content.workspaces - - if (!newWorkspaces) { - return originalContent - } - - // validate workspaces content being appended - const hasInvalidWorkspaces = () => - newWorkspaces.some(w => !(typeof w === 'string')) - if (!newWorkspaces.length || hasInvalidWorkspaces()) { - throw Object.assign( - new TypeError('workspaces should be an array of strings.'), - { code: 'EWORKSPACESINVALID' } - ) - } - - return { - ...originalContent, - workspaces: [ - ...newWorkspaces, - ], - } -} - -module.exports = updateWorkspaces diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/package.json deleted file mode 100644 index 5fea06ace7a81..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "name": "@npmcli/package-json", - "version": "5.2.1", - "description": "Programmatic API to update package.json", - "main": "lib/index.js", - "files": [ - "bin/", - "lib/" - ], - "scripts": { - "snap": "tap", - "test": "tap", - "lint": "npm run eslint", - "lintfix": "npm run eslint -- --fix", - "posttest": "npm run lint", - "postsnap": "npm run lintfix --", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" - }, - "keywords": [ - "npm", - "oss" - ], - "author": "GitHub Inc.", - "license": "ISC", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.23.3", - "read-package-json": "^7.0.0", - "read-package-json-fast": "^3.0.2", - "tap": "^16.0.1" - }, - "dependencies": { - "@npmcli/git": "^5.0.0", - "glob": "^10.2.2", - "hosted-git-info": "^7.0.0", - "json-parse-even-better-errors": "^3.0.0", - "normalize-package-data": "^6.0.0", - "proc-log": "^4.0.0", - "semver": "^7.5.3" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/package-json.git" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.23.3", - "publish": "true" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/LICENSE deleted file mode 100644 index 8f90f96f4c6c5..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) npm, Inc. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE NPM DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, -OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, -DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS -ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS -SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/lib/escape.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/lib/escape.js deleted file mode 100644 index 9aca8bde70a6e..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/lib/escape.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict' - -// eslint-disable-next-line max-len -// this code adapted from: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ -const cmd = (input, doubleEscape) => { - if (!input.length) { - return '""' - } - - let result - if (!/[ \t\n\v"]/.test(input)) { - result = input - } else { - result = '"' - for (let i = 0; i <= input.length; ++i) { - let slashCount = 0 - while (input[i] === '\\') { - ++i - ++slashCount - } - - if (i === input.length) { - result += '\\'.repeat(slashCount * 2) - break - } - - if (input[i] === '"') { - result += '\\'.repeat(slashCount * 2 + 1) - result += input[i] - } else { - result += '\\'.repeat(slashCount) - result += input[i] - } - } - result += '"' - } - - // and finally, prefix shell meta chars with a ^ - result = result.replace(/[ !%^&()<>|"]/g, '^$&') - if (doubleEscape) { - result = result.replace(/[ !%^&()<>|"]/g, '^$&') - } - - return result -} - -const sh = (input) => { - if (!input.length) { - return `''` - } - - if (!/[\t\n\r "#$&'()*;<>?\\`|~]/.test(input)) { - return input - } - - // replace single quotes with '\'' and wrap the whole result in a fresh set of quotes - const result = `'${input.replace(/'/g, `'\\''`)}'` - // if the input string already had single quotes around it, clean those up - .replace(/^(?:'')+(?!$)/, '') - .replace(/\\'''/g, `\\'`) - - return result -} - -module.exports = { - cmd, - sh, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/lib/index.js deleted file mode 100644 index e147cb8f9c746..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/lib/index.js +++ /dev/null @@ -1,206 +0,0 @@ -'use strict' - -const { spawn } = require('child_process') -const os = require('os') -const which = require('which') - -const escape = require('./escape.js') - -// 'extra' object is for decorating the error a bit more -const promiseSpawn = (cmd, args, opts = {}, extra = {}) => { - if (opts.shell) { - return spawnWithShell(cmd, args, opts, extra) - } - - let resolve, reject - const promise = new Promise((_resolve, _reject) => { - resolve = _resolve - reject = _reject - }) - - // Create error here so we have a more useful stack trace when rejecting - const closeError = new Error('command failed') - - const stdout = [] - const stderr = [] - - const getResult = (result) => ({ - cmd, - args, - ...result, - ...stdioResult(stdout, stderr, opts), - ...extra, - }) - const rejectWithOpts = (er, erOpts) => { - const resultError = getResult(erOpts) - reject(Object.assign(er, resultError)) - } - - const proc = spawn(cmd, args, opts) - promise.stdin = proc.stdin - promise.process = proc - - proc.on('error', rejectWithOpts) - - if (proc.stdout) { - proc.stdout.on('data', c => stdout.push(c)) - proc.stdout.on('error', rejectWithOpts) - } - - if (proc.stderr) { - proc.stderr.on('data', c => stderr.push(c)) - proc.stderr.on('error', rejectWithOpts) - } - - proc.on('close', (code, signal) => { - if (code || signal) { - rejectWithOpts(closeError, { code, signal }) - } else { - resolve(getResult({ code, signal })) - } - }) - - return promise -} - -const spawnWithShell = (cmd, args, opts, extra) => { - let command = opts.shell - // if shell is set to true, we use a platform default. we can't let the core - // spawn method decide this for us because we need to know what shell is in use - // ahead of time so that we can escape arguments properly. we don't need coverage here. - if (command === true) { - // istanbul ignore next - command = process.platform === 'win32' ? process.env.ComSpec : 'sh' - } - - const options = { ...opts, shell: false } - const realArgs = [] - let script = cmd - - // first, determine if we're in windows because if we are we need to know if we're - // running an .exe or a .cmd/.bat since the latter requires extra escaping - const isCmd = /(?:^|\\)cmd(?:\.exe)?$/i.test(command) - if (isCmd) { - let doubleEscape = false - - // find the actual command we're running - let initialCmd = '' - let insideQuotes = false - for (let i = 0; i < cmd.length; ++i) { - const char = cmd.charAt(i) - if (char === ' ' && !insideQuotes) { - break - } - - initialCmd += char - if (char === '"' || char === "'") { - insideQuotes = !insideQuotes - } - } - - let pathToInitial - try { - pathToInitial = which.sync(initialCmd, { - path: (options.env && findInObject(options.env, 'PATH')) || process.env.PATH, - pathext: (options.env && findInObject(options.env, 'PATHEXT')) || process.env.PATHEXT, - }).toLowerCase() - } catch (err) { - pathToInitial = initialCmd.toLowerCase() - } - - doubleEscape = pathToInitial.endsWith('.cmd') || pathToInitial.endsWith('.bat') - for (const arg of args) { - script += ` ${escape.cmd(arg, doubleEscape)}` - } - realArgs.push('/d', '/s', '/c', script) - options.windowsVerbatimArguments = true - } else { - for (const arg of args) { - script += ` ${escape.sh(arg)}` - } - realArgs.push('-c', script) - } - - return promiseSpawn(command, realArgs, options, extra) -} - -// open a file with the default application as defined by the user's OS -const open = (_args, opts = {}, extra = {}) => { - const options = { ...opts, shell: true } - const args = [].concat(_args) - - let platform = process.platform - // process.platform === 'linux' may actually indicate WSL, if that's the case - // we want to treat things as win32 anyway so the host can open the argument - if (platform === 'linux' && os.release().toLowerCase().includes('microsoft')) { - platform = 'win32' - } - - let command = options.command - if (!command) { - if (platform === 'win32') { - // spawnWithShell does not do the additional os.release() check, so we - // have to force the shell here to make sure we treat WSL as windows. - options.shell = process.env.ComSpec - // also, the start command accepts a title so to make sure that we don't - // accidentally interpret the first arg as the title, we stick an empty - // string immediately after the start command - command = 'start ""' - } else if (platform === 'darwin') { - command = 'open' - } else { - command = 'xdg-open' - } - } - - return spawnWithShell(command, args, options, extra) -} -promiseSpawn.open = open - -const isPipe = (stdio = 'pipe', fd) => { - if (stdio === 'pipe' || stdio === null) { - return true - } - - if (Array.isArray(stdio)) { - return isPipe(stdio[fd], fd) - } - - return false -} - -const stdioResult = (stdout, stderr, { stdioString = true, stdio }) => { - const result = { - stdout: null, - stderr: null, - } - - // stdio is [stdin, stdout, stderr] - if (isPipe(stdio, 1)) { - result.stdout = Buffer.concat(stdout) - if (stdioString) { - result.stdout = result.stdout.toString().trim() - } - } - - if (isPipe(stdio, 2)) { - result.stderr = Buffer.concat(stderr) - if (stdioString) { - result.stderr = result.stderr.toString().trim() - } - } - - return result -} - -// case insensitive lookup in an object -const findInObject = (obj, key) => { - key = key.toLowerCase() - for (const objKey of Object.keys(obj).sort()) { - if (objKey.toLowerCase() === key) { - return obj[objKey] - } - } -} - -module.exports = promiseSpawn diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/package.json deleted file mode 100644 index 1b633f84596d2..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "@npmcli/promise-spawn", - "version": "7.0.2", - "files": [ - "bin/", - "lib/" - ], - "main": "./lib/index.js", - "description": "spawn processes the way the npm cli likes to do", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/promise-spawn.git" - }, - "author": "GitHub Inc.", - "license": "ISC", - "scripts": { - "test": "tap", - "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint", - "postsnap": "npm run lintfix --", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force" - }, - "tap": { - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "spawk": "^1.7.1", - "tap": "^16.0.1" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true - }, - "dependencies": { - "which": "^4.0.0" - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/LICENSE deleted file mode 100644 index c21644115c85d..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2024 npm - -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/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/deep-map.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/deep-map.js deleted file mode 100644 index b555cf9fc4c8b..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/deep-map.js +++ /dev/null @@ -1,78 +0,0 @@ -function filterError (input) { - return { - errorType: input.name, - message: input.message, - stack: input.stack, - ...(input.code ? { code: input.code } : {}), - ...(input.statusCode ? { statusCode: input.statusCode } : {}), - } -} - -const deepMap = (input, handler = v => v, path = ['$'], seen = new Set([input])) => { - // this is in an effort to maintain bole's error logging behavior - if (path.join('.') === '$' && input instanceof Error) { - return deepMap({ err: filterError(input) }, handler, path, seen) - } - if (input instanceof Error) { - return deepMap(filterError(input), handler, path, seen) - } - if (input instanceof Buffer) { - return `[unable to log instanceof buffer]` - } - if (input instanceof Uint8Array) { - return `[unable to log instanceof Uint8Array]` - } - - if (Array.isArray(input)) { - const result = [] - for (let i = 0; i < input.length; i++) { - const element = input[i] - const elementPath = [...path, i] - if (element instanceof Object) { - if (!seen.has(element)) { // avoid getting stuck in circular reference - seen.add(element) - result.push(deepMap(handler(element, elementPath), handler, elementPath, seen)) - } - } else { - result.push(handler(element, elementPath)) - } - } - return result - } - - if (input === null) { - return null - } else if (typeof input === 'object' || typeof input === 'function') { - const result = {} - - for (const propertyName of Object.getOwnPropertyNames(input)) { - // skip logging internal properties - if (propertyName.startsWith('_')) { - continue - } - - try { - const property = input[propertyName] - const propertyPath = [...path, propertyName] - if (property instanceof Object) { - if (!seen.has(property)) { // avoid getting stuck in circular reference - seen.add(property) - result[propertyName] = deepMap( - handler(property, propertyPath), handler, propertyPath, seen - ) - } - } else { - result[propertyName] = handler(property, propertyPath) - } - } catch (err) { - // a getter may throw an error - result[propertyName] = `[error getting value: ${err.message}]` - } - } - return result - } - - return handler(input, path) -} - -module.exports = { deepMap } diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/index.js deleted file mode 100644 index 9b10c7f6a0081..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/index.js +++ /dev/null @@ -1,44 +0,0 @@ -const matchers = require('./matchers') -const { redactUrlPassword } = require('./utils') - -const REPLACE = '***' - -const redact = (value) => { - if (typeof value !== 'string' || !value) { - return value - } - return redactUrlPassword(value, REPLACE) - .replace(matchers.NPM_SECRET.pattern, `npm_${REPLACE}`) - .replace(matchers.UUID.pattern, REPLACE) -} - -// split on \s|= similar to how nopt parses options -const splitAndRedact = (str) => { - // stateful regex, don't move out of this scope - const splitChars = /[\s=]/g - - let match = null - let result = '' - let index = 0 - while (match = splitChars.exec(str)) { - result += redact(str.slice(index, match.index)) + match[0] - index = splitChars.lastIndex - } - - return result + redact(str.slice(index)) -} - -// replaces auth info in an array of arguments or in a strings -const redactLog = (arg) => { - if (typeof arg === 'string') { - return splitAndRedact(arg) - } else if (Array.isArray(arg)) { - return arg.map((a) => typeof a === 'string' ? splitAndRedact(a) : a) - } - return arg -} - -module.exports = { - redact, - redactLog, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/matchers.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/matchers.js deleted file mode 100644 index fe9b9071de8a1..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/matchers.js +++ /dev/null @@ -1,81 +0,0 @@ -const TYPE_REGEX = 'regex' -const TYPE_URL = 'url' -const TYPE_PATH = 'path' - -const NPM_SECRET = { - type: TYPE_REGEX, - pattern: /\b(npms?_)[a-zA-Z0-9]{36,48}\b/gi, - replacement: `[REDACTED_NPM_SECRET]`, -} - -const AUTH_HEADER = { - type: TYPE_REGEX, - pattern: /\b(Basic\s+|Bearer\s+)[\w+=\-.]+\b/gi, - replacement: `[REDACTED_AUTH_HEADER]`, -} - -const JSON_WEB_TOKEN = { - type: TYPE_REGEX, - pattern: /\b[A-Za-z0-9-_]{10,}(?!\.\d+\.)\.[A-Za-z0-9-_]{3,}\.[A-Za-z0-9-_]{20,}\b/gi, - replacement: `[REDACTED_JSON_WEB_TOKEN]`, -} - -const UUID = { - type: TYPE_REGEX, - pattern: /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, - replacement: `[REDACTED_UUID]`, -} - -const URL_MATCHER = { - type: TYPE_REGEX, - pattern: /(?:https?|ftp):\/\/[^\s/"$.?#].[^\s"]*/gi, - replacement: '[REDACTED_URL]', -} - -const DEEP_HEADER_AUTHORIZATION = { - type: TYPE_PATH, - predicate: ({ path }) => path.endsWith('.headers.authorization'), - replacement: '[REDACTED_HEADER_AUTHORIZATION]', -} - -const DEEP_HEADER_SET_COOKIE = { - type: TYPE_PATH, - predicate: ({ path }) => path.endsWith('.headers.set-cookie'), - replacement: '[REDACTED_HEADER_SET_COOKIE]', -} - -const REWRITE_REQUEST = { - type: TYPE_PATH, - predicate: ({ path }) => path.endsWith('.request'), - replacement: (input) => ({ - method: input?.method, - path: input?.path, - headers: input?.headers, - url: input?.url, - }), -} - -const REWRITE_RESPONSE = { - type: TYPE_PATH, - predicate: ({ path }) => path.endsWith('.response'), - replacement: (input) => ({ - data: input?.data, - status: input?.status, - headers: input?.headers, - }), -} - -module.exports = { - TYPE_REGEX, - TYPE_URL, - TYPE_PATH, - NPM_SECRET, - AUTH_HEADER, - JSON_WEB_TOKEN, - UUID, - URL_MATCHER, - DEEP_HEADER_AUTHORIZATION, - DEEP_HEADER_SET_COOKIE, - REWRITE_REQUEST, - REWRITE_RESPONSE, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/server.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/server.js deleted file mode 100644 index 669e834da6131..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/server.js +++ /dev/null @@ -1,34 +0,0 @@ -const { - AUTH_HEADER, - JSON_WEB_TOKEN, - NPM_SECRET, - DEEP_HEADER_AUTHORIZATION, - DEEP_HEADER_SET_COOKIE, - REWRITE_REQUEST, - REWRITE_RESPONSE, -} = require('./matchers') - -const { - redactUrlMatcher, - redactUrlPasswordMatcher, - redactMatchers, -} = require('./utils') - -const { deepMap } = require('./deep-map') - -const _redact = redactMatchers( - NPM_SECRET, - AUTH_HEADER, - JSON_WEB_TOKEN, - DEEP_HEADER_AUTHORIZATION, - DEEP_HEADER_SET_COOKIE, - REWRITE_REQUEST, - REWRITE_RESPONSE, - redactUrlMatcher( - redactUrlPasswordMatcher() - ) -) - -const redact = (input) => deepMap(input, (value, path) => _redact(value, { path })) - -module.exports = { redact } diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/utils.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/utils.js deleted file mode 100644 index 8395ab25fc373..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/lib/utils.js +++ /dev/null @@ -1,202 +0,0 @@ -const { - URL_MATCHER, - TYPE_URL, - TYPE_REGEX, - TYPE_PATH, -} = require('./matchers') - -/** - * creates a string of asterisks, - * this forces a minimum asterisk for security purposes - */ -const asterisk = (length = 0) => { - length = typeof length === 'string' ? length.length : length - if (length < 8) { - return '*'.repeat(8) - } - return '*'.repeat(length) -} - -/** - * escapes all special regex chars - * @see https://stackoverflow.com/a/9310752 - * @see https://github.com/tc39/proposal-regex-escaping - */ -const escapeRegExp = (text) => { - return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, `\\$&`) -} - -/** - * provieds a regex "or" of the url versions of a string - */ -const urlEncodeRegexGroup = (value) => { - const decoded = decodeURIComponent(value) - const encoded = encodeURIComponent(value) - const union = [...new Set([encoded, decoded, value])].map(escapeRegExp).join('|') - return union -} - -/** - * a tagged template literal that returns a regex ensures all variables are excaped - */ -const urlEncodeRegexTag = (strings, ...values) => { - let pattern = '' - for (let i = 0; i < values.length; i++) { - pattern += strings[i] + `(${urlEncodeRegexGroup(values[i])})` - } - pattern += strings[strings.length - 1] - return new RegExp(pattern) -} - -/** - * creates a matcher for redacting url hostname - */ -const redactUrlHostnameMatcher = ({ hostname, replacement } = {}) => ({ - type: TYPE_URL, - predicate: ({ url }) => url.hostname === hostname, - pattern: ({ url }) => { - return urlEncodeRegexTag`(^${url.protocol}//${url.username}:.+@)?${url.hostname}` - }, - replacement: `$1${replacement || asterisk()}`, -}) - -/** - * creates a matcher for redacting url search / query parameter values - */ -const redactUrlSearchParamsMatcher = ({ param, replacement } = {}) => ({ - type: TYPE_URL, - predicate: ({ url }) => url.searchParams.has(param), - pattern: ({ url }) => urlEncodeRegexTag`(${param}=)${url.searchParams.get(param)}`, - replacement: `$1${replacement || asterisk()}`, -}) - -/** creates a matcher for redacting the url password */ -const redactUrlPasswordMatcher = ({ replacement } = {}) => ({ - type: TYPE_URL, - predicate: ({ url }) => url.password, - pattern: ({ url }) => urlEncodeRegexTag`(^${url.protocol}//${url.username}:)${url.password}`, - replacement: `$1${replacement || asterisk()}`, -}) - -const redactUrlReplacement = (...matchers) => (subValue) => { - try { - const url = new URL(subValue) - return redactMatchers(...matchers)(subValue, { url }) - } catch (err) { - return subValue - } -} - -/** - * creates a matcher / submatcher for urls, this function allows you to first - * collect all urls within a larger string and then pass those urls to a - * submatcher - * - * @example - * console.log("this will first match all urls, then pass those urls to the password patcher") - * redactMatchers(redactUrlMatcher(redactUrlPasswordMatcher())) - * - * @example - * console.log( - * "this will assume you are passing in a string that is a url, and will redact the password" - * ) - * redactMatchers(redactUrlPasswordMatcher()) - * - */ -const redactUrlMatcher = (...matchers) => { - return { - ...URL_MATCHER, - replacement: redactUrlReplacement(...matchers), - } -} - -const matcherFunctions = { - [TYPE_REGEX]: (matcher) => (value) => { - if (typeof value === 'string') { - value = value.replace(matcher.pattern, matcher.replacement) - } - return value - }, - [TYPE_URL]: (matcher) => (value, ctx) => { - if (typeof value === 'string') { - try { - const url = ctx?.url || new URL(value) - const { predicate, pattern } = matcher - const predicateValue = predicate({ url }) - if (predicateValue) { - value = value.replace(pattern({ url }), matcher.replacement) - } - } catch (_e) { - return value - } - } - return value - }, - [TYPE_PATH]: (matcher) => (value, ctx) => { - const rawPath = ctx?.path - const path = rawPath.join('.').toLowerCase() - const { predicate, replacement } = matcher - const replace = typeof replacement === 'function' ? replacement : () => replacement - const shouldRun = predicate({ rawPath, path }) - if (shouldRun) { - value = replace(value, { rawPath, path }) - } - return value - }, -} - -/** converts a matcher to a function */ -const redactMatcher = (matcher) => { - return matcherFunctions[matcher.type](matcher) -} - -/** converts a series of matchers to a function */ -const redactMatchers = (...matchers) => (value, ctx) => { - const flatMatchers = matchers.flat() - return flatMatchers.reduce((result, matcher) => { - const fn = (typeof matcher === 'function') ? matcher : redactMatcher(matcher) - return fn(result, ctx) - }, value) -} - -/** - * replacement handler, keeping $1 (if it exists) and replacing the - * rest of the string with asterisks, maintaining string length - */ -const redactDynamicReplacement = () => (value, start) => { - if (typeof start === 'number') { - return asterisk(value) - } - return start + asterisk(value.substring(start.length).length) -} - -/** - * replacement handler, keeping $1 (if it exists) and replacing the - * rest of the string with a fixed number of asterisks - */ -const redactFixedReplacement = (length) => (_value, start) => { - if (typeof start === 'number') { - return asterisk(length) - } - return start + asterisk(length) -} - -const redactUrlPassword = (value, replacement) => { - return redactMatchers(redactUrlPasswordMatcher({ replacement }))(value) -} - -module.exports = { - asterisk, - escapeRegExp, - urlEncodeRegexGroup, - urlEncodeRegexTag, - redactUrlHostnameMatcher, - redactUrlSearchParamsMatcher, - redactUrlPasswordMatcher, - redactUrlMatcher, - redactUrlReplacement, - redactDynamicReplacement, - redactFixedReplacement, - redactMatchers, - redactUrlPassword, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/package.json deleted file mode 100644 index 831387ca54106..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "@npmcli/redact", - "version": "2.0.1", - "description": "Redact sensitive npm information from output", - "main": "lib/index.js", - "exports": { - ".": "./lib/index.js", - "./server": "./lib/server.js", - "./package.json": "./package.json" - }, - "scripts": { - "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" - }, - "keywords": [], - "author": "GitHub Inc.", - "license": "ISC", - "files": [ - "bin/", - "lib/" - ], - "repository": { - "type": "git", - "url": "https://github.com/npm/redact.git" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.3", - "publish": true - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ], - "timeout": 120 - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.2", - "@npmcli/template-oss": "4.21.3", - "tap": "^16.3.10" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/LICENSE deleted file mode 100644 index 19cec97b18468..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) npm, Inc. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/is-server-package.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/is-server-package.js deleted file mode 100644 index c36c40d4898d5..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/is-server-package.js +++ /dev/null @@ -1,11 +0,0 @@ -const { stat } = require('node:fs/promises') -const { resolve } = require('node:path') - -module.exports = async path => { - try { - const st = await stat(resolve(path, 'server.js')) - return st.isFile() - } catch (er) { - return false - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/make-spawn-args.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/make-spawn-args.js deleted file mode 100644 index 8a32d7198cb2e..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/make-spawn-args.js +++ /dev/null @@ -1,40 +0,0 @@ -/* eslint camelcase: "off" */ -const setPATH = require('./set-path.js') -const { resolve } = require('path') -const npm_config_node_gyp = require.resolve('node-gyp/bin/node-gyp.js') - -const makeSpawnArgs = options => { - const { - event, - path, - scriptShell = true, - binPaths, - env, - stdio, - cmd, - args, - stdioString, - } = options - - const spawnEnv = setPATH(path, binPaths, { - // we need to at least save the PATH environment var - ...process.env, - ...env, - npm_package_json: resolve(path, 'package.json'), - npm_lifecycle_event: event, - npm_lifecycle_script: cmd, - npm_config_node_gyp, - }) - - const spawnOpts = { - env: spawnEnv, - stdioString, - stdio, - cwd: path, - shell: scriptShell, - } - - return [cmd, args, spawnOpts] -} - -module.exports = makeSpawnArgs diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/node-gyp-bin/node-gyp b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/node-gyp-bin/node-gyp deleted file mode 100755 index 5bec64d961a3a..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/node-gyp-bin/node-gyp +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env sh -node "$npm_config_node_gyp" "$@" diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/node-gyp-bin/node-gyp.cmd b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/node-gyp-bin/node-gyp.cmd deleted file mode 100755 index 4c6987ac9868b..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/node-gyp-bin/node-gyp.cmd +++ /dev/null @@ -1 +0,0 @@ -@node "%npm_config_node_gyp%" %* diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/package-envs.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/package-envs.js deleted file mode 100644 index 612f850fb076c..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/package-envs.js +++ /dev/null @@ -1,29 +0,0 @@ -const packageEnvs = (vals, prefix, env = {}) => { - for (const [key, val] of Object.entries(vals)) { - if (val === undefined) { - continue - } else if (val === null || val === false) { - env[`${prefix}${key}`] = '' - } else if (Array.isArray(val)) { - val.forEach((item, index) => { - packageEnvs({ [`${key}_${index}`]: item }, `${prefix}`, env) - }) - } else if (typeof val === 'object') { - packageEnvs(val, `${prefix}${key}_`, env) - } else { - env[`${prefix}${key}`] = String(val) - } - } - return env -} - -// https://github.com/npm/rfcs/pull/183 defines which fields we put into the environment -module.exports = pkg => { - return packageEnvs({ - name: pkg.name, - version: pkg.version, - config: pkg.config, - engines: pkg.engines, - bin: pkg.bin, - }, 'npm_package_') -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/run-script-pkg.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/run-script-pkg.js deleted file mode 100644 index 9900c96315f85..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/run-script-pkg.js +++ /dev/null @@ -1,112 +0,0 @@ -const makeSpawnArgs = require('./make-spawn-args.js') -const promiseSpawn = require('@npmcli/promise-spawn') -const packageEnvs = require('./package-envs.js') -const { isNodeGypPackage, defaultGypInstallScript } = require('@npmcli/node-gyp') -const signalManager = require('./signal-manager.js') -const isServerPackage = require('./is-server-package.js') - -const runScriptPkg = async options => { - const { - event, - path, - scriptShell, - binPaths = false, - env = {}, - stdio = 'pipe', - pkg, - args = [], - stdioString, - // how long to wait for a process.kill signal - // only exposed here so that we can make the test go a bit faster. - signalTimeout = 500, - } = options - - const { scripts = {}, gypfile } = pkg - let cmd = null - if (options.cmd) { - cmd = options.cmd - } else if (pkg.scripts && pkg.scripts[event]) { - cmd = pkg.scripts[event] - } else if ( - // If there is no preinstall or install script, default to rebuilding node-gyp packages. - event === 'install' && - !scripts.install && - !scripts.preinstall && - gypfile !== false && - await isNodeGypPackage(path) - ) { - cmd = defaultGypInstallScript - } else if (event === 'start' && await isServerPackage(path)) { - cmd = 'node server.js' - } - - if (!cmd) { - return { code: 0, signal: null } - } - - let inputEnd = () => {} - if (stdio === 'inherit') { - let banner - if (pkg._id) { - banner = `\n> ${pkg._id} ${event}\n` - } else { - banner = `\n> ${event}\n` - } - banner += `> ${cmd.trim().replace(/\n/g, '\n> ')}` - if (args.length) { - banner += ` ${args.join(' ')}` - } - banner += '\n' - const { output, input } = require('proc-log') - output.standard(banner) - inputEnd = input.start() - } - - const [spawnShell, spawnArgs, spawnOpts] = makeSpawnArgs({ - event, - path, - scriptShell, - binPaths, - env: { ...env, ...packageEnvs(pkg) }, - stdio, - cmd, - args, - stdioString, - }) - - const p = promiseSpawn(spawnShell, spawnArgs, spawnOpts, { - event, - script: cmd, - pkgid: pkg._id, - path, - }) - - if (stdio === 'inherit') { - signalManager.add(p.process) - } - - if (p.stdin) { - p.stdin.end() - } - - return p.catch(er => { - const { signal } = er - // coverage disabled because win32 never emits signals - /* istanbul ignore next */ - if (stdio === 'inherit' && signal) { - // by the time we reach here, the child has already exited. we send the - // signal back to ourselves again so that npm will exit with the same - // status as the child - process.kill(process.pid, signal) - - // just in case we don't die, reject after 500ms - // this also keeps the node process open long enough to actually - // get the signal, rather than terminating gracefully. - return new Promise((res, rej) => setTimeout(() => rej(er), signalTimeout)) - } else { - throw er - } - }).finally(inputEnd) -} - -module.exports = runScriptPkg diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/run-script.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/run-script.js deleted file mode 100644 index b00304c8d6e7f..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/run-script.js +++ /dev/null @@ -1,15 +0,0 @@ -const PackageJson = require('@npmcli/package-json') -const runScriptPkg = require('./run-script-pkg.js') -const validateOptions = require('./validate-options.js') -const isServerPackage = require('./is-server-package.js') - -const runScript = async options => { - validateOptions(options) - if (options.pkg) { - return runScriptPkg(options) - } - const { content: pkg } = await PackageJson.normalize(options.path) - return runScriptPkg({ ...options, pkg }) -} - -module.exports = Object.assign(runScript, { isServerPackage }) diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/set-path.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/set-path.js deleted file mode 100644 index c59c270d9969a..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/set-path.js +++ /dev/null @@ -1,45 +0,0 @@ -const { resolve, dirname, delimiter } = require('path') -// the path here is relative, even though it does not need to be -// in order to make the posix tests pass in windows -const nodeGypPath = resolve(__dirname, '../lib/node-gyp-bin') - -// Windows typically calls its PATH environ 'Path', but this is not -// guaranteed, nor is it guaranteed to be the only one. Merge them -// all together in the order they appear in the object. -const setPATH = (projectPath, binPaths, env) => { - const PATH = Object.keys(env).filter(p => /^path$/i.test(p) && env[p]) - .map(p => env[p].split(delimiter)) - .reduce((set, p) => set.concat(p.filter(concatted => !set.includes(concatted))), []) - .join(delimiter) - - const pathArr = [] - if (binPaths) { - pathArr.push(...binPaths) - } - // unshift the ./node_modules/.bin from every folder - // walk up until dirname() does nothing, at the root - // XXX we should specify a cwd that we don't go above - let p = projectPath - let pp - do { - pathArr.push(resolve(p, 'node_modules', '.bin')) - pp = p - p = dirname(p) - } while (p !== pp) - pathArr.push(nodeGypPath, PATH) - - const pathVal = pathArr.join(delimiter) - - // XXX include the node-gyp-bin path somehow? Probably better for - // npm or arborist or whoever to just provide that by putting it in - // the PATH environ, since that's preserved anyway. - for (const key of Object.keys(env)) { - if (/^path$/i.test(key)) { - env[key] = pathVal - } - } - - return env -} - -module.exports = setPATH diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/signal-manager.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/signal-manager.js deleted file mode 100644 index a099a4af2b9be..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/signal-manager.js +++ /dev/null @@ -1,50 +0,0 @@ -const runningProcs = new Set() -let handlersInstalled = false - -const forwardedSignals = [ - 'SIGINT', - 'SIGTERM', -] - -// no-op, this is so receiving the signal doesn't cause us to exit immediately -// instead, we exit after all children have exited when we re-send the signal -// to ourselves. see the catch handler at the bottom of run-script-pkg.js -const handleSignal = signal => { - for (const proc of runningProcs) { - proc.kill(signal) - } -} - -const setupListeners = () => { - for (const signal of forwardedSignals) { - process.on(signal, handleSignal) - } - handlersInstalled = true -} - -const cleanupListeners = () => { - if (runningProcs.size === 0) { - for (const signal of forwardedSignals) { - process.removeListener(signal, handleSignal) - } - handlersInstalled = false - } -} - -const add = proc => { - runningProcs.add(proc) - if (!handlersInstalled) { - setupListeners() - } - - proc.once('exit', () => { - runningProcs.delete(proc) - cleanupListeners() - }) -} - -module.exports = { - add, - handleSignal, - forwardedSignals, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/validate-options.js b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/validate-options.js deleted file mode 100644 index 8d855916ecd15..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/lib/validate-options.js +++ /dev/null @@ -1,39 +0,0 @@ -const validateOptions = options => { - if (typeof options !== 'object' || !options) { - throw new TypeError('invalid options object provided to runScript') - } - - const { - event, - path, - scriptShell, - env = {}, - stdio = 'pipe', - args = [], - cmd, - } = options - - if (!event || typeof event !== 'string') { - throw new TypeError('valid event not provided to runScript') - } - if (!path || typeof path !== 'string') { - throw new TypeError('valid path not provided to runScript') - } - if (scriptShell !== undefined && typeof scriptShell !== 'string') { - throw new TypeError('invalid scriptShell option provided to runScript') - } - if (typeof env !== 'object' || !env) { - throw new TypeError('invalid env option provided to runScript') - } - if (typeof stdio !== 'string' && !Array.isArray(stdio)) { - throw new TypeError('invalid stdio option provided to runScript') - } - if (!Array.isArray(args) || args.some(a => typeof a !== 'string')) { - throw new TypeError('invalid args option provided to runScript') - } - if (cmd !== undefined && typeof cmd !== 'string') { - throw new TypeError('invalid cmd option provided to runScript') - } -} - -module.exports = validateOptions diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/package.json deleted file mode 100644 index 8a83e726fbeb2..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@npmcli/run-script", - "version": "8.1.0", - "description": "Run a lifecycle script for a package (descendant of npm-lifecycle)", - "author": "GitHub Inc.", - "license": "ISC", - "scripts": { - "test": "tap", - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "postlint": "template-oss-check", - "snap": "tap", - "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.4", - "spawk": "^1.8.1", - "tap": "^16.0.1" - }, - "dependencies": { - "@npmcli/node-gyp": "^3.0.0", - "@npmcli/package-json": "^5.0.0", - "@npmcli/promise-spawn": "^7.0.0", - "node-gyp": "^10.0.0", - "proc-log": "^4.0.0", - "which": "^4.0.0" - }, - "files": [ - "bin/", - "lib/" - ], - "main": "lib/run-script.js", - "repository": { - "type": "git", - "url": "https://github.com/npm/run-script.git" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.4", - "publish": "true" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/LICENSE.md b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/LICENSE.md deleted file mode 100644 index 8d28acf866d93..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/LICENSE.md +++ /dev/null @@ -1,16 +0,0 @@ -ISC License - -Copyright (c) npm, Inc. - -Permission to use, copy, modify, and/or distribute this software for -any purpose with or without fee is hereby granted, provided that the -above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS -ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR -CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE -USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/path.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/path.js deleted file mode 100644 index ad5a76a4f73f2..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/path.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict' - -const contentVer = require('../../package.json')['cache-version'].content -const hashToSegments = require('../util/hash-to-segments') -const path = require('path') -const ssri = require('ssri') - -// Current format of content file path: -// -// sha512-BaSE64Hex= -> -// ~/.my-cache/content-v2/sha512/ba/da/55deadbeefc0ffee -// -module.exports = contentPath - -function contentPath (cache, integrity) { - const sri = ssri.parse(integrity, { single: true }) - // contentPath is the *strongest* algo given - return path.join( - contentDir(cache), - sri.algorithm, - ...hashToSegments(sri.hexDigest()) - ) -} - -module.exports.contentDir = contentDir - -function contentDir (cache) { - return path.join(cache, `content-v${contentVer}`) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/read.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/read.js deleted file mode 100644 index 5f6192c3cec56..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/read.js +++ /dev/null @@ -1,165 +0,0 @@ -'use strict' - -const fs = require('fs/promises') -const fsm = require('fs-minipass') -const ssri = require('ssri') -const contentPath = require('./path') -const Pipeline = require('minipass-pipeline') - -module.exports = read - -const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024 -async function read (cache, integrity, opts = {}) { - const { size } = opts - const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { - // get size - const stat = size ? { size } : await fs.stat(cpath) - return { stat, cpath, sri } - }) - - if (stat.size > MAX_SINGLE_READ_SIZE) { - return readPipeline(cpath, stat.size, sri, new Pipeline()).concat() - } - - const data = await fs.readFile(cpath, { encoding: null }) - - if (stat.size !== data.length) { - throw sizeError(stat.size, data.length) - } - - if (!ssri.checkData(data, sri)) { - throw integrityError(sri, cpath) - } - - return data -} - -const readPipeline = (cpath, size, sri, stream) => { - stream.push( - new fsm.ReadStream(cpath, { - size, - readSize: MAX_SINGLE_READ_SIZE, - }), - ssri.integrityStream({ - integrity: sri, - size, - }) - ) - return stream -} - -module.exports.stream = readStream -module.exports.readStream = readStream - -function readStream (cache, integrity, opts = {}) { - const { size } = opts - const stream = new Pipeline() - // Set all this up to run on the stream and then just return the stream - Promise.resolve().then(async () => { - const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { - // get size - const stat = size ? { size } : await fs.stat(cpath) - return { stat, cpath, sri } - }) - - return readPipeline(cpath, stat.size, sri, stream) - }).catch(err => stream.emit('error', err)) - - return stream -} - -module.exports.copy = copy - -function copy (cache, integrity, dest) { - return withContentSri(cache, integrity, (cpath) => { - return fs.copyFile(cpath, dest) - }) -} - -module.exports.hasContent = hasContent - -async function hasContent (cache, integrity) { - if (!integrity) { - return false - } - - try { - return await withContentSri(cache, integrity, async (cpath, sri) => { - const stat = await fs.stat(cpath) - return { size: stat.size, sri, stat } - }) - } catch (err) { - if (err.code === 'ENOENT') { - return false - } - - if (err.code === 'EPERM') { - /* istanbul ignore else */ - if (process.platform !== 'win32') { - throw err - } else { - return false - } - } - } -} - -async function withContentSri (cache, integrity, fn) { - const sri = ssri.parse(integrity) - // If `integrity` has multiple entries, pick the first digest - // with available local data. - const algo = sri.pickAlgorithm() - const digests = sri[algo] - - if (digests.length <= 1) { - const cpath = contentPath(cache, digests[0]) - return fn(cpath, digests[0]) - } else { - // Can't use race here because a generic error can happen before - // a ENOENT error, and can happen before a valid result - const results = await Promise.all(digests.map(async (meta) => { - try { - return await withContentSri(cache, meta, fn) - } catch (err) { - if (err.code === 'ENOENT') { - return Object.assign( - new Error('No matching content found for ' + sri.toString()), - { code: 'ENOENT' } - ) - } - return err - } - })) - // Return the first non error if it is found - const result = results.find((r) => !(r instanceof Error)) - if (result) { - return result - } - - // Throw the No matching content found error - const enoentError = results.find((r) => r.code === 'ENOENT') - if (enoentError) { - throw enoentError - } - - // Throw generic error - throw results.find((r) => r instanceof Error) - } -} - -function sizeError (expected, found) { - /* eslint-disable-next-line max-len */ - const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) - err.expected = expected - err.found = found - err.code = 'EBADSIZE' - return err -} - -function integrityError (sri, path) { - const err = new Error(`Integrity verification failed for ${sri} (${path})`) - err.code = 'EINTEGRITY' - err.sri = sri - err.path = path - return err -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/rm.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/rm.js deleted file mode 100644 index ce58d679e4cb2..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/rm.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict' - -const fs = require('fs/promises') -const contentPath = require('./path') -const { hasContent } = require('./read') - -module.exports = rm - -async function rm (cache, integrity) { - const content = await hasContent(cache, integrity) - // ~pretty~ sure we can't end up with a content lacking sri, but be safe - if (content && content.sri) { - await fs.rm(contentPath(cache, content.sri), { recursive: true, force: true }) - return true - } else { - return false - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/write.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/write.js deleted file mode 100644 index e7187abca8788..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/content/write.js +++ /dev/null @@ -1,206 +0,0 @@ -'use strict' - -const events = require('events') - -const contentPath = require('./path') -const fs = require('fs/promises') -const { moveFile } = require('@npmcli/fs') -const { Minipass } = require('minipass') -const Pipeline = require('minipass-pipeline') -const Flush = require('minipass-flush') -const path = require('path') -const ssri = require('ssri') -const uniqueFilename = require('unique-filename') -const fsm = require('fs-minipass') - -module.exports = write - -// Cache of move operations in process so we don't duplicate -const moveOperations = new Map() - -async function write (cache, data, opts = {}) { - const { algorithms, size, integrity } = opts - - if (typeof size === 'number' && data.length !== size) { - throw sizeError(size, data.length) - } - - const sri = ssri.fromData(data, algorithms ? { algorithms } : {}) - if (integrity && !ssri.checkData(data, integrity, opts)) { - throw checksumError(integrity, sri) - } - - for (const algo in sri) { - const tmp = await makeTmp(cache, opts) - const hash = sri[algo].toString() - try { - await fs.writeFile(tmp.target, data, { flag: 'wx' }) - await moveToDestination(tmp, cache, hash, opts) - } finally { - if (!tmp.moved) { - await fs.rm(tmp.target, { recursive: true, force: true }) - } - } - } - return { integrity: sri, size: data.length } -} - -module.exports.stream = writeStream - -// writes proxied to the 'inputStream' that is passed to the Promise -// 'end' is deferred until content is handled. -class CacacheWriteStream extends Flush { - constructor (cache, opts) { - super() - this.opts = opts - this.cache = cache - this.inputStream = new Minipass() - this.inputStream.on('error', er => this.emit('error', er)) - this.inputStream.on('drain', () => this.emit('drain')) - this.handleContentP = null - } - - write (chunk, encoding, cb) { - if (!this.handleContentP) { - this.handleContentP = handleContent( - this.inputStream, - this.cache, - this.opts - ) - this.handleContentP.catch(error => this.emit('error', error)) - } - return this.inputStream.write(chunk, encoding, cb) - } - - flush (cb) { - this.inputStream.end(() => { - if (!this.handleContentP) { - const e = new Error('Cache input stream was empty') - e.code = 'ENODATA' - // empty streams are probably emitting end right away. - // defer this one tick by rejecting a promise on it. - return Promise.reject(e).catch(cb) - } - // eslint-disable-next-line promise/catch-or-return - this.handleContentP.then( - (res) => { - res.integrity && this.emit('integrity', res.integrity) - // eslint-disable-next-line promise/always-return - res.size !== null && this.emit('size', res.size) - cb() - }, - (er) => cb(er) - ) - }) - } -} - -function writeStream (cache, opts = {}) { - return new CacacheWriteStream(cache, opts) -} - -async function handleContent (inputStream, cache, opts) { - const tmp = await makeTmp(cache, opts) - try { - const res = await pipeToTmp(inputStream, cache, tmp.target, opts) - await moveToDestination( - tmp, - cache, - res.integrity, - opts - ) - return res - } finally { - if (!tmp.moved) { - await fs.rm(tmp.target, { recursive: true, force: true }) - } - } -} - -async function pipeToTmp (inputStream, cache, tmpTarget, opts) { - const outStream = new fsm.WriteStream(tmpTarget, { - flags: 'wx', - }) - - if (opts.integrityEmitter) { - // we need to create these all simultaneously since they can fire in any order - const [integrity, size] = await Promise.all([ - events.once(opts.integrityEmitter, 'integrity').then(res => res[0]), - events.once(opts.integrityEmitter, 'size').then(res => res[0]), - new Pipeline(inputStream, outStream).promise(), - ]) - return { integrity, size } - } - - let integrity - let size - const hashStream = ssri.integrityStream({ - integrity: opts.integrity, - algorithms: opts.algorithms, - size: opts.size, - }) - hashStream.on('integrity', i => { - integrity = i - }) - hashStream.on('size', s => { - size = s - }) - - const pipeline = new Pipeline(inputStream, hashStream, outStream) - await pipeline.promise() - return { integrity, size } -} - -async function makeTmp (cache, opts) { - const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) - await fs.mkdir(path.dirname(tmpTarget), { recursive: true }) - return { - target: tmpTarget, - moved: false, - } -} - -async function moveToDestination (tmp, cache, sri) { - const destination = contentPath(cache, sri) - const destDir = path.dirname(destination) - if (moveOperations.has(destination)) { - return moveOperations.get(destination) - } - moveOperations.set( - destination, - fs.mkdir(destDir, { recursive: true }) - .then(async () => { - await moveFile(tmp.target, destination, { overwrite: false }) - tmp.moved = true - return tmp.moved - }) - .catch(err => { - if (!err.message.startsWith('The destination file exists')) { - throw Object.assign(err, { code: 'EEXIST' }) - } - }).finally(() => { - moveOperations.delete(destination) - }) - - ) - return moveOperations.get(destination) -} - -function sizeError (expected, found) { - /* eslint-disable-next-line max-len */ - const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) - err.expected = expected - err.found = found - err.code = 'EBADSIZE' - return err -} - -function checksumError (expected, found) { - const err = new Error(`Integrity check failed: - Wanted: ${expected} - Found: ${found}`) - err.code = 'EINTEGRITY' - err.expected = expected - err.found = found - return err -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/entry-index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/entry-index.js deleted file mode 100644 index 89c28f2f257d4..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/entry-index.js +++ /dev/null @@ -1,336 +0,0 @@ -'use strict' - -const crypto = require('crypto') -const { - appendFile, - mkdir, - readFile, - readdir, - rm, - writeFile, -} = require('fs/promises') -const { Minipass } = require('minipass') -const path = require('path') -const ssri = require('ssri') -const uniqueFilename = require('unique-filename') - -const contentPath = require('./content/path') -const hashToSegments = require('./util/hash-to-segments') -const indexV = require('../package.json')['cache-version'].index -const { moveFile } = require('@npmcli/fs') - -const pMap = require('p-map') -const lsStreamConcurrency = 5 - -module.exports.NotFoundError = class NotFoundError extends Error { - constructor (cache, key) { - super(`No cache entry for ${key} found in ${cache}`) - this.code = 'ENOENT' - this.cache = cache - this.key = key - } -} - -module.exports.compact = compact - -async function compact (cache, key, matchFn, opts = {}) { - const bucket = bucketPath(cache, key) - const entries = await bucketEntries(bucket) - const newEntries = [] - // we loop backwards because the bottom-most result is the newest - // since we add new entries with appendFile - for (let i = entries.length - 1; i >= 0; --i) { - const entry = entries[i] - // a null integrity could mean either a delete was appended - // or the user has simply stored an index that does not map - // to any content. we determine if the user wants to keep the - // null integrity based on the validateEntry function passed in options. - // if the integrity is null and no validateEntry is provided, we break - // as we consider the null integrity to be a deletion of everything - // that came before it. - if (entry.integrity === null && !opts.validateEntry) { - break - } - - // if this entry is valid, and it is either the first entry or - // the newEntries array doesn't already include an entry that - // matches this one based on the provided matchFn, then we add - // it to the beginning of our list - if ((!opts.validateEntry || opts.validateEntry(entry) === true) && - (newEntries.length === 0 || - !newEntries.find((oldEntry) => matchFn(oldEntry, entry)))) { - newEntries.unshift(entry) - } - } - - const newIndex = '\n' + newEntries.map((entry) => { - const stringified = JSON.stringify(entry) - const hash = hashEntry(stringified) - return `${hash}\t${stringified}` - }).join('\n') - - const setup = async () => { - const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) - await mkdir(path.dirname(target), { recursive: true }) - return { - target, - moved: false, - } - } - - const teardown = async (tmp) => { - if (!tmp.moved) { - return rm(tmp.target, { recursive: true, force: true }) - } - } - - const write = async (tmp) => { - await writeFile(tmp.target, newIndex, { flag: 'wx' }) - await mkdir(path.dirname(bucket), { recursive: true }) - // we use @npmcli/move-file directly here because we - // want to overwrite the existing file - await moveFile(tmp.target, bucket) - tmp.moved = true - } - - // write the file atomically - const tmp = await setup() - try { - await write(tmp) - } finally { - await teardown(tmp) - } - - // we reverse the list we generated such that the newest - // entries come first in order to make looping through them easier - // the true passed to formatEntry tells it to keep null - // integrity values, if they made it this far it's because - // validateEntry returned true, and as such we should return it - return newEntries.reverse().map((entry) => formatEntry(cache, entry, true)) -} - -module.exports.insert = insert - -async function insert (cache, key, integrity, opts = {}) { - const { metadata, size, time } = opts - const bucket = bucketPath(cache, key) - const entry = { - key, - integrity: integrity && ssri.stringify(integrity), - time: time || Date.now(), - size, - metadata, - } - try { - await mkdir(path.dirname(bucket), { recursive: true }) - const stringified = JSON.stringify(entry) - // NOTE - Cleverness ahoy! - // - // This works because it's tremendously unlikely for an entry to corrupt - // another while still preserving the string length of the JSON in - // question. So, we just slap the length in there and verify it on read. - // - // Thanks to @isaacs for the whiteboarding session that ended up with - // this. - await appendFile(bucket, `\n${hashEntry(stringified)}\t${stringified}`) - } catch (err) { - if (err.code === 'ENOENT') { - return undefined - } - - throw err - } - return formatEntry(cache, entry) -} - -module.exports.find = find - -async function find (cache, key) { - const bucket = bucketPath(cache, key) - try { - const entries = await bucketEntries(bucket) - return entries.reduce((latest, next) => { - if (next && next.key === key) { - return formatEntry(cache, next) - } else { - return latest - } - }, null) - } catch (err) { - if (err.code === 'ENOENT') { - return null - } else { - throw err - } - } -} - -module.exports.delete = del - -function del (cache, key, opts = {}) { - if (!opts.removeFully) { - return insert(cache, key, null, opts) - } - - const bucket = bucketPath(cache, key) - return rm(bucket, { recursive: true, force: true }) -} - -module.exports.lsStream = lsStream - -function lsStream (cache) { - const indexDir = bucketDir(cache) - const stream = new Minipass({ objectMode: true }) - - // Set all this up to run on the stream and then just return the stream - Promise.resolve().then(async () => { - const buckets = await readdirOrEmpty(indexDir) - await pMap(buckets, async (bucket) => { - const bucketPath = path.join(indexDir, bucket) - const subbuckets = await readdirOrEmpty(bucketPath) - await pMap(subbuckets, async (subbucket) => { - const subbucketPath = path.join(bucketPath, subbucket) - - // "/cachename//./*" - const subbucketEntries = await readdirOrEmpty(subbucketPath) - await pMap(subbucketEntries, async (entry) => { - const entryPath = path.join(subbucketPath, entry) - try { - const entries = await bucketEntries(entryPath) - // using a Map here prevents duplicate keys from showing up - // twice, I guess? - const reduced = entries.reduce((acc, entry) => { - acc.set(entry.key, entry) - return acc - }, new Map()) - // reduced is a map of key => entry - for (const entry of reduced.values()) { - const formatted = formatEntry(cache, entry) - if (formatted) { - stream.write(formatted) - } - } - } catch (err) { - if (err.code === 'ENOENT') { - return undefined - } - throw err - } - }, - { concurrency: lsStreamConcurrency }) - }, - { concurrency: lsStreamConcurrency }) - }, - { concurrency: lsStreamConcurrency }) - stream.end() - return stream - }).catch(err => stream.emit('error', err)) - - return stream -} - -module.exports.ls = ls - -async function ls (cache) { - const entries = await lsStream(cache).collect() - return entries.reduce((acc, xs) => { - acc[xs.key] = xs - return acc - }, {}) -} - -module.exports.bucketEntries = bucketEntries - -async function bucketEntries (bucket, filter) { - const data = await readFile(bucket, 'utf8') - return _bucketEntries(data, filter) -} - -function _bucketEntries (data) { - const entries = [] - data.split('\n').forEach((entry) => { - if (!entry) { - return - } - - const pieces = entry.split('\t') - if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) { - // Hash is no good! Corruption or malice? Doesn't matter! - // EJECT EJECT - return - } - let obj - try { - obj = JSON.parse(pieces[1]) - } catch (_) { - // eslint-ignore-next-line no-empty-block - } - // coverage disabled here, no need to test with an entry that parses to something falsey - // istanbul ignore else - if (obj) { - entries.push(obj) - } - }) - return entries -} - -module.exports.bucketDir = bucketDir - -function bucketDir (cache) { - return path.join(cache, `index-v${indexV}`) -} - -module.exports.bucketPath = bucketPath - -function bucketPath (cache, key) { - const hashed = hashKey(key) - return path.join.apply( - path, - [bucketDir(cache)].concat(hashToSegments(hashed)) - ) -} - -module.exports.hashKey = hashKey - -function hashKey (key) { - return hash(key, 'sha256') -} - -module.exports.hashEntry = hashEntry - -function hashEntry (str) { - return hash(str, 'sha1') -} - -function hash (str, digest) { - return crypto - .createHash(digest) - .update(str) - .digest('hex') -} - -function formatEntry (cache, entry, keepAll) { - // Treat null digests as deletions. They'll shadow any previous entries. - if (!entry.integrity && !keepAll) { - return null - } - - return { - key: entry.key, - integrity: entry.integrity, - path: entry.integrity ? contentPath(cache, entry.integrity) : undefined, - size: entry.size, - time: entry.time, - metadata: entry.metadata, - } -} - -function readdirOrEmpty (dir) { - return readdir(dir).catch((err) => { - if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { - return [] - } - - throw err - }) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/get.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/get.js deleted file mode 100644 index 80ec206c7ecaa..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/get.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict' - -const Collect = require('minipass-collect') -const { Minipass } = require('minipass') -const Pipeline = require('minipass-pipeline') - -const index = require('./entry-index') -const memo = require('./memoization') -const read = require('./content/read') - -async function getData (cache, key, opts = {}) { - const { integrity, memoize, size } = opts - const memoized = memo.get(cache, key, opts) - if (memoized && memoize !== false) { - return { - metadata: memoized.entry.metadata, - data: memoized.data, - integrity: memoized.entry.integrity, - size: memoized.entry.size, - } - } - - const entry = await index.find(cache, key, opts) - if (!entry) { - throw new index.NotFoundError(cache, key) - } - const data = await read(cache, entry.integrity, { integrity, size }) - if (memoize) { - memo.put(cache, entry, data, opts) - } - - return { - data, - metadata: entry.metadata, - size: entry.size, - integrity: entry.integrity, - } -} -module.exports = getData - -async function getDataByDigest (cache, key, opts = {}) { - const { integrity, memoize, size } = opts - const memoized = memo.get.byDigest(cache, key, opts) - if (memoized && memoize !== false) { - return memoized - } - - const res = await read(cache, key, { integrity, size }) - if (memoize) { - memo.put.byDigest(cache, key, res, opts) - } - return res -} -module.exports.byDigest = getDataByDigest - -const getMemoizedStream = (memoized) => { - const stream = new Minipass() - stream.on('newListener', function (ev, cb) { - ev === 'metadata' && cb(memoized.entry.metadata) - ev === 'integrity' && cb(memoized.entry.integrity) - ev === 'size' && cb(memoized.entry.size) - }) - stream.end(memoized.data) - return stream -} - -function getStream (cache, key, opts = {}) { - const { memoize, size } = opts - const memoized = memo.get(cache, key, opts) - if (memoized && memoize !== false) { - return getMemoizedStream(memoized) - } - - const stream = new Pipeline() - // Set all this up to run on the stream and then just return the stream - Promise.resolve().then(async () => { - const entry = await index.find(cache, key) - if (!entry) { - throw new index.NotFoundError(cache, key) - } - - stream.emit('metadata', entry.metadata) - stream.emit('integrity', entry.integrity) - stream.emit('size', entry.size) - stream.on('newListener', function (ev, cb) { - ev === 'metadata' && cb(entry.metadata) - ev === 'integrity' && cb(entry.integrity) - ev === 'size' && cb(entry.size) - }) - - const src = read.readStream( - cache, - entry.integrity, - { ...opts, size: typeof size !== 'number' ? entry.size : size } - ) - - if (memoize) { - const memoStream = new Collect.PassThrough() - memoStream.on('collect', data => memo.put(cache, entry, data, opts)) - stream.unshift(memoStream) - } - stream.unshift(src) - return stream - }).catch((err) => stream.emit('error', err)) - - return stream -} - -module.exports.stream = getStream - -function getStreamDigest (cache, integrity, opts = {}) { - const { memoize } = opts - const memoized = memo.get.byDigest(cache, integrity, opts) - if (memoized && memoize !== false) { - const stream = new Minipass() - stream.end(memoized) - return stream - } else { - const stream = read.readStream(cache, integrity, opts) - if (!memoize) { - return stream - } - - const memoStream = new Collect.PassThrough() - memoStream.on('collect', data => memo.put.byDigest( - cache, - integrity, - data, - opts - )) - return new Pipeline(stream, memoStream) - } -} - -module.exports.stream.byDigest = getStreamDigest - -function info (cache, key, opts = {}) { - const { memoize } = opts - const memoized = memo.get(cache, key, opts) - if (memoized && memoize !== false) { - return Promise.resolve(memoized.entry) - } else { - return index.find(cache, key) - } -} -module.exports.info = info - -async function copy (cache, key, dest, opts = {}) { - const entry = await index.find(cache, key, opts) - if (!entry) { - throw new index.NotFoundError(cache, key) - } - await read.copy(cache, entry.integrity, dest, opts) - return { - metadata: entry.metadata, - size: entry.size, - integrity: entry.integrity, - } -} - -module.exports.copy = copy - -async function copyByDigest (cache, key, dest, opts = {}) { - await read.copy(cache, key, dest, opts) - return key -} - -module.exports.copy.byDigest = copyByDigest - -module.exports.hasContent = read.hasContent diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/index.js deleted file mode 100644 index c9b0da5f3a271..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/index.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict' - -const get = require('./get.js') -const put = require('./put.js') -const rm = require('./rm.js') -const verify = require('./verify.js') -const { clearMemoized } = require('./memoization.js') -const tmp = require('./util/tmp.js') -const index = require('./entry-index.js') - -module.exports.index = {} -module.exports.index.compact = index.compact -module.exports.index.insert = index.insert - -module.exports.ls = index.ls -module.exports.ls.stream = index.lsStream - -module.exports.get = get -module.exports.get.byDigest = get.byDigest -module.exports.get.stream = get.stream -module.exports.get.stream.byDigest = get.stream.byDigest -module.exports.get.copy = get.copy -module.exports.get.copy.byDigest = get.copy.byDigest -module.exports.get.info = get.info -module.exports.get.hasContent = get.hasContent - -module.exports.put = put -module.exports.put.stream = put.stream - -module.exports.rm = rm.entry -module.exports.rm.all = rm.all -module.exports.rm.entry = module.exports.rm -module.exports.rm.content = rm.content - -module.exports.clearMemoized = clearMemoized - -module.exports.tmp = {} -module.exports.tmp.mkdir = tmp.mkdir -module.exports.tmp.withTmp = tmp.withTmp - -module.exports.verify = verify -module.exports.verify.lastRun = verify.lastRun diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/memoization.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/memoization.js deleted file mode 100644 index 2ecc60912e456..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/memoization.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict' - -const { LRUCache } = require('lru-cache') - -const MEMOIZED = new LRUCache({ - max: 500, - maxSize: 50 * 1024 * 1024, // 50MB - ttl: 3 * 60 * 1000, // 3 minutes - sizeCalculation: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length, -}) - -module.exports.clearMemoized = clearMemoized - -function clearMemoized () { - const old = {} - MEMOIZED.forEach((v, k) => { - old[k] = v - }) - MEMOIZED.clear() - return old -} - -module.exports.put = put - -function put (cache, entry, data, opts) { - pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data }) - putDigest(cache, entry.integrity, data, opts) -} - -module.exports.put.byDigest = putDigest - -function putDigest (cache, integrity, data, opts) { - pickMem(opts).set(`digest:${cache}:${integrity}`, data) -} - -module.exports.get = get - -function get (cache, key, opts) { - return pickMem(opts).get(`key:${cache}:${key}`) -} - -module.exports.get.byDigest = getDigest - -function getDigest (cache, integrity, opts) { - return pickMem(opts).get(`digest:${cache}:${integrity}`) -} - -class ObjProxy { - constructor (obj) { - this.obj = obj - } - - get (key) { - return this.obj[key] - } - - set (key, val) { - this.obj[key] = val - } -} - -function pickMem (opts) { - if (!opts || !opts.memoize) { - return MEMOIZED - } else if (opts.memoize.get && opts.memoize.set) { - return opts.memoize - } else if (typeof opts.memoize === 'object') { - return new ObjProxy(opts.memoize) - } else { - return MEMOIZED - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/put.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/put.js deleted file mode 100644 index 9fc932d5f6dec..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/put.js +++ /dev/null @@ -1,80 +0,0 @@ -'use strict' - -const index = require('./entry-index') -const memo = require('./memoization') -const write = require('./content/write') -const Flush = require('minipass-flush') -const { PassThrough } = require('minipass-collect') -const Pipeline = require('minipass-pipeline') - -const putOpts = (opts) => ({ - algorithms: ['sha512'], - ...opts, -}) - -module.exports = putData - -async function putData (cache, key, data, opts = {}) { - const { memoize } = opts - opts = putOpts(opts) - const res = await write(cache, data, opts) - const entry = await index.insert(cache, key, res.integrity, { ...opts, size: res.size }) - if (memoize) { - memo.put(cache, entry, data, opts) - } - - return res.integrity -} - -module.exports.stream = putStream - -function putStream (cache, key, opts = {}) { - const { memoize } = opts - opts = putOpts(opts) - let integrity - let size - let error - - let memoData - const pipeline = new Pipeline() - // first item in the pipeline is the memoizer, because we need - // that to end first and get the collected data. - if (memoize) { - const memoizer = new PassThrough().on('collect', data => { - memoData = data - }) - pipeline.push(memoizer) - } - - // contentStream is a write-only, not a passthrough - // no data comes out of it. - const contentStream = write.stream(cache, opts) - .on('integrity', (int) => { - integrity = int - }) - .on('size', (s) => { - size = s - }) - .on('error', (err) => { - error = err - }) - - pipeline.push(contentStream) - - // last but not least, we write the index and emit hash and size, - // and memoize if we're doing that - pipeline.push(new Flush({ - async flush () { - if (!error) { - const entry = await index.insert(cache, key, integrity, { ...opts, size }) - if (memoize && memoData) { - memo.put(cache, entry, memoData, opts) - } - pipeline.emit('integrity', integrity) - pipeline.emit('size', size) - } - }, - })) - - return pipeline -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/rm.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/rm.js deleted file mode 100644 index a94760c7cf243..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/rm.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict' - -const { rm } = require('fs/promises') -const glob = require('./util/glob.js') -const index = require('./entry-index') -const memo = require('./memoization') -const path = require('path') -const rmContent = require('./content/rm') - -module.exports = entry -module.exports.entry = entry - -function entry (cache, key, opts) { - memo.clearMemoized() - return index.delete(cache, key, opts) -} - -module.exports.content = content - -function content (cache, integrity) { - memo.clearMemoized() - return rmContent(cache, integrity) -} - -module.exports.all = all - -async function all (cache) { - memo.clearMemoized() - const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true }) - return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true }))) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/util/glob.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/util/glob.js deleted file mode 100644 index 8500c1c16a429..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/util/glob.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict' - -const { glob } = require('glob') -const path = require('path') - -const globify = (pattern) => pattern.split(path.win32.sep).join(path.posix.sep) -module.exports = (path, options) => glob(globify(path), options) diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/util/hash-to-segments.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/util/hash-to-segments.js deleted file mode 100644 index 445599b503808..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/util/hash-to-segments.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict' - -module.exports = hashToSegments - -function hashToSegments (hash) { - return [hash.slice(0, 2), hash.slice(2, 4), hash.slice(4)] -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/util/tmp.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/util/tmp.js deleted file mode 100644 index 0bf5302136ebe..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/util/tmp.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict' - -const { withTempDir } = require('@npmcli/fs') -const fs = require('fs/promises') -const path = require('path') - -module.exports.mkdir = mktmpdir - -async function mktmpdir (cache, opts = {}) { - const { tmpPrefix } = opts - const tmpDir = path.join(cache, 'tmp') - await fs.mkdir(tmpDir, { recursive: true, owner: 'inherit' }) - // do not use path.join(), it drops the trailing / if tmpPrefix is unset - const target = `${tmpDir}${path.sep}${tmpPrefix || ''}` - return fs.mkdtemp(target, { owner: 'inherit' }) -} - -module.exports.withTmp = withTmp - -function withTmp (cache, opts, cb) { - if (!cb) { - cb = opts - opts = {} - } - return withTempDir(path.join(cache, 'tmp'), cb, opts) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/verify.js b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/verify.js deleted file mode 100644 index d7423da1295b6..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/lib/verify.js +++ /dev/null @@ -1,257 +0,0 @@ -'use strict' - -const { - mkdir, - readFile, - rm, - stat, - truncate, - writeFile, -} = require('fs/promises') -const pMap = require('p-map') -const contentPath = require('./content/path') -const fsm = require('fs-minipass') -const glob = require('./util/glob.js') -const index = require('./entry-index') -const path = require('path') -const ssri = require('ssri') - -const hasOwnProperty = (obj, key) => - Object.prototype.hasOwnProperty.call(obj, key) - -const verifyOpts = (opts) => ({ - concurrency: 20, - log: { silly () {} }, - ...opts, -}) - -module.exports = verify - -async function verify (cache, opts) { - opts = verifyOpts(opts) - opts.log.silly('verify', 'verifying cache at', cache) - - const steps = [ - markStartTime, - fixPerms, - garbageCollect, - rebuildIndex, - cleanTmp, - writeVerifile, - markEndTime, - ] - - const stats = {} - for (const step of steps) { - const label = step.name - const start = new Date() - const s = await step(cache, opts) - if (s) { - Object.keys(s).forEach((k) => { - stats[k] = s[k] - }) - } - const end = new Date() - if (!stats.runTime) { - stats.runTime = {} - } - stats.runTime[label] = end - start - } - stats.runTime.total = stats.endTime - stats.startTime - opts.log.silly( - 'verify', - 'verification finished for', - cache, - 'in', - `${stats.runTime.total}ms` - ) - return stats -} - -async function markStartTime () { - return { startTime: new Date() } -} - -async function markEndTime () { - return { endTime: new Date() } -} - -async function fixPerms (cache, opts) { - opts.log.silly('verify', 'fixing cache permissions') - await mkdir(cache, { recursive: true }) - return null -} - -// Implements a naive mark-and-sweep tracing garbage collector. -// -// The algorithm is basically as follows: -// 1. Read (and filter) all index entries ("pointers") -// 2. Mark each integrity value as "live" -// 3. Read entire filesystem tree in `content-vX/` dir -// 4. If content is live, verify its checksum and delete it if it fails -// 5. If content is not marked as live, rm it. -// -async function garbageCollect (cache, opts) { - opts.log.silly('verify', 'garbage collecting content') - const indexStream = index.lsStream(cache) - const liveContent = new Set() - indexStream.on('data', (entry) => { - if (opts.filter && !opts.filter(entry)) { - return - } - - // integrity is stringified, re-parse it so we can get each hash - const integrity = ssri.parse(entry.integrity) - for (const algo in integrity) { - liveContent.add(integrity[algo].toString()) - } - }) - await new Promise((resolve, reject) => { - indexStream.on('end', resolve).on('error', reject) - }) - const contentDir = contentPath.contentDir(cache) - const files = await glob(path.join(contentDir, '**'), { - follow: false, - nodir: true, - nosort: true, - }) - const stats = { - verifiedContent: 0, - reclaimedCount: 0, - reclaimedSize: 0, - badContentCount: 0, - keptSize: 0, - } - await pMap( - files, - async (f) => { - const split = f.split(/[/\\]/) - const digest = split.slice(split.length - 3).join('') - const algo = split[split.length - 4] - const integrity = ssri.fromHex(digest, algo) - if (liveContent.has(integrity.toString())) { - const info = await verifyContent(f, integrity) - if (!info.valid) { - stats.reclaimedCount++ - stats.badContentCount++ - stats.reclaimedSize += info.size - } else { - stats.verifiedContent++ - stats.keptSize += info.size - } - } else { - // No entries refer to this content. We can delete. - stats.reclaimedCount++ - const s = await stat(f) - await rm(f, { recursive: true, force: true }) - stats.reclaimedSize += s.size - } - return stats - }, - { concurrency: opts.concurrency } - ) - return stats -} - -async function verifyContent (filepath, sri) { - const contentInfo = {} - try { - const { size } = await stat(filepath) - contentInfo.size = size - contentInfo.valid = true - await ssri.checkStream(new fsm.ReadStream(filepath), sri) - } catch (err) { - if (err.code === 'ENOENT') { - return { size: 0, valid: false } - } - if (err.code !== 'EINTEGRITY') { - throw err - } - - await rm(filepath, { recursive: true, force: true }) - contentInfo.valid = false - } - return contentInfo -} - -async function rebuildIndex (cache, opts) { - opts.log.silly('verify', 'rebuilding index') - const entries = await index.ls(cache) - const stats = { - missingContent: 0, - rejectedEntries: 0, - totalEntries: 0, - } - const buckets = {} - for (const k in entries) { - /* istanbul ignore else */ - if (hasOwnProperty(entries, k)) { - const hashed = index.hashKey(k) - const entry = entries[k] - const excluded = opts.filter && !opts.filter(entry) - excluded && stats.rejectedEntries++ - if (buckets[hashed] && !excluded) { - buckets[hashed].push(entry) - } else if (buckets[hashed] && excluded) { - // skip - } else if (excluded) { - buckets[hashed] = [] - buckets[hashed]._path = index.bucketPath(cache, k) - } else { - buckets[hashed] = [entry] - buckets[hashed]._path = index.bucketPath(cache, k) - } - } - } - await pMap( - Object.keys(buckets), - (key) => { - return rebuildBucket(cache, buckets[key], stats, opts) - }, - { concurrency: opts.concurrency } - ) - return stats -} - -async function rebuildBucket (cache, bucket, stats) { - await truncate(bucket._path) - // This needs to be serialized because cacache explicitly - // lets very racy bucket conflicts clobber each other. - for (const entry of bucket) { - const content = contentPath(cache, entry.integrity) - try { - await stat(content) - await index.insert(cache, entry.key, entry.integrity, { - metadata: entry.metadata, - size: entry.size, - time: entry.time, - }) - stats.totalEntries++ - } catch (err) { - if (err.code === 'ENOENT') { - stats.rejectedEntries++ - stats.missingContent++ - } else { - throw err - } - } - } -} - -function cleanTmp (cache, opts) { - opts.log.silly('verify', 'cleaning tmp directory') - return rm(path.join(cache, 'tmp'), { recursive: true, force: true }) -} - -async function writeVerifile (cache, opts) { - const verifile = path.join(cache, '_lastverified') - opts.log.silly('verify', 'writing verifile to ' + verifile) - return writeFile(verifile, `${Date.now()}`) -} - -module.exports.lastRun = lastRun - -async function lastRun (cache) { - const data = await readFile(path.join(cache, '_lastverified'), { encoding: 'utf8' }) - return new Date(+data) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/package.json deleted file mode 100644 index 6e6219158ed75..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/cacache/package.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "name": "cacache", - "version": "18.0.4", - "cache-version": { - "content": "2", - "index": "5" - }, - "description": "Fast, fault-tolerant, cross-platform, disk-based, data-agnostic, content-addressable cache.", - "main": "lib/index.js", - "files": [ - "bin/", - "lib/" - ], - "scripts": { - "test": "tap", - "snap": "tap", - "coverage": "tap", - "test-docker": "docker run -it --rm --name pacotest -v \"$PWD\":/tmp -w /tmp node:latest npm test", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "npmclilint": "npmcli-lint", - "lintfix": "npm run lint -- --fix", - "postsnap": "npm run lintfix --", - "postlint": "template-oss-check", - "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/cacache.git" - }, - "keywords": [ - "cache", - "caching", - "content-addressable", - "sri", - "sri hash", - "subresource integrity", - "cache", - "storage", - "store", - "file store", - "filesystem", - "disk cache", - "disk storage" - ], - "license": "ISC", - "dependencies": { - "@npmcli/fs": "^3.1.0", - "fs-minipass": "^3.0.0", - "glob": "^10.2.2", - "lru-cache": "^10.0.1", - "minipass": "^7.0.3", - "minipass-collect": "^2.0.1", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "p-map": "^4.0.0", - "ssri": "^10.0.0", - "tar": "^6.1.11", - "unique-filename": "^3.0.0" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "windowsCI": false, - "version": "4.22.0", - "publish": "true" - }, - "author": "GitHub Inc.", - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/LICENSE deleted file mode 100644 index 45055763dc838..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2015, Rebecca Turner - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/from-url.js b/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/from-url.js deleted file mode 100644 index efc1247d59d12..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/from-url.js +++ /dev/null @@ -1,122 +0,0 @@ -'use strict' - -const parseUrl = require('./parse-url') - -// look for github shorthand inputs, such as npm/cli -const isGitHubShorthand = (arg) => { - // it cannot contain whitespace before the first # - // it cannot start with a / because that's probably an absolute file path - // but it must include a slash since repos are username/repository - // it cannot start with a . because that's probably a relative file path - // it cannot start with an @ because that's a scoped package if it passes the other tests - // it cannot contain a : before a # because that tells us that there's a protocol - // a second / may not exist before a # - const firstHash = arg.indexOf('#') - const firstSlash = arg.indexOf('/') - const secondSlash = arg.indexOf('/', firstSlash + 1) - const firstColon = arg.indexOf(':') - const firstSpace = /\s/.exec(arg) - const firstAt = arg.indexOf('@') - - const spaceOnlyAfterHash = !firstSpace || (firstHash > -1 && firstSpace.index > firstHash) - const atOnlyAfterHash = firstAt === -1 || (firstHash > -1 && firstAt > firstHash) - const colonOnlyAfterHash = firstColon === -1 || (firstHash > -1 && firstColon > firstHash) - const secondSlashOnlyAfterHash = secondSlash === -1 || (firstHash > -1 && secondSlash > firstHash) - const hasSlash = firstSlash > 0 - // if a # is found, what we really want to know is that the character - // immediately before # is not a / - const doesNotEndWithSlash = firstHash > -1 ? arg[firstHash - 1] !== '/' : !arg.endsWith('/') - const doesNotStartWithDot = !arg.startsWith('.') - - return spaceOnlyAfterHash && hasSlash && doesNotEndWithSlash && - doesNotStartWithDot && atOnlyAfterHash && colonOnlyAfterHash && - secondSlashOnlyAfterHash -} - -module.exports = (giturl, opts, { gitHosts, protocols }) => { - if (!giturl) { - return - } - - const correctedUrl = isGitHubShorthand(giturl) ? `github:${giturl}` : giturl - const parsed = parseUrl(correctedUrl, protocols) - if (!parsed) { - return - } - - const gitHostShortcut = gitHosts.byShortcut[parsed.protocol] - const gitHostDomain = gitHosts.byDomain[parsed.hostname.startsWith('www.') - ? parsed.hostname.slice(4) - : parsed.hostname] - const gitHostName = gitHostShortcut || gitHostDomain - if (!gitHostName) { - return - } - - const gitHostInfo = gitHosts[gitHostShortcut || gitHostDomain] - let auth = null - if (protocols[parsed.protocol]?.auth && (parsed.username || parsed.password)) { - auth = `${parsed.username}${parsed.password ? ':' + parsed.password : ''}` - } - - let committish = null - let user = null - let project = null - let defaultRepresentation = null - - try { - if (gitHostShortcut) { - let pathname = parsed.pathname.startsWith('/') ? parsed.pathname.slice(1) : parsed.pathname - const firstAt = pathname.indexOf('@') - // we ignore auth for shortcuts, so just trim it out - if (firstAt > -1) { - pathname = pathname.slice(firstAt + 1) - } - - const lastSlash = pathname.lastIndexOf('/') - if (lastSlash > -1) { - user = decodeURIComponent(pathname.slice(0, lastSlash)) - // we want nulls only, never empty strings - if (!user) { - user = null - } - project = decodeURIComponent(pathname.slice(lastSlash + 1)) - } else { - project = decodeURIComponent(pathname) - } - - if (project.endsWith('.git')) { - project = project.slice(0, -4) - } - - if (parsed.hash) { - committish = decodeURIComponent(parsed.hash.slice(1)) - } - - defaultRepresentation = 'shortcut' - } else { - if (!gitHostInfo.protocols.includes(parsed.protocol)) { - return - } - - const segments = gitHostInfo.extract(parsed) - if (!segments) { - return - } - - user = segments.user && decodeURIComponent(segments.user) - project = decodeURIComponent(segments.project) - committish = decodeURIComponent(segments.committish) - defaultRepresentation = protocols[parsed.protocol]?.name || parsed.protocol.slice(0, -1) - } - } catch (err) { - /* istanbul ignore else */ - if (err instanceof URIError) { - return - } else { - throw err - } - } - - return [gitHostName, user, auth, project, committish, defaultRepresentation, opts] -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/hosts.js b/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/hosts.js deleted file mode 100644 index 9a08efd1b2d7e..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/hosts.js +++ /dev/null @@ -1,227 +0,0 @@ -/* eslint-disable max-len */ - -'use strict' - -const maybeJoin = (...args) => args.every(arg => arg) ? args.join('') : '' -const maybeEncode = (arg) => arg ? encodeURIComponent(arg) : '' -const formatHashFragment = (f) => f.toLowerCase().replace(/^\W+|\/|\W+$/g, '').replace(/\W+/g, '-') - -const defaults = { - sshtemplate: ({ domain, user, project, committish }) => - `git@${domain}:${user}/${project}.git${maybeJoin('#', committish)}`, - sshurltemplate: ({ domain, user, project, committish }) => - `git+ssh://git@${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, - edittemplate: ({ domain, user, project, committish, editpath, path }) => - `https://${domain}/${user}/${project}${maybeJoin('/', editpath, '/', maybeEncode(committish || 'HEAD'), '/', path)}`, - browsetemplate: ({ domain, user, project, committish, treepath }) => - `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}`, - browsetreetemplate: ({ domain, user, project, committish, treepath, path, fragment, hashformat }) => - `https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish || 'HEAD')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`, - browseblobtemplate: ({ domain, user, project, committish, blobpath, path, fragment, hashformat }) => - `https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish || 'HEAD')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`, - docstemplate: ({ domain, user, project, treepath, committish }) => - `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}#readme`, - httpstemplate: ({ auth, domain, user, project, committish }) => - `git+https://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, - filetemplate: ({ domain, user, project, committish, path }) => - `https://${domain}/${user}/${project}/raw/${maybeEncode(committish || 'HEAD')}/${path}`, - shortcuttemplate: ({ type, user, project, committish }) => - `${type}:${user}/${project}${maybeJoin('#', committish)}`, - pathtemplate: ({ user, project, committish }) => - `${user}/${project}${maybeJoin('#', committish)}`, - bugstemplate: ({ domain, user, project }) => - `https://${domain}/${user}/${project}/issues`, - hashformat: formatHashFragment, -} - -const hosts = {} -hosts.github = { - // First two are insecure and generally shouldn't be used any more, but - // they are still supported. - protocols: ['git:', 'http:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'], - domain: 'github.com', - treepath: 'tree', - blobpath: 'blob', - editpath: 'edit', - filetemplate: ({ auth, user, project, committish, path }) => - `https://${maybeJoin(auth, '@')}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish || 'HEAD')}/${path}`, - gittemplate: ({ auth, domain, user, project, committish }) => - `git://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, - tarballtemplate: ({ domain, user, project, committish }) => - `https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish || 'HEAD')}`, - extract: (url) => { - let [, user, project, type, committish] = url.pathname.split('/', 5) - if (type && type !== 'tree') { - return - } - - if (!type) { - committish = url.hash.slice(1) - } - - if (project && project.endsWith('.git')) { - project = project.slice(0, -4) - } - - if (!user || !project) { - return - } - - return { user, project, committish } - }, -} - -hosts.bitbucket = { - protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'], - domain: 'bitbucket.org', - treepath: 'src', - blobpath: 'src', - editpath: '?mode=edit', - edittemplate: ({ domain, user, project, committish, treepath, path, editpath }) => - `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish || 'HEAD'), '/', path, editpath)}`, - tarballtemplate: ({ domain, user, project, committish }) => - `https://${domain}/${user}/${project}/get/${maybeEncode(committish || 'HEAD')}.tar.gz`, - extract: (url) => { - let [, user, project, aux] = url.pathname.split('/', 4) - if (['get'].includes(aux)) { - return - } - - if (project && project.endsWith('.git')) { - project = project.slice(0, -4) - } - - if (!user || !project) { - return - } - - return { user, project, committish: url.hash.slice(1) } - }, -} - -hosts.gitlab = { - protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'], - domain: 'gitlab.com', - treepath: 'tree', - blobpath: 'tree', - editpath: '-/edit', - httpstemplate: ({ auth, domain, user, project, committish }) => - `git+https://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, - tarballtemplate: ({ domain, user, project, committish }) => - `https://${domain}/${user}/${project}/repository/archive.tar.gz?ref=${maybeEncode(committish || 'HEAD')}`, - extract: (url) => { - const path = url.pathname.slice(1) - if (path.includes('/-/') || path.includes('/archive.tar.gz')) { - return - } - - const segments = path.split('/') - let project = segments.pop() - if (project.endsWith('.git')) { - project = project.slice(0, -4) - } - - const user = segments.join('/') - if (!user || !project) { - return - } - - return { user, project, committish: url.hash.slice(1) } - }, -} - -hosts.gist = { - protocols: ['git:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'], - domain: 'gist.github.com', - editpath: 'edit', - sshtemplate: ({ domain, project, committish }) => - `git@${domain}:${project}.git${maybeJoin('#', committish)}`, - sshurltemplate: ({ domain, project, committish }) => - `git+ssh://git@${domain}/${project}.git${maybeJoin('#', committish)}`, - edittemplate: ({ domain, user, project, committish, editpath }) => - `https://${domain}/${user}/${project}${maybeJoin('/', maybeEncode(committish))}/${editpath}`, - browsetemplate: ({ domain, project, committish }) => - `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`, - browsetreetemplate: ({ domain, project, committish, path, hashformat }) => - `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}${maybeJoin('#', hashformat(path))}`, - browseblobtemplate: ({ domain, project, committish, path, hashformat }) => - `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}${maybeJoin('#', hashformat(path))}`, - docstemplate: ({ domain, project, committish }) => - `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`, - httpstemplate: ({ domain, project, committish }) => - `git+https://${domain}/${project}.git${maybeJoin('#', committish)}`, - filetemplate: ({ user, project, committish, path }) => - `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin('/', maybeEncode(committish))}/${path}`, - shortcuttemplate: ({ type, project, committish }) => - `${type}:${project}${maybeJoin('#', committish)}`, - pathtemplate: ({ project, committish }) => - `${project}${maybeJoin('#', committish)}`, - bugstemplate: ({ domain, project }) => - `https://${domain}/${project}`, - gittemplate: ({ domain, project, committish }) => - `git://${domain}/${project}.git${maybeJoin('#', committish)}`, - tarballtemplate: ({ project, committish }) => - `https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish || 'HEAD')}`, - extract: (url) => { - let [, user, project, aux] = url.pathname.split('/', 4) - if (aux === 'raw') { - return - } - - if (!project) { - if (!user) { - return - } - - project = user - user = null - } - - if (project.endsWith('.git')) { - project = project.slice(0, -4) - } - - return { user, project, committish: url.hash.slice(1) } - }, - hashformat: function (fragment) { - return fragment && 'file-' + formatHashFragment(fragment) - }, -} - -hosts.sourcehut = { - protocols: ['git+ssh:', 'https:'], - domain: 'git.sr.ht', - treepath: 'tree', - blobpath: 'tree', - filetemplate: ({ domain, user, project, committish, path }) => - `https://${domain}/${user}/${project}/blob/${maybeEncode(committish) || 'HEAD'}/${path}`, - httpstemplate: ({ domain, user, project, committish }) => - `https://${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, - tarballtemplate: ({ domain, user, project, committish }) => - `https://${domain}/${user}/${project}/archive/${maybeEncode(committish) || 'HEAD'}.tar.gz`, - bugstemplate: () => null, - extract: (url) => { - let [, user, project, aux] = url.pathname.split('/', 4) - - // tarball url - if (['archive'].includes(aux)) { - return - } - - if (project && project.endsWith('.git')) { - project = project.slice(0, -4) - } - - if (!user || !project) { - return - } - - return { user, project, committish: url.hash.slice(1) } - }, -} - -for (const [name, host] of Object.entries(hosts)) { - hosts[name] = Object.assign({}, defaults, host) -} - -module.exports = hosts diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/index.js deleted file mode 100644 index 0c9d0b08c866b..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/index.js +++ /dev/null @@ -1,179 +0,0 @@ -'use strict' - -const { LRUCache } = require('lru-cache') -const hosts = require('./hosts.js') -const fromUrl = require('./from-url.js') -const parseUrl = require('./parse-url.js') - -const cache = new LRUCache({ max: 1000 }) - -class GitHost { - constructor (type, user, auth, project, committish, defaultRepresentation, opts = {}) { - Object.assign(this, GitHost.#gitHosts[type], { - type, - user, - auth, - project, - committish, - default: defaultRepresentation, - opts, - }) - } - - static #gitHosts = { byShortcut: {}, byDomain: {} } - static #protocols = { - 'git+ssh:': { name: 'sshurl' }, - 'ssh:': { name: 'sshurl' }, - 'git+https:': { name: 'https', auth: true }, - 'git:': { auth: true }, - 'http:': { auth: true }, - 'https:': { auth: true }, - 'git+http:': { auth: true }, - } - - static addHost (name, host) { - GitHost.#gitHosts[name] = host - GitHost.#gitHosts.byDomain[host.domain] = name - GitHost.#gitHosts.byShortcut[`${name}:`] = name - GitHost.#protocols[`${name}:`] = { name } - } - - static fromUrl (giturl, opts) { - if (typeof giturl !== 'string') { - return - } - - const key = giturl + JSON.stringify(opts || {}) - - if (!cache.has(key)) { - const hostArgs = fromUrl(giturl, opts, { - gitHosts: GitHost.#gitHosts, - protocols: GitHost.#protocols, - }) - cache.set(key, hostArgs ? new GitHost(...hostArgs) : undefined) - } - - return cache.get(key) - } - - static parseUrl (url) { - return parseUrl(url) - } - - #fill (template, opts) { - if (typeof template !== 'function') { - return null - } - - const options = { ...this, ...this.opts, ...opts } - - // the path should always be set so we don't end up with 'undefined' in urls - if (!options.path) { - options.path = '' - } - - // template functions will insert the leading slash themselves - if (options.path.startsWith('/')) { - options.path = options.path.slice(1) - } - - if (options.noCommittish) { - options.committish = null - } - - const result = template(options) - return options.noGitPlus && result.startsWith('git+') ? result.slice(4) : result - } - - hash () { - return this.committish ? `#${this.committish}` : '' - } - - ssh (opts) { - return this.#fill(this.sshtemplate, opts) - } - - sshurl (opts) { - return this.#fill(this.sshurltemplate, opts) - } - - browse (path, ...args) { - // not a string, treat path as opts - if (typeof path !== 'string') { - return this.#fill(this.browsetemplate, path) - } - - if (typeof args[0] !== 'string') { - return this.#fill(this.browsetreetemplate, { ...args[0], path }) - } - - return this.#fill(this.browsetreetemplate, { ...args[1], fragment: args[0], path }) - } - - // If the path is known to be a file, then browseFile should be used. For some hosts - // the url is the same as browse, but for others like GitHub a file can use both `/tree/` - // and `/blob/` in the path. When using a default committish of `HEAD` then the `/tree/` - // path will redirect to a specific commit. Using the `/blob/` path avoids this and - // does not redirect to a different commit. - browseFile (path, ...args) { - if (typeof args[0] !== 'string') { - return this.#fill(this.browseblobtemplate, { ...args[0], path }) - } - - return this.#fill(this.browseblobtemplate, { ...args[1], fragment: args[0], path }) - } - - docs (opts) { - return this.#fill(this.docstemplate, opts) - } - - bugs (opts) { - return this.#fill(this.bugstemplate, opts) - } - - https (opts) { - return this.#fill(this.httpstemplate, opts) - } - - git (opts) { - return this.#fill(this.gittemplate, opts) - } - - shortcut (opts) { - return this.#fill(this.shortcuttemplate, opts) - } - - path (opts) { - return this.#fill(this.pathtemplate, opts) - } - - tarball (opts) { - return this.#fill(this.tarballtemplate, { ...opts, noCommittish: false }) - } - - file (path, opts) { - return this.#fill(this.filetemplate, { ...opts, path }) - } - - edit (path, opts) { - return this.#fill(this.edittemplate, { ...opts, path }) - } - - getDefaultRepresentation () { - return this.default - } - - toString (opts) { - if (this.default && typeof this[this.default] === 'function') { - return this[this.default](opts) - } - - return this.sshurl(opts) - } -} - -for (const [name, host] of Object.entries(hosts)) { - GitHost.addHost(name, host) -} - -module.exports = GitHost diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/parse-url.js b/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/parse-url.js deleted file mode 100644 index 7d5489c008ab4..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/lib/parse-url.js +++ /dev/null @@ -1,78 +0,0 @@ -const url = require('url') - -const lastIndexOfBefore = (str, char, beforeChar) => { - const startPosition = str.indexOf(beforeChar) - return str.lastIndexOf(char, startPosition > -1 ? startPosition : Infinity) -} - -const safeUrl = (u) => { - try { - return new url.URL(u) - } catch { - // this fn should never throw - } -} - -// accepts input like git:github.com:user/repo and inserts the // after the first : -const correctProtocol = (arg, protocols) => { - const firstColon = arg.indexOf(':') - const proto = arg.slice(0, firstColon + 1) - if (Object.prototype.hasOwnProperty.call(protocols, proto)) { - return arg - } - - const firstAt = arg.indexOf('@') - if (firstAt > -1) { - if (firstAt > firstColon) { - return `git+ssh://${arg}` - } else { - return arg - } - } - - const doubleSlash = arg.indexOf('//') - if (doubleSlash === firstColon + 1) { - return arg - } - - return `${arg.slice(0, firstColon + 1)}//${arg.slice(firstColon + 1)}` -} - -// attempt to correct an scp style url so that it will parse with `new URL()` -const correctUrl = (giturl) => { - // ignore @ that come after the first hash since the denotes the start - // of a committish which can contain @ characters - const firstAt = lastIndexOfBefore(giturl, '@', '#') - // ignore colons that come after the hash since that could include colons such as: - // git@github.com:user/package-2#semver:^1.0.0 - const lastColonBeforeHash = lastIndexOfBefore(giturl, ':', '#') - - if (lastColonBeforeHash > firstAt) { - // the last : comes after the first @ (or there is no @) - // like it would in: - // proto://hostname.com:user/repo - // username@hostname.com:user/repo - // :password@hostname.com:user/repo - // username:password@hostname.com:user/repo - // proto://username@hostname.com:user/repo - // proto://:password@hostname.com:user/repo - // proto://username:password@hostname.com:user/repo - // then we replace the last : with a / to create a valid path - giturl = giturl.slice(0, lastColonBeforeHash) + '/' + giturl.slice(lastColonBeforeHash + 1) - } - - if (lastIndexOfBefore(giturl, ':', '#') === -1 && giturl.indexOf('//') === -1) { - // we have no : at all - // as it would be in: - // username@hostname.com/user/repo - // then we prepend a protocol - giturl = `git+ssh://${giturl}` - } - - return giturl -} - -module.exports = (giturl, protocols) => { - const withProtocol = protocols ? correctProtocol(giturl, protocols) : giturl - return safeUrl(withProtocol) || safeUrl(correctUrl(withProtocol)) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/package.json deleted file mode 100644 index d7eebd474f625..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "name": "hosted-git-info", - "version": "7.0.2", - "description": "Provides metadata and conversions from repository urls for GitHub, Bitbucket and GitLab", - "main": "./lib/index.js", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/hosted-git-info.git" - }, - "keywords": [ - "git", - "github", - "bitbucket", - "gitlab" - ], - "author": "GitHub Inc.", - "license": "ISC", - "bugs": { - "url": "https://github.com/npm/hosted-git-info/issues" - }, - "homepage": "https://github.com/npm/hosted-git-info", - "scripts": { - "posttest": "npm run lint", - "snap": "tap", - "test": "tap", - "test:coverage": "tap --coverage-report=html", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" - }, - "dependencies": { - "lru-cache": "^10.0.1" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" - }, - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "tap": { - "color": 1, - "coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/ini/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/ini/LICENSE deleted file mode 100644 index 19129e315fe59..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/ini/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/ini/lib/ini.js b/node_modules/@npmcli/metavuln-calculator/node_modules/ini/lib/ini.js deleted file mode 100644 index beb390d0b0ee2..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/ini/lib/ini.js +++ /dev/null @@ -1,280 +0,0 @@ -const { hasOwnProperty } = Object.prototype - -const encode = (obj, opt = {}) => { - if (typeof opt === 'string') { - opt = { section: opt } - } - opt.align = opt.align === true - opt.newline = opt.newline === true - opt.sort = opt.sort === true - opt.whitespace = opt.whitespace === true || opt.align === true - // The `typeof` check is required because accessing the `process` directly fails on browsers. - /* istanbul ignore next */ - opt.platform = opt.platform || (typeof process !== 'undefined' && process.platform) - opt.bracketedArray = opt.bracketedArray !== false - - /* istanbul ignore next */ - const eol = opt.platform === 'win32' ? '\r\n' : '\n' - const separator = opt.whitespace ? ' = ' : '=' - const children = [] - - const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj) - - let padToChars = 0 - // If aligning on the separator, then padToChars is determined as follows: - // 1. Get the keys - // 2. Exclude keys pointing to objects unless the value is null or an array - // 3. Add `[]` to array keys - // 4. Ensure non empty set of keys - // 5. Reduce the set to the longest `safe` key - // 6. Get the `safe` length - if (opt.align) { - padToChars = safe( - ( - keys - .filter(k => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== 'object') - .map(k => Array.isArray(obj[k]) ? `${k}[]` : k) - ) - .concat(['']) - .reduce((a, b) => safe(a).length >= safe(b).length ? a : b) - ).length - } - - let out = '' - const arraySuffix = opt.bracketedArray ? '[]' : '' - - for (const k of keys) { - const val = obj[k] - if (val && Array.isArray(val)) { - for (const item of val) { - out += safe(`${k}${arraySuffix}`).padEnd(padToChars, ' ') + separator + safe(item) + eol - } - } else if (val && typeof val === 'object') { - children.push(k) - } else { - out += safe(k).padEnd(padToChars, ' ') + separator + safe(val) + eol - } - } - - if (opt.section && out.length) { - out = '[' + safe(opt.section) + ']' + (opt.newline ? eol + eol : eol) + out - } - - for (const k of children) { - const nk = splitSections(k, '.').join('\\.') - const section = (opt.section ? opt.section + '.' : '') + nk - const child = encode(obj[k], { - ...opt, - section, - }) - if (out.length && child.length) { - out += eol - } - - out += child - } - - return out -} - -function splitSections (str, separator) { - var lastMatchIndex = 0 - var lastSeparatorIndex = 0 - var nextIndex = 0 - var sections = [] - - do { - nextIndex = str.indexOf(separator, lastMatchIndex) - - if (nextIndex !== -1) { - lastMatchIndex = nextIndex + separator.length - - if (nextIndex > 0 && str[nextIndex - 1] === '\\') { - continue - } - - sections.push(str.slice(lastSeparatorIndex, nextIndex)) - lastSeparatorIndex = nextIndex + separator.length - } - } while (nextIndex !== -1) - - sections.push(str.slice(lastSeparatorIndex)) - - return sections -} - -const decode = (str, opt = {}) => { - opt.bracketedArray = opt.bracketedArray !== false - const out = Object.create(null) - let p = out - let section = null - // section |key = value - const re = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i - const lines = str.split(/[\r\n]+/g) - const duplicates = {} - - for (const line of lines) { - if (!line || line.match(/^\s*[;#]/) || line.match(/^\s*$/)) { - continue - } - const match = line.match(re) - if (!match) { - continue - } - if (match[1] !== undefined) { - section = unsafe(match[1]) - if (section === '__proto__') { - // not allowed - // keep parsing the section, but don't attach it. - p = Object.create(null) - continue - } - p = out[section] = out[section] || Object.create(null) - continue - } - const keyRaw = unsafe(match[2]) - let isArray - if (opt.bracketedArray) { - isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]' - } else { - duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1 - isArray = duplicates[keyRaw] > 1 - } - const key = isArray && keyRaw.endsWith('[]') - ? keyRaw.slice(0, -2) : keyRaw - - if (key === '__proto__') { - 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 (isArray) { - if (!hasOwnProperty.call(p, key)) { - p[key] = [] - } else if (!Array.isArray(p[key])) { - p[key] = [p[key]] - } - } - - // safeguard against resetting a previously defined - // array by accidentally forgetting the brackets - if (Array.isArray(p[key])) { - 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. - 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 - const parts = splitSections(k, '.') - p = out - const l = parts.pop() - const nl = l.replace(/\\\./g, '.') - for (const part of parts) { - if (part === '__proto__') { - continue - } - if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object') { - p[part] = Object.create(null) - } - p = p[part] - } - if (p === out && nl === l) { - continue - } - - p[nl] = out[k] - remove.push(k) - } - for (const del of remove) { - delete out[del] - } - - return out -} - -const isQuoted = val => { - return (val.startsWith('"') && val.endsWith('"')) || - (val.startsWith("'") && val.endsWith("'")) -} - -const safe = val => { - if ( - typeof val !== 'string' || - val.match(/[=\r\n]/) || - val.match(/^\[/) || - (val.length > 1 && isQuoted(val)) || - val !== val.trim() - ) { - return JSON.stringify(val) - } - return val.split(';').join('\\;').split('#').join('\\#') -} - -const unsafe = val => { - val = (val || '').trim() - if (isQuoted(val)) { - // remove the single quotes before calling JSON.parse - if (val.charAt(0) === "'") { - val = val.slice(1, -1) - } - try { - val = JSON.parse(val) - } catch { - // ignore errors - } - } else { - // walk the val to find the first not-escaped ; character - 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 - } else { - unesc += '\\' + c - } - - esc = false - } else if (';#'.indexOf(c) !== -1) { - break - } else if (c === '\\') { - esc = true - } else { - unesc += c - } - } - if (esc) { - unesc += '\\' - } - - return unesc.trim() - } - return val -} - -module.exports = { - parse: decode, - decode, - stringify: encode, - encode, - safe, - unsafe, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/ini/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/ini/package.json deleted file mode 100644 index 67aa927825947..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/ini/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "author": "GitHub Inc.", - "name": "ini", - "description": "An ini encoder/decoder for node", - "version": "4.1.3", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/ini.git" - }, - "main": "lib/ini.js", - "scripts": { - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "test": "tap", - "snap": "tap", - "posttest": "npm run lint", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" - }, - "license": "ISC", - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/LICENSE deleted file mode 100644 index c925dbe826b67..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) 2016-2022 Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/index.js deleted file mode 100644 index cefcb66b5c543..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/index.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.sync = exports.isexe = exports.posix = exports.win32 = void 0; -const posix = __importStar(require("./posix.js")); -exports.posix = posix; -const win32 = __importStar(require("./win32.js")); -exports.win32 = win32; -__exportStar(require("./options.js"), exports); -const platform = process.env._ISEXE_TEST_PLATFORM_ || process.platform; -const impl = platform === 'win32' ? win32 : posix; -/** - * Determine whether a path is executable on the current platform. - */ -exports.isexe = impl.isexe; -/** - * Synchronously determine whether a path is executable on the - * current platform. - */ -exports.sync = impl.sync; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/options.js b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/options.js deleted file mode 100644 index 0dfad0762cc32..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/options.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=options.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/package.json deleted file mode 100644 index 5bbefffbabee3..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/package.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "type": "commonjs" -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/posix.js b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/posix.js deleted file mode 100644 index 3bc5e79d7007e..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/posix.js +++ /dev/null @@ -1,67 +0,0 @@ -"use strict"; -/** - * This is the Posix implementation of isexe, which uses the file - * mode and uid/gid values. - * - * @module - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.sync = exports.isexe = void 0; -const fs_1 = require("fs"); -const promises_1 = require("fs/promises"); -/** - * Determine whether a path is executable according to the mode and - * current (or specified) user and group IDs. - */ -const isexe = async (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(await (0, promises_1.stat)(path), options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -exports.isexe = isexe; -/** - * Synchronously determine whether a path is executable according to - * the mode and current (or specified) user and group IDs. - */ -const sync = (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat((0, fs_1.statSync)(path), options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -exports.sync = sync; -const checkStat = (stat, options) => stat.isFile() && checkMode(stat, options); -const checkMode = (stat, options) => { - const myUid = options.uid ?? process.getuid?.(); - const myGroups = options.groups ?? process.getgroups?.() ?? []; - const myGid = options.gid ?? process.getgid?.() ?? myGroups[0]; - if (myUid === undefined || myGid === undefined) { - throw new Error('cannot get uid or gid'); - } - const groups = new Set([myGid, ...myGroups]); - const mod = stat.mode; - const uid = stat.uid; - const gid = stat.gid; - const u = parseInt('100', 8); - const g = parseInt('010', 8); - const o = parseInt('001', 8); - const ug = u | g; - return !!(mod & o || - (mod & g && groups.has(gid)) || - (mod & u && uid === myUid) || - (mod & ug && myUid === 0)); -}; -//# sourceMappingURL=posix.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/win32.js b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/win32.js deleted file mode 100644 index fa7a4d2f7d240..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/cjs/win32.js +++ /dev/null @@ -1,62 +0,0 @@ -"use strict"; -/** - * This is the Windows implementation of isexe, which uses the file - * extension and PATHEXT setting. - * - * @module - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.sync = exports.isexe = void 0; -const fs_1 = require("fs"); -const promises_1 = require("fs/promises"); -/** - * Determine whether a path is executable based on the file extension - * and PATHEXT environment variable (or specified pathExt option) - */ -const isexe = async (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(await (0, promises_1.stat)(path), path, options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -exports.isexe = isexe; -/** - * Synchronously determine whether a path is executable based on the file - * extension and PATHEXT environment variable (or specified pathExt option) - */ -const sync = (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat((0, fs_1.statSync)(path), path, options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -exports.sync = sync; -const checkPathExt = (path, options) => { - const { pathExt = process.env.PATHEXT || '' } = options; - const peSplit = pathExt.split(';'); - if (peSplit.indexOf('') !== -1) { - return true; - } - for (let i = 0; i < peSplit.length; i++) { - const p = peSplit[i].toLowerCase(); - const ext = path.substring(path.length - p.length).toLowerCase(); - if (p && ext === p) { - return true; - } - } - return false; -}; -const checkStat = (stat, path, options) => stat.isFile() && checkPathExt(path, options); -//# sourceMappingURL=win32.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/index.js deleted file mode 100644 index 1e309acd7355e..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/index.js +++ /dev/null @@ -1,16 +0,0 @@ -import * as posix from './posix.js'; -import * as win32 from './win32.js'; -export * from './options.js'; -export { win32, posix }; -const platform = process.env._ISEXE_TEST_PLATFORM_ || process.platform; -const impl = platform === 'win32' ? win32 : posix; -/** - * Determine whether a path is executable on the current platform. - */ -export const isexe = impl.isexe; -/** - * Synchronously determine whether a path is executable on the - * current platform. - */ -export const sync = impl.sync; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/options.js b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/options.js deleted file mode 100644 index e9ded40bd5b2c..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/options.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=options.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/package.json deleted file mode 100644 index 3dbc1ca591c05..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/package.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "type": "module" -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/posix.js b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/posix.js deleted file mode 100644 index c453776c0452f..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/posix.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * This is the Posix implementation of isexe, which uses the file - * mode and uid/gid values. - * - * @module - */ -import { statSync } from 'fs'; -import { stat } from 'fs/promises'; -/** - * Determine whether a path is executable according to the mode and - * current (or specified) user and group IDs. - */ -export const isexe = async (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(await stat(path), options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -/** - * Synchronously determine whether a path is executable according to - * the mode and current (or specified) user and group IDs. - */ -export const sync = (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(statSync(path), options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -const checkStat = (stat, options) => stat.isFile() && checkMode(stat, options); -const checkMode = (stat, options) => { - const myUid = options.uid ?? process.getuid?.(); - const myGroups = options.groups ?? process.getgroups?.() ?? []; - const myGid = options.gid ?? process.getgid?.() ?? myGroups[0]; - if (myUid === undefined || myGid === undefined) { - throw new Error('cannot get uid or gid'); - } - const groups = new Set([myGid, ...myGroups]); - const mod = stat.mode; - const uid = stat.uid; - const gid = stat.gid; - const u = parseInt('100', 8); - const g = parseInt('010', 8); - const o = parseInt('001', 8); - const ug = u | g; - return !!(mod & o || - (mod & g && groups.has(gid)) || - (mod & u && uid === myUid) || - (mod & ug && myUid === 0)); -}; -//# sourceMappingURL=posix.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/win32.js b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/win32.js deleted file mode 100644 index a354ee2a5115c..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/dist/mjs/win32.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * This is the Windows implementation of isexe, which uses the file - * extension and PATHEXT setting. - * - * @module - */ -import { statSync } from 'fs'; -import { stat } from 'fs/promises'; -/** - * Determine whether a path is executable based on the file extension - * and PATHEXT environment variable (or specified pathExt option) - */ -export const isexe = async (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(await stat(path), path, options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -/** - * Synchronously determine whether a path is executable based on the file - * extension and PATHEXT environment variable (or specified pathExt option) - */ -export const sync = (path, options = {}) => { - const { ignoreErrors = false } = options; - try { - return checkStat(statSync(path), path, options); - } - catch (e) { - const er = e; - if (ignoreErrors || er.code === 'EACCES') - return false; - throw er; - } -}; -const checkPathExt = (path, options) => { - const { pathExt = process.env.PATHEXT || '' } = options; - const peSplit = pathExt.split(';'); - if (peSplit.indexOf('') !== -1) { - return true; - } - for (let i = 0; i < peSplit.length; i++) { - const p = peSplit[i].toLowerCase(); - const ext = path.substring(path.length - p.length).toLowerCase(); - if (p && ext === p) { - return true; - } - } - return false; -}; -const checkStat = (stat, path, options) => stat.isFile() && checkPathExt(path, options); -//# sourceMappingURL=win32.js.map \ No newline at end of file diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/package.json deleted file mode 100644 index a0e2cd04bfdbf..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/isexe/package.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "name": "isexe", - "version": "3.1.1", - "description": "Minimal module to check if a file is executable.", - "main": "./dist/cjs/index.js", - "module": "./dist/mjs/index.js", - "types": "./dist/cjs/index.js", - "files": [ - "dist" - ], - "exports": { - ".": { - "import": { - "types": "./dist/mjs/index.d.ts", - "default": "./dist/mjs/index.js" - }, - "require": { - "types": "./dist/cjs/index.d.ts", - "default": "./dist/cjs/index.js" - } - }, - "./posix": { - "import": { - "types": "./dist/mjs/posix.d.ts", - "default": "./dist/mjs/posix.js" - }, - "require": { - "types": "./dist/cjs/posix.d.ts", - "default": "./dist/cjs/posix.js" - } - }, - "./win32": { - "import": { - "types": "./dist/mjs/win32.d.ts", - "default": "./dist/mjs/win32.js" - }, - "require": { - "types": "./dist/cjs/win32.d.ts", - "default": "./dist/cjs/win32.js" - } - }, - "./package.json": "./package.json" - }, - "devDependencies": { - "@types/node": "^20.4.5", - "@types/tap": "^15.0.8", - "c8": "^8.0.1", - "mkdirp": "^0.5.1", - "prettier": "^2.8.8", - "rimraf": "^2.5.0", - "sync-content": "^1.0.2", - "tap": "^16.3.8", - "ts-node": "^10.9.1", - "typedoc": "^0.24.8", - "typescript": "^5.1.6" - }, - "scripts": { - "preversion": "npm test", - "postversion": "npm publish", - "prepublishOnly": "git push origin --follow-tags", - "prepare": "tsc -p tsconfig/cjs.json && tsc -p tsconfig/esm.json && bash ./scripts/fixup.sh", - "pretest": "npm run prepare", - "presnap": "npm run prepare", - "test": "c8 tap", - "snap": "c8 tap", - "format": "prettier --write . --loglevel warn --ignore-path ../../.prettierignore --cache", - "typedoc": "typedoc --tsconfig tsconfig/esm.json ./src/*.ts" - }, - "author": "Isaac Z. Schlueter (http://blog.izs.me/)", - "license": "ISC", - "tap": { - "coverage": false, - "node-arg": [ - "--enable-source-maps", - "--no-warnings", - "--loader", - "ts-node/esm" - ], - "ts": false - }, - "prettier": { - "semi": false, - "printWidth": 75, - "tabWidth": 2, - "useTabs": false, - "singleQuote": true, - "jsxSingleQuote": false, - "bracketSameLine": true, - "arrowParens": "avoid", - "endOfLine": "lf" - }, - "repository": "https://github.com/isaacs/isexe", - "engines": { - "node": ">=16" - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors/LICENSE.md b/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors/LICENSE.md deleted file mode 100644 index 6991b7cbb89db..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors/LICENSE.md +++ /dev/null @@ -1,25 +0,0 @@ -Copyright 2017 Kat Marchán -Copyright npm, Inc. - -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. - ---- - -This library is a fork of 'better-json-errors' by Kat Marchán, extended and -distributed under the terms of the MIT license above. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors/lib/index.js deleted file mode 100644 index 3ffdaac96d2dc..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors/lib/index.js +++ /dev/null @@ -1,137 +0,0 @@ -'use strict' - -const INDENT = Symbol.for('indent') -const NEWLINE = Symbol.for('newline') - -const DEFAULT_NEWLINE = '\n' -const DEFAULT_INDENT = ' ' -const BOM = /^\uFEFF/ - -// only respect indentation if we got a line break, otherwise squash it -// things other than objects and arrays aren't indented, so ignore those -// Important: in both of these regexps, the $1 capture group is the newline -// or undefined, and the $2 capture group is the indent, or undefined. -const FORMAT = /^\s*[{[]((?:\r?\n)+)([\s\t]*)/ -const EMPTY = /^(?:\{\}|\[\])((?:\r?\n)+)?$/ - -// Node 20 puts single quotes around the token and a comma after it -const UNEXPECTED_TOKEN = /^Unexpected token '?(.)'?(,)? /i - -const hexify = (char) => { - const h = char.charCodeAt(0).toString(16).toUpperCase() - return `0x${h.length % 2 ? '0' : ''}${h}` -} - -// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) -// because the buffer-to-string conversion in `fs.readFileSync()` -// translates it to FEFF, the UTF-16 BOM. -const stripBOM = (txt) => String(txt).replace(BOM, '') - -const makeParsedError = (msg, parsing, position = 0) => ({ - message: `${msg} while parsing ${parsing}`, - position, -}) - -const parseError = (e, txt, context = 20) => { - let msg = e.message - - if (!txt) { - return makeParsedError(msg, 'empty string') - } - - const badTokenMatch = msg.match(UNEXPECTED_TOKEN) - const badIndexMatch = msg.match(/ position\s+(\d+)/i) - - if (badTokenMatch) { - msg = msg.replace( - UNEXPECTED_TOKEN, - `Unexpected token ${JSON.stringify(badTokenMatch[1])} (${hexify(badTokenMatch[1])})$2 ` - ) - } - - let errIdx - if (badIndexMatch) { - errIdx = +badIndexMatch[1] - } else /* istanbul ignore next - doesnt happen in Node 22 */ if ( - msg.match(/^Unexpected end of JSON.*/i) - ) { - errIdx = txt.length - 1 - } - - if (errIdx == null) { - return makeParsedError(msg, `'${txt.slice(0, context * 2)}'`) - } - - const start = errIdx <= context ? 0 : errIdx - context - const end = errIdx + context >= txt.length ? txt.length : errIdx + context - const slice = `${start ? '...' : ''}${txt.slice(start, end)}${end === txt.length ? '' : '...'}` - - return makeParsedError( - msg, - `${txt === slice ? '' : 'near '}${JSON.stringify(slice)}`, - errIdx - ) -} - -class JSONParseError extends SyntaxError { - constructor (er, txt, context, caller) { - const metadata = parseError(er, txt, context) - super(metadata.message) - Object.assign(this, metadata) - this.code = 'EJSONPARSE' - this.systemError = er - Error.captureStackTrace(this, caller || this.constructor) - } - - get name () { - return this.constructor.name - } - - set name (n) {} - - get [Symbol.toStringTag] () { - return this.constructor.name - } -} - -const parseJson = (txt, reviver) => { - const result = JSON.parse(txt, reviver) - if (result && typeof result === 'object') { - // get the indentation so that we can save it back nicely - // if the file starts with {" then we have an indent of '', ie, none - // otherwise, pick the indentation of the next line after the first \n If the - // pattern doesn't match, then it means no indentation. JSON.stringify ignores - // symbols, so this is reasonably safe. if the string is '{}' or '[]', then - // use the default 2-space indent. - const match = txt.match(EMPTY) || txt.match(FORMAT) || [null, '', ''] - result[NEWLINE] = match[1] ?? DEFAULT_NEWLINE - result[INDENT] = match[2] ?? DEFAULT_INDENT - } - return result -} - -const parseJsonError = (raw, reviver, context) => { - const txt = stripBOM(raw) - try { - return parseJson(txt, reviver) - } catch (e) { - if (typeof raw !== 'string' && !Buffer.isBuffer(raw)) { - const msg = Array.isArray(raw) && raw.length === 0 ? 'an empty array' : String(raw) - throw Object.assign( - new TypeError(`Cannot parse ${msg}`), - { code: 'EJSONPARSE', systemError: e } - ) - } - throw new JSONParseError(e, txt, context, parseJsonError) - } -} - -module.exports = parseJsonError -parseJsonError.JSONParseError = JSONParseError -parseJsonError.noExceptions = (raw, reviver) => { - try { - return parseJson(stripBOM(raw), reviver) - } catch { - // no exceptions - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors/package.json deleted file mode 100644 index c7156df325fa2..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "json-parse-even-better-errors", - "version": "3.0.2", - "description": "JSON.parse with context information on error", - "main": "lib/index.js", - "files": [ - "bin/", - "lib/" - ], - "scripts": { - "test": "tap", - "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/json-parse-even-better-errors.git" - }, - "keywords": [ - "JSON", - "parser" - ], - "author": "GitHub Inc.", - "license": "MIT", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.3.0" - }, - "tap": { - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/LICENSE deleted file mode 100644 index 1808eb2844231..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -ISC License - -Copyright 2017-2022 (c) npm, Inc. - -Permission to use, copy, modify, and/or distribute this software for -any purpose with or without fee is hereby granted, provided that the -above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS -ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR -CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE -USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/entry.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/entry.js deleted file mode 100644 index bfcfacbcc95e1..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/entry.js +++ /dev/null @@ -1,471 +0,0 @@ -const { Request, Response } = require('minipass-fetch') -const { Minipass } = require('minipass') -const MinipassFlush = require('minipass-flush') -const cacache = require('cacache') -const url = require('url') - -const CachingMinipassPipeline = require('../pipeline.js') -const CachePolicy = require('./policy.js') -const cacheKey = require('./key.js') -const remote = require('../remote.js') - -const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop) - -// allow list for request headers that will be written to the cache index -// note: we will also store any request headers -// that are named in a response's vary header -const KEEP_REQUEST_HEADERS = [ - 'accept-charset', - 'accept-encoding', - 'accept-language', - 'accept', - 'cache-control', -] - -// allow list for response headers that will be written to the cache index -// note: we must not store the real response's age header, or when we load -// a cache policy based on the metadata it will think the cached response -// is always stale -const KEEP_RESPONSE_HEADERS = [ - 'cache-control', - 'content-encoding', - 'content-language', - 'content-type', - 'date', - 'etag', - 'expires', - 'last-modified', - 'link', - 'location', - 'pragma', - 'vary', -] - -// return an object containing all metadata to be written to the index -const getMetadata = (request, response, options) => { - const metadata = { - time: Date.now(), - url: request.url, - reqHeaders: {}, - resHeaders: {}, - - // options on which we must match the request and vary the response - options: { - compress: options.compress != null ? options.compress : request.compress, - }, - } - - // only save the status if it's not a 200 or 304 - if (response.status !== 200 && response.status !== 304) { - metadata.status = response.status - } - - for (const name of KEEP_REQUEST_HEADERS) { - if (request.headers.has(name)) { - metadata.reqHeaders[name] = request.headers.get(name) - } - } - - // if the request's host header differs from the host in the url - // we need to keep it, otherwise it's just noise and we ignore it - const host = request.headers.get('host') - const parsedUrl = new url.URL(request.url) - if (host && parsedUrl.host !== host) { - metadata.reqHeaders.host = host - } - - // if the response has a vary header, make sure - // we store the relevant request headers too - if (response.headers.has('vary')) { - const vary = response.headers.get('vary') - // a vary of "*" means every header causes a different response. - // in that scenario, we do not include any additional headers - // as the freshness check will always fail anyway and we don't - // want to bloat the cache indexes - if (vary !== '*') { - // copy any other request headers that will vary the response - const varyHeaders = vary.trim().toLowerCase().split(/\s*,\s*/) - for (const name of varyHeaders) { - if (request.headers.has(name)) { - metadata.reqHeaders[name] = request.headers.get(name) - } - } - } - } - - for (const name of KEEP_RESPONSE_HEADERS) { - if (response.headers.has(name)) { - metadata.resHeaders[name] = response.headers.get(name) - } - } - - for (const name of options.cacheAdditionalHeaders) { - if (response.headers.has(name)) { - metadata.resHeaders[name] = response.headers.get(name) - } - } - - return metadata -} - -// symbols used to hide objects that may be lazily evaluated in a getter -const _request = Symbol('request') -const _response = Symbol('response') -const _policy = Symbol('policy') - -class CacheEntry { - constructor ({ entry, request, response, options }) { - if (entry) { - this.key = entry.key - this.entry = entry - // previous versions of this module didn't write an explicit timestamp in - // the metadata, so fall back to the entry's timestamp. we can't use the - // entry timestamp to determine staleness because cacache will update it - // when it verifies its data - this.entry.metadata.time = this.entry.metadata.time || this.entry.time - } else { - this.key = cacheKey(request) - } - - this.options = options - - // these properties are behind getters that lazily evaluate - this[_request] = request - this[_response] = response - this[_policy] = null - } - - // returns a CacheEntry instance that satisfies the given request - // or undefined if no existing entry satisfies - static async find (request, options) { - try { - // compacts the index and returns an array of unique entries - var matches = await cacache.index.compact(options.cachePath, cacheKey(request), (A, B) => { - const entryA = new CacheEntry({ entry: A, options }) - const entryB = new CacheEntry({ entry: B, options }) - return entryA.policy.satisfies(entryB.request) - }, { - validateEntry: (entry) => { - // clean out entries with a buggy content-encoding value - if (entry.metadata && - entry.metadata.resHeaders && - entry.metadata.resHeaders['content-encoding'] === null) { - return false - } - - // if an integrity is null, it needs to have a status specified - if (entry.integrity === null) { - return !!(entry.metadata && entry.metadata.status) - } - - return true - }, - }) - } catch (err) { - // if the compact request fails, ignore the error and return - return - } - - // a cache mode of 'reload' means to behave as though we have no cache - // on the way to the network. return undefined to allow cacheFetch to - // create a brand new request no matter what. - if (options.cache === 'reload') { - return - } - - // find the specific entry that satisfies the request - let match - for (const entry of matches) { - const _entry = new CacheEntry({ - entry, - options, - }) - - if (_entry.policy.satisfies(request)) { - match = _entry - break - } - } - - return match - } - - // if the user made a PUT/POST/PATCH then we invalidate our - // cache for the same url by deleting the index entirely - static async invalidate (request, options) { - const key = cacheKey(request) - try { - await cacache.rm.entry(options.cachePath, key, { removeFully: true }) - } catch (err) { - // ignore errors - } - } - - get request () { - if (!this[_request]) { - this[_request] = new Request(this.entry.metadata.url, { - method: 'GET', - headers: this.entry.metadata.reqHeaders, - ...this.entry.metadata.options, - }) - } - - return this[_request] - } - - get response () { - if (!this[_response]) { - this[_response] = new Response(null, { - url: this.entry.metadata.url, - counter: this.options.counter, - status: this.entry.metadata.status || 200, - headers: { - ...this.entry.metadata.resHeaders, - 'content-length': this.entry.size, - }, - }) - } - - return this[_response] - } - - get policy () { - if (!this[_policy]) { - this[_policy] = new CachePolicy({ - entry: this.entry, - request: this.request, - response: this.response, - options: this.options, - }) - } - - return this[_policy] - } - - // wraps the response in a pipeline that stores the data - // in the cache while the user consumes it - async store (status) { - // if we got a status other than 200, 301, or 308, - // or the CachePolicy forbid storage, append the - // cache status header and return it untouched - if ( - this.request.method !== 'GET' || - ![200, 301, 308].includes(this.response.status) || - !this.policy.storable() - ) { - this.response.headers.set('x-local-cache-status', 'skip') - return this.response - } - - const size = this.response.headers.get('content-length') - const cacheOpts = { - algorithms: this.options.algorithms, - metadata: getMetadata(this.request, this.response, this.options), - size, - integrity: this.options.integrity, - integrityEmitter: this.response.body.hasIntegrityEmitter && this.response.body, - } - - let body = null - // we only set a body if the status is a 200, redirects are - // stored as metadata only - if (this.response.status === 200) { - let cacheWriteResolve, cacheWriteReject - const cacheWritePromise = new Promise((resolve, reject) => { - cacheWriteResolve = resolve - cacheWriteReject = reject - }).catch((err) => { - body.emit('error', err) - }) - - body = new CachingMinipassPipeline({ events: ['integrity', 'size'] }, new MinipassFlush({ - flush () { - return cacheWritePromise - }, - })) - // this is always true since if we aren't reusing the one from the remote fetch, we - // are using the one from cacache - body.hasIntegrityEmitter = true - - const onResume = () => { - const tee = new Minipass() - const cacheStream = cacache.put.stream(this.options.cachePath, this.key, cacheOpts) - // re-emit the integrity and size events on our new response body so they can be reused - cacheStream.on('integrity', i => body.emit('integrity', i)) - cacheStream.on('size', s => body.emit('size', s)) - // stick a flag on here so downstream users will know if they can expect integrity events - tee.pipe(cacheStream) - // TODO if the cache write fails, log a warning but return the response anyway - // eslint-disable-next-line promise/catch-or-return - cacheStream.promise().then(cacheWriteResolve, cacheWriteReject) - body.unshift(tee) - body.unshift(this.response.body) - } - - body.once('resume', onResume) - body.once('end', () => body.removeListener('resume', onResume)) - } else { - await cacache.index.insert(this.options.cachePath, this.key, null, cacheOpts) - } - - // note: we do not set the x-local-cache-hash header because we do not know - // the hash value until after the write to the cache completes, which doesn't - // happen until after the response has been sent and it's too late to write - // the header anyway - this.response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) - this.response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) - this.response.headers.set('x-local-cache-mode', 'stream') - this.response.headers.set('x-local-cache-status', status) - this.response.headers.set('x-local-cache-time', new Date().toISOString()) - const newResponse = new Response(body, { - url: this.response.url, - status: this.response.status, - headers: this.response.headers, - counter: this.options.counter, - }) - return newResponse - } - - // use the cached data to create a response and return it - async respond (method, options, status) { - let response - if (method === 'HEAD' || [301, 308].includes(this.response.status)) { - // if the request is a HEAD, or the response is a redirect, - // then the metadata in the entry already includes everything - // we need to build a response - response = this.response - } else { - // we're responding with a full cached response, so create a body - // that reads from cacache and attach it to a new Response - const body = new Minipass() - const headers = { ...this.policy.responseHeaders() } - - const onResume = () => { - const cacheStream = cacache.get.stream.byDigest( - this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } - ) - cacheStream.on('error', async (err) => { - cacheStream.pause() - if (err.code === 'EINTEGRITY') { - await cacache.rm.content( - this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } - ) - } - if (err.code === 'ENOENT' || err.code === 'EINTEGRITY') { - await CacheEntry.invalidate(this.request, this.options) - } - body.emit('error', err) - cacheStream.resume() - }) - // emit the integrity and size events based on our metadata so we're consistent - body.emit('integrity', this.entry.integrity) - body.emit('size', Number(headers['content-length'])) - cacheStream.pipe(body) - } - - body.once('resume', onResume) - body.once('end', () => body.removeListener('resume', onResume)) - response = new Response(body, { - url: this.entry.metadata.url, - counter: options.counter, - status: 200, - headers, - }) - } - - response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) - response.headers.set('x-local-cache-hash', encodeURIComponent(this.entry.integrity)) - response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) - response.headers.set('x-local-cache-mode', 'stream') - response.headers.set('x-local-cache-status', status) - response.headers.set('x-local-cache-time', new Date(this.entry.metadata.time).toUTCString()) - return response - } - - // use the provided request along with this cache entry to - // revalidate the stored response. returns a response, either - // from the cache or from the update - async revalidate (request, options) { - const revalidateRequest = new Request(request, { - headers: this.policy.revalidationHeaders(request), - }) - - try { - // NOTE: be sure to remove the headers property from the - // user supplied options, since we have already defined - // them on the new request object. if they're still in the - // options then those will overwrite the ones from the policy - var response = await remote(revalidateRequest, { - ...options, - headers: undefined, - }) - } catch (err) { - // if the network fetch fails, return the stale - // cached response unless it has a cache-control - // of 'must-revalidate' - if (!this.policy.mustRevalidate) { - return this.respond(request.method, options, 'stale') - } - - throw err - } - - if (this.policy.revalidated(revalidateRequest, response)) { - // we got a 304, write a new index to the cache and respond from cache - const metadata = getMetadata(request, response, options) - // 304 responses do not include headers that are specific to the response data - // since they do not include a body, so we copy values for headers that were - // in the old cache entry to the new one, if the new metadata does not already - // include that header - for (const name of KEEP_RESPONSE_HEADERS) { - if ( - !hasOwnProperty(metadata.resHeaders, name) && - hasOwnProperty(this.entry.metadata.resHeaders, name) - ) { - metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] - } - } - - for (const name of options.cacheAdditionalHeaders) { - const inMeta = hasOwnProperty(metadata.resHeaders, name) - const inEntry = hasOwnProperty(this.entry.metadata.resHeaders, name) - const inPolicy = hasOwnProperty(this.policy.response.headers, name) - - // if the header is in the existing entry, but it is not in the metadata - // then we need to write it to the metadata as this will refresh the on-disk cache - if (!inMeta && inEntry) { - metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] - } - // if the header is in the metadata, but not in the policy, then we need to set - // it in the policy so that it's included in the immediate response. future - // responses will load a new cache entry, so we don't need to change that - if (!inPolicy && inMeta) { - this.policy.response.headers[name] = metadata.resHeaders[name] - } - } - - try { - await cacache.index.insert(options.cachePath, this.key, this.entry.integrity, { - size: this.entry.size, - metadata, - }) - } catch (err) { - // if updating the cache index fails, we ignore it and - // respond anyway - } - return this.respond(request.method, options, 'revalidated') - } - - // if we got a modified response, create a new entry based on it - const newEntry = new CacheEntry({ - request, - response, - options, - }) - - // respond with the new entry while writing it to the cache - return newEntry.store('updated') - } -} - -module.exports = CacheEntry diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/errors.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/errors.js deleted file mode 100644 index 67a66573bebe6..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/errors.js +++ /dev/null @@ -1,11 +0,0 @@ -class NotCachedError extends Error { - constructor (url) { - /* eslint-disable-next-line max-len */ - super(`request to ${url} failed: cache mode is 'only-if-cached' but no cached response is available.`) - this.code = 'ENOTCACHED' - } -} - -module.exports = { - NotCachedError, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/index.js deleted file mode 100644 index 0de49d23fb933..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/index.js +++ /dev/null @@ -1,49 +0,0 @@ -const { NotCachedError } = require('./errors.js') -const CacheEntry = require('./entry.js') -const remote = require('../remote.js') - -// do whatever is necessary to get a Response and return it -const cacheFetch = async (request, options) => { - // try to find a cached entry that satisfies this request - const entry = await CacheEntry.find(request, options) - if (!entry) { - // no cached result, if the cache mode is 'only-if-cached' that's a failure - if (options.cache === 'only-if-cached') { - throw new NotCachedError(request.url) - } - - // otherwise, we make a request, store it and return it - const response = await remote(request, options) - const newEntry = new CacheEntry({ request, response, options }) - return newEntry.store('miss') - } - - // we have a cached response that satisfies this request, however if the cache - // mode is 'no-cache' then we send the revalidation request no matter what - if (options.cache === 'no-cache') { - return entry.revalidate(request, options) - } - - // if the cached entry is not stale, or if the cache mode is 'force-cache' or - // 'only-if-cached' we can respond with the cached entry. set the status - // based on the result of needsRevalidation and respond - const _needsRevalidation = entry.policy.needsRevalidation(request) - if (options.cache === 'force-cache' || - options.cache === 'only-if-cached' || - !_needsRevalidation) { - return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit') - } - - // if we got here, the cache entry is stale so revalidate it - return entry.revalidate(request, options) -} - -cacheFetch.invalidate = async (request, options) => { - if (!options.cachePath) { - return - } - - return CacheEntry.invalidate(request, options) -} - -module.exports = cacheFetch diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/key.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/key.js deleted file mode 100644 index f7684d562b7fa..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/key.js +++ /dev/null @@ -1,17 +0,0 @@ -const { URL, format } = require('url') - -// options passed to url.format() when generating a key -const formatOptions = { - auth: false, - fragment: false, - search: true, - unicode: false, -} - -// returns a string to be used as the cache key for the Request -const cacheKey = (request) => { - const parsed = new URL(request.url) - return `make-fetch-happen:request-cache:${format(parsed, formatOptions)}` -} - -module.exports = cacheKey diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/policy.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/policy.js deleted file mode 100644 index ada3c8600dae9..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/cache/policy.js +++ /dev/null @@ -1,161 +0,0 @@ -const CacheSemantics = require('http-cache-semantics') -const Negotiator = require('negotiator') -const ssri = require('ssri') - -// options passed to http-cache-semantics constructor -const policyOptions = { - shared: false, - ignoreCargoCult: true, -} - -// a fake empty response, used when only testing the -// request for storability -const emptyResponse = { status: 200, headers: {} } - -// returns a plain object representation of the Request -const requestObject = (request) => { - const _obj = { - method: request.method, - url: request.url, - headers: {}, - compress: request.compress, - } - - request.headers.forEach((value, key) => { - _obj.headers[key] = value - }) - - return _obj -} - -// returns a plain object representation of the Response -const responseObject = (response) => { - const _obj = { - status: response.status, - headers: {}, - } - - response.headers.forEach((value, key) => { - _obj.headers[key] = value - }) - - return _obj -} - -class CachePolicy { - constructor ({ entry, request, response, options }) { - this.entry = entry - this.request = requestObject(request) - this.response = responseObject(response) - this.options = options - this.policy = new CacheSemantics(this.request, this.response, policyOptions) - - if (this.entry) { - // if we have an entry, copy the timestamp to the _responseTime - // this is necessary because the CacheSemantics constructor forces - // the value to Date.now() which means a policy created from a - // cache entry is likely to always identify itself as stale - this.policy._responseTime = this.entry.metadata.time - } - } - - // static method to quickly determine if a request alone is storable - static storable (request, options) { - // no cachePath means no caching - if (!options.cachePath) { - return false - } - - // user explicitly asked not to cache - if (options.cache === 'no-store') { - return false - } - - // we only cache GET and HEAD requests - if (!['GET', 'HEAD'].includes(request.method)) { - return false - } - - // otherwise, let http-cache-semantics make the decision - // based on the request's headers - const policy = new CacheSemantics(requestObject(request), emptyResponse, policyOptions) - return policy.storable() - } - - // returns true if the policy satisfies the request - satisfies (request) { - const _req = requestObject(request) - if (this.request.headers.host !== _req.headers.host) { - return false - } - - if (this.request.compress !== _req.compress) { - return false - } - - const negotiatorA = new Negotiator(this.request) - const negotiatorB = new Negotiator(_req) - - if (JSON.stringify(negotiatorA.mediaTypes()) !== JSON.stringify(negotiatorB.mediaTypes())) { - return false - } - - if (JSON.stringify(negotiatorA.languages()) !== JSON.stringify(negotiatorB.languages())) { - return false - } - - if (JSON.stringify(negotiatorA.encodings()) !== JSON.stringify(negotiatorB.encodings())) { - return false - } - - if (this.options.integrity) { - return ssri.parse(this.options.integrity).match(this.entry.integrity) - } - - return true - } - - // returns true if the request and response allow caching - storable () { - return this.policy.storable() - } - - // NOTE: this is a hack to avoid parsing the cache-control - // header ourselves, it returns true if the response's - // cache-control contains must-revalidate - get mustRevalidate () { - return !!this.policy._rescc['must-revalidate'] - } - - // returns true if the cached response requires revalidation - // for the given request - needsRevalidation (request) { - const _req = requestObject(request) - // force method to GET because we only cache GETs - // but can serve a HEAD from a cached GET - _req.method = 'GET' - return !this.policy.satisfiesWithoutRevalidation(_req) - } - - responseHeaders () { - return this.policy.responseHeaders() - } - - // returns a new object containing the appropriate headers - // to send a revalidation request - revalidationHeaders (request) { - const _req = requestObject(request) - return this.policy.revalidationHeaders(_req) - } - - // returns true if the request/response was revalidated - // successfully. returns false if a new response was received - revalidated (request, response) { - const _req = requestObject(request) - const _res = responseObject(response) - const policy = this.policy.revalidatedPolicy(_req, _res) - return !policy.modified - } -} - -module.exports = CachePolicy diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/fetch.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/fetch.js deleted file mode 100644 index 233ba67e16550..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/fetch.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict' - -const { FetchError, Request, isRedirect } = require('minipass-fetch') -const url = require('url') - -const CachePolicy = require('./cache/policy.js') -const cache = require('./cache/index.js') -const remote = require('./remote.js') - -// given a Request, a Response and user options -// return true if the response is a redirect that -// can be followed. we throw errors that will result -// in the fetch being rejected if the redirect is -// possible but invalid for some reason -const canFollowRedirect = (request, response, options) => { - if (!isRedirect(response.status)) { - return false - } - - if (options.redirect === 'manual') { - return false - } - - if (options.redirect === 'error') { - throw new FetchError(`redirect mode is set to error: ${request.url}`, - 'no-redirect', { code: 'ENOREDIRECT' }) - } - - if (!response.headers.has('location')) { - throw new FetchError(`redirect location header missing for: ${request.url}`, - 'no-location', { code: 'EINVALIDREDIRECT' }) - } - - if (request.counter >= request.follow) { - throw new FetchError(`maximum redirect reached at: ${request.url}`, - 'max-redirect', { code: 'EMAXREDIRECT' }) - } - - return true -} - -// given a Request, a Response, and the user's options return an object -// with a new Request and a new options object that will be used for -// following the redirect -const getRedirect = (request, response, options) => { - const _opts = { ...options } - const location = response.headers.get('location') - const redirectUrl = new url.URL(location, /^https?:/.test(location) ? undefined : request.url) - // Comment below is used under the following license: - /** - * @license - * Copyright (c) 2010-2012 Mikeal Rogers - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS - * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language - * governing permissions and limitations under the License. - */ - - // Remove authorization if changing hostnames (but not if just - // changing ports or protocols). This matches the behavior of request: - // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138 - if (new url.URL(request.url).hostname !== redirectUrl.hostname) { - request.headers.delete('authorization') - request.headers.delete('cookie') - } - - // for POST request with 301/302 response, or any request with 303 response, - // use GET when following redirect - if ( - response.status === 303 || - (request.method === 'POST' && [301, 302].includes(response.status)) - ) { - _opts.method = 'GET' - _opts.body = null - request.headers.delete('content-length') - } - - _opts.headers = {} - request.headers.forEach((value, key) => { - _opts.headers[key] = value - }) - - _opts.counter = ++request.counter - const redirectReq = new Request(url.format(redirectUrl), _opts) - return { - request: redirectReq, - options: _opts, - } -} - -const fetch = async (request, options) => { - const response = CachePolicy.storable(request, options) - ? await cache(request, options) - : await remote(request, options) - - // if the request wasn't a GET or HEAD, and the response - // status is between 200 and 399 inclusive, invalidate the - // request url - if (!['GET', 'HEAD'].includes(request.method) && - response.status >= 200 && - response.status <= 399) { - await cache.invalidate(request, options) - } - - if (!canFollowRedirect(request, response, options)) { - return response - } - - const redirect = getRedirect(request, response, options) - return fetch(redirect.request, redirect.options) -} - -module.exports = fetch diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/index.js deleted file mode 100644 index 2f12e8e1b6113..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/index.js +++ /dev/null @@ -1,41 +0,0 @@ -const { FetchError, Headers, Request, Response } = require('minipass-fetch') - -const configureOptions = require('./options.js') -const fetch = require('./fetch.js') - -const makeFetchHappen = (url, opts) => { - const options = configureOptions(opts) - - const request = new Request(url, options) - return fetch(request, options) -} - -makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => { - if (typeof defaultUrl === 'object') { - defaultOptions = defaultUrl - defaultUrl = null - } - - const defaultedFetch = (url, options = {}) => { - const finalUrl = url || defaultUrl - const finalOptions = { - ...defaultOptions, - ...options, - headers: { - ...defaultOptions.headers, - ...options.headers, - }, - } - return wrappedFetch(finalUrl, finalOptions) - } - - defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) => - makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch) - return defaultedFetch -} - -module.exports = makeFetchHappen -module.exports.FetchError = FetchError -module.exports.Headers = Headers -module.exports.Request = Request -module.exports.Response = Response diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/options.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/options.js deleted file mode 100644 index f77511279f831..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/options.js +++ /dev/null @@ -1,54 +0,0 @@ -const dns = require('dns') - -const conditionalHeaders = [ - 'if-modified-since', - 'if-none-match', - 'if-unmodified-since', - 'if-match', - 'if-range', -] - -const configureOptions = (opts) => { - const { strictSSL, ...options } = { ...opts } - options.method = options.method ? options.method.toUpperCase() : 'GET' - options.rejectUnauthorized = strictSSL !== false - - if (!options.retry) { - options.retry = { retries: 0 } - } else if (typeof options.retry === 'string') { - const retries = parseInt(options.retry, 10) - if (isFinite(retries)) { - options.retry = { retries } - } else { - options.retry = { retries: 0 } - } - } else if (typeof options.retry === 'number') { - options.retry = { retries: options.retry } - } else { - options.retry = { retries: 0, ...options.retry } - } - - options.dns = { ttl: 5 * 60 * 1000, lookup: dns.lookup, ...options.dns } - - options.cache = options.cache || 'default' - if (options.cache === 'default') { - const hasConditionalHeader = Object.keys(options.headers || {}).some((name) => { - return conditionalHeaders.includes(name.toLowerCase()) - }) - if (hasConditionalHeader) { - options.cache = 'no-store' - } - } - - options.cacheAdditionalHeaders = options.cacheAdditionalHeaders || [] - - // cacheManager is deprecated, but if it's set and - // cachePath is not we should copy it to the new field - if (options.cacheManager && !options.cachePath) { - options.cachePath = options.cacheManager - } - - return options -} - -module.exports = configureOptions diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/pipeline.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/pipeline.js deleted file mode 100644 index b1d221b2d0ce3..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/pipeline.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict' - -const MinipassPipeline = require('minipass-pipeline') - -class CachingMinipassPipeline extends MinipassPipeline { - #events = [] - #data = new Map() - - constructor (opts, ...streams) { - // CRITICAL: do NOT pass the streams to the call to super(), this will start - // the flow of data and potentially cause the events we need to catch to emit - // before we've finished our own setup. instead we call super() with no args, - // finish our setup, and then push the streams into ourselves to start the - // data flow - super() - this.#events = opts.events - - /* istanbul ignore next - coverage disabled because this is pointless to test here */ - if (streams.length) { - this.push(...streams) - } - } - - on (event, handler) { - if (this.#events.includes(event) && this.#data.has(event)) { - return handler(...this.#data.get(event)) - } - - return super.on(event, handler) - } - - emit (event, ...data) { - if (this.#events.includes(event)) { - this.#data.set(event, data) - } - - return super.emit(event, ...data) - } -} - -module.exports = CachingMinipassPipeline diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/remote.js b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/remote.js deleted file mode 100644 index 8554564074de6..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/lib/remote.js +++ /dev/null @@ -1,131 +0,0 @@ -const { Minipass } = require('minipass') -const fetch = require('minipass-fetch') -const promiseRetry = require('promise-retry') -const ssri = require('ssri') -const { log } = require('proc-log') - -const CachingMinipassPipeline = require('./pipeline.js') -const { getAgent } = require('@npmcli/agent') -const pkg = require('../package.json') - -const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})` - -const RETRY_ERRORS = [ - 'ECONNRESET', // remote socket closed on us - 'ECONNREFUSED', // remote host refused to open connection - 'EADDRINUSE', // failed to bind to a local port (proxy?) - 'ETIMEDOUT', // someone in the transaction is WAY TOO SLOW - // from @npmcli/agent - 'ECONNECTIONTIMEOUT', - 'EIDLETIMEOUT', - 'ERESPONSETIMEOUT', - 'ETRANSFERTIMEOUT', - // Known codes we do NOT retry on: - // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline) - // EINVALIDPROXY // invalid protocol from @npmcli/agent - // EINVALIDRESPONSE // invalid status code from @npmcli/agent -] - -const RETRY_TYPES = [ - 'request-timeout', -] - -// make a request directly to the remote source, -// retrying certain classes of errors as well as -// following redirects (through the cache if necessary) -// and verifying response integrity -const remoteFetch = (request, options) => { - const agent = getAgent(request.url, options) - if (!request.headers.has('connection')) { - request.headers.set('connection', agent ? 'keep-alive' : 'close') - } - - if (!request.headers.has('user-agent')) { - request.headers.set('user-agent', USER_AGENT) - } - - // keep our own options since we're overriding the agent - // and the redirect mode - const _opts = { - ...options, - agent, - redirect: 'manual', - } - - return promiseRetry(async (retryHandler, attemptNum) => { - const req = new fetch.Request(request, _opts) - try { - let res = await fetch(req, _opts) - if (_opts.integrity && res.status === 200) { - // we got a 200 response and the user has specified an expected - // integrity value, so wrap the response in an ssri stream to verify it - const integrityStream = ssri.integrityStream({ - algorithms: _opts.algorithms, - integrity: _opts.integrity, - size: _opts.size, - }) - const pipeline = new CachingMinipassPipeline({ - events: ['integrity', 'size'], - }, res.body, integrityStream) - // we also propagate the integrity and size events out to the pipeline so we can use - // this new response body as an integrityEmitter for cacache - integrityStream.on('integrity', i => pipeline.emit('integrity', i)) - integrityStream.on('size', s => pipeline.emit('size', s)) - res = new fetch.Response(pipeline, res) - // set an explicit flag so we know if our response body will emit integrity and size - res.body.hasIntegrityEmitter = true - } - - res.headers.set('x-fetch-attempts', attemptNum) - - // do not retry POST requests, or requests with a streaming body - // do retry requests with a 408, 420, 429 or 500+ status in the response - const isStream = Minipass.isStream(req.body) - const isRetriable = req.method !== 'POST' && - !isStream && - ([408, 420, 429].includes(res.status) || res.status >= 500) - - if (isRetriable) { - if (typeof options.onRetry === 'function') { - options.onRetry(res) - } - - /* eslint-disable-next-line max-len */ - log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${res.status}`) - return retryHandler(res) - } - - return res - } catch (err) { - const code = (err.code === 'EPROMISERETRY') - ? err.retried.code - : err.code - - // err.retried will be the thing that was thrown from above - // if it's a response, we just got a bad status code and we - // can re-throw to allow the retry - const isRetryError = err.retried instanceof fetch.Response || - (RETRY_ERRORS.includes(code) && RETRY_TYPES.includes(err.type)) - - if (req.method === 'POST' || isRetryError) { - throw err - } - - if (typeof options.onRetry === 'function') { - options.onRetry(err) - } - - log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${err.code}`) - return retryHandler(err) - } - }, options.retry).catch((err) => { - // don't reject for http errors, just return them - if (err.status >= 400 && err.type !== 'system') { - return err - } - - throw err - }) -} - -module.exports = remoteFetch diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/package.json deleted file mode 100644 index 7adb4d1e7f971..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "name": "make-fetch-happen", - "version": "13.0.1", - "description": "Opinionated, caching, retrying fetch client", - "main": "lib/index.js", - "files": [ - "bin/", - "lib/" - ], - "scripts": { - "test": "tap", - "posttest": "npm run lint", - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "postlint": "template-oss-check", - "snap": "tap", - "template-oss-apply": "template-oss-apply --force" - }, - "repository": { - "type": "git", - "url": "https://github.com/npm/make-fetch-happen.git" - }, - "keywords": [ - "http", - "request", - "fetch", - "mean girls", - "caching", - "cache", - "subresource integrity" - ], - "author": "GitHub Inc.", - "license": "ISC", - "dependencies": { - "@npmcli/agent": "^2.0.0", - "cacache": "^18.0.0", - "http-cache-semantics": "^4.1.1", - "is-lambda": "^1.0.1", - "minipass": "^7.0.2", - "minipass-fetch": "^3.0.0", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "negotiator": "^0.6.3", - "proc-log": "^4.2.0", - "promise-retry": "^2.0.1", - "ssri": "^10.0.0" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.4", - "nock": "^13.2.4", - "safe-buffer": "^5.2.1", - "standard-version": "^9.3.2", - "tap": "^16.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "tap": { - "color": 1, - "files": "test/*.js", - "check-coverage": true, - "timeout": 60, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.4", - "publish": "true" - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/LICENSE deleted file mode 100644 index 19d1364a8ac08..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -This package contains code originally written by Isaac Z. Schlueter. -Used with permission. - -Copyright (c) Meryn Stol ("Author") -All rights reserved. - -The BSD License - -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. - -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/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/extract_description.js b/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/extract_description.js deleted file mode 100644 index 631966b5f29af..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/extract_description.js +++ /dev/null @@ -1,24 +0,0 @@ -module.exports = extractDescription - -// Extracts description from contents of a readme file in markdown format -function extractDescription (d) { - if (!d) { - return - } - if (d === 'ERROR: No README data found!') { - return - } - // the first block of text before the first heading - // that isn't the first line heading - d = d.trim().split('\n') - let s = 0 - while (d[s] && d[s].trim().match(/^(#|$)/)) { - s++ - } - const l = d.length - let e = s + 1 - while (e < l && d[e].trim()) { - e++ - } - return d.slice(s, e).join(' ').trim() -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/fixer.js b/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/fixer.js deleted file mode 100644 index 1c30cad65e6cb..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/fixer.js +++ /dev/null @@ -1,475 +0,0 @@ -var isValidSemver = require('semver/functions/valid') -var cleanSemver = require('semver/functions/clean') -var validateLicense = require('validate-npm-package-license') -var hostedGitInfo = require('hosted-git-info') -var moduleBuiltin = require('node:module') -var depTypes = ['dependencies', 'devDependencies', 'optionalDependencies'] -var extractDescription = require('./extract_description') -var url = require('url') -var typos = require('./typos.json') - -var isEmail = str => str.includes('@') && (str.indexOf('@') < str.lastIndexOf('.')) - -module.exports = { - // default warning function - warn: function () {}, - - fixRepositoryField: function (data) { - if (data.repositories) { - this.warn('repositories') - data.repository = data.repositories[0] - } - if (!data.repository) { - return this.warn('missingRepository') - } - if (typeof data.repository === 'string') { - data.repository = { - type: 'git', - url: data.repository, - } - } - var r = data.repository.url || '' - if (r) { - var hosted = hostedGitInfo.fromUrl(r) - if (hosted) { - r = data.repository.url - = hosted.getDefaultRepresentation() === 'shortcut' ? hosted.https() : hosted.toString() - } - } - - if (r.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)) { - this.warn('brokenGitUrl', r) - } - }, - - fixTypos: function (data) { - Object.keys(typos.topLevel).forEach(function (d) { - if (Object.prototype.hasOwnProperty.call(data, d)) { - this.warn('typo', d, typos.topLevel[d]) - } - }, this) - }, - - fixScriptsField: function (data) { - if (!data.scripts) { - return - } - if (typeof data.scripts !== 'object') { - this.warn('nonObjectScripts') - delete data.scripts - return - } - Object.keys(data.scripts).forEach(function (k) { - if (typeof data.scripts[k] !== 'string') { - this.warn('nonStringScript') - delete data.scripts[k] - } else if (typos.script[k] && !data.scripts[typos.script[k]]) { - this.warn('typo', k, typos.script[k], 'scripts') - } - }, this) - }, - - fixFilesField: function (data) { - var files = data.files - if (files && !Array.isArray(files)) { - this.warn('nonArrayFiles') - delete data.files - } else if (data.files) { - data.files = data.files.filter(function (file) { - if (!file || typeof file !== 'string') { - this.warn('invalidFilename', file) - return false - } else { - return true - } - }, this) - } - }, - - fixBinField: function (data) { - if (!data.bin) { - return - } - if (typeof data.bin === 'string') { - var b = {} - var match - if (match = data.name.match(/^@[^/]+[/](.*)$/)) { - b[match[1]] = data.bin - } else { - b[data.name] = data.bin - } - data.bin = b - } - }, - - fixManField: function (data) { - if (!data.man) { - return - } - if (typeof data.man === 'string') { - data.man = [data.man] - } - }, - fixBundleDependenciesField: function (data) { - var bdd = 'bundledDependencies' - var bd = 'bundleDependencies' - if (data[bdd] && !data[bd]) { - data[bd] = data[bdd] - delete data[bdd] - } - if (data[bd] && !Array.isArray(data[bd])) { - this.warn('nonArrayBundleDependencies') - delete data[bd] - } else if (data[bd]) { - data[bd] = data[bd].filter(function (filtered) { - if (!filtered || typeof filtered !== 'string') { - this.warn('nonStringBundleDependency', filtered) - return false - } else { - if (!data.dependencies) { - data.dependencies = {} - } - if (!Object.prototype.hasOwnProperty.call(data.dependencies, filtered)) { - this.warn('nonDependencyBundleDependency', filtered) - data.dependencies[filtered] = '*' - } - return true - } - }, this) - } - }, - - fixDependencies: function (data) { - objectifyDeps(data, this.warn) - addOptionalDepsToDeps(data, this.warn) - this.fixBundleDependenciesField(data) - - ;['dependencies', 'devDependencies'].forEach(function (deps) { - if (!(deps in data)) { - return - } - if (!data[deps] || typeof data[deps] !== 'object') { - this.warn('nonObjectDependencies', deps) - delete data[deps] - return - } - Object.keys(data[deps]).forEach(function (d) { - var r = data[deps][d] - if (typeof r !== 'string') { - this.warn('nonStringDependency', d, JSON.stringify(r)) - delete data[deps][d] - } - var hosted = hostedGitInfo.fromUrl(data[deps][d]) - if (hosted) { - data[deps][d] = hosted.toString() - } - }, this) - }, this) - }, - - fixModulesField: function (data) { - if (data.modules) { - this.warn('deprecatedModules') - delete data.modules - } - }, - - fixKeywordsField: function (data) { - if (typeof data.keywords === 'string') { - data.keywords = data.keywords.split(/,\s+/) - } - if (data.keywords && !Array.isArray(data.keywords)) { - delete data.keywords - this.warn('nonArrayKeywords') - } else if (data.keywords) { - data.keywords = data.keywords.filter(function (kw) { - if (typeof kw !== 'string' || !kw) { - this.warn('nonStringKeyword') - return false - } else { - return true - } - }, this) - } - }, - - fixVersionField: function (data, strict) { - // allow "loose" semver 1.0 versions in non-strict mode - // enforce strict semver 2.0 compliance in strict mode - var loose = !strict - if (!data.version) { - data.version = '' - return true - } - if (!isValidSemver(data.version, loose)) { - throw new Error('Invalid version: "' + data.version + '"') - } - data.version = cleanSemver(data.version, loose) - return true - }, - - fixPeople: function (data) { - modifyPeople(data, unParsePerson) - modifyPeople(data, parsePerson) - }, - - fixNameField: function (data, options) { - if (typeof options === 'boolean') { - options = { strict: options } - } else if (typeof options === 'undefined') { - options = {} - } - var strict = options.strict - if (!data.name && !strict) { - data.name = '' - return - } - if (typeof data.name !== 'string') { - throw new Error('name field must be a string.') - } - if (!strict) { - data.name = data.name.trim() - } - ensureValidName(data.name, strict, options.allowLegacyCase) - if (moduleBuiltin.builtinModules.includes(data.name)) { - this.warn('conflictingName', data.name) - } - }, - - fixDescriptionField: function (data) { - if (data.description && typeof data.description !== 'string') { - this.warn('nonStringDescription') - delete data.description - } - if (data.readme && !data.description) { - data.description = extractDescription(data.readme) - } - if (data.description === undefined) { - delete data.description - } - if (!data.description) { - this.warn('missingDescription') - } - }, - - fixReadmeField: function (data) { - if (!data.readme) { - this.warn('missingReadme') - data.readme = 'ERROR: No README data found!' - } - }, - - fixBugsField: function (data) { - if (!data.bugs && data.repository && data.repository.url) { - var hosted = hostedGitInfo.fromUrl(data.repository.url) - if (hosted && hosted.bugs()) { - data.bugs = { url: hosted.bugs() } - } - } else if (data.bugs) { - if (typeof data.bugs === 'string') { - if (isEmail(data.bugs)) { - data.bugs = { email: data.bugs } - /* eslint-disable-next-line node/no-deprecated-api */ - } else if (url.parse(data.bugs).protocol) { - data.bugs = { url: data.bugs } - } else { - this.warn('nonEmailUrlBugsString') - } - } else { - bugsTypos(data.bugs, this.warn) - var oldBugs = data.bugs - data.bugs = {} - if (oldBugs.url) { - /* eslint-disable-next-line node/no-deprecated-api */ - if (typeof (oldBugs.url) === 'string' && url.parse(oldBugs.url).protocol) { - data.bugs.url = oldBugs.url - } else { - this.warn('nonUrlBugsUrlField') - } - } - if (oldBugs.email) { - if (typeof (oldBugs.email) === 'string' && isEmail(oldBugs.email)) { - data.bugs.email = oldBugs.email - } else { - this.warn('nonEmailBugsEmailField') - } - } - } - if (!data.bugs.email && !data.bugs.url) { - delete data.bugs - this.warn('emptyNormalizedBugs') - } - } - }, - - fixHomepageField: function (data) { - if (!data.homepage && data.repository && data.repository.url) { - var hosted = hostedGitInfo.fromUrl(data.repository.url) - if (hosted && hosted.docs()) { - data.homepage = hosted.docs() - } - } - if (!data.homepage) { - return - } - - if (typeof data.homepage !== 'string') { - this.warn('nonUrlHomepage') - return delete data.homepage - } - /* eslint-disable-next-line node/no-deprecated-api */ - if (!url.parse(data.homepage).protocol) { - data.homepage = 'http://' + data.homepage - } - }, - - fixLicenseField: function (data) { - const license = data.license || data.licence - if (!license) { - return this.warn('missingLicense') - } - if ( - typeof (license) !== 'string' || - license.length < 1 || - license.trim() === '' - ) { - return this.warn('invalidLicense') - } - if (!validateLicense(license).validForNewPackages) { - return this.warn('invalidLicense') - } - }, -} - -function isValidScopedPackageName (spec) { - if (spec.charAt(0) !== '@') { - return false - } - - var rest = spec.slice(1).split('/') - if (rest.length !== 2) { - return false - } - - return rest[0] && rest[1] && - rest[0] === encodeURIComponent(rest[0]) && - rest[1] === encodeURIComponent(rest[1]) -} - -function isCorrectlyEncodedName (spec) { - return !spec.match(/[/@\s+%:]/) && - spec === encodeURIComponent(spec) -} - -function ensureValidName (name, strict, allowLegacyCase) { - if (name.charAt(0) === '.' || - !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) || - (strict && (!allowLegacyCase) && name !== name.toLowerCase()) || - name.toLowerCase() === 'node_modules' || - name.toLowerCase() === 'favicon.ico') { - throw new Error('Invalid name: ' + JSON.stringify(name)) - } -} - -function modifyPeople (data, fn) { - if (data.author) { - data.author = fn(data.author) - }['maintainers', 'contributors'].forEach(function (set) { - if (!Array.isArray(data[set])) { - return - } - data[set] = data[set].map(fn) - }) - return data -} - -function unParsePerson (person) { - if (typeof person === 'string') { - return person - } - var name = person.name || '' - var u = person.url || person.web - var wrappedUrl = u ? (' (' + u + ')') : '' - var e = person.email || person.mail - var wrappedEmail = e ? (' <' + e + '>') : '' - return name + wrappedEmail + wrappedUrl -} - -function parsePerson (person) { - if (typeof person !== 'string') { - return person - } - var matchedName = person.match(/^([^(<]+)/) - var matchedUrl = person.match(/\(([^()]+)\)/) - var matchedEmail = person.match(/<([^<>]+)>/) - var obj = {} - if (matchedName && matchedName[0].trim()) { - obj.name = matchedName[0].trim() - } - if (matchedEmail) { - obj.email = matchedEmail[1] - } - if (matchedUrl) { - obj.url = matchedUrl[1] - } - return obj -} - -function addOptionalDepsToDeps (data) { - var o = data.optionalDependencies - if (!o) { - return - } - var d = data.dependencies || {} - Object.keys(o).forEach(function (k) { - d[k] = o[k] - }) - data.dependencies = d -} - -function depObjectify (deps, type, warn) { - if (!deps) { - return {} - } - if (typeof deps === 'string') { - deps = deps.trim().split(/[\n\r\s\t ,]+/) - } - if (!Array.isArray(deps)) { - return deps - } - warn('deprecatedArrayDependencies', type) - var o = {} - deps.filter(function (d) { - return typeof d === 'string' - }).forEach(function (d) { - d = d.trim().split(/(:?[@\s><=])/) - var dn = d.shift() - var dv = d.join('') - dv = dv.trim() - dv = dv.replace(/^@/, '') - o[dn] = dv - }) - return o -} - -function objectifyDeps (data, warn) { - depTypes.forEach(function (type) { - if (!data[type]) { - return - } - data[type] = depObjectify(data[type], type, warn) - }) -} - -function bugsTypos (bugs, warn) { - if (!bugs) { - return - } - Object.keys(bugs).forEach(function (k) { - if (typos.bugs[k]) { - warn('typo', k, typos.bugs[k], 'bugs') - bugs[typos.bugs[k]] = bugs[k] - delete bugs[k] - } - }) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/make_warning.js b/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/make_warning.js deleted file mode 100644 index 3be9c86539952..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/make_warning.js +++ /dev/null @@ -1,22 +0,0 @@ -var util = require('util') -var messages = require('./warning_messages.json') - -module.exports = function () { - var args = Array.prototype.slice.call(arguments, 0) - var warningName = args.shift() - if (warningName === 'typo') { - return makeTypoWarning.apply(null, args) - } else { - var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'" - args.unshift(msgTemplate) - return util.format.apply(null, args) - } -} - -function makeTypoWarning (providedName, probableName, field) { - if (field) { - providedName = field + "['" + providedName + "']" - probableName = field + "['" + probableName + "']" - } - return util.format(messages.typo, providedName, probableName) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/normalize.js b/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/normalize.js deleted file mode 100644 index e806f110315aa..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/normalize.js +++ /dev/null @@ -1,48 +0,0 @@ -module.exports = normalize - -var fixer = require('./fixer') -normalize.fixer = fixer - -var makeWarning = require('./make_warning') - -var fieldsToFix = ['name', 'version', 'description', 'repository', 'modules', 'scripts', - 'files', 'bin', 'man', 'bugs', 'keywords', 'readme', 'homepage', 'license'] -var otherThingsToFix = ['dependencies', 'people', 'typos'] - -var thingsToFix = fieldsToFix.map(function (fieldName) { - return ucFirst(fieldName) + 'Field' -}) -// two ways to do this in CoffeeScript on only one line, sub-70 chars: -// thingsToFix = fieldsToFix.map (name) -> ucFirst(name) + "Field" -// thingsToFix = (ucFirst(name) + "Field" for name in fieldsToFix) -thingsToFix = thingsToFix.concat(otherThingsToFix) - -function normalize (data, warn, strict) { - if (warn === true) { - warn = null - strict = true - } - if (!strict) { - strict = false - } - if (!warn || data.private) { - warn = function () { /* noop */ } - } - - if (data.scripts && - data.scripts.install === 'node-gyp rebuild' && - !data.scripts.preinstall) { - data.gypfile = true - } - fixer.warn = function () { - warn(makeWarning.apply(null, arguments)) - } - thingsToFix.forEach(function (thingName) { - fixer['fix' + ucFirst(thingName)](data, strict) - }) - data._id = data.name + '@' + data.version -} - -function ucFirst (string) { - return string.charAt(0).toUpperCase() + string.slice(1) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/safe_format.js b/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/safe_format.js deleted file mode 100644 index 5fc888e5450cd..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/safe_format.js +++ /dev/null @@ -1,11 +0,0 @@ -var util = require('util') - -module.exports = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.forEach(function (arg) { - if (!arg) { - throw new TypeError('Bad arguments.') - } - }) - return util.format.apply(null, arguments) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/typos.json b/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/typos.json deleted file mode 100644 index 7f9dd283b30ff..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/typos.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "topLevel": { - "dependancies": "dependencies" - ,"dependecies": "dependencies" - ,"depdenencies": "dependencies" - ,"devEependencies": "devDependencies" - ,"depends": "dependencies" - ,"dev-dependencies": "devDependencies" - ,"devDependences": "devDependencies" - ,"devDepenencies": "devDependencies" - ,"devdependencies": "devDependencies" - ,"repostitory": "repository" - ,"repo": "repository" - ,"prefereGlobal": "preferGlobal" - ,"hompage": "homepage" - ,"hampage": "homepage" - ,"autohr": "author" - ,"autor": "author" - ,"contributers": "contributors" - ,"publicationConfig": "publishConfig" - ,"script": "scripts" - }, - "bugs": { "web": "url", "name": "url" }, - "script": { "server": "start", "tests": "test" } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/warning_messages.json b/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/warning_messages.json deleted file mode 100644 index 4890f506ed965..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/lib/warning_messages.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "repositories": "'repositories' (plural) Not supported. Please pick one as the 'repository' field" - ,"missingRepository": "No repository field." - ,"brokenGitUrl": "Probably broken git url: %s" - ,"nonObjectScripts": "scripts must be an object" - ,"nonStringScript": "script values must be string commands" - ,"nonArrayFiles": "Invalid 'files' member" - ,"invalidFilename": "Invalid filename in 'files' list: %s" - ,"nonArrayBundleDependencies": "Invalid 'bundleDependencies' list. Must be array of package names" - ,"nonStringBundleDependency": "Invalid bundleDependencies member: %s" - ,"nonDependencyBundleDependency": "Non-dependency in bundleDependencies: %s" - ,"nonObjectDependencies": "%s field must be an object" - ,"nonStringDependency": "Invalid dependency: %s %s" - ,"deprecatedArrayDependencies": "specifying %s as array is deprecated" - ,"deprecatedModules": "modules field is deprecated" - ,"nonArrayKeywords": "keywords should be an array of strings" - ,"nonStringKeyword": "keywords should be an array of strings" - ,"conflictingName": "%s is also the name of a node core module." - ,"nonStringDescription": "'description' field should be a string" - ,"missingDescription": "No description" - ,"missingReadme": "No README data" - ,"missingLicense": "No license field." - ,"nonEmailUrlBugsString": "Bug string field must be url, email, or {email,url}" - ,"nonUrlBugsUrlField": "bugs.url field must be a string url. Deleted." - ,"nonEmailBugsEmailField": "bugs.email field must be a string email. Deleted." - ,"emptyNormalizedBugs": "Normalized value of bugs field is an empty object. Deleted." - ,"nonUrlHomepage": "homepage field must be a string url. Deleted." - ,"invalidLicense": "license should be a valid SPDX license expression" - ,"typo": "%s should probably be %s." -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/package.json deleted file mode 100644 index 04a7647abe65c..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "normalize-package-data", - "version": "6.0.2", - "author": "GitHub Inc.", - "description": "Normalizes data that can be found in package.json files.", - "license": "BSD-2-Clause", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/normalize-package-data.git" - }, - "main": "lib/normalize.js", - "scripts": { - "test": "tap", - "npmclilint": "npmcli-lint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint", - "postsnap": "npm run lintfix --", - "postlint": "template-oss-check", - "snap": "tap", - "template-oss-apply": "template-oss-apply --force" - }, - "dependencies": { - "hosted-git-info": "^7.0.0", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" - }, - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" - }, - "tap": { - "branches": 86, - "functions": 92, - "lines": 86, - "statements": 86, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled/LICENSE deleted file mode 100644 index 20a4762540923..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) npm, Inc. and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled/lib/index.js deleted file mode 100644 index f5ee0bb3ea765..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled/lib/index.js +++ /dev/null @@ -1,254 +0,0 @@ -'use strict' - -// walk the tree of deps starting from the top level list of bundled deps -// Any deps at the top level that are depended on by a bundled dep that -// does not have that dep in its own node_modules folder are considered -// bundled deps as well. This list of names can be passed to npm-packlist -// as the "bundled" argument. Additionally, packageJsonCache is shared so -// packlist doesn't have to re-read files already consumed in this pass - -const fs = require('fs') -const path = require('path') -const EE = require('events').EventEmitter -// we don't care about the package bins, but we share a pj cache -// with other modules that DO care about it, so keep it nice. -const normalizePackageBin = require('npm-normalize-package-bin') - -class BundleWalker extends EE { - constructor (opt) { - opt = opt || {} - super(opt) - this.path = path.resolve(opt.path || process.cwd()) - - this.parent = opt.parent || null - if (this.parent) { - this.result = this.parent.result - // only collect results in node_modules folders at the top level - // since the node_modules in a bundled dep is included always - if (!this.parent.parent) { - const base = path.basename(this.path) - const scope = path.basename(path.dirname(this.path)) - this.result.add(/^@/.test(scope) ? scope + '/' + base : base) - } - this.root = this.parent.root - this.packageJsonCache = this.parent.packageJsonCache - } else { - this.result = new Set() - this.root = this.path - this.packageJsonCache = opt.packageJsonCache || new Map() - } - - this.seen = new Set() - this.didDone = false - this.children = 0 - this.node_modules = [] - this.package = null - this.bundle = null - } - - addListener (ev, fn) { - return this.on(ev, fn) - } - - on (ev, fn) { - const ret = super.on(ev, fn) - if (ev === 'done' && this.didDone) { - this.emit('done', this.result) - } - return ret - } - - done () { - if (!this.didDone) { - this.didDone = true - if (!this.parent) { - const res = Array.from(this.result) - this.result = res - this.emit('done', res) - } else { - this.emit('done') - } - } - } - - start () { - const pj = path.resolve(this.path, 'package.json') - if (this.packageJsonCache.has(pj)) { - this.onPackage(this.packageJsonCache.get(pj)) - } else { - this.readPackageJson(pj) - } - return this - } - - readPackageJson (pj) { - fs.readFile(pj, (er, data) => - er ? this.done() : this.onPackageJson(pj, data)) - } - - onPackageJson (pj, data) { - try { - this.package = normalizePackageBin(JSON.parse(data + '')) - } catch (er) { - return this.done() - } - this.packageJsonCache.set(pj, this.package) - this.onPackage(this.package) - } - - allDepsBundled (pkg) { - return Object.keys(pkg.dependencies || {}).concat( - Object.keys(pkg.optionalDependencies || {})) - } - - onPackage (pkg) { - // all deps are bundled if we got here as a child. - // otherwise, only bundle bundledDeps - // Get a unique-ified array with a short-lived Set - const bdRaw = this.parent ? this.allDepsBundled(pkg) - : pkg.bundleDependencies || pkg.bundledDependencies || [] - - const bd = Array.from(new Set( - Array.isArray(bdRaw) ? bdRaw - : bdRaw === true ? this.allDepsBundled(pkg) - : Object.keys(bdRaw))) - - if (!bd.length) { - return this.done() - } - - this.bundle = bd - this.readModules() - } - - readModules () { - readdirNodeModules(this.path + '/node_modules', (er, nm) => - er ? this.onReaddir([]) : this.onReaddir(nm)) - } - - onReaddir (nm) { - // keep track of what we have, in case children need it - this.node_modules = nm - - this.bundle.forEach(dep => this.childDep(dep)) - if (this.children === 0) { - this.done() - } - } - - childDep (dep) { - if (this.node_modules.indexOf(dep) !== -1) { - if (!this.seen.has(dep)) { - this.seen.add(dep) - this.child(dep) - } - } else if (this.parent) { - this.parent.childDep(dep) - } - } - - child (dep) { - const p = this.path + '/node_modules/' + dep - this.children += 1 - const child = new BundleWalker({ - path: p, - parent: this, - }) - child.on('done', () => { - if (--this.children === 0) { - this.done() - } - }) - child.start() - } -} - -class BundleWalkerSync extends BundleWalker { - start () { - super.start() - this.done() - return this - } - - readPackageJson (pj) { - try { - this.onPackageJson(pj, fs.readFileSync(pj)) - } catch { - // empty catch - } - return this - } - - readModules () { - try { - this.onReaddir(readdirNodeModulesSync(this.path + '/node_modules')) - } catch { - this.onReaddir([]) - } - } - - child (dep) { - new BundleWalkerSync({ - path: this.path + '/node_modules/' + dep, - parent: this, - }).start() - } -} - -const readdirNodeModules = (nm, cb) => { - fs.readdir(nm, (er, set) => { - if (er) { - cb(er) - } else { - const scopes = set.filter(f => /^@/.test(f)) - if (!scopes.length) { - cb(null, set) - } else { - const unscoped = set.filter(f => !/^@/.test(f)) - let count = scopes.length - scopes.forEach(scope => { - fs.readdir(nm + '/' + scope, (readdirEr, pkgs) => { - if (readdirEr || !pkgs.length) { - unscoped.push(scope) - } else { - unscoped.push.apply(unscoped, pkgs.map(p => scope + '/' + p)) - } - if (--count === 0) { - cb(null, unscoped) - } - }) - }) - } - } - }) -} - -const readdirNodeModulesSync = nm => { - const set = fs.readdirSync(nm) - const unscoped = set.filter(f => !/^@/.test(f)) - const scopes = set.filter(f => /^@/.test(f)).map(scope => { - try { - const pkgs = fs.readdirSync(nm + '/' + scope) - return pkgs.length ? pkgs.map(p => scope + '/' + p) : [scope] - } catch (er) { - return [scope] - } - }).reduce((a, b) => a.concat(b), []) - return unscoped.concat(scopes) -} - -const walk = (options, callback) => { - const p = new Promise((resolve, reject) => { - new BundleWalker(options).on('done', resolve).on('error', reject).start() - }) - return callback ? p.then(res => callback(null, res), callback) : p -} - -const walkSync = options => { - return new BundleWalkerSync(options).start().result -} - -module.exports = walk -walk.sync = walkSync -walk.BundleWalker = BundleWalker -walk.BundleWalkerSync = BundleWalkerSync diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled/package.json deleted file mode 100644 index 2744ca6af67fc..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "npm-bundled", - "version": "3.0.1", - "description": "list things in node_modules that are bundledDependencies, or transitive dependencies thereof", - "main": "lib/index.js", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/npm-bundled.git" - }, - "author": "GitHub Inc.", - "license": "ISC", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "mutate-fs": "^2.1.1", - "tap": "^16.3.0" - }, - "scripts": { - "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" - }, - "files": [ - "bin/", - "lib/" - ], - "dependencies": { - "npm-normalize-package-bin": "^3.0.0" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-install-checks/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-install-checks/LICENSE deleted file mode 100644 index 3bed8320c15b2..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-install-checks/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) Robert Kowalski and Isaac Z. Schlueter ("Authors") -All rights reserved. - -The BSD License - -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. - -THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS 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/@npmcli/metavuln-calculator/node_modules/npm-install-checks/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-install-checks/lib/index.js deleted file mode 100644 index 545472b61dc60..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-install-checks/lib/index.js +++ /dev/null @@ -1,101 +0,0 @@ -const semver = require('semver') - -const checkEngine = (target, npmVer, nodeVer, force = false) => { - const nodev = force ? null : nodeVer - const eng = target.engines - const opt = { includePrerelease: true } - if (!eng) { - return - } - - const nodeFail = nodev && eng.node && !semver.satisfies(nodev, eng.node, opt) - const npmFail = npmVer && eng.npm && !semver.satisfies(npmVer, eng.npm, opt) - if (nodeFail || npmFail) { - throw Object.assign(new Error('Unsupported engine'), { - pkgid: target._id, - current: { node: nodeVer, npm: npmVer }, - required: eng, - code: 'EBADENGINE', - }) - } -} - -const isMusl = (file) => file.includes('libc.musl-') || file.includes('ld-musl-') - -const checkPlatform = (target, force = false, environment = {}) => { - if (force) { - return - } - - const platform = environment.os || process.platform - const arch = environment.cpu || process.arch - const osOk = target.os ? checkList(platform, target.os) : true - const cpuOk = target.cpu ? checkList(arch, target.cpu) : true - - let libcOk = true - let libcFamily = null - if (target.libc) { - // libc checks only work in linux, any value is a failure if we aren't - if (environment.libc) { - libcOk = checkList(environment.libc, target.libc) - } else if (platform !== 'linux') { - libcOk = false - } else { - const report = process.report.getReport() - if (report.header?.glibcVersionRuntime) { - libcFamily = 'glibc' - } else if (Array.isArray(report.sharedObjects) && report.sharedObjects.some(isMusl)) { - libcFamily = 'musl' - } - libcOk = libcFamily ? checkList(libcFamily, target.libc) : false - } - } - - if (!osOk || !cpuOk || !libcOk) { - throw Object.assign(new Error('Unsupported platform'), { - pkgid: target._id, - current: { - os: platform, - cpu: arch, - libc: libcFamily, - }, - required: { - os: target.os, - cpu: target.cpu, - libc: target.libc, - }, - code: 'EBADPLATFORM', - }) - } -} - -const checkList = (value, list) => { - if (typeof list === 'string') { - list = [list] - } - if (list.length === 1 && list[0] === 'any') { - return true - } - // match none of the negated values, and at least one of the - // non-negated values, if any are present. - let negated = 0 - let match = false - for (const entry of list) { - const negate = entry.charAt(0) === '!' - const test = negate ? entry.slice(1) : entry - if (negate) { - negated++ - if (value === test) { - return false - } - } else { - match = match || value === test - } - } - return match || negated === list.length -} - -module.exports = { - checkEngine, - checkPlatform, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-install-checks/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-install-checks/package.json deleted file mode 100644 index 11a3b87750e25..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-install-checks/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "npm-install-checks", - "version": "6.3.0", - "description": "Check the engines and platform fields in package.json", - "main": "lib/index.js", - "dependencies": { - "semver": "^7.1.1" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.19.0", - "tap": "^16.0.1" - }, - "scripts": { - "test": "tap", - "lint": "eslint \"**/*.js\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" - }, - "repository": { - "type": "git", - "url": "https://github.com/npm/npm-install-checks.git" - }, - "keywords": [ - "npm,", - "install" - ], - "license": "BSD-2-Clause", - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "author": "GitHub Inc.", - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.19.0", - "publish": "true" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg/LICENSE deleted file mode 100644 index 19cec97b18468..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) npm, Inc. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg/lib/npa.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg/lib/npa.js deleted file mode 100644 index 8094b3e732cd9..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg/lib/npa.js +++ /dev/null @@ -1,415 +0,0 @@ -'use strict' -module.exports = npa -module.exports.resolve = resolve -module.exports.toPurl = toPurl -module.exports.Result = Result - -const { URL } = require('url') -const HostedGit = require('hosted-git-info') -const semver = require('semver') -const path = global.FAKE_WINDOWS ? require('path').win32 : require('path') -const validatePackageName = require('validate-npm-package-name') -const { homedir } = require('os') -const { log } = require('proc-log') - -const isWindows = process.platform === 'win32' || global.FAKE_WINDOWS -const hasSlashes = isWindows ? /\\|[/]/ : /[/]/ -const isURL = /^(?:git[+])?[a-z]+:/i -const isGit = /^[^@]+@[^:.]+\.[^:]+:.+$/i -const isFilename = /[.](?:tgz|tar.gz|tar)$/i - -function npa (arg, where) { - let name - let spec - if (typeof arg === 'object') { - if (arg instanceof Result && (!where || where === arg.where)) { - return arg - } else if (arg.name && arg.rawSpec) { - return npa.resolve(arg.name, arg.rawSpec, where || arg.where) - } else { - return npa(arg.raw, where || arg.where) - } - } - const nameEndsAt = arg[0] === '@' ? arg.slice(1).indexOf('@') + 1 : arg.indexOf('@') - const namePart = nameEndsAt > 0 ? arg.slice(0, nameEndsAt) : arg - if (isURL.test(arg)) { - spec = arg - } else if (isGit.test(arg)) { - spec = `git+ssh://${arg}` - } else if (namePart[0] !== '@' && (hasSlashes.test(namePart) || isFilename.test(namePart))) { - spec = arg - } else if (nameEndsAt > 0) { - name = namePart - spec = arg.slice(nameEndsAt + 1) || '*' - } else { - const valid = validatePackageName(arg) - if (valid.validForOldPackages) { - name = arg - spec = '*' - } else { - spec = arg - } - } - return resolve(name, spec, where, arg) -} - -const isFilespec = isWindows ? /^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/ : /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/ - -function resolve (name, spec, where, arg) { - const res = new Result({ - raw: arg, - name: name, - rawSpec: spec, - fromArgument: arg != null, - }) - - if (name) { - res.setName(name) - } - - if (spec && (isFilespec.test(spec) || /^file:/i.test(spec))) { - return fromFile(res, where) - } else if (spec && /^npm:/i.test(spec)) { - return fromAlias(res, where) - } - - const hosted = HostedGit.fromUrl(spec, { - noGitPlus: true, - noCommittish: true, - }) - if (hosted) { - return fromHostedGit(res, hosted) - } else if (spec && isURL.test(spec)) { - return fromURL(res) - } else if (spec && (hasSlashes.test(spec) || isFilename.test(spec))) { - return fromFile(res, where) - } else { - return fromRegistry(res) - } -} - -const defaultRegistry = 'https://registry.npmjs.org' - -function toPurl (arg, reg = defaultRegistry) { - const res = npa(arg) - - if (res.type !== 'version') { - throw invalidPurlType(res.type, res.raw) - } - - // URI-encode leading @ of scoped packages - let purl = 'pkg:npm/' + res.name.replace(/^@/, '%40') + '@' + res.rawSpec - if (reg !== defaultRegistry) { - purl += '?repository_url=' + reg - } - - return purl -} - -function invalidPackageName (name, valid, raw) { - // eslint-disable-next-line max-len - const err = new Error(`Invalid package name "${name}" of package "${raw}": ${valid.errors.join('; ')}.`) - err.code = 'EINVALIDPACKAGENAME' - return err -} - -function invalidTagName (name, raw) { - // eslint-disable-next-line max-len - const err = new Error(`Invalid tag name "${name}" of package "${raw}": Tags may not have any characters that encodeURIComponent encodes.`) - err.code = 'EINVALIDTAGNAME' - return err -} - -function invalidPurlType (type, raw) { - // eslint-disable-next-line max-len - const err = new Error(`Invalid type "${type}" of package "${raw}": Purl can only be generated for "version" types.`) - err.code = 'EINVALIDPURLTYPE' - return err -} - -function Result (opts) { - this.type = opts.type - this.registry = opts.registry - this.where = opts.where - if (opts.raw == null) { - this.raw = opts.name ? opts.name + '@' + opts.rawSpec : opts.rawSpec - } else { - this.raw = opts.raw - } - - this.name = undefined - this.escapedName = undefined - this.scope = undefined - this.rawSpec = opts.rawSpec || '' - this.saveSpec = opts.saveSpec - this.fetchSpec = opts.fetchSpec - if (opts.name) { - this.setName(opts.name) - } - this.gitRange = opts.gitRange - this.gitCommittish = opts.gitCommittish - this.gitSubdir = opts.gitSubdir - this.hosted = opts.hosted -} - -Result.prototype.setName = function (name) { - const valid = validatePackageName(name) - if (!valid.validForOldPackages) { - throw invalidPackageName(name, valid, this.raw) - } - - this.name = name - this.scope = name[0] === '@' ? name.slice(0, name.indexOf('/')) : undefined - // scoped packages in couch must have slash url-encoded, e.g. @foo%2Fbar - this.escapedName = name.replace('/', '%2f') - return this -} - -Result.prototype.toString = function () { - const full = [] - if (this.name != null && this.name !== '') { - full.push(this.name) - } - const spec = this.saveSpec || this.fetchSpec || this.rawSpec - if (spec != null && spec !== '') { - full.push(spec) - } - return full.length ? full.join('@') : this.raw -} - -Result.prototype.toJSON = function () { - const result = Object.assign({}, this) - delete result.hosted - return result -} - -// sets res.gitCommittish, res.gitRange, and res.gitSubdir -function setGitAttrs (res, committish) { - if (!committish) { - res.gitCommittish = null - return - } - - // for each :: separated item: - for (const part of committish.split('::')) { - // if the item has no : the n it is a commit-ish - if (!part.includes(':')) { - if (res.gitRange) { - throw new Error('cannot override existing semver range with a committish') - } - if (res.gitCommittish) { - throw new Error('cannot override existing committish with a second committish') - } - res.gitCommittish = part - continue - } - // split on name:value - const [name, value] = part.split(':') - // if name is semver do semver lookup of ref or tag - if (name === 'semver') { - if (res.gitCommittish) { - throw new Error('cannot override existing committish with a semver range') - } - if (res.gitRange) { - throw new Error('cannot override existing semver range with a second semver range') - } - res.gitRange = decodeURIComponent(value) - continue - } - if (name === 'path') { - if (res.gitSubdir) { - throw new Error('cannot override existing path with a second path') - } - res.gitSubdir = `/${value}` - continue - } - log.warn('npm-package-arg', `ignoring unknown key "${name}"`) - } -} - -function fromFile (res, where) { - if (!where) { - where = process.cwd() - } - res.type = isFilename.test(res.rawSpec) ? 'file' : 'directory' - res.where = where - - // always put the '/' on where when resolving urls, or else - // file:foo from /path/to/bar goes to /path/to/foo, when we want - // it to be /path/to/bar/foo - - let specUrl - let resolvedUrl - const prefix = (!/^file:/.test(res.rawSpec) ? 'file:' : '') - const rawWithPrefix = prefix + res.rawSpec - let rawNoPrefix = rawWithPrefix.replace(/^file:/, '') - try { - resolvedUrl = new URL(rawWithPrefix, `file://${path.resolve(where)}/`) - specUrl = new URL(rawWithPrefix) - } catch (originalError) { - const er = new Error('Invalid file: URL, must comply with RFC 8089') - throw Object.assign(er, { - raw: res.rawSpec, - spec: res, - where, - originalError, - }) - } - - // XXX backwards compatibility lack of compliance with RFC 8089 - if (resolvedUrl.host && resolvedUrl.host !== 'localhost') { - const rawSpec = res.rawSpec.replace(/^file:\/\//, 'file:///') - resolvedUrl = new URL(rawSpec, `file://${path.resolve(where)}/`) - specUrl = new URL(rawSpec) - rawNoPrefix = rawSpec.replace(/^file:/, '') - } - // turn file:/../foo into file:../foo - // for 1, 2 or 3 leading slashes since we attempted - // in the previous step to make it a file protocol url with a leading slash - if (/^\/{1,3}\.\.?(\/|$)/.test(rawNoPrefix)) { - const rawSpec = res.rawSpec.replace(/^file:\/{1,3}/, 'file:') - resolvedUrl = new URL(rawSpec, `file://${path.resolve(where)}/`) - specUrl = new URL(rawSpec) - rawNoPrefix = rawSpec.replace(/^file:/, '') - } - // XXX end RFC 8089 violation backwards compatibility section - - // turn /C:/blah into just C:/blah on windows - let specPath = decodeURIComponent(specUrl.pathname) - let resolvedPath = decodeURIComponent(resolvedUrl.pathname) - if (isWindows) { - specPath = specPath.replace(/^\/+([a-z]:\/)/i, '$1') - resolvedPath = resolvedPath.replace(/^\/+([a-z]:\/)/i, '$1') - } - - // replace ~ with homedir, but keep the ~ in the saveSpec - // otherwise, make it relative to where param - if (/^\/~(\/|$)/.test(specPath)) { - res.saveSpec = `file:${specPath.substr(1)}` - resolvedPath = path.resolve(homedir(), specPath.substr(3)) - } else if (!path.isAbsolute(rawNoPrefix)) { - res.saveSpec = `file:${path.relative(where, resolvedPath)}` - } else { - res.saveSpec = `file:${path.resolve(resolvedPath)}` - } - - res.fetchSpec = path.resolve(where, resolvedPath) - return res -} - -function fromHostedGit (res, hosted) { - res.type = 'git' - res.hosted = hosted - res.saveSpec = hosted.toString({ noGitPlus: false, noCommittish: false }) - res.fetchSpec = hosted.getDefaultRepresentation() === 'shortcut' ? null : hosted.toString() - setGitAttrs(res, hosted.committish) - return res -} - -function unsupportedURLType (protocol, spec) { - const err = new Error(`Unsupported URL Type "${protocol}": ${spec}`) - err.code = 'EUNSUPPORTEDPROTOCOL' - return err -} - -function fromURL (res) { - let rawSpec = res.rawSpec - res.saveSpec = rawSpec - if (rawSpec.startsWith('git+ssh:')) { - // git ssh specifiers are overloaded to also use scp-style git - // specifiers, so we have to parse those out and treat them special. - // They are NOT true URIs, so we can't hand them to URL. - - // This regex looks for things that look like: - // git+ssh://git@my.custom.git.com:username/project.git#deadbeef - // ...and various combinations. The username in the beginning is *required*. - const matched = rawSpec.match(/^git\+ssh:\/\/([^:#]+:[^#]+(?:\.git)?)(?:#(.*))?$/i) - if (matched && !matched[1].match(/:[0-9]+\/?.*$/i)) { - res.type = 'git' - setGitAttrs(res, matched[2]) - res.fetchSpec = matched[1] - return res - } - } else if (rawSpec.startsWith('git+file://')) { - // URL can't handle windows paths - rawSpec = rawSpec.replace(/\\/g, '/') - } - const parsedUrl = new URL(rawSpec) - // check the protocol, and then see if it's git or not - switch (parsedUrl.protocol) { - case 'git:': - case 'git+http:': - case 'git+https:': - case 'git+rsync:': - case 'git+ftp:': - case 'git+file:': - case 'git+ssh:': - res.type = 'git' - setGitAttrs(res, parsedUrl.hash.slice(1)) - if (parsedUrl.protocol === 'git+file:' && /^git\+file:\/\/[a-z]:/i.test(rawSpec)) { - // URL can't handle drive letters on windows file paths, the host can't contain a : - res.fetchSpec = `git+file://${parsedUrl.host.toLowerCase()}:${parsedUrl.pathname}` - } else { - parsedUrl.hash = '' - res.fetchSpec = parsedUrl.toString() - } - if (res.fetchSpec.startsWith('git+')) { - res.fetchSpec = res.fetchSpec.slice(4) - } - break - case 'http:': - case 'https:': - res.type = 'remote' - res.fetchSpec = res.saveSpec - break - - default: - throw unsupportedURLType(parsedUrl.protocol, rawSpec) - } - - return res -} - -function fromAlias (res, where) { - const subSpec = npa(res.rawSpec.substr(4), where) - if (subSpec.type === 'alias') { - throw new Error('nested aliases not supported') - } - - if (!subSpec.registry) { - throw new Error('aliases only work for registry deps') - } - - if (!subSpec.name) { - throw new Error('aliases must have a name') - } - - res.subSpec = subSpec - res.registry = true - res.type = 'alias' - res.saveSpec = null - res.fetchSpec = null - return res -} - -function fromRegistry (res) { - res.registry = true - const spec = res.rawSpec.trim() - // no save spec for registry components as we save based on the fetched - // version, not on the argument so this can't compute that. - res.saveSpec = null - res.fetchSpec = spec - const version = semver.valid(spec, true) - const range = semver.validRange(spec, true) - if (version) { - res.type = 'version' - } else if (range) { - res.type = 'range' - } else { - if (encodeURIComponent(spec) !== spec) { - throw invalidTagName(spec, res.raw) - } - res.type = 'tag' - } - return res -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg/package.json deleted file mode 100644 index d3f6fd7cf0a05..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "name": "npm-package-arg", - "version": "11.0.3", - "description": "Parse the things that can be arguments to `npm install`", - "main": "./lib/npa.js", - "directories": { - "test": "test" - }, - "files": [ - "bin/", - "lib/" - ], - "dependencies": { - "hosted-git-info": "^7.0.0", - "proc-log": "^4.0.0", - "semver": "^7.3.5", - "validate-npm-package-name": "^5.0.0" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.23.1", - "tap": "^16.0.1" - }, - "scripts": { - "test": "tap", - "snap": "tap", - "npmclilint": "npmcli-lint", - "lint": "npm run eslint", - "lintfix": "npm run eslint -- --fix", - "posttest": "npm run lint", - "postsnap": "npm run lintfix --", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/npm-package-arg.git" - }, - "author": "GitHub Inc.", - "license": "ISC", - "bugs": { - "url": "https://github.com/npm/npm-package-arg/issues" - }, - "homepage": "https://github.com/npm/npm-package-arg", - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "tap": { - "branches": 97, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.23.1", - "publish": true - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest/LICENSE.md b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest/LICENSE.md deleted file mode 100644 index 8d28acf866d93..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest/LICENSE.md +++ /dev/null @@ -1,16 +0,0 @@ -ISC License - -Copyright (c) npm, Inc. - -Permission to use, copy, modify, and/or distribute this software for -any purpose with or without fee is hereby granted, provided that the -above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS -ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR -CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE -USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest/lib/index.js deleted file mode 100644 index 82807971844bf..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest/lib/index.js +++ /dev/null @@ -1,224 +0,0 @@ -'use strict' - -const npa = require('npm-package-arg') -const semver = require('semver') -const { checkEngine } = require('npm-install-checks') -const normalizeBin = require('npm-normalize-package-bin') - -const engineOk = (manifest, npmVersion, nodeVersion) => { - try { - checkEngine(manifest, npmVersion, nodeVersion) - return true - } catch (_) { - return false - } -} - -const isBefore = (verTimes, ver, time) => - !verTimes || !verTimes[ver] || Date.parse(verTimes[ver]) <= time - -const avoidSemverOpt = { includePrerelease: true, loose: true } -const shouldAvoid = (ver, avoid) => - avoid && semver.satisfies(ver, avoid, avoidSemverOpt) - -const decorateAvoid = (result, avoid) => - result && shouldAvoid(result.version, avoid) - ? { ...result, _shouldAvoid: true } - : result - -const pickManifest = (packument, wanted, opts) => { - const { - defaultTag = 'latest', - before = null, - nodeVersion = process.version, - npmVersion = null, - includeStaged = false, - avoid = null, - avoidStrict = false, - } = opts - - const { name, time: verTimes } = packument - const versions = packument.versions || {} - - if (avoidStrict) { - const looseOpts = { - ...opts, - avoidStrict: false, - } - - const result = pickManifest(packument, wanted, looseOpts) - if (!result || !result._shouldAvoid) { - return result - } - - const caret = pickManifest(packument, `^${result.version}`, looseOpts) - if (!caret || !caret._shouldAvoid) { - return { - ...caret, - _outsideDependencyRange: true, - _isSemVerMajor: false, - } - } - - const star = pickManifest(packument, '*', looseOpts) - if (!star || !star._shouldAvoid) { - return { - ...star, - _outsideDependencyRange: true, - _isSemVerMajor: true, - } - } - - throw Object.assign(new Error(`No avoidable versions for ${name}`), { - code: 'ETARGET', - name, - wanted, - avoid, - before, - versions: Object.keys(versions), - }) - } - - const staged = (includeStaged && packument.stagedVersions && - packument.stagedVersions.versions) || {} - const restricted = (packument.policyRestrictions && - packument.policyRestrictions.versions) || {} - - const time = before && verTimes ? +(new Date(before)) : Infinity - const spec = npa.resolve(name, wanted || defaultTag) - const type = spec.type - const distTags = packument['dist-tags'] || {} - - if (type !== 'tag' && type !== 'version' && type !== 'range') { - throw new Error('Only tag, version, and range are supported') - } - - // if the type is 'tag', and not just the implicit default, then it must - // be that exactly, or nothing else will do. - if (wanted && type === 'tag') { - const ver = distTags[wanted] - // if the version in the dist-tags is before the before date, then - // we use that. Otherwise, we get the highest precedence version - // prior to the dist-tag. - if (isBefore(verTimes, ver, time)) { - return decorateAvoid(versions[ver] || staged[ver] || restricted[ver], avoid) - } else { - return pickManifest(packument, `<=${ver}`, opts) - } - } - - // similarly, if a specific version, then only that version will do - if (wanted && type === 'version') { - const ver = semver.clean(wanted, { loose: true }) - const mani = versions[ver] || staged[ver] || restricted[ver] - return isBefore(verTimes, ver, time) ? decorateAvoid(mani, avoid) : null - } - - // ok, sort based on our heuristics, and pick the best fit - const range = type === 'range' ? wanted : '*' - - // if the range is *, then we prefer the 'latest' if available - // but skip this if it should be avoided, in that case we have - // to try a little harder. - const defaultVer = distTags[defaultTag] - if (defaultVer && - (range === '*' || semver.satisfies(defaultVer, range, { loose: true })) && - !restricted[defaultVer] && - !shouldAvoid(defaultVer, avoid)) { - const mani = versions[defaultVer] - const ok = mani && - isBefore(verTimes, defaultVer, time) && - engineOk(mani, npmVersion, nodeVersion) && - !mani.deprecated && - !staged[defaultVer] - if (ok) { - return mani - } - } - - // ok, actually have to sort the list and take the winner - const allEntries = Object.entries(versions) - .concat(Object.entries(staged)) - .concat(Object.entries(restricted)) - .filter(([ver]) => isBefore(verTimes, ver, time)) - - if (!allEntries.length) { - throw Object.assign(new Error(`No versions available for ${name}`), { - code: 'ENOVERSIONS', - name, - type, - wanted, - before, - versions: Object.keys(versions), - }) - } - - const sortSemverOpt = { loose: true } - const entries = allEntries.filter(([ver]) => - semver.satisfies(ver, range, { loose: true })) - .sort((a, b) => { - const [vera, mania] = a - const [verb, manib] = b - const notavoida = !shouldAvoid(vera, avoid) - const notavoidb = !shouldAvoid(verb, avoid) - const notrestra = !restricted[vera] - const notrestrb = !restricted[verb] - const notstagea = !staged[vera] - const notstageb = !staged[verb] - const notdepra = !mania.deprecated - const notdeprb = !manib.deprecated - const enginea = engineOk(mania, npmVersion, nodeVersion) - const engineb = engineOk(manib, npmVersion, nodeVersion) - // sort by: - // - not an avoided version - // - not restricted - // - not staged - // - not deprecated and engine ok - // - engine ok - // - not deprecated - // - semver - return (notavoidb - notavoida) || - (notrestrb - notrestra) || - (notstageb - notstagea) || - ((notdeprb && engineb) - (notdepra && enginea)) || - (engineb - enginea) || - (notdeprb - notdepra) || - semver.rcompare(vera, verb, sortSemverOpt) - }) - - return decorateAvoid(entries[0] && entries[0][1], avoid) -} - -module.exports = (packument, wanted, opts = {}) => { - const mani = pickManifest(packument, wanted, opts) - const picked = mani && normalizeBin(mani) - const policyRestrictions = packument.policyRestrictions - const restricted = (policyRestrictions && policyRestrictions.versions) || {} - - if (picked && !restricted[picked.version]) { - return picked - } - - const { before = null, defaultTag = 'latest' } = opts - const bstr = before ? new Date(before).toLocaleString() : '' - const { name } = packument - const pckg = `${name}@${wanted}` + - (before ? ` with a date before ${bstr}` : '') - - const isForbidden = picked && !!restricted[picked.version] - const polMsg = isForbidden ? policyRestrictions.message : '' - - const msg = !isForbidden ? `No matching version found for ${pckg}.` - : `Could not download ${pckg} due to policy violations:\n${polMsg}` - - const code = isForbidden ? 'E403' : 'ETARGET' - throw Object.assign(new Error(msg), { - code, - type: npa.resolve(packument.name, wanted).type, - wanted, - versions: Object.keys(packument.versions ?? {}), - name, - distTags: packument['dist-tags'], - defaultTag, - }) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest/package.json deleted file mode 100644 index 4c0dd50630def..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "npm-pick-manifest", - "version": "9.1.0", - "description": "Resolves a matching manifest from a package metadata document according to standard npm semver resolution rules.", - "main": "./lib", - "files": [ - "bin/", - "lib/" - ], - "scripts": { - "coverage": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "test": "tap", - "posttest": "npm run lint", - "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "template-oss-apply": "template-oss-apply --force" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/npm-pick-manifest.git" - }, - "keywords": [ - "npm", - "semver", - "package manager" - ], - "author": "GitHub Inc.", - "license": "ISC", - "dependencies": { - "npm-install-checks": "^6.0.0", - "npm-normalize-package-bin": "^3.0.0", - "npm-package-arg": "^11.0.0", - "semver": "^7.3.5" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" - }, - "tap": { - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/LICENSE.md b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/LICENSE.md deleted file mode 100644 index 5fc208ff122e0..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ - - -ISC License - -Copyright npm, Inc. - -Permission to use, copy, modify, and/or distribute this -software for any purpose with or without fee is hereby -granted, provided that the above copyright notice and this -permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL -WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO -EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE -USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/auth.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/auth.js deleted file mode 100644 index 9270025fa8d90..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/auth.js +++ /dev/null @@ -1,181 +0,0 @@ -'use strict' -const fs = require('fs') -const npa = require('npm-package-arg') -const { URL } = require('url') - -// Find the longest registry key that is used for some kind of auth -// in the options. Returns the registry key and the auth config. -const regFromURI = (uri, opts) => { - const parsed = new URL(uri) - // try to find a config key indicating we have auth for this registry - // can be one of :_authToken, :_auth, :_password and :username, or - // :certfile and :keyfile - // We walk up the "path" until we're left with just //[:], - // stopping when we reach '//'. - let regKey = `//${parsed.host}${parsed.pathname}` - while (regKey.length > '//'.length) { - const authKey = hasAuth(regKey, opts) - // got some auth for this URI - if (authKey) { - return { regKey, authKey } - } - - // can be either //host/some/path/:_auth or //host/some/path:_auth - // walk up by removing EITHER what's after the slash OR the slash itself - regKey = regKey.replace(/([^/]+|\/)$/, '') - } - return { regKey: false, authKey: null } -} - -// Not only do we want to know if there is auth, but if we are calling `npm -// logout` we want to know what config value specifically provided it. This is -// so we can look up where the config came from to delete it (i.e. user vs -// project) -const hasAuth = (regKey, opts) => { - if (opts[`${regKey}:_authToken`]) { - return '_authToken' - } - if (opts[`${regKey}:_auth`]) { - return '_auth' - } - if (opts[`${regKey}:username`] && opts[`${regKey}:_password`]) { - // 'password' can be inferred to also be present - return 'username' - } - if (opts[`${regKey}:certfile`] && opts[`${regKey}:keyfile`]) { - // 'keyfile' can be inferred to also be present - return 'certfile' - } - return false -} - -const sameHost = (a, b) => { - const parsedA = new URL(a) - const parsedB = new URL(b) - return parsedA.host === parsedB.host -} - -const getRegistry = opts => { - const { spec } = opts - const { scope: specScope, subSpec } = spec ? npa(spec) : {} - const subSpecScope = subSpec && subSpec.scope - const scope = subSpec ? subSpecScope : specScope - const scopeReg = scope && opts[`${scope}:registry`] - return scopeReg || opts.registry -} - -const maybeReadFile = file => { - try { - return fs.readFileSync(file, 'utf8') - } catch (er) { - if (er.code !== 'ENOENT') { - throw er - } - return null - } -} - -const getAuth = (uri, opts = {}) => { - const { forceAuth } = opts - if (!uri) { - throw new Error('URI is required') - } - const { regKey, authKey } = regFromURI(uri, forceAuth || opts) - - // we are only allowed to use what's in forceAuth if specified - if (forceAuth && !regKey) { - return new Auth({ - // if we force auth we don't want to refer back to anything in config - regKey: false, - authKey: null, - scopeAuthKey: null, - token: forceAuth._authToken || forceAuth.token, - username: forceAuth.username, - password: forceAuth._password || forceAuth.password, - auth: forceAuth._auth || forceAuth.auth, - certfile: forceAuth.certfile, - keyfile: forceAuth.keyfile, - }) - } - - // no auth for this URI, but might have it for the registry - if (!regKey) { - const registry = getRegistry(opts) - if (registry && uri !== registry && sameHost(uri, registry)) { - return getAuth(registry, opts) - } else if (registry !== opts.registry) { - // If making a tarball request to a different base URI than the - // registry where we logged in, but the same auth SHOULD be sent - // to that artifact host, then we track where it was coming in from, - // and warn the user if we get a 4xx error on it. - const { regKey: scopeAuthKey, authKey: _authKey } = regFromURI(registry, opts) - return new Auth({ scopeAuthKey, regKey: scopeAuthKey, authKey: _authKey }) - } - } - - const { - [`${regKey}:_authToken`]: token, - [`${regKey}:username`]: username, - [`${regKey}:_password`]: password, - [`${regKey}:_auth`]: auth, - [`${regKey}:certfile`]: certfile, - [`${regKey}:keyfile`]: keyfile, - } = opts - - return new Auth({ - scopeAuthKey: null, - regKey, - authKey, - token, - auth, - username, - password, - certfile, - keyfile, - }) -} - -class Auth { - constructor ({ - token, - auth, - username, - password, - scopeAuthKey, - certfile, - keyfile, - regKey, - authKey, - }) { - // same as regKey but only present for scoped auth. Should have been named scopeRegKey - this.scopeAuthKey = scopeAuthKey - // `${regKey}:${authKey}` will get you back to the auth config that gave us auth - this.regKey = regKey - this.authKey = authKey - this.token = null - this.auth = null - this.isBasicAuth = false - this.cert = null - this.key = null - if (token) { - this.token = token - } else if (auth) { - this.auth = auth - } else if (username && password) { - const p = Buffer.from(password, 'base64').toString('utf8') - this.auth = Buffer.from(`${username}:${p}`, 'utf8').toString('base64') - this.isBasicAuth = true - } - // mTLS may be used in conjunction with another auth method above - if (certfile && keyfile) { - const cert = maybeReadFile(certfile, 'utf-8') - const key = maybeReadFile(keyfile, 'utf-8') - if (cert && key) { - this.cert = cert - this.key = key - } - } - } -} - -module.exports = getAuth diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/check-response.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/check-response.js deleted file mode 100644 index 65eea2963b0b4..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/check-response.js +++ /dev/null @@ -1,100 +0,0 @@ -'use strict' - -const errors = require('./errors.js') -const { Response } = require('minipass-fetch') -const defaultOpts = require('./default-opts.js') -const { log } = require('proc-log') -const { redact: cleanUrl } = require('@npmcli/redact') - -/* eslint-disable-next-line max-len */ -const moreInfoUrl = 'https://github.com/npm/cli/wiki/No-auth-for-URI,-but-auth-present-for-scoped-registry' -const checkResponse = - async ({ method, uri, res, startTime, auth, opts }) => { - opts = { ...defaultOpts, ...opts } - if (res.headers.has('npm-notice') && !res.headers.has('x-local-cache')) { - log.notice('', res.headers.get('npm-notice')) - } - - if (res.status >= 400) { - logRequest(method, res, startTime) - if (auth && auth.scopeAuthKey && !auth.token && !auth.auth) { - // we didn't have auth for THIS request, but we do have auth for - // requests to the registry indicated by the spec's scope value. - // Warn the user. - log.warn('registry', `No auth for URI, but auth present for scoped registry. - -URI: ${uri} -Scoped Registry Key: ${auth.scopeAuthKey} - -More info here: ${moreInfoUrl}`) - } - return checkErrors(method, res, startTime, opts) - } else { - res.body.on('end', () => logRequest(method, res, startTime, opts)) - if (opts.ignoreBody) { - res.body.resume() - return new Response(null, res) - } - return res - } - } -module.exports = checkResponse - -function logRequest (method, res, startTime) { - const elapsedTime = Date.now() - startTime - const attempt = res.headers.get('x-fetch-attempts') - const attemptStr = attempt && attempt > 1 ? ` attempt #${attempt}` : '' - const cacheStatus = res.headers.get('x-local-cache-status') - const cacheStr = cacheStatus ? ` (cache ${cacheStatus})` : '' - const urlStr = cleanUrl(res.url) - - log.http( - 'fetch', - `${method.toUpperCase()} ${res.status} ${urlStr} ${elapsedTime}ms${attemptStr}${cacheStr}` - ) -} - -function checkErrors (method, res, startTime, opts) { - return res.buffer() - .catch(() => null) - .then(body => { - let parsed = body - try { - parsed = JSON.parse(body.toString('utf8')) - } catch { - // ignore errors - } - if (res.status === 401 && res.headers.get('www-authenticate')) { - const auth = res.headers.get('www-authenticate') - .split(/,\s*/) - .map(s => s.toLowerCase()) - if (auth.indexOf('ipaddress') !== -1) { - throw new errors.HttpErrorAuthIPAddress( - method, res, parsed, opts.spec - ) - } else if (auth.indexOf('otp') !== -1) { - throw new errors.HttpErrorAuthOTP( - method, res, parsed, opts.spec - ) - } else { - throw new errors.HttpErrorAuthUnknown( - method, res, parsed, opts.spec - ) - } - } else if ( - res.status === 401 && - body != null && - /one-time pass/.test(body.toString('utf8')) - ) { - // Heuristic for malformed OTP responses that don't include the - // www-authenticate header. - throw new errors.HttpErrorAuthOTP( - method, res, parsed, opts.spec - ) - } else { - throw new errors.HttpErrorGeneral( - method, res, parsed, opts.spec - ) - } - }) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/default-opts.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/default-opts.js deleted file mode 100644 index f0847f0b507e2..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/default-opts.js +++ /dev/null @@ -1,19 +0,0 @@ -const pkg = require('../package.json') -module.exports = { - maxSockets: 12, - method: 'GET', - registry: 'https://registry.npmjs.org/', - timeout: 5 * 60 * 1000, // 5 minutes - strictSSL: true, - noProxy: process.env.NOPROXY, - userAgent: `${pkg.name - }@${ - pkg.version - }/node@${ - process.version - }+${ - process.arch - } (${ - process.platform - })`, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/errors.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/errors.js deleted file mode 100644 index 5bf6b012a24ef..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/errors.js +++ /dev/null @@ -1,80 +0,0 @@ -'use strict' - -const { URL } = require('node:url') - -function packageName (href) { - try { - let basePath = new URL(href).pathname.slice(1) - if (!basePath.match(/^-/)) { - basePath = basePath.split('/') - var index = basePath.indexOf('_rewrite') - if (index === -1) { - index = basePath.length - 1 - } else { - index++ - } - return decodeURIComponent(basePath[index]) - } - } catch { - // this is ok - } -} - -class HttpErrorBase extends Error { - constructor (method, res, body, spec) { - super() - this.name = this.constructor.name - this.headers = typeof res.headers?.raw === 'function' ? res.headers.raw() : res.headers - this.statusCode = res.status - this.code = `E${res.status}` - this.method = method - this.uri = res.url - this.body = body - this.pkgid = spec ? spec.toString() : packageName(res.url) - Error.captureStackTrace(this, this.constructor) - } -} - -class HttpErrorGeneral extends HttpErrorBase { - constructor (method, res, body, spec) { - super(method, res, body, spec) - this.message = `${res.status} ${res.statusText} - ${ - this.method.toUpperCase() - } ${ - this.spec || this.uri - }${ - (body && body.error) ? ' - ' + body.error : '' - }` - } -} - -class HttpErrorAuthOTP extends HttpErrorBase { - constructor (method, res, body, spec) { - super(method, res, body, spec) - this.message = 'OTP required for authentication' - this.code = 'EOTP' - } -} - -class HttpErrorAuthIPAddress extends HttpErrorBase { - constructor (method, res, body, spec) { - super(method, res, body, spec) - this.message = 'Login is not allowed from your IP address' - this.code = 'EAUTHIP' - } -} - -class HttpErrorAuthUnknown extends HttpErrorBase { - constructor (method, res, body, spec) { - super(method, res, body, spec) - this.message = 'Unable to authenticate, need: ' + res.headers.get('www-authenticate') - } -} - -module.exports = { - HttpErrorBase, - HttpErrorGeneral, - HttpErrorAuthOTP, - HttpErrorAuthIPAddress, - HttpErrorAuthUnknown, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/index.js deleted file mode 100644 index 898c8125bfe0e..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/index.js +++ /dev/null @@ -1,247 +0,0 @@ -'use strict' - -const { HttpErrorAuthOTP } = require('./errors.js') -const checkResponse = require('./check-response.js') -const getAuth = require('./auth.js') -const fetch = require('make-fetch-happen') -const JSONStream = require('./json-stream') -const npa = require('npm-package-arg') -const qs = require('querystring') -const url = require('url') -const zlib = require('minizlib') -const { Minipass } = require('minipass') - -const defaultOpts = require('./default-opts.js') - -// WhatWG URL throws if it's not fully resolved -const urlIsValid = u => { - try { - return !!new url.URL(u) - } catch (_) { - return false - } -} - -module.exports = regFetch -function regFetch (uri, /* istanbul ignore next */ opts_ = {}) { - const opts = { - ...defaultOpts, - ...opts_, - } - - // if we did not get a fully qualified URI, then we look at the registry - // config or relevant scope to resolve it. - const uriValid = urlIsValid(uri) - let registry = opts.registry || defaultOpts.registry - if (!uriValid) { - registry = opts.registry = ( - (opts.spec && pickRegistry(opts.spec, opts)) || - opts.registry || - registry - ) - uri = `${ - registry.trim().replace(/\/?$/g, '') - }/${ - uri.trim().replace(/^\//, '') - }` - // asserts that this is now valid - new url.URL(uri) - } - - const method = opts.method || 'GET' - - // through that takes into account the scope, the prefix of `uri`, etc - const startTime = Date.now() - const auth = getAuth(uri, opts) - const headers = getHeaders(uri, auth, opts) - let body = opts.body - const bodyIsStream = Minipass.isStream(body) - const bodyIsPromise = body && - typeof body === 'object' && - typeof body.then === 'function' - - if ( - body && !bodyIsStream && !bodyIsPromise && typeof body !== 'string' && !Buffer.isBuffer(body) - ) { - headers['content-type'] = headers['content-type'] || 'application/json' - body = JSON.stringify(body) - } else if (body && !headers['content-type']) { - headers['content-type'] = 'application/octet-stream' - } - - if (opts.gzip) { - headers['content-encoding'] = 'gzip' - if (bodyIsStream) { - const gz = new zlib.Gzip() - body.on('error', /* istanbul ignore next: unlikely and hard to test */ - err => gz.emit('error', err)) - body = body.pipe(gz) - } else if (!bodyIsPromise) { - body = new zlib.Gzip().end(body).concat() - } - } - - const parsed = new url.URL(uri) - - if (opts.query) { - const q = typeof opts.query === 'string' ? qs.parse(opts.query) - : opts.query - - Object.keys(q).forEach(key => { - if (q[key] !== undefined) { - parsed.searchParams.set(key, q[key]) - } - }) - uri = url.format(parsed) - } - - if (parsed.searchParams.get('write') === 'true' && method === 'GET') { - // do not cache, because this GET is fetching a rev that will be - // used for a subsequent PUT or DELETE, so we need to conditionally - // update cache. - opts.offline = false - opts.preferOffline = false - opts.preferOnline = true - } - - const doFetch = async fetchBody => { - const p = fetch(uri, { - agent: opts.agent, - algorithms: opts.algorithms, - body: fetchBody, - cache: getCacheMode(opts), - cachePath: opts.cache, - ca: opts.ca, - cert: auth.cert || opts.cert, - headers, - integrity: opts.integrity, - key: auth.key || opts.key, - localAddress: opts.localAddress, - maxSockets: opts.maxSockets, - memoize: opts.memoize, - method: method, - noProxy: opts.noProxy, - proxy: opts.httpsProxy || opts.proxy, - retry: opts.retry ? opts.retry : { - retries: opts.fetchRetries, - factor: opts.fetchRetryFactor, - minTimeout: opts.fetchRetryMintimeout, - maxTimeout: opts.fetchRetryMaxtimeout, - }, - strictSSL: opts.strictSSL, - timeout: opts.timeout || 30 * 1000, - }).then(res => checkResponse({ - method, - uri, - res, - registry, - startTime, - auth, - opts, - })) - - if (typeof opts.otpPrompt === 'function') { - return p.catch(async er => { - if (er instanceof HttpErrorAuthOTP) { - let otp - // if otp fails to complete, we fail with that failure - try { - otp = await opts.otpPrompt() - } catch (_) { - // ignore this error - } - // if no otp provided, or otpPrompt errored, throw the original HTTP error - if (!otp) { - throw er - } - return regFetch(uri, { ...opts, otp }) - } - throw er - }) - } else { - return p - } - } - - return Promise.resolve(body).then(doFetch) -} - -module.exports.getAuth = getAuth - -module.exports.json = fetchJSON -function fetchJSON (uri, opts) { - return regFetch(uri, opts).then(res => res.json()) -} - -module.exports.json.stream = fetchJSONStream -function fetchJSONStream (uri, jsonPath, - /* istanbul ignore next */ opts_ = {}) { - const opts = { ...defaultOpts, ...opts_ } - const parser = JSONStream.parse(jsonPath, opts.mapJSON) - regFetch(uri, opts).then(res => - res.body.on('error', - /* istanbul ignore next: unlikely and difficult to test */ - er => parser.emit('error', er)).pipe(parser) - ).catch(er => parser.emit('error', er)) - return parser -} - -module.exports.pickRegistry = pickRegistry -function pickRegistry (spec, opts = {}) { - spec = npa(spec) - let registry = spec.scope && - opts[spec.scope.replace(/^@?/, '@') + ':registry'] - - if (!registry && opts.scope) { - registry = opts[opts.scope.replace(/^@?/, '@') + ':registry'] - } - - if (!registry) { - registry = opts.registry || defaultOpts.registry - } - - return registry -} - -function getCacheMode (opts) { - return opts.offline ? 'only-if-cached' - : opts.preferOffline ? 'force-cache' - : opts.preferOnline ? 'no-cache' - : 'default' -} - -function getHeaders (uri, auth, opts) { - const headers = Object.assign({ - 'user-agent': opts.userAgent, - }, opts.headers || {}) - - if (opts.authType) { - headers['npm-auth-type'] = opts.authType - } - - if (opts.scope) { - headers['npm-scope'] = opts.scope - } - - if (opts.npmSession) { - headers['npm-session'] = opts.npmSession - } - - if (opts.npmCommand) { - headers['npm-command'] = opts.npmCommand - } - - // If a tarball is hosted on a different place than the manifest, only send - // credentials on `alwaysAuth` - if (auth.token) { - headers.authorization = `Bearer ${auth.token}` - } else if (auth.auth) { - headers.authorization = `Basic ${auth.auth}` - } - - if (opts.otp) { - headers['npm-otp'] = opts.otp - } - - return headers -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/json-stream.js b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/json-stream.js deleted file mode 100644 index 36b05ad4a20b9..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/lib/json-stream.js +++ /dev/null @@ -1,223 +0,0 @@ -const Parser = require('jsonparse') -const { Minipass } = require('minipass') - -class JSONStreamError extends Error { - constructor (err, caller) { - super(err.message) - Error.captureStackTrace(this, caller || this.constructor) - } - - get name () { - return 'JSONStreamError' - } -} - -const check = (x, y) => - typeof x === 'string' ? String(y) === x - : x && typeof x.test === 'function' ? x.test(y) - : typeof x === 'boolean' || typeof x === 'object' ? x - : typeof x === 'function' ? x(y) - : false - -class JSONStream extends Minipass { - #count = 0 - #ending = false - #footer = null - #header = null - #map = null - #onTokenOriginal - #parser - #path = null - #root = null - - constructor (opts) { - super({ - ...opts, - objectMode: true, - }) - - const parser = this.#parser = new Parser() - parser.onValue = value => this.#onValue(value) - this.#onTokenOriginal = parser.onToken - parser.onToken = (token, value) => this.#onToken(token, value) - parser.onError = er => this.#onError(er) - - this.#path = typeof opts.path === 'string' - ? opts.path.split('.').map(e => - e === '$*' ? { emitKey: true } - : e === '*' ? true - : e === '' ? { recurse: true } - : e) - : Array.isArray(opts.path) && opts.path.length ? opts.path - : null - - if (typeof opts.map === 'function') { - this.#map = opts.map - } - } - - #setHeaderFooter (key, value) { - // header has not been emitted yet - if (this.#header !== false) { - this.#header = this.#header || {} - this.#header[key] = value - } - - // footer has not been emitted yet but header has - if (this.#footer !== false && this.#header === false) { - this.#footer = this.#footer || {} - this.#footer[key] = value - } - } - - #onError (er) { - // error will always happen during a write() call. - const caller = this.#ending ? this.end : this.write - this.#ending = false - return this.emit('error', new JSONStreamError(er, caller)) - } - - #onToken (token, value) { - const parser = this.#parser - this.#onTokenOriginal.call(this.#parser, token, value) - if (parser.stack.length === 0) { - if (this.#root) { - const root = this.#root - if (!this.#path) { - super.write(root) - } - this.#root = null - this.#count = 0 - } - } - } - - #onValue (value) { - const parser = this.#parser - // the LAST onValue encountered is the root object. - // just overwrite it each time. - this.#root = value - - if (!this.#path) { - return - } - - let i = 0 // iterates on path - let j = 0 // iterates on stack - let emitKey = false - while (i < this.#path.length) { - const key = this.#path[i] - j++ - - if (key && !key.recurse) { - const c = (j === parser.stack.length) ? parser : parser.stack[j] - if (!c) { - return - } - if (!check(key, c.key)) { - this.#setHeaderFooter(c.key, value) - return - } - emitKey = !!key.emitKey - i++ - } else { - i++ - if (i >= this.#path.length) { - return - } - const nextKey = this.#path[i] - if (!nextKey) { - return - } - while (true) { - const c = (j === parser.stack.length) ? parser : parser.stack[j] - if (!c) { - return - } - if (check(nextKey, c.key)) { - i++ - if (!Object.isFrozen(parser.stack[j])) { - parser.stack[j].value = null - } - break - } else { - this.#setHeaderFooter(c.key, value) - } - j++ - } - } - } - - // emit header - if (this.#header) { - const header = this.#header - this.#header = false - this.emit('header', header) - } - if (j !== parser.stack.length) { - return - } - - this.#count++ - const actualPath = parser.stack.slice(1) - .map(e => e.key).concat([parser.key]) - if (value !== null && value !== undefined) { - const data = this.#map ? this.#map(value, actualPath) : value - if (data !== null && data !== undefined) { - const emit = emitKey ? { value: data } : data - if (emitKey) { - emit.key = parser.key - } - super.write(emit) - } - } - - if (parser.value) { - delete parser.value[parser.key] - } - - for (const k of parser.stack) { - k.value = null - } - } - - write (chunk, encoding) { - if (typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding) - } else if (!Buffer.isBuffer(chunk)) { - return this.emit('error', new TypeError( - 'Can only parse JSON from string or buffer input')) - } - this.#parser.write(chunk) - return this.flowing - } - - end (chunk, encoding) { - this.#ending = true - if (chunk) { - this.write(chunk, encoding) - } - - const h = this.#header - this.#header = null - const f = this.#footer - this.#footer = null - if (h) { - this.emit('header', h) - } - if (f) { - this.emit('footer', f) - } - return super.end() - } - - static get JSONStreamError () { - return JSONStreamError - } - - static parse (path, map) { - return new JSONStream({ path, map }) - } -} - -module.exports = JSONStream diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/package.json deleted file mode 100644 index 07ea620d15317..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "name": "npm-registry-fetch", - "version": "17.1.0", - "description": "Fetch-based http client for use with npm registry APIs", - "main": "lib", - "files": [ - "bin/", - "lib/" - ], - "scripts": { - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "test": "tap", - "posttest": "npm run lint", - "npmclilint": "npmcli-lint", - "postsnap": "npm run lintfix --", - "postlint": "template-oss-check", - "snap": "tap", - "template-oss-apply": "template-oss-apply --force" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/npm-registry-fetch.git" - }, - "keywords": [ - "npm", - "registry", - "fetch" - ], - "author": "GitHub Inc.", - "license": "ISC", - "dependencies": { - "@npmcli/redact": "^2.0.0", - "jsonparse": "^1.3.1", - "make-fetch-happen": "^13.0.0", - "minipass": "^7.0.2", - "minipass-fetch": "^3.0.0", - "minizlib": "^2.1.2", - "npm-package-arg": "^11.0.0", - "proc-log": "^4.0.0" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "cacache": "^18.0.0", - "nock": "^13.2.4", - "require-inject": "^1.4.4", - "ssri": "^10.0.0", - "tap": "^16.0.1" - }, - "tap": { - "check-coverage": true, - "test-ignore": "test[\\\\/](util|cache)[\\\\/]", - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/LICENSE deleted file mode 100644 index a03cd0ed0b338..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter, Kat Marchán, npm, Inc., and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/bin/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/bin/index.js deleted file mode 100755 index f35b62ca71a53..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/bin/index.js +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env node - -const run = conf => { - const pacote = require('../') - switch (conf._[0]) { - case 'resolve': - case 'manifest': - case 'packument': - if (conf._[0] === 'resolve' && conf.long) { - return pacote.manifest(conf._[1], conf).then(mani => ({ - resolved: mani._resolved, - integrity: mani._integrity, - from: mani._from, - })) - } - return pacote[conf._[0]](conf._[1], conf) - - case 'tarball': - if (!conf._[2] || conf._[2] === '-') { - return pacote.tarball.stream(conf._[1], stream => { - stream.pipe( - conf.testStdout || - /* istanbul ignore next */ - process.stdout - ) - // make sure it resolves something falsey - return stream.promise().then(() => { - return false - }) - }, conf) - } else { - return pacote.tarball.file(conf._[1], conf._[2], conf) - } - - case 'extract': - return pacote.extract(conf._[1], conf._[2], conf) - - default: /* istanbul ignore next */ { - throw new Error(`bad command: ${conf._[0]}`) - } - } -} - -const version = require('../package.json').version -const usage = () => -`Pacote - The JavaScript Package Handler, v${version} - -Usage: - - pacote resolve - Resolve a specifier and output the fully resolved target - Returns integrity and from if '--long' flag is set. - - pacote manifest - Fetch a manifest and print to stdout - - pacote packument - Fetch a full packument and print to stdout - - pacote tarball [] - Fetch a package tarball and save to - If is missing or '-', the tarball will be streamed to stdout. - - pacote extract - Extract a package to the destination folder. - -Configuration values all match the names of configs passed to npm, or -options passed to Pacote. Additional flags for this executable: - - --long Print an object from 'resolve', including integrity and spec. - --json Print result objects as JSON rather than node's default. - (This is the default if stdout is not a TTY.) - --help -h Print this helpful text. - -For example '--cache=/path/to/folder' will use that folder as the cache. -` - -const shouldJSON = (conf, result) => - conf.json || - !process.stdout.isTTY && - conf.json === undefined && - result && - typeof result === 'object' - -const pretty = (conf, result) => - shouldJSON(conf, result) ? JSON.stringify(result, 0, 2) : result - -let addedLogListener = false -const main = args => { - const conf = parse(args) - if (conf.help || conf.h) { - return console.log(usage()) - } - - if (!addedLogListener) { - process.on('log', console.error) - addedLogListener = true - } - - try { - return run(conf) - .then(result => result && console.log(pretty(conf, result))) - .catch(er => { - console.error(er) - process.exit(1) - }) - } catch (er) { - console.error(er.message) - console.error(usage()) - } -} - -const parseArg = arg => { - const split = arg.slice(2).split('=') - const k = split.shift() - const v = split.join('=') - const no = /^no-/.test(k) && !v - const key = (no ? k.slice(3) : k) - .replace(/^tag$/, 'defaultTag') - .replace(/-([a-z])/g, (_, c) => c.toUpperCase()) - const value = v ? v.replace(/^~/, process.env.HOME) : !no - return { key, value } -} - -const parse = args => { - const conf = { - _: [], - cache: process.env.HOME + '/.npm/_cacache', - } - let dashdash = false - args.forEach(arg => { - if (dashdash) { - conf._.push(arg) - } else if (arg === '--') { - dashdash = true - } else if (arg === '-h') { - conf.help = true - } else if (/^--/.test(arg)) { - const { key, value } = parseArg(arg) - conf[key] = value - } else { - conf._.push(arg) - } - }) - return conf -} - -if (module === require.main) { - main(process.argv.slice(2)) -} else { - module.exports = { - main, - run, - usage, - parseArg, - parse, - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/dir.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/dir.js deleted file mode 100644 index f3229b34e463a..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/dir.js +++ /dev/null @@ -1,100 +0,0 @@ -const { resolve } = require('node:path') -const packlist = require('npm-packlist') -const runScript = require('@npmcli/run-script') -const tar = require('tar') -const { Minipass } = require('minipass') -const Fetcher = require('./fetcher.js') -const FileFetcher = require('./file.js') -const _ = require('./util/protected.js') -const tarCreateOptions = require('./util/tar-create-options.js') - -class DirFetcher extends Fetcher { - constructor (spec, opts) { - super(spec, opts) - // just the fully resolved filename - this.resolved = this.spec.fetchSpec - - this.tree = opts.tree || null - this.Arborist = opts.Arborist || null - } - - // exposes tarCreateOptions as public API - static tarCreateOptions (manifest) { - return tarCreateOptions(manifest) - } - - get types () { - return ['directory'] - } - - #prepareDir () { - return this.manifest().then(mani => { - if (!mani.scripts || !mani.scripts.prepare) { - return - } - - // we *only* run prepare. - // pre/post-pack is run by the npm CLI for publish and pack, - // but this function is *also* run when installing git deps - const stdio = this.opts.foregroundScripts ? 'inherit' : 'pipe' - - return runScript({ - pkg: mani, - event: 'prepare', - path: this.resolved, - stdio, - env: { - npm_package_resolved: this.resolved, - npm_package_integrity: this.integrity, - npm_package_json: resolve(this.resolved, 'package.json'), - }, - }) - }) - } - - [_.tarballFromResolved] () { - if (!this.tree && !this.Arborist) { - throw new Error('DirFetcher requires either a tree or an Arborist constructor to pack') - } - - const stream = new Minipass() - stream.resolved = this.resolved - stream.integrity = this.integrity - - const { prefix, workspaces } = this.opts - - // run the prepare script, get the list of files, and tar it up - // pipe to the stream, and proxy errors the chain. - this.#prepareDir() - .then(async () => { - if (!this.tree) { - const arb = new this.Arborist({ path: this.resolved }) - this.tree = await arb.loadActual() - } - return packlist(this.tree, { path: this.resolved, prefix, workspaces }) - }) - .then(files => tar.c(tarCreateOptions(this.package), files) - .on('error', er => stream.emit('error', er)).pipe(stream)) - .catch(er => stream.emit('error', er)) - return stream - } - - manifest () { - if (this.package) { - return Promise.resolve(this.package) - } - - return this[_.readPackageJson](this.resolved) - .then(mani => this.package = { - ...mani, - _integrity: this.integrity && String(this.integrity), - _resolved: this.resolved, - _from: this.from, - }) - } - - packument () { - return FileFetcher.prototype.packument.apply(this) - } -} -module.exports = DirFetcher diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/fetcher.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/fetcher.js deleted file mode 100644 index cc2c2db70c697..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/fetcher.js +++ /dev/null @@ -1,489 +0,0 @@ -// This is the base class that the other fetcher types in lib -// all descend from. -// It handles the unpacking and retry logic that is shared among -// all of the other Fetcher types. - -const { basename, dirname } = require('node:path') -const { rm, mkdir } = require('node:fs/promises') -const PackageJson = require('@npmcli/package-json') -const cacache = require('cacache') -const fsm = require('fs-minipass') -const getContents = require('@npmcli/installed-package-contents') -const npa = require('npm-package-arg') -const retry = require('promise-retry') -const ssri = require('ssri') -const tar = require('tar') -const { Minipass } = require('minipass') -const { log } = require('proc-log') -const _ = require('./util/protected.js') -const cacheDir = require('./util/cache-dir.js') -const isPackageBin = require('./util/is-package-bin.js') -const removeTrailingSlashes = require('./util/trailing-slashes.js') - -// Pacote is only concerned with the package.json contents -const packageJsonPrepare = (p) => PackageJson.prepare(p).then(pkg => pkg.content) -const packageJsonNormalize = (p) => PackageJson.normalize(p).then(pkg => pkg.content) - -class FetcherBase { - constructor (spec, opts) { - if (!opts || typeof opts !== 'object') { - throw new TypeError('options object is required') - } - this.spec = npa(spec, opts.where) - - this.allowGitIgnore = !!opts.allowGitIgnore - - // a bit redundant because presumably the caller already knows this, - // but it makes it easier to not have to keep track of the requested - // spec when we're dispatching thousands of these at once, and normalizing - // is nice. saveSpec is preferred if set, because it turns stuff like - // x/y#committish into github:x/y#committish. use name@rawSpec for - // registry deps so that we turn xyz and xyz@ -> xyz@ - this.from = this.spec.registry - ? `${this.spec.name}@${this.spec.rawSpec}` : this.spec.saveSpec - - this.#assertType() - // clone the opts object so that others aren't upset when we mutate it - // by adding/modifying the integrity value. - this.opts = { ...opts } - - this.cache = opts.cache || cacheDir().cacache - this.tufCache = opts.tufCache || cacheDir().tufcache - this.resolved = opts.resolved || null - - // default to caching/verifying with sha512, that's what we usually have - // need to change this default, or start overriding it, when sha512 - // is no longer strong enough. - this.defaultIntegrityAlgorithm = opts.defaultIntegrityAlgorithm || 'sha512' - - if (typeof opts.integrity === 'string') { - this.opts.integrity = ssri.parse(opts.integrity) - } - - this.package = null - this.type = this.constructor.name - this.fmode = opts.fmode || 0o666 - this.dmode = opts.dmode || 0o777 - // we don't need a default umask, because we don't chmod files coming - // out of package tarballs. they're forced to have a mode that is - // valid, regardless of what's in the tarball entry, and then we let - // the process's umask setting do its job. but if configured, we do - // respect it. - this.umask = opts.umask || 0 - - this.preferOnline = !!opts.preferOnline - this.preferOffline = !!opts.preferOffline - this.offline = !!opts.offline - - this.before = opts.before - this.fullMetadata = this.before ? true : !!opts.fullMetadata - this.fullReadJson = !!opts.fullReadJson - this[_.readPackageJson] = this.fullReadJson - ? packageJsonPrepare - : packageJsonNormalize - - // rrh is a registry hostname or 'never' or 'always' - // defaults to registry.npmjs.org - this.replaceRegistryHost = (!opts.replaceRegistryHost || opts.replaceRegistryHost === 'npmjs') ? - 'registry.npmjs.org' : opts.replaceRegistryHost - - this.defaultTag = opts.defaultTag || 'latest' - this.registry = removeTrailingSlashes(opts.registry || 'https://registry.npmjs.org') - - // command to run 'prepare' scripts on directories and git dirs - // To use pacote with yarn, for example, set npmBin to 'yarn' - // and npmCliConfig with yarn's equivalents. - this.npmBin = opts.npmBin || 'npm' - - // command to install deps for preparing - this.npmInstallCmd = opts.npmInstallCmd || ['install', '--force'] - - // XXX fill more of this in based on what we know from this.opts - // we explicitly DO NOT fill in --tag, though, since we are often - // going to be packing in the context of a publish, which may set - // a dist-tag, but certainly wants to keep defaulting to latest. - this.npmCliConfig = opts.npmCliConfig || [ - `--cache=${dirname(this.cache)}`, - `--prefer-offline=${!!this.preferOffline}`, - `--prefer-online=${!!this.preferOnline}`, - `--offline=${!!this.offline}`, - ...(this.before ? [`--before=${this.before.toISOString()}`] : []), - '--no-progress', - '--no-save', - '--no-audit', - // override any omit settings from the environment - '--include=dev', - '--include=peer', - '--include=optional', - // we need the actual things, not just the lockfile - '--no-package-lock-only', - '--no-dry-run', - ] - } - - get integrity () { - return this.opts.integrity || null - } - - set integrity (i) { - if (!i) { - return - } - - i = ssri.parse(i) - const current = this.opts.integrity - - // do not ever update an existing hash value, but do - // merge in NEW algos and hashes that we don't already have. - if (current) { - current.merge(i) - } else { - this.opts.integrity = i - } - } - - get notImplementedError () { - return new Error('not implemented in this fetcher type: ' + this.type) - } - - // override in child classes - // Returns a Promise that resolves to this.resolved string value - resolve () { - return this.resolved ? Promise.resolve(this.resolved) - : Promise.reject(this.notImplementedError) - } - - packument () { - return Promise.reject(this.notImplementedError) - } - - // override in child class - // returns a manifest containing: - // - name - // - version - // - _resolved - // - _integrity - // - plus whatever else was in there (corgi, full metadata, or pj file) - manifest () { - return Promise.reject(this.notImplementedError) - } - - // private, should be overridden. - // Note that they should *not* calculate or check integrity or cache, - // but *just* return the raw tarball data stream. - [_.tarballFromResolved] () { - throw this.notImplementedError - } - - // public, should not be overridden - tarball () { - return this.tarballStream(stream => stream.concat().then(data => { - data.integrity = this.integrity && String(this.integrity) - data.resolved = this.resolved - data.from = this.from - return data - })) - } - - // private - // Note: cacache will raise a EINTEGRITY error if the integrity doesn't match - #tarballFromCache () { - return cacache.get.stream.byDigest(this.cache, this.integrity, this.opts) - } - - get [_.cacheFetches] () { - return true - } - - #istream (stream) { - // if not caching this, just return it - if (!this.opts.cache || !this[_.cacheFetches]) { - // instead of creating a new integrity stream, we only piggyback on the - // provided stream's events - if (stream.hasIntegrityEmitter) { - stream.on('integrity', i => this.integrity = i) - return stream - } - - const istream = ssri.integrityStream(this.opts) - istream.on('integrity', i => this.integrity = i) - stream.on('error', err => istream.emit('error', err)) - return stream.pipe(istream) - } - - // we have to return a stream that gets ALL the data, and proxies errors, - // but then pipe from the original tarball stream into the cache as well. - // To do this without losing any data, and since the cacache put stream - // is not a passthrough, we have to pipe from the original stream into - // the cache AFTER we pipe into the middleStream. Since the cache stream - // has an asynchronous flush to write its contents to disk, we need to - // defer the middleStream end until the cache stream ends. - const middleStream = new Minipass() - stream.on('error', err => middleStream.emit('error', err)) - stream.pipe(middleStream, { end: false }) - const cstream = cacache.put.stream( - this.opts.cache, - `pacote:tarball:${this.from}`, - this.opts - ) - cstream.on('integrity', i => this.integrity = i) - cstream.on('error', err => stream.emit('error', err)) - stream.pipe(cstream) - - // eslint-disable-next-line promise/catch-or-return - cstream.promise().catch(() => {}).then(() => middleStream.end()) - return middleStream - } - - pickIntegrityAlgorithm () { - return this.integrity ? this.integrity.pickAlgorithm(this.opts) - : this.defaultIntegrityAlgorithm - } - - // TODO: check error class, once those are rolled out to our deps - isDataCorruptionError (er) { - return er.code === 'EINTEGRITY' || er.code === 'Z_DATA_ERROR' - } - - // override the types getter - get types () { - return false - } - - #assertType () { - if (this.types && !this.types.includes(this.spec.type)) { - throw new TypeError(`Wrong spec type (${ - this.spec.type - }) for ${ - this.constructor.name - }. Supported types: ${this.types.join(', ')}`) - } - } - - // We allow ENOENTs from cacache, but not anywhere else. - // An ENOENT trying to read a tgz file, for example, is Right Out. - isRetriableError (er) { - // TODO: check error class, once those are rolled out to our deps - return this.isDataCorruptionError(er) || - er.code === 'ENOENT' || - er.code === 'EISDIR' - } - - // Mostly internal, but has some uses - // Pass in a function which returns a promise - // Function will be called 1 or more times with streams that may fail. - // Retries: - // Function MUST handle errors on the stream by rejecting the promise, - // so that retry logic can pick it up and either retry or fail whatever - // promise it was making (ie, failing extraction, etc.) - // - // The return value of this method is a Promise that resolves the same - // as whatever the streamHandler resolves to. - // - // This should never be overridden by child classes, but it is public. - tarballStream (streamHandler) { - // Only short-circuit via cache if we have everything else we'll need, - // and the user has not expressed a preference for checking online. - - const fromCache = ( - !this.preferOnline && - this.integrity && - this.resolved - ) ? streamHandler(this.#tarballFromCache()).catch(er => { - if (this.isDataCorruptionError(er)) { - log.warn('tarball', `cached data for ${ - this.spec - } (${this.integrity}) seems to be corrupted. Refreshing cache.`) - return this.cleanupCached().then(() => { - throw er - }) - } else { - throw er - } - }) : null - - const fromResolved = er => { - if (er) { - if (!this.isRetriableError(er)) { - throw er - } - log.silly('tarball', `no local data for ${ - this.spec - }. Extracting by manifest.`) - } - return this.resolve().then(() => retry(tryAgain => - streamHandler(this.#istream(this[_.tarballFromResolved]())) - .catch(streamErr => { - // Most likely data integrity. A cache ENOENT error is unlikely - // here, since we're definitely not reading from the cache, but it - // IS possible that the fetch subsystem accessed the cache, and the - // entry got blown away or something. Try one more time to be sure. - if (this.isRetriableError(streamErr)) { - log.warn('tarball', `tarball data for ${ - this.spec - } (${this.integrity}) seems to be corrupted. Trying again.`) - return this.cleanupCached().then(() => tryAgain(streamErr)) - } - throw streamErr - }), { retries: 1, minTimeout: 0, maxTimeout: 0 })) - } - - return fromCache ? fromCache.catch(fromResolved) : fromResolved() - } - - cleanupCached () { - return cacache.rm.content(this.cache, this.integrity, this.opts) - } - - #empty (path) { - return getContents({ path, depth: 1 }).then(contents => Promise.all( - contents.map(entry => rm(entry, { recursive: true, force: true })))) - } - - async #mkdir (dest) { - await this.#empty(dest) - return await mkdir(dest, { recursive: true }) - } - - // extraction is always the same. the only difference is where - // the tarball comes from. - async extract (dest) { - await this.#mkdir(dest) - return this.tarballStream((tarball) => this.#extract(dest, tarball)) - } - - #toFile (dest) { - return this.tarballStream(str => new Promise((res, rej) => { - const writer = new fsm.WriteStream(dest) - str.on('error', er => writer.emit('error', er)) - writer.on('error', er => rej(er)) - writer.on('close', () => res({ - integrity: this.integrity && String(this.integrity), - resolved: this.resolved, - from: this.from, - })) - str.pipe(writer) - })) - } - - // don't use this.#mkdir because we don't want to rimraf anything - async tarballFile (dest) { - const dir = dirname(dest) - await mkdir(dir, { recursive: true }) - return this.#toFile(dest) - } - - #extract (dest, tarball) { - const extractor = tar.x(this.#tarxOptions({ cwd: dest })) - const p = new Promise((resolve, reject) => { - extractor.on('end', () => { - resolve({ - resolved: this.resolved, - integrity: this.integrity && String(this.integrity), - from: this.from, - }) - }) - - extractor.on('error', er => { - log.warn('tar', er.message) - log.silly('tar', er) - reject(er) - }) - - tarball.on('error', er => reject(er)) - }) - - tarball.pipe(extractor) - return p - } - - // always ensure that entries are at least as permissive as our configured - // dmode/fmode, but never more permissive than the umask allows. - #entryMode (path, mode, type) { - const m = /Directory|GNUDumpDir/.test(type) ? this.dmode - : /File$/.test(type) ? this.fmode - : /* istanbul ignore next - should never happen in a pkg */ 0 - - // make sure package bins are executable - const exe = isPackageBin(this.package, path) ? 0o111 : 0 - // always ensure that files are read/writable by the owner - return ((mode | m) & ~this.umask) | exe | 0o600 - } - - #tarxOptions ({ cwd }) { - const sawIgnores = new Set() - return { - cwd, - noChmod: true, - noMtime: true, - filter: (name, entry) => { - if (/Link$/.test(entry.type)) { - return false - } - entry.mode = this.#entryMode(entry.path, entry.mode, entry.type) - // this replicates the npm pack behavior where .gitignore files - // are treated like .npmignore files, but only if a .npmignore - // file is not present. - if (/File$/.test(entry.type)) { - const base = basename(entry.path) - if (base === '.npmignore') { - sawIgnores.add(entry.path) - } else if (base === '.gitignore' && !this.allowGitIgnore) { - // rename, but only if there's not already a .npmignore - const ni = entry.path.replace(/\.gitignore$/, '.npmignore') - if (sawIgnores.has(ni)) { - return false - } - entry.path = ni - } - return true - } - }, - strip: 1, - onwarn: /* istanbul ignore next - we can trust that tar logs */ - (code, msg, data) => { - log.warn('tar', code, msg) - log.silly('tar', code, msg, data) - }, - umask: this.umask, - // always ignore ownership info from tarball metadata - preserveOwner: false, - } - } -} - -module.exports = FetcherBase - -// Child classes -const GitFetcher = require('./git.js') -const RegistryFetcher = require('./registry.js') -const FileFetcher = require('./file.js') -const DirFetcher = require('./dir.js') -const RemoteFetcher = require('./remote.js') - -// Get an appropriate fetcher object from a spec and options -FetcherBase.get = (rawSpec, opts = {}) => { - const spec = npa(rawSpec, opts.where) - switch (spec.type) { - case 'git': - return new GitFetcher(spec, opts) - - case 'remote': - return new RemoteFetcher(spec, opts) - - case 'version': - case 'range': - case 'tag': - case 'alias': - return new RegistryFetcher(spec.subSpec || spec, opts) - - case 'file': - return new FileFetcher(spec, opts) - - case 'directory': - return new DirFetcher(spec, opts) - - default: - throw new TypeError('Unknown spec type: ' + spec.type) - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/file.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/file.js deleted file mode 100644 index 2021325085e4f..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/file.js +++ /dev/null @@ -1,94 +0,0 @@ -const { resolve } = require('node:path') -const { stat, chmod } = require('node:fs/promises') -const cacache = require('cacache') -const fsm = require('fs-minipass') -const Fetcher = require('./fetcher.js') -const _ = require('./util/protected.js') - -class FileFetcher extends Fetcher { - constructor (spec, opts) { - super(spec, opts) - // just the fully resolved filename - this.resolved = this.spec.fetchSpec - } - - get types () { - return ['file'] - } - - manifest () { - if (this.package) { - return Promise.resolve(this.package) - } - - // have to unpack the tarball for this. - return cacache.tmp.withTmp(this.cache, this.opts, dir => - this.extract(dir) - .then(() => this[_.readPackageJson](dir)) - .then(mani => this.package = { - ...mani, - _integrity: this.integrity && String(this.integrity), - _resolved: this.resolved, - _from: this.from, - })) - } - - #exeBins (pkg, dest) { - if (!pkg.bin) { - return Promise.resolve() - } - - return Promise.all(Object.keys(pkg.bin).map(async k => { - const script = resolve(dest, pkg.bin[k]) - // Best effort. Ignore errors here, the only result is that - // a bin script is not executable. But if it's missing or - // something, we just leave it for a later stage to trip over - // when we can provide a more useful contextual error. - try { - const st = await stat(script) - const mode = st.mode | 0o111 - if (mode === st.mode) { - return - } - await chmod(script, mode) - } catch { - // Ignore errors here - } - })) - } - - extract (dest) { - // if we've already loaded the manifest, then the super got it. - // but if not, read the unpacked manifest and chmod properly. - return super.extract(dest) - .then(result => this.package ? result - : this[_.readPackageJson](dest).then(pkg => - this.#exeBins(pkg, dest)).then(() => result)) - } - - [_.tarballFromResolved] () { - // create a read stream and return it - return new fsm.ReadStream(this.resolved) - } - - packument () { - // simulate based on manifest - return this.manifest().then(mani => ({ - name: mani.name, - 'dist-tags': { - [this.defaultTag]: mani.version, - }, - versions: { - [mani.version]: { - ...mani, - dist: { - tarball: `file:${this.resolved}`, - integrity: this.integrity && String(this.integrity), - }, - }, - }, - })) - } -} - -module.exports = FileFetcher diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/git.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/git.js deleted file mode 100644 index 077193a86f026..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/git.js +++ /dev/null @@ -1,317 +0,0 @@ -const cacache = require('cacache') -const git = require('@npmcli/git') -const npa = require('npm-package-arg') -const pickManifest = require('npm-pick-manifest') -const { Minipass } = require('minipass') -const { log } = require('proc-log') -const DirFetcher = require('./dir.js') -const Fetcher = require('./fetcher.js') -const FileFetcher = require('./file.js') -const RemoteFetcher = require('./remote.js') -const _ = require('./util/protected.js') -const addGitSha = require('./util/add-git-sha.js') -const npm = require('./util/npm.js') - -const hashre = /^[a-f0-9]{40}$/ - -// get the repository url. -// prefer https if there's auth, since ssh will drop that. -// otherwise, prefer ssh if available (more secure). -// We have to add the git+ back because npa suppresses it. -const repoUrl = (h, opts) => - h.sshurl && !(h.https && h.auth) && addGitPlus(h.sshurl(opts)) || - h.https && addGitPlus(h.https(opts)) - -// add git+ to the url, but only one time. -const addGitPlus = url => url && `git+${url}`.replace(/^(git\+)+/, 'git+') - -class GitFetcher extends Fetcher { - constructor (spec, opts) { - super(spec, opts) - - // we never want to compare integrity for git dependencies: npm/rfcs#525 - if (this.opts.integrity) { - delete this.opts.integrity - log.warn(`skipping integrity check for git dependency ${this.spec.fetchSpec}`) - } - - this.resolvedRef = null - if (this.spec.hosted) { - this.from = this.spec.hosted.shortcut({ noCommittish: false }) - } - - // shortcut: avoid full clone when we can go straight to the tgz - // if we have the full sha and it's a hosted git platform - if (this.spec.gitCommittish && hashre.test(this.spec.gitCommittish)) { - this.resolvedSha = this.spec.gitCommittish - // use hosted.tarball() when we shell to RemoteFetcher later - this.resolved = this.spec.hosted - ? repoUrl(this.spec.hosted, { noCommittish: false }) - : this.spec.rawSpec - } else { - this.resolvedSha = '' - } - - this.Arborist = opts.Arborist || null - } - - // just exposed to make it easier to test all the combinations - static repoUrl (hosted, opts) { - return repoUrl(hosted, opts) - } - - get types () { - return ['git'] - } - - resolve () { - // likely a hosted git repo with a sha, so get the tarball url - // but in general, no reason to resolve() more than necessary! - if (this.resolved) { - return super.resolve() - } - - // fetch the git repo and then look at the current hash - const h = this.spec.hosted - // try to use ssh, fall back to git. - return h - ? this.#resolvedFromHosted(h) - : this.#resolvedFromRepo(this.spec.fetchSpec) - } - - // first try https, since that's faster and passphrase-less for - // public repos, and supports private repos when auth is provided. - // Fall back to SSH to support private repos - // NB: we always store the https url in resolved field if auth - // is present, otherwise ssh if the hosted type provides it - #resolvedFromHosted (hosted) { - return this.#resolvedFromRepo(hosted.https && hosted.https()).catch(er => { - // Throw early since we know pathspec errors will fail again if retried - if (er instanceof git.errors.GitPathspecError) { - throw er - } - const ssh = hosted.sshurl && hosted.sshurl() - // no fallthrough if we can't fall through or have https auth - if (!ssh || hosted.auth) { - throw er - } - return this.#resolvedFromRepo(ssh) - }) - } - - #resolvedFromRepo (gitRemote) { - // XXX make this a custom error class - if (!gitRemote) { - return Promise.reject(new Error(`No git url for ${this.spec}`)) - } - const gitRange = this.spec.gitRange - const name = this.spec.name - return git.revs(gitRemote, this.opts).then(remoteRefs => { - return gitRange ? pickManifest({ - versions: remoteRefs.versions, - 'dist-tags': remoteRefs['dist-tags'], - name, - }, gitRange, this.opts) - : this.spec.gitCommittish ? - remoteRefs.refs[this.spec.gitCommittish] || - remoteRefs.refs[remoteRefs.shas[this.spec.gitCommittish]] - : remoteRefs.refs.HEAD // no git committish, get default head - }).then(revDoc => { - // the committish provided isn't in the rev list - // things like HEAD~3 or @yesterday can land here. - if (!revDoc || !revDoc.sha) { - return this.#resolvedFromClone() - } - - this.resolvedRef = revDoc - this.resolvedSha = revDoc.sha - this.#addGitSha(revDoc.sha) - return this.resolved - }) - } - - #setResolvedWithSha (withSha) { - // we haven't cloned, so a tgz download is still faster - // of course, if it's not a known host, we can't do that. - this.resolved = !this.spec.hosted ? withSha - : repoUrl(npa(withSha).hosted, { noCommittish: false }) - } - - // when we get the git sha, we affix it to our spec to build up - // either a git url with a hash, or a tarball download URL - #addGitSha (sha) { - this.#setResolvedWithSha(addGitSha(this.spec, sha)) - } - - #resolvedFromClone () { - // do a full or shallow clone, then look at the HEAD - // kind of wasteful, but no other option, really - return this.#clone(() => this.resolved) - } - - #prepareDir (dir) { - return this[_.readPackageJson](dir).then(mani => { - // no need if we aren't going to do any preparation. - const scripts = mani.scripts - if (!mani.workspaces && (!scripts || !( - scripts.postinstall || - scripts.build || - scripts.preinstall || - scripts.install || - scripts.prepack || - scripts.prepare))) { - return - } - - // to avoid cases where we have an cycle of git deps that depend - // on one another, we only ever do preparation for one instance - // of a given git dep along the chain of installations. - // Note that this does mean that a dependency MAY in theory end up - // trying to run its prepare script using a dependency that has not - // been properly prepared itself, but that edge case is smaller - // and less hazardous than a fork bomb of npm and git commands. - const noPrepare = !process.env._PACOTE_NO_PREPARE_ ? [] - : process.env._PACOTE_NO_PREPARE_.split('\n') - if (noPrepare.includes(this.resolved)) { - log.info('prepare', 'skip prepare, already seen', this.resolved) - return - } - noPrepare.push(this.resolved) - - // the DirFetcher will do its own preparation to run the prepare scripts - // All we have to do is put the deps in place so that it can succeed. - return npm( - this.npmBin, - [].concat(this.npmInstallCmd).concat(this.npmCliConfig), - dir, - { ...process.env, _PACOTE_NO_PREPARE_: noPrepare.join('\n') }, - { message: 'git dep preparation failed' } - ) - }) - } - - [_.tarballFromResolved] () { - const stream = new Minipass() - stream.resolved = this.resolved - stream.from = this.from - - // check it out and then shell out to the DirFetcher tarball packer - this.#clone(dir => this.#prepareDir(dir) - .then(() => new Promise((res, rej) => { - if (!this.Arborist) { - throw new Error('GitFetcher requires an Arborist constructor to pack a tarball') - } - const df = new DirFetcher(`file:${dir}`, { - ...this.opts, - Arborist: this.Arborist, - resolved: null, - integrity: null, - }) - const dirStream = df[_.tarballFromResolved]() - dirStream.on('error', rej) - dirStream.on('end', res) - dirStream.pipe(stream) - }))).catch( - /* istanbul ignore next: very unlikely and hard to test */ - er => stream.emit('error', er) - ) - return stream - } - - // clone a git repo into a temp folder (or fetch and unpack if possible) - // handler accepts a directory, and returns a promise that resolves - // when we're done with it, at which point, cacache deletes it - // - // TODO: after cloning, create a tarball of the folder, and add to the cache - // with cacache.put.stream(), using a key that's deterministic based on the - // spec and repo, so that we don't ever clone the same thing multiple times. - #clone (handler, tarballOk = true) { - const o = { tmpPrefix: 'git-clone' } - const ref = this.resolvedSha || this.spec.gitCommittish - const h = this.spec.hosted - const resolved = this.resolved - - // can be set manually to false to fall back to actual git clone - tarballOk = tarballOk && - h && resolved === repoUrl(h, { noCommittish: false }) && h.tarball - - return cacache.tmp.withTmp(this.cache, o, async tmp => { - // if we're resolved, and have a tarball url, shell out to RemoteFetcher - if (tarballOk) { - const nameat = this.spec.name ? `${this.spec.name}@` : '' - return new RemoteFetcher(h.tarball({ noCommittish: false }), { - ...this.opts, - allowGitIgnore: true, - pkgid: `git:${nameat}${this.resolved}`, - resolved: this.resolved, - integrity: null, // it'll always be different, if we have one - }).extract(tmp).then(() => handler(tmp), er => { - // fall back to ssh download if tarball fails - if (er.constructor.name.match(/^Http/)) { - return this.#clone(handler, false) - } else { - throw er - } - }) - } - - const sha = await ( - h ? this.#cloneHosted(ref, tmp) - : this.#cloneRepo(this.spec.fetchSpec, ref, tmp) - ) - this.resolvedSha = sha - if (!this.resolved) { - await this.#addGitSha(sha) - } - return handler(tmp) - }) - } - - // first try https, since that's faster and passphrase-less for - // public repos, and supports private repos when auth is provided. - // Fall back to SSH to support private repos - // NB: we always store the https url in resolved field if auth - // is present, otherwise ssh if the hosted type provides it - #cloneHosted (ref, tmp) { - const hosted = this.spec.hosted - return this.#cloneRepo(hosted.https({ noCommittish: true }), ref, tmp) - .catch(er => { - // Throw early since we know pathspec errors will fail again if retried - if (er instanceof git.errors.GitPathspecError) { - throw er - } - const ssh = hosted.sshurl && hosted.sshurl({ noCommittish: true }) - // no fallthrough if we can't fall through or have https auth - if (!ssh || hosted.auth) { - throw er - } - return this.#cloneRepo(ssh, ref, tmp) - }) - } - - #cloneRepo (repo, ref, tmp) { - const { opts, spec } = this - return git.clone(repo, ref, tmp, { ...opts, spec }) - } - - manifest () { - if (this.package) { - return Promise.resolve(this.package) - } - - return this.spec.hosted && this.resolved - ? FileFetcher.prototype.manifest.apply(this) - : this.#clone(dir => - this[_.readPackageJson](dir) - .then(mani => this.package = { - ...mani, - _resolved: this.resolved, - _from: this.from, - })) - } - - packument () { - return FileFetcher.prototype.packument.apply(this) - } -} -module.exports = GitFetcher diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/index.js deleted file mode 100644 index f35314d275d5f..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/index.js +++ /dev/null @@ -1,23 +0,0 @@ -const { get } = require('./fetcher.js') -const GitFetcher = require('./git.js') -const RegistryFetcher = require('./registry.js') -const FileFetcher = require('./file.js') -const DirFetcher = require('./dir.js') -const RemoteFetcher = require('./remote.js') - -const tarball = (spec, opts) => get(spec, opts).tarball() -tarball.stream = (spec, handler, opts) => get(spec, opts).tarballStream(handler) -tarball.file = (spec, dest, opts) => get(spec, opts).tarballFile(dest) - -module.exports = { - GitFetcher, - RegistryFetcher, - FileFetcher, - DirFetcher, - RemoteFetcher, - resolve: (spec, opts) => get(spec, opts).resolve(), - extract: (spec, dest, opts) => get(spec, opts).extract(dest), - manifest: (spec, opts) => get(spec, opts).manifest(), - packument: (spec, opts) => get(spec, opts).packument(), - tarball, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/registry.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/registry.js deleted file mode 100644 index 1ecf4ee177349..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/registry.js +++ /dev/null @@ -1,369 +0,0 @@ -const crypto = require('node:crypto') -const PackageJson = require('@npmcli/package-json') -const pickManifest = require('npm-pick-manifest') -const ssri = require('ssri') -const npa = require('npm-package-arg') -const sigstore = require('sigstore') -const fetch = require('npm-registry-fetch') -const Fetcher = require('./fetcher.js') -const RemoteFetcher = require('./remote.js') -const pacoteVersion = require('../package.json').version -const removeTrailingSlashes = require('./util/trailing-slashes.js') -const _ = require('./util/protected.js') - -// Corgis are cute. 🐕🐶 -const corgiDoc = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*' -const fullDoc = 'application/json' - -// Some really old packages have no time field in their packument so we need a -// cutoff date. -const MISSING_TIME_CUTOFF = '2015-01-01T00:00:00.000Z' - -class RegistryFetcher extends Fetcher { - #cacheKey - constructor (spec, opts) { - super(spec, opts) - - // you usually don't want to fetch the same packument multiple times in - // the span of a given script or command, no matter how many pacote calls - // are made, so this lets us avoid doing that. It's only relevant for - // registry fetchers, because other types simulate their packument from - // the manifest, which they memoize on this.package, so it's very cheap - // already. - this.packumentCache = this.opts.packumentCache || null - - this.registry = fetch.pickRegistry(spec, opts) - this.packumentUrl = `${removeTrailingSlashes(this.registry)}/${this.spec.escapedName}` - this.#cacheKey = `${this.fullMetadata ? 'full' : 'corgi'}:${this.packumentUrl}` - - const parsed = new URL(this.registry) - const regKey = `//${parsed.host}${parsed.pathname}` - // unlike the nerf-darted auth keys, this one does *not* allow a mismatch - // of trailing slashes. It must match exactly. - if (this.opts[`${regKey}:_keys`]) { - this.registryKeys = this.opts[`${regKey}:_keys`] - } - - // XXX pacote <=9 has some logic to ignore opts.resolved if - // the resolved URL doesn't go to the same registry. - // Consider reproducing that here, to throw away this.resolved - // in that case. - } - - async resolve () { - // fetching the manifest sets resolved and (if present) integrity - await this.manifest() - if (!this.resolved) { - throw Object.assign( - new Error('Invalid package manifest: no `dist.tarball` field'), - { package: this.spec.toString() } - ) - } - return this.resolved - } - - #headers () { - return { - // npm will override UA, but ensure that we always send *something* - 'user-agent': this.opts.userAgent || - `pacote/${pacoteVersion} node/${process.version}`, - ...(this.opts.headers || {}), - 'pacote-version': pacoteVersion, - 'pacote-req-type': 'packument', - 'pacote-pkg-id': `registry:${this.spec.name}`, - accept: this.fullMetadata ? fullDoc : corgiDoc, - } - } - - async packument () { - // note this might be either an in-flight promise for a request, - // or the actual packument, but we never want to make more than - // one request at a time for the same thing regardless. - if (this.packumentCache?.has(this.#cacheKey)) { - return this.packumentCache.get(this.#cacheKey) - } - - // npm-registry-fetch the packument - // set the appropriate header for corgis if fullMetadata isn't set - // return the res.json() promise - try { - const res = await fetch(this.packumentUrl, { - ...this.opts, - headers: this.#headers(), - spec: this.spec, - - // never check integrity for packuments themselves - integrity: null, - }) - const packument = await res.json() - const contentLength = res.headers.get('content-length') - if (contentLength) { - packument._contentLength = Number(contentLength) - } - this.packumentCache?.set(this.#cacheKey, packument) - return packument - } catch (err) { - this.packumentCache?.delete(this.#cacheKey) - if (err.code !== 'E404' || this.fullMetadata) { - throw err - } - // possible that corgis are not supported by this registry - this.fullMetadata = true - return this.packument() - } - } - - async manifest () { - if (this.package) { - return this.package - } - - // When verifying signatures, we need to fetch the full/uncompressed - // packument to get publish time as this is not included in the - // corgi/compressed packument. - if (this.opts.verifySignatures) { - this.fullMetadata = true - } - - const packument = await this.packument() - const steps = PackageJson.normalizeSteps.filter(s => s !== '_attributes') - const mani = await new PackageJson().fromContent(pickManifest(packument, this.spec.fetchSpec, { - ...this.opts, - defaultTag: this.defaultTag, - before: this.before, - })).normalize({ steps }).then(p => p.content) - - /* XXX add ETARGET and E403 revalidation of cached packuments here */ - - // add _time from packument if fetched with fullMetadata - const time = packument.time?.[mani.version] - if (time) { - mani._time = time - } - - // add _resolved and _integrity from dist object - const { dist } = mani - if (dist) { - this.resolved = mani._resolved = dist.tarball - mani._from = this.from - const distIntegrity = dist.integrity ? ssri.parse(dist.integrity) - : dist.shasum ? ssri.fromHex(dist.shasum, 'sha1', { ...this.opts }) - : null - if (distIntegrity) { - if (this.integrity && !this.integrity.match(distIntegrity)) { - // only bork if they have algos in common. - // otherwise we end up breaking if we have saved a sha512 - // previously for the tarball, but the manifest only - // provides a sha1, which is possible for older publishes. - // Otherwise, this is almost certainly a case of holding it - // wrong, and will result in weird or insecure behavior - // later on when building package tree. - for (const algo of Object.keys(this.integrity)) { - if (distIntegrity[algo]) { - throw Object.assign(new Error( - `Integrity checksum failed when using ${algo}: ` + - `wanted ${this.integrity} but got ${distIntegrity}.` - ), { code: 'EINTEGRITY' }) - } - } - } - // made it this far, the integrity is worthwhile. accept it. - // the setter here will take care of merging it into what we already - // had. - this.integrity = distIntegrity - } - } - if (this.integrity) { - mani._integrity = String(this.integrity) - if (dist.signatures) { - if (this.opts.verifySignatures) { - // validate and throw on error, then set _signatures - const message = `${mani._id}:${mani._integrity}` - for (const signature of dist.signatures) { - const publicKey = this.registryKeys && - this.registryKeys.filter(key => (key.keyid === signature.keyid))[0] - if (!publicKey) { - throw Object.assign(new Error( - `${mani._id} has a registry signature with keyid: ${signature.keyid} ` + - 'but no corresponding public key can be found' - ), { code: 'EMISSINGSIGNATUREKEY' }) - } - - const publishedTime = Date.parse(mani._time || MISSING_TIME_CUTOFF) - const validPublicKey = !publicKey.expires || - publishedTime < Date.parse(publicKey.expires) - if (!validPublicKey) { - throw Object.assign(new Error( - `${mani._id} has a registry signature with keyid: ${signature.keyid} ` + - `but the corresponding public key has expired ${publicKey.expires}` - ), { code: 'EEXPIREDSIGNATUREKEY' }) - } - const verifier = crypto.createVerify('SHA256') - verifier.write(message) - verifier.end() - const valid = verifier.verify( - publicKey.pemkey, - signature.sig, - 'base64' - ) - if (!valid) { - throw Object.assign(new Error( - `${mani._id} has an invalid registry signature with ` + - `keyid: ${publicKey.keyid} and signature: ${signature.sig}` - ), { - code: 'EINTEGRITYSIGNATURE', - keyid: publicKey.keyid, - signature: signature.sig, - resolved: mani._resolved, - integrity: mani._integrity, - }) - } - } - mani._signatures = dist.signatures - } else { - mani._signatures = dist.signatures - } - } - - if (dist.attestations) { - if (this.opts.verifyAttestations) { - // Always fetch attestations from the current registry host - const attestationsPath = new URL(dist.attestations.url).pathname - const attestationsUrl = removeTrailingSlashes(this.registry) + attestationsPath - const res = await fetch(attestationsUrl, { - ...this.opts, - // disable integrity check for attestations json payload, we check the - // integrity in the verification steps below - integrity: null, - }) - const { attestations } = await res.json() - const bundles = attestations.map(({ predicateType, bundle }) => { - const statement = JSON.parse( - Buffer.from(bundle.dsseEnvelope.payload, 'base64').toString('utf8') - ) - const keyid = bundle.dsseEnvelope.signatures[0].keyid - const signature = bundle.dsseEnvelope.signatures[0].sig - - return { - predicateType, - bundle, - statement, - keyid, - signature, - } - }) - - const attestationKeyIds = bundles.map((b) => b.keyid).filter((k) => !!k) - const attestationRegistryKeys = (this.registryKeys || []) - .filter(key => attestationKeyIds.includes(key.keyid)) - if (!attestationRegistryKeys.length) { - throw Object.assign(new Error( - `${mani._id} has attestations but no corresponding public key(s) can be found` - ), { code: 'EMISSINGSIGNATUREKEY' }) - } - - for (const { predicateType, bundle, keyid, signature, statement } of bundles) { - const publicKey = attestationRegistryKeys.find(key => key.keyid === keyid) - // Publish attestations have a keyid set and a valid public key must be found - if (keyid) { - if (!publicKey) { - throw Object.assign(new Error( - `${mani._id} has attestations with keyid: ${keyid} ` + - 'but no corresponding public key can be found' - ), { code: 'EMISSINGSIGNATUREKEY' }) - } - - const integratedTime = new Date( - Number( - bundle.verificationMaterial.tlogEntries[0].integratedTime - ) * 1000 - ) - const validPublicKey = !publicKey.expires || - (integratedTime < Date.parse(publicKey.expires)) - if (!validPublicKey) { - throw Object.assign(new Error( - `${mani._id} has attestations with keyid: ${keyid} ` + - `but the corresponding public key has expired ${publicKey.expires}` - ), { code: 'EEXPIREDSIGNATUREKEY' }) - } - } - - const subject = { - name: statement.subject[0].name, - sha512: statement.subject[0].digest.sha512, - } - - // Only type 'version' can be turned into a PURL - const purl = this.spec.type === 'version' ? npa.toPurl(this.spec) : this.spec - // Verify the statement subject matches the package, version - if (subject.name !== purl) { - throw Object.assign(new Error( - `${mani._id} package name and version (PURL): ${purl} ` + - `doesn't match what was signed: ${subject.name}` - ), { code: 'EATTESTATIONSUBJECT' }) - } - - // Verify the statement subject matches the tarball integrity - const integrityHexDigest = ssri.parse(this.integrity).hexDigest() - if (subject.sha512 !== integrityHexDigest) { - throw Object.assign(new Error( - `${mani._id} package integrity (hex digest): ` + - `${integrityHexDigest} ` + - `doesn't match what was signed: ${subject.sha512}` - ), { code: 'EATTESTATIONSUBJECT' }) - } - - try { - // Provenance attestations are signed with a signing certificate - // (including the key) so we don't need to return a public key. - // - // Publish attestations are signed with a keyid so we need to - // specify a public key from the keys endpoint: `registry-host.tld/-/npm/v1/keys` - const options = { - tufCachePath: this.tufCache, - tufForceCache: true, - keySelector: publicKey ? () => publicKey.pemkey : undefined, - } - await sigstore.verify(bundle, options) - } catch (e) { - throw Object.assign(new Error( - `${mani._id} failed to verify attestation: ${e.message}` - ), { - code: 'EATTESTATIONVERIFY', - predicateType, - keyid, - signature, - resolved: mani._resolved, - integrity: mani._integrity, - }) - } - } - mani._attestations = dist.attestations - } else { - mani._attestations = dist.attestations - } - } - } - - this.package = mani - return this.package - } - - [_.tarballFromResolved] () { - // we use a RemoteFetcher to get the actual tarball stream - return new RemoteFetcher(this.resolved, { - ...this.opts, - resolved: this.resolved, - pkgid: `registry:${this.spec.name}@${this.resolved}`, - })[_.tarballFromResolved]() - } - - get types () { - return [ - 'tag', - 'version', - 'range', - ] - } -} -module.exports = RegistryFetcher diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/remote.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/remote.js deleted file mode 100644 index bd321e65a1f18..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/remote.js +++ /dev/null @@ -1,89 +0,0 @@ -const fetch = require('npm-registry-fetch') -const { Minipass } = require('minipass') -const Fetcher = require('./fetcher.js') -const FileFetcher = require('./file.js') -const _ = require('./util/protected.js') -const pacoteVersion = require('../package.json').version - -class RemoteFetcher extends Fetcher { - constructor (spec, opts) { - super(spec, opts) - this.resolved = this.spec.fetchSpec - const resolvedURL = new URL(this.resolved) - if (this.replaceRegistryHost !== 'never' - && (this.replaceRegistryHost === 'always' - || this.replaceRegistryHost === resolvedURL.host)) { - this.resolved = new URL(resolvedURL.pathname, this.registry).href - } - - // nam is a fermented pork sausage that is good to eat - const nameat = this.spec.name ? `${this.spec.name}@` : '' - this.pkgid = opts.pkgid ? opts.pkgid : `remote:${nameat}${this.resolved}` - } - - // Don't need to cache tarball fetches in pacote, because make-fetch-happen - // will write into cacache anyway. - get [_.cacheFetches] () { - return false - } - - [_.tarballFromResolved] () { - const stream = new Minipass() - stream.hasIntegrityEmitter = true - - const fetchOpts = { - ...this.opts, - headers: this.#headers(), - spec: this.spec, - integrity: this.integrity, - algorithms: [this.pickIntegrityAlgorithm()], - } - - // eslint-disable-next-line promise/always-return - fetch(this.resolved, fetchOpts).then(res => { - res.body.on('error', - /* istanbul ignore next - exceedingly rare and hard to simulate */ - er => stream.emit('error', er) - ) - - res.body.on('integrity', i => { - this.integrity = i - stream.emit('integrity', i) - }) - - res.body.pipe(stream) - }).catch(er => stream.emit('error', er)) - - return stream - } - - #headers () { - return { - // npm will override this, but ensure that we always send *something* - 'user-agent': this.opts.userAgent || - `pacote/${pacoteVersion} node/${process.version}`, - ...(this.opts.headers || {}), - 'pacote-version': pacoteVersion, - 'pacote-req-type': 'tarball', - 'pacote-pkg-id': this.pkgid, - ...(this.integrity ? { 'pacote-integrity': String(this.integrity) } - : {}), - ...(this.opts.headers || {}), - } - } - - get types () { - return ['remote'] - } - - // getting a packument and/or manifest is the same as with a file: spec. - // unpack the tarball stream, and then read from the package.json file. - packument () { - return FileFetcher.prototype.packument.apply(this) - } - - manifest () { - return FileFetcher.prototype.manifest.apply(this) - } -} -module.exports = RemoteFetcher diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/add-git-sha.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/add-git-sha.js deleted file mode 100644 index 843fe5b600caf..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/add-git-sha.js +++ /dev/null @@ -1,15 +0,0 @@ -// add a sha to a git remote url spec -const addGitSha = (spec, sha) => { - if (spec.hosted) { - const h = spec.hosted - const opt = { noCommittish: true } - const base = h.https && h.auth ? h.https(opt) : h.shortcut(opt) - - return `${base}#${sha}` - } else { - // don't use new URL for this, because it doesn't handle scp urls - return spec.rawSpec.replace(/#.*$/, '') + `#${sha}` - } -} - -module.exports = addGitSha diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/cache-dir.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/cache-dir.js deleted file mode 100644 index ba5683a7bb5bf..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/cache-dir.js +++ /dev/null @@ -1,15 +0,0 @@ -const { resolve } = require('node:path') -const { tmpdir, homedir } = require('node:os') - -module.exports = (fakePlatform = false) => { - const temp = tmpdir() - const uidOrPid = process.getuid ? process.getuid() : process.pid - const home = homedir() || resolve(temp, 'npm-' + uidOrPid) - const platform = fakePlatform || process.platform - const cacheExtra = platform === 'win32' ? 'npm-cache' : '.npm' - const cacheRoot = (platform === 'win32' && process.env.LOCALAPPDATA) || home - return { - cacache: resolve(cacheRoot, cacheExtra, '_cacache'), - tufcache: resolve(cacheRoot, cacheExtra, '_tuf'), - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/is-package-bin.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/is-package-bin.js deleted file mode 100644 index 49a3f73f537ce..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/is-package-bin.js +++ /dev/null @@ -1,25 +0,0 @@ -// Function to determine whether a path is in the package.bin set. -// Used to prevent issues when people publish a package from a -// windows machine, and then install with --no-bin-links. -// -// Note: this is not possible in remote or file fetchers, since -// we don't have the manifest until AFTER we've unpacked. But the -// main use case is registry fetching with git a distant second, -// so that's an acceptable edge case to not handle. - -const binObj = (name, bin) => - typeof bin === 'string' ? { [name]: bin } : bin - -const hasBin = (pkg, path) => { - const bin = binObj(pkg.name, pkg.bin) - const p = path.replace(/^[^\\/]*\//, '') - for (const kv of Object.entries(bin)) { - if (kv[1] === p) { - return true - } - } - return false -} - -module.exports = (pkg, path) => - pkg && pkg.bin ? hasBin(pkg, path) : false diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/npm.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/npm.js deleted file mode 100644 index a3005c255565f..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/npm.js +++ /dev/null @@ -1,14 +0,0 @@ -// run an npm command -const spawn = require('@npmcli/promise-spawn') - -module.exports = (npmBin, npmCommand, cwd, env, extra) => { - const isJS = npmBin.endsWith('.js') - const cmd = isJS ? process.execPath : npmBin - const args = (isJS ? [npmBin] : []).concat(npmCommand) - // when installing to run the `prepare` script for a git dep, we need - // to ensure that we don't run into a cycle of checking out packages - // in temp directories. this lets us link previously-seen repos that - // are also being prepared. - - return spawn(cmd, args, { cwd, env }, extra) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/protected.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/protected.js deleted file mode 100644 index e05203b481e6a..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/protected.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = { - cacheFetches: Symbol.for('pacote.Fetcher._cacheFetches'), - readPackageJson: Symbol.for('package.Fetcher._readPackageJson'), - tarballFromResolved: Symbol.for('pacote.Fetcher._tarballFromResolved'), -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/tar-create-options.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/tar-create-options.js deleted file mode 100644 index d070f0f7ba2d4..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/tar-create-options.js +++ /dev/null @@ -1,31 +0,0 @@ -const isPackageBin = require('./is-package-bin.js') - -const tarCreateOptions = manifest => ({ - cwd: manifest._resolved, - prefix: 'package/', - portable: true, - gzip: { - // forcing the level to 9 seems to avoid some - // platform specific optimizations that cause - // integrity mismatch errors due to differing - // end results after compression - level: 9, - }, - - // ensure that package bins are always executable - // Note that npm-packlist is already filtering out - // anything that is not a regular file, ignored by - // .npmignore or package.json "files", etc. - filter: (path, stat) => { - if (isPackageBin(manifest, path)) { - stat.mode |= 0o111 - } - return true - }, - - // Provide a specific date in the 1980s for the benefit of zip, - // which is confounded by files dated at the Unix epoch 0. - mtime: new Date('1985-10-26T08:15:00.000Z'), -}) - -module.exports = tarCreateOptions diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/trailing-slashes.js b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/trailing-slashes.js deleted file mode 100644 index c50cb6173b92e..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/lib/util/trailing-slashes.js +++ /dev/null @@ -1,10 +0,0 @@ -const removeTrailingSlashes = (input) => { - // in order to avoid regexp redos detection - let output = input - while (output.endsWith('/')) { - output = output.slice(0, -1) - } - return output -} - -module.exports = removeTrailingSlashes diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/package.json deleted file mode 100644 index caadaf2db50c8..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/pacote/package.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "name": "pacote", - "version": "18.0.6", - "description": "JavaScript package downloader", - "author": "GitHub Inc.", - "bin": { - "pacote": "bin/index.js" - }, - "license": "ISC", - "main": "lib/index.js", - "scripts": { - "test": "tap", - "snap": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "posttest": "npm run lint", - "template-oss-apply": "template-oss-apply --force" - }, - "tap": { - "timeout": 300, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "devDependencies": { - "@npmcli/arborist": "^7.1.0", - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "hosted-git-info": "^7.0.0", - "mutate-fs": "^2.1.1", - "nock": "^13.2.4", - "npm-registry-mock": "^1.3.2", - "tap": "^16.0.1" - }, - "files": [ - "bin/", - "lib/" - ], - "keywords": [ - "packages", - "npm", - "git" - ], - "dependencies": { - "@npmcli/git": "^5.0.0", - "@npmcli/installed-package-contents": "^2.0.1", - "@npmcli/package-json": "^5.1.0", - "@npmcli/promise-spawn": "^7.0.0", - "@npmcli/run-script": "^8.0.0", - "cacache": "^18.0.0", - "fs-minipass": "^3.0.0", - "minipass": "^7.0.2", - "npm-package-arg": "^11.0.0", - "npm-packlist": "^8.0.0", - "npm-pick-manifest": "^9.0.0", - "npm-registry-fetch": "^17.0.0", - "proc-log": "^4.0.0", - "promise-retry": "^2.0.1", - "sigstore": "^2.2.0", - "ssri": "^10.0.0", - "tar": "^6.1.11" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/pacote.git" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "windowsCI": false, - "publish": "true" - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log/LICENSE deleted file mode 100644 index 83837797202b7..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) GitHub, Inc. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log/lib/index.js deleted file mode 100644 index 86d90861078da..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log/lib/index.js +++ /dev/null @@ -1,153 +0,0 @@ -const META = Symbol('proc-log.meta') -module.exports = { - META: META, - output: { - LEVELS: [ - 'standard', - 'error', - 'buffer', - 'flush', - ], - KEYS: { - standard: 'standard', - error: 'error', - buffer: 'buffer', - flush: 'flush', - }, - standard: function (...args) { - return process.emit('output', 'standard', ...args) - }, - error: function (...args) { - return process.emit('output', 'error', ...args) - }, - buffer: function (...args) { - return process.emit('output', 'buffer', ...args) - }, - flush: function (...args) { - return process.emit('output', 'flush', ...args) - }, - }, - log: { - LEVELS: [ - 'notice', - 'error', - 'warn', - 'info', - 'verbose', - 'http', - 'silly', - 'timing', - 'pause', - 'resume', - ], - KEYS: { - notice: 'notice', - error: 'error', - warn: 'warn', - info: 'info', - verbose: 'verbose', - http: 'http', - silly: 'silly', - timing: 'timing', - pause: 'pause', - resume: 'resume', - }, - error: function (...args) { - return process.emit('log', 'error', ...args) - }, - notice: function (...args) { - return process.emit('log', 'notice', ...args) - }, - warn: function (...args) { - return process.emit('log', 'warn', ...args) - }, - info: function (...args) { - return process.emit('log', 'info', ...args) - }, - verbose: function (...args) { - return process.emit('log', 'verbose', ...args) - }, - http: function (...args) { - return process.emit('log', 'http', ...args) - }, - silly: function (...args) { - return process.emit('log', 'silly', ...args) - }, - timing: function (...args) { - return process.emit('log', 'timing', ...args) - }, - pause: function () { - return process.emit('log', 'pause') - }, - resume: function () { - return process.emit('log', 'resume') - }, - }, - time: { - LEVELS: [ - 'start', - 'end', - ], - KEYS: { - start: 'start', - end: 'end', - }, - start: function (name, fn) { - process.emit('time', 'start', name) - function end () { - return process.emit('time', 'end', name) - } - if (typeof fn === 'function') { - const res = fn() - if (res && res.finally) { - return res.finally(end) - } - end() - return res - } - return end - }, - end: function (name) { - return process.emit('time', 'end', name) - }, - }, - input: { - LEVELS: [ - 'start', - 'end', - 'read', - ], - KEYS: { - start: 'start', - end: 'end', - read: 'read', - }, - start: function (fn) { - process.emit('input', 'start') - function end () { - return process.emit('input', 'end') - } - if (typeof fn === 'function') { - const res = fn() - if (res && res.finally) { - return res.finally(end) - } - end() - return res - } - return end - }, - end: function () { - return process.emit('input', 'end') - }, - read: function (...args) { - let resolve, reject - const promise = new Promise((_resolve, _reject) => { - resolve = _resolve - reject = _reject - }) - process.emit('input', 'read', resolve, reject, ...args) - return promise - }, - }, -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log/package.json deleted file mode 100644 index 4ab89102ecc9b..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/proc-log/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "proc-log", - "version": "4.2.0", - "files": [ - "bin/", - "lib/" - ], - "main": "lib/index.js", - "description": "just emit 'log' events on the process object", - "repository": { - "type": "git", - "url": "https://github.com/npm/proc-log.git" - }, - "author": "GitHub Inc.", - "license": "ISC", - "scripts": { - "test": "tap", - "snap": "tap", - "posttest": "npm run lint", - "postsnap": "eslint index.js test/*.js --fix", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "lintfix": "npm run lint -- --fix", - "template-oss-apply": "template-oss-apply --force" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.3", - "tap": "^16.0.1" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.3", - "publish": true - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/ssri/LICENSE.md b/node_modules/@npmcli/metavuln-calculator/node_modules/ssri/LICENSE.md deleted file mode 100644 index e335388869f50..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/ssri/LICENSE.md +++ /dev/null @@ -1,16 +0,0 @@ -ISC License - -Copyright 2021 (c) npm, Inc. - -Permission to use, copy, modify, and/or distribute this software for -any purpose with or without fee is hereby granted, provided that the -above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS -ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR -CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE -USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/ssri/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/ssri/lib/index.js deleted file mode 100644 index 7d749ed480fb9..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/ssri/lib/index.js +++ /dev/null @@ -1,580 +0,0 @@ -'use strict' - -const crypto = require('crypto') -const { Minipass } = require('minipass') - -const SPEC_ALGORITHMS = ['sha512', 'sha384', 'sha256'] -const DEFAULT_ALGORITHMS = ['sha512'] - -// TODO: this should really be a hardcoded list of algorithms we support, -// rather than [a-z0-9]. -const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i -const SRI_REGEX = /^([a-z0-9]+)-([^?]+)([?\S*]*)$/ -const STRICT_SRI_REGEX = /^([a-z0-9]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)?$/ -const VCHAR_REGEX = /^[\x21-\x7E]+$/ - -const getOptString = options => options?.length ? `?${options.join('?')}` : '' - -class IntegrityStream extends Minipass { - #emittedIntegrity - #emittedSize - #emittedVerified - - constructor (opts) { - super() - this.size = 0 - this.opts = opts - - // may be overridden later, but set now for class consistency - this.#getOptions() - - // options used for calculating stream. can't be changed. - if (opts?.algorithms) { - this.algorithms = [...opts.algorithms] - } else { - this.algorithms = [...DEFAULT_ALGORITHMS] - } - if (this.algorithm !== null && !this.algorithms.includes(this.algorithm)) { - this.algorithms.push(this.algorithm) - } - - this.hashes = this.algorithms.map(crypto.createHash) - } - - #getOptions () { - // For verification - this.sri = this.opts?.integrity ? parse(this.opts?.integrity, this.opts) : null - this.expectedSize = this.opts?.size - - if (!this.sri) { - this.algorithm = null - } else if (this.sri.isHash) { - this.goodSri = true - this.algorithm = this.sri.algorithm - } else { - this.goodSri = !this.sri.isEmpty() - this.algorithm = this.sri.pickAlgorithm(this.opts) - } - - this.digests = this.goodSri ? this.sri[this.algorithm] : null - this.optString = getOptString(this.opts?.options) - } - - on (ev, handler) { - if (ev === 'size' && this.#emittedSize) { - return handler(this.#emittedSize) - } - - if (ev === 'integrity' && this.#emittedIntegrity) { - return handler(this.#emittedIntegrity) - } - - if (ev === 'verified' && this.#emittedVerified) { - return handler(this.#emittedVerified) - } - - return super.on(ev, handler) - } - - emit (ev, data) { - if (ev === 'end') { - this.#onEnd() - } - return super.emit(ev, data) - } - - write (data) { - this.size += data.length - this.hashes.forEach(h => h.update(data)) - return super.write(data) - } - - #onEnd () { - if (!this.goodSri) { - this.#getOptions() - } - const newSri = parse(this.hashes.map((h, i) => { - return `${this.algorithms[i]}-${h.digest('base64')}${this.optString}` - }).join(' '), this.opts) - // Integrity verification mode - const match = this.goodSri && newSri.match(this.sri, this.opts) - if (typeof this.expectedSize === 'number' && this.size !== this.expectedSize) { - /* eslint-disable-next-line max-len */ - const err = new Error(`stream size mismatch when checking ${this.sri}.\n Wanted: ${this.expectedSize}\n Found: ${this.size}`) - err.code = 'EBADSIZE' - err.found = this.size - err.expected = this.expectedSize - err.sri = this.sri - this.emit('error', err) - } else if (this.sri && !match) { - /* eslint-disable-next-line max-len */ - const err = new Error(`${this.sri} integrity checksum failed when using ${this.algorithm}: wanted ${this.digests} but got ${newSri}. (${this.size} bytes)`) - err.code = 'EINTEGRITY' - err.found = newSri - err.expected = this.digests - err.algorithm = this.algorithm - err.sri = this.sri - this.emit('error', err) - } else { - this.#emittedSize = this.size - this.emit('size', this.size) - this.#emittedIntegrity = newSri - this.emit('integrity', newSri) - if (match) { - this.#emittedVerified = match - this.emit('verified', match) - } - } - } -} - -class Hash { - get isHash () { - return true - } - - constructor (hash, opts) { - const strict = opts?.strict - this.source = hash.trim() - - // set default values so that we make V8 happy to - // always see a familiar object template. - this.digest = '' - this.algorithm = '' - this.options = [] - - // 3.1. Integrity metadata (called "Hash" by ssri) - // https://w3c.github.io/webappsec-subresource-integrity/#integrity-metadata-description - const match = this.source.match( - strict - ? STRICT_SRI_REGEX - : SRI_REGEX - ) - if (!match) { - return - } - if (strict && !SPEC_ALGORITHMS.includes(match[1])) { - return - } - this.algorithm = match[1] - this.digest = match[2] - - const rawOpts = match[3] - if (rawOpts) { - this.options = rawOpts.slice(1).split('?') - } - } - - hexDigest () { - return this.digest && Buffer.from(this.digest, 'base64').toString('hex') - } - - toJSON () { - return this.toString() - } - - match (integrity, opts) { - const other = parse(integrity, opts) - if (!other) { - return false - } - if (other.isIntegrity) { - const algo = other.pickAlgorithm(opts, [this.algorithm]) - - if (!algo) { - return false - } - - const foundHash = other[algo].find(hash => hash.digest === this.digest) - - if (foundHash) { - return foundHash - } - - return false - } - return other.digest === this.digest ? other : false - } - - toString (opts) { - if (opts?.strict) { - // Strict mode enforces the standard as close to the foot of the - // letter as it can. - if (!( - // The spec has very restricted productions for algorithms. - // https://www.w3.org/TR/CSP2/#source-list-syntax - SPEC_ALGORITHMS.includes(this.algorithm) && - // Usually, if someone insists on using a "different" base64, we - // leave it as-is, since there's multiple standards, and the - // specified is not a URL-safe variant. - // https://www.w3.org/TR/CSP2/#base64_value - this.digest.match(BASE64_REGEX) && - // Option syntax is strictly visual chars. - // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-option-expression - // https://tools.ietf.org/html/rfc5234#appendix-B.1 - this.options.every(opt => opt.match(VCHAR_REGEX)) - )) { - return '' - } - } - return `${this.algorithm}-${this.digest}${getOptString(this.options)}` - } -} - -function integrityHashToString (toString, sep, opts, hashes) { - const toStringIsNotEmpty = toString !== '' - - let shouldAddFirstSep = false - let complement = '' - - const lastIndex = hashes.length - 1 - - for (let i = 0; i < lastIndex; i++) { - const hashString = Hash.prototype.toString.call(hashes[i], opts) - - if (hashString) { - shouldAddFirstSep = true - - complement += hashString - complement += sep - } - } - - const finalHashString = Hash.prototype.toString.call(hashes[lastIndex], opts) - - if (finalHashString) { - shouldAddFirstSep = true - complement += finalHashString - } - - if (toStringIsNotEmpty && shouldAddFirstSep) { - return toString + sep + complement - } - - return toString + complement -} - -class Integrity { - get isIntegrity () { - return true - } - - toJSON () { - return this.toString() - } - - isEmpty () { - return Object.keys(this).length === 0 - } - - toString (opts) { - let sep = opts?.sep || ' ' - let toString = '' - - if (opts?.strict) { - // Entries must be separated by whitespace, according to spec. - sep = sep.replace(/\S+/g, ' ') - - for (const hash of SPEC_ALGORITHMS) { - if (this[hash]) { - toString = integrityHashToString(toString, sep, opts, this[hash]) - } - } - } else { - for (const hash of Object.keys(this)) { - toString = integrityHashToString(toString, sep, opts, this[hash]) - } - } - - return toString - } - - concat (integrity, opts) { - const other = typeof integrity === 'string' - ? integrity - : stringify(integrity, opts) - return parse(`${this.toString(opts)} ${other}`, opts) - } - - hexDigest () { - return parse(this, { single: true }).hexDigest() - } - - // add additional hashes to an integrity value, but prevent - // *changing* an existing integrity hash. - merge (integrity, opts) { - const other = parse(integrity, opts) - for (const algo in other) { - if (this[algo]) { - if (!this[algo].find(hash => - other[algo].find(otherhash => - hash.digest === otherhash.digest))) { - throw new Error('hashes do not match, cannot update integrity') - } - } else { - this[algo] = other[algo] - } - } - } - - match (integrity, opts) { - const other = parse(integrity, opts) - if (!other) { - return false - } - const algo = other.pickAlgorithm(opts, Object.keys(this)) - return ( - !!algo && - this[algo] && - other[algo] && - this[algo].find(hash => - other[algo].find(otherhash => - hash.digest === otherhash.digest - ) - ) - ) || false - } - - // Pick the highest priority algorithm present, optionally also limited to a - // set of hashes found in another integrity. When limiting it may return - // nothing. - pickAlgorithm (opts, hashes) { - const pickAlgorithm = opts?.pickAlgorithm || getPrioritizedHash - const keys = Object.keys(this).filter(k => { - if (hashes?.length) { - return hashes.includes(k) - } - return true - }) - if (keys.length) { - return keys.reduce((acc, algo) => pickAlgorithm(acc, algo) || acc) - } - // no intersection between this and hashes, - return null - } -} - -module.exports.parse = parse -function parse (sri, opts) { - if (!sri) { - return null - } - if (typeof sri === 'string') { - return _parse(sri, opts) - } else if (sri.algorithm && sri.digest) { - const fullSri = new Integrity() - fullSri[sri.algorithm] = [sri] - return _parse(stringify(fullSri, opts), opts) - } else { - return _parse(stringify(sri, opts), opts) - } -} - -function _parse (integrity, opts) { - // 3.4.3. Parse metadata - // https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata - if (opts?.single) { - return new Hash(integrity, opts) - } - const hashes = integrity.trim().split(/\s+/).reduce((acc, string) => { - const hash = new Hash(string, opts) - if (hash.algorithm && hash.digest) { - const algo = hash.algorithm - if (!acc[algo]) { - acc[algo] = [] - } - acc[algo].push(hash) - } - return acc - }, new Integrity()) - return hashes.isEmpty() ? null : hashes -} - -module.exports.stringify = stringify -function stringify (obj, opts) { - if (obj.algorithm && obj.digest) { - return Hash.prototype.toString.call(obj, opts) - } else if (typeof obj === 'string') { - return stringify(parse(obj, opts), opts) - } else { - return Integrity.prototype.toString.call(obj, opts) - } -} - -module.exports.fromHex = fromHex -function fromHex (hexDigest, algorithm, opts) { - const optString = getOptString(opts?.options) - return parse( - `${algorithm}-${ - Buffer.from(hexDigest, 'hex').toString('base64') - }${optString}`, opts - ) -} - -module.exports.fromData = fromData -function fromData (data, opts) { - const algorithms = opts?.algorithms || [...DEFAULT_ALGORITHMS] - const optString = getOptString(opts?.options) - return algorithms.reduce((acc, algo) => { - const digest = crypto.createHash(algo).update(data).digest('base64') - const hash = new Hash( - `${algo}-${digest}${optString}`, - opts - ) - /* istanbul ignore else - it would be VERY strange if the string we - * just calculated with an algo did not have an algo or digest. - */ - if (hash.algorithm && hash.digest) { - const hashAlgo = hash.algorithm - if (!acc[hashAlgo]) { - acc[hashAlgo] = [] - } - acc[hashAlgo].push(hash) - } - return acc - }, new Integrity()) -} - -module.exports.fromStream = fromStream -function fromStream (stream, opts) { - const istream = integrityStream(opts) - return new Promise((resolve, reject) => { - stream.pipe(istream) - stream.on('error', reject) - istream.on('error', reject) - let sri - istream.on('integrity', s => { - sri = s - }) - istream.on('end', () => resolve(sri)) - istream.resume() - }) -} - -module.exports.checkData = checkData -function checkData (data, sri, opts) { - sri = parse(sri, opts) - if (!sri || !Object.keys(sri).length) { - if (opts?.error) { - throw Object.assign( - new Error('No valid integrity hashes to check against'), { - code: 'EINTEGRITY', - } - ) - } else { - return false - } - } - const algorithm = sri.pickAlgorithm(opts) - const digest = crypto.createHash(algorithm).update(data).digest('base64') - const newSri = parse({ algorithm, digest }) - const match = newSri.match(sri, opts) - opts = opts || {} - if (match || !(opts.error)) { - return match - } else if (typeof opts.size === 'number' && (data.length !== opts.size)) { - /* eslint-disable-next-line max-len */ - const err = new Error(`data size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${data.length}`) - err.code = 'EBADSIZE' - err.found = data.length - err.expected = opts.size - err.sri = sri - throw err - } else { - /* eslint-disable-next-line max-len */ - const err = new Error(`Integrity checksum failed when using ${algorithm}: Wanted ${sri}, but got ${newSri}. (${data.length} bytes)`) - err.code = 'EINTEGRITY' - err.found = newSri - err.expected = sri - err.algorithm = algorithm - err.sri = sri - throw err - } -} - -module.exports.checkStream = checkStream -function checkStream (stream, sri, opts) { - opts = opts || Object.create(null) - opts.integrity = sri - sri = parse(sri, opts) - if (!sri || !Object.keys(sri).length) { - return Promise.reject(Object.assign( - new Error('No valid integrity hashes to check against'), { - code: 'EINTEGRITY', - } - )) - } - const checker = integrityStream(opts) - return new Promise((resolve, reject) => { - stream.pipe(checker) - stream.on('error', reject) - checker.on('error', reject) - let verified - checker.on('verified', s => { - verified = s - }) - checker.on('end', () => resolve(verified)) - checker.resume() - }) -} - -module.exports.integrityStream = integrityStream -function integrityStream (opts = Object.create(null)) { - return new IntegrityStream(opts) -} - -module.exports.create = createIntegrity -function createIntegrity (opts) { - const algorithms = opts?.algorithms || [...DEFAULT_ALGORITHMS] - const optString = getOptString(opts?.options) - - const hashes = algorithms.map(crypto.createHash) - - return { - update: function (chunk, enc) { - hashes.forEach(h => h.update(chunk, enc)) - return this - }, - digest: function () { - const integrity = algorithms.reduce((acc, algo) => { - const digest = hashes.shift().digest('base64') - const hash = new Hash( - `${algo}-${digest}${optString}`, - opts - ) - /* istanbul ignore else - it would be VERY strange if the hash we - * just calculated with an algo did not have an algo or digest. - */ - if (hash.algorithm && hash.digest) { - const hashAlgo = hash.algorithm - if (!acc[hashAlgo]) { - acc[hashAlgo] = [] - } - acc[hashAlgo].push(hash) - } - return acc - }, new Integrity()) - - return integrity - }, - } -} - -const NODE_HASHES = crypto.getHashes() - -// This is a Best Effort™ at a reasonable priority for hash algos -const DEFAULT_PRIORITY = [ - 'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', - // TODO - it's unclear _which_ of these Node will actually use as its name - // for the algorithm, so we guesswork it based on the OpenSSL names. - 'sha3', - 'sha3-256', 'sha3-384', 'sha3-512', - 'sha3_256', 'sha3_384', 'sha3_512', -].filter(algo => NODE_HASHES.includes(algo)) - -function getPrioritizedHash (algo1, algo2) { - /* eslint-disable-next-line max-len */ - return DEFAULT_PRIORITY.indexOf(algo1.toLowerCase()) >= DEFAULT_PRIORITY.indexOf(algo2.toLowerCase()) - ? algo1 - : algo2 -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/ssri/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/ssri/package.json deleted file mode 100644 index 28395414e4643..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/ssri/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "name": "ssri", - "version": "10.0.6", - "description": "Standard Subresource Integrity library -- parses, serializes, generates, and verifies integrity metadata according to the SRI spec.", - "main": "lib/index.js", - "files": [ - "bin/", - "lib/" - ], - "scripts": { - "prerelease": "npm t", - "postrelease": "npm publish", - "posttest": "npm run lint", - "test": "tap", - "coverage": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap" - }, - "tap": { - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/ssri.git" - }, - "keywords": [ - "w3c", - "web", - "security", - "integrity", - "checksum", - "hashing", - "subresource integrity", - "sri", - "sri hash", - "sri string", - "sri generator", - "html" - ], - "author": "GitHub Inc.", - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": "true" - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename/LICENSE deleted file mode 100644 index 69619c125ea7e..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename/LICENSE +++ /dev/null @@ -1,5 +0,0 @@ -Copyright npm, Inc - -Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename/lib/index.js deleted file mode 100644 index d067d2e709809..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename/lib/index.js +++ /dev/null @@ -1,7 +0,0 @@ -var path = require('path') - -var uniqueSlug = require('unique-slug') - -module.exports = function (filepath, prefix, uniq) { - return path.join(filepath, (prefix ? prefix + '-' : '') + uniqueSlug(uniq)) -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename/package.json deleted file mode 100644 index b2fbf0666489a..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "unique-filename", - "version": "3.0.0", - "description": "Generate a unique filename for use in temporary directories or caches.", - "main": "lib/index.js", - "scripts": { - "test": "tap", - "lint": "eslint \"**/*.js\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" - }, - "repository": { - "type": "git", - "url": "https://github.com/npm/unique-filename.git" - }, - "keywords": [], - "author": "GitHub Inc.", - "license": "ISC", - "bugs": { - "url": "https://github.com/iarna/unique-filename/issues" - }, - "homepage": "https://github.com/iarna/unique-filename", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.5.1", - "tap": "^16.3.0" - }, - "dependencies": { - "unique-slug": "^4.0.0" - }, - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.5.1" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug/LICENSE deleted file mode 100644 index 7953647e7760b..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright npm, Inc - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug/lib/index.js deleted file mode 100644 index 1bac84d95d730..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug/lib/index.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict' -var MurmurHash3 = require('imurmurhash') - -module.exports = function (uniq) { - if (uniq) { - var hash = new MurmurHash3(uniq) - return ('00000000' + hash.result().toString(16)).slice(-8) - } else { - return (Math.random().toString(16) + '0000000').slice(2, 10) - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug/package.json deleted file mode 100644 index 33732cdbb4285..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "unique-slug", - "version": "4.0.0", - "description": "Generate a unique character string suitible for use in files and URLs.", - "main": "lib/index.js", - "scripts": { - "test": "tap", - "lint": "eslint \"**/*.js\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" - }, - "keywords": [], - "author": "GitHub Inc.", - "license": "ISC", - "devDependencies": { - "@npmcli/eslint-config": "^3.1.0", - "@npmcli/template-oss": "4.5.1", - "tap": "^16.3.0" - }, - "repository": { - "type": "git", - "url": "https://github.com/npm/unique-slug.git" - }, - "dependencies": { - "imurmurhash": "^0.1.4" - }, - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.5.1" - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name/LICENSE deleted file mode 100644 index fdcd63b302308..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name/LICENSE +++ /dev/null @@ -1,6 +0,0 @@ -Copyright (c) 2015, npm, Inc - - -Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name/lib/index.js deleted file mode 100644 index fd800d5a5eae1..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name/lib/index.js +++ /dev/null @@ -1,105 +0,0 @@ -'use strict' -const { builtinModules: builtins } = require('module') - -var scopedPackagePattern = new RegExp('^(?:@([^/]+?)[/])?([^/]+?)$') -var blacklist = [ - 'node_modules', - 'favicon.ico', -] - -function validate (name) { - var warnings = [] - var errors = [] - - if (name === null) { - errors.push('name cannot be null') - return done(warnings, errors) - } - - if (name === undefined) { - errors.push('name cannot be undefined') - return done(warnings, errors) - } - - if (typeof name !== 'string') { - errors.push('name must be a string') - return done(warnings, errors) - } - - if (!name.length) { - errors.push('name length must be greater than zero') - } - - if (name.match(/^\./)) { - errors.push('name cannot start with a period') - } - - if (name.match(/^_/)) { - errors.push('name cannot start with an underscore') - } - - if (name.trim() !== name) { - errors.push('name cannot contain leading or trailing spaces') - } - - // No funny business - blacklist.forEach(function (blacklistedName) { - if (name.toLowerCase() === blacklistedName) { - errors.push(blacklistedName + ' is a blacklisted name') - } - }) - - // Generate warnings for stuff that used to be allowed - - // core module names like http, events, util, etc - if (builtins.includes(name.toLowerCase())) { - warnings.push(name + ' is a core module name') - } - - if (name.length > 214) { - warnings.push('name can no longer contain more than 214 characters') - } - - // mIxeD CaSe nAMEs - if (name.toLowerCase() !== name) { - warnings.push('name can no longer contain capital letters') - } - - if (/[~'!()*]/.test(name.split('/').slice(-1)[0])) { - warnings.push('name can no longer contain special characters ("~\'!()*")') - } - - if (encodeURIComponent(name) !== name) { - // Maybe it's a scoped package name, like @user/package - var nameMatch = name.match(scopedPackagePattern) - if (nameMatch) { - var user = nameMatch[1] - var pkg = nameMatch[2] - if (encodeURIComponent(user) === user && encodeURIComponent(pkg) === pkg) { - return done(warnings, errors) - } - } - - errors.push('name can only contain URL-friendly characters') - } - - return done(warnings, errors) -} - -var done = function (warnings, errors) { - var result = { - validForNewPackages: errors.length === 0 && warnings.length === 0, - validForOldPackages: errors.length === 0, - warnings: warnings, - errors: errors, - } - if (!result.warnings.length) { - delete result.warnings - } - if (!result.errors.length) { - delete result.errors - } - return result -} - -module.exports = validate diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name/package.json deleted file mode 100644 index 8a38b66e1d3e4..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "name": "validate-npm-package-name", - "version": "5.0.1", - "description": "Give me a string and I'll tell you if it's a valid npm package name", - "main": "lib/", - "directories": { - "test": "test" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "tap": "^16.0.1" - }, - "scripts": { - "cov:test": "TAP_FLAGS='--cov' npm run test:code", - "test:code": "tap ${TAP_FLAGS:-'--'} test/*.js", - "test:style": "standard", - "test": "tap", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/npm/validate-npm-package-name.git" - }, - "keywords": [ - "npm", - "package", - "names", - "validation" - ], - "author": "GitHub Inc.", - "license": "ISC", - "bugs": { - "url": "https://github.com/npm/validate-npm-package-name/issues" - }, - "homepage": "https://github.com/npm/validate-npm-package-name", - "files": [ - "bin/", - "lib/" - ], - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "publish": true - }, - "tap": { - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/which/LICENSE b/node_modules/@npmcli/metavuln-calculator/node_modules/which/LICENSE deleted file mode 100644 index 19129e315fe59..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/which/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/which/bin/which.js b/node_modules/@npmcli/metavuln-calculator/node_modules/which/bin/which.js deleted file mode 100755 index 6df16f21acf93..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/which/bin/which.js +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env node - -const which = require('../lib') -const argv = process.argv.slice(2) - -const usage = (err) => { - if (err) { - console.error(`which: ${err}`) - } - console.error('usage: which [-as] program ...') - process.exit(1) -} - -if (!argv.length) { - return usage() -} - -let dashdash = false -const [commands, flags] = argv.reduce((acc, arg) => { - if (dashdash || arg === '--') { - dashdash = true - return acc - } - - if (!/^-/.test(arg)) { - acc[0].push(arg) - return acc - } - - for (const flag of arg.slice(1).split('')) { - if (flag === 's') { - acc[1].silent = true - } else if (flag === 'a') { - acc[1].all = true - } else { - usage(`illegal option -- ${flag}`) - } - } - - return acc -}, [[], {}]) - -for (const command of commands) { - try { - const res = which.sync(command, { all: flags.all }) - if (!flags.silent) { - console.log([].concat(res).join('\n')) - } - } catch (err) { - process.exitCode = 1 - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/which/lib/index.js b/node_modules/@npmcli/metavuln-calculator/node_modules/which/lib/index.js deleted file mode 100644 index 2fd358baf888f..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/which/lib/index.js +++ /dev/null @@ -1,111 +0,0 @@ -const { isexe, sync: isexeSync } = require('isexe') -const { join, delimiter, sep, posix } = require('path') - -const isWindows = process.platform === 'win32' - -// used to check for slashed in commands passed in. always checks for the posix -// seperator on all platforms, and checks for the current separator when not on -// a posix platform. don't use the isWindows check for this since that is mocked -// in tests but we still need the code to actually work when called. that is also -// why it is ignored from coverage. -/* istanbul ignore next */ -const rSlash = new RegExp(`[${posix.sep}${sep === posix.sep ? '' : sep}]`.replace(/(\\)/g, '\\$1')) -const rRel = new RegExp(`^\\.${rSlash.source}`) - -const getNotFoundError = (cmd) => - Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) - -const getPathInfo = (cmd, { - path: optPath = process.env.PATH, - pathExt: optPathExt = process.env.PATHEXT, - delimiter: optDelimiter = delimiter, -}) => { - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - const pathEnv = cmd.match(rSlash) ? [''] : [ - // windows always checks the cwd first - ...(isWindows ? [process.cwd()] : []), - ...(optPath || /* istanbul ignore next: very unusual */ '').split(optDelimiter), - ] - - if (isWindows) { - const pathExtExe = optPathExt || - ['.EXE', '.CMD', '.BAT', '.COM'].join(optDelimiter) - const pathExt = pathExtExe.split(optDelimiter).flatMap((item) => [item, item.toLowerCase()]) - if (cmd.includes('.') && pathExt[0] !== '') { - pathExt.unshift('') - } - return { pathEnv, pathExt, pathExtExe } - } - - return { pathEnv, pathExt: [''] } -} - -const getPathPart = (raw, cmd) => { - const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw - const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : '' - return prefix + join(pathPart, cmd) -} - -const which = async (cmd, opt = {}) => { - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] - - for (const envPart of pathEnv) { - const p = getPathPart(envPart, cmd) - - for (const ext of pathExt) { - const withExt = p + ext - const is = await isexe(withExt, { pathExt: pathExtExe, ignoreErrors: true }) - if (is) { - if (!opt.all) { - return withExt - } - found.push(withExt) - } - } - } - - if (opt.all && found.length) { - return found - } - - if (opt.nothrow) { - return null - } - - throw getNotFoundError(cmd) -} - -const whichSync = (cmd, opt = {}) => { - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] - - for (const pathEnvPart of pathEnv) { - const p = getPathPart(pathEnvPart, cmd) - - for (const ext of pathExt) { - const withExt = p + ext - const is = isexeSync(withExt, { pathExt: pathExtExe, ignoreErrors: true }) - if (is) { - if (!opt.all) { - return withExt - } - found.push(withExt) - } - } - } - - if (opt.all && found.length) { - return found - } - - if (opt.nothrow) { - return null - } - - throw getNotFoundError(cmd) -} - -module.exports = which -which.sync = whichSync diff --git a/node_modules/@npmcli/metavuln-calculator/node_modules/which/package.json b/node_modules/@npmcli/metavuln-calculator/node_modules/which/package.json deleted file mode 100644 index 515bfb22ca0e1..0000000000000 --- a/node_modules/@npmcli/metavuln-calculator/node_modules/which/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "author": "GitHub Inc.", - "name": "which", - "description": "Like which(1) unix command. Find the first instance of an executable in the PATH.", - "version": "4.0.0", - "repository": { - "type": "git", - "url": "https://github.com/npm/node-which.git" - }, - "main": "lib/index.js", - "bin": { - "node-which": "./bin/which.js" - }, - "license": "ISC", - "dependencies": { - "isexe": "^3.1.1" - }, - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.18.0", - "tap": "^16.3.0" - }, - "scripts": { - "test": "tap", - "lint": "eslint \"**/*.js\"", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "lintfix": "npm run lint -- --fix", - "snap": "tap", - "posttest": "npm run lint" - }, - "files": [ - "bin/", - "lib/" - ], - "tap": { - "check-coverage": true, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "engines": { - "node": "^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "ciVersions": [ - "16.13.0", - "16.x", - "18.0.0", - "18.x" - ], - "version": "4.18.0", - "publish": "true" - } -} diff --git a/node_modules/@npmcli/metavuln-calculator/package.json b/node_modules/@npmcli/metavuln-calculator/package.json index a7ec02d2ee72b..d4c3cf54d83ea 100644 --- a/node_modules/@npmcli/metavuln-calculator/package.json +++ b/node_modules/@npmcli/metavuln-calculator/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/metavuln-calculator", - "version": "7.1.1", + "version": "8.0.0", "main": "lib/index.js", "files": [ "bin/", @@ -18,9 +18,9 @@ "posttest": "npm run lint", "snap": "tap", "postsnap": "npm run lint", - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "lint": "npm run eslint", + "lintfix": "npm run eslint -- --fix", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force" }, @@ -33,24 +33,24 @@ ] }, "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "4.23.3", "require-inject": "^1.4.4", "tap": "^16.0.1" }, "dependencies": { - "cacache": "^18.0.0", - "json-parse-even-better-errors": "^3.0.0", - "pacote": "^18.0.0", - "proc-log": "^4.1.0", + "cacache": "^19.0.0", + "json-parse-even-better-errors": "^4.0.0", + "pacote": "^19.0.0", + "proc-log": "^5.0.0", "semver": "^7.3.5" }, "engines": { - "node": "^16.14.0 || >=18.0.0" + "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", + "version": "4.23.3", "publish": "true", "ciVersions": [ "16.14.0", diff --git a/node_modules/ignore-walk/LICENSE b/node_modules/ignore-walk/LICENSE deleted file mode 100644 index 19129e315fe59..0000000000000 --- a/node_modules/ignore-walk/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/ignore-walk/lib/index.js b/node_modules/ignore-walk/lib/index.js deleted file mode 100644 index 366d95e2d516c..0000000000000 --- a/node_modules/ignore-walk/lib/index.js +++ /dev/null @@ -1,310 +0,0 @@ -'use strict' - -const fs = require('fs') -const path = require('path') -const EE = require('events').EventEmitter -const Minimatch = require('minimatch').Minimatch - -class Walker extends EE { - constructor (opts) { - opts = opts || {} - super(opts) - // set to true if this.path is a symlink, whether follow is true or not - this.isSymbolicLink = opts.isSymbolicLink - this.path = opts.path || process.cwd() - this.basename = path.basename(this.path) - this.ignoreFiles = opts.ignoreFiles || ['.ignore'] - this.ignoreRules = {} - this.parent = opts.parent || null - this.includeEmpty = !!opts.includeEmpty - this.root = this.parent ? this.parent.root : this.path - this.follow = !!opts.follow - this.result = this.parent ? this.parent.result : new Set() - this.entries = null - this.sawError = false - this.exact = opts.exact - } - - sort (a, b) { - return a.localeCompare(b, 'en') - } - - emit (ev, data) { - let ret = false - if (!(this.sawError && ev === 'error')) { - if (ev === 'error') { - this.sawError = true - } else if (ev === 'done' && !this.parent) { - data = Array.from(data) - .map(e => /^@/.test(e) ? `./${e}` : e).sort(this.sort) - this.result = data - } - - if (ev === 'error' && this.parent) { - ret = this.parent.emit('error', data) - } else { - ret = super.emit(ev, data) - } - } - return ret - } - - start () { - fs.readdir(this.path, (er, entries) => - er ? this.emit('error', er) : this.onReaddir(entries)) - return this - } - - isIgnoreFile (e) { - return e !== '.' && - e !== '..' && - this.ignoreFiles.indexOf(e) !== -1 - } - - onReaddir (entries) { - this.entries = entries - if (entries.length === 0) { - if (this.includeEmpty) { - this.result.add(this.path.slice(this.root.length + 1)) - } - this.emit('done', this.result) - } else { - const hasIg = this.entries.some(e => - this.isIgnoreFile(e)) - - if (hasIg) { - this.addIgnoreFiles() - } else { - this.filterEntries() - } - } - } - - addIgnoreFiles () { - const newIg = this.entries - .filter(e => this.isIgnoreFile(e)) - - let igCount = newIg.length - const then = () => { - if (--igCount === 0) { - this.filterEntries() - } - } - - newIg.forEach(e => this.addIgnoreFile(e, then)) - } - - addIgnoreFile (file, then) { - const ig = path.resolve(this.path, file) - fs.readFile(ig, 'utf8', (er, data) => - er ? this.emit('error', er) : this.onReadIgnoreFile(file, data, then)) - } - - onReadIgnoreFile (file, data, then) { - const mmopt = { - matchBase: true, - dot: true, - flipNegate: true, - nocase: true, - } - const rules = data.split(/\r?\n/) - .filter(line => !/^#|^$/.test(line.trim())) - .map(rule => { - return new Minimatch(rule.trim(), mmopt) - }) - - this.ignoreRules[file] = rules - - then() - } - - filterEntries () { - // at this point we either have ignore rules, or just inheriting - // this exclusion is at the point where we know the list of - // entries in the dir, but don't know what they are. since - // some of them *might* be directories, we have to run the - // match in dir-mode as well, so that we'll pick up partials - // of files that will be included later. Anything included - // at this point will be checked again later once we know - // what it is. - const filtered = this.entries.map(entry => { - // at this point, we don't know if it's a dir or not. - const passFile = this.filterEntry(entry) - const passDir = this.filterEntry(entry, true) - return (passFile || passDir) ? [entry, passFile, passDir] : false - }).filter(e => e) - - // now we stat them all - // if it's a dir, and passes as a dir, then recurse - // if it's not a dir, but passes as a file, add to set - let entryCount = filtered.length - if (entryCount === 0) { - this.emit('done', this.result) - } else { - const then = () => { - if (--entryCount === 0) { - this.emit('done', this.result) - } - } - filtered.forEach(filt => { - const entry = filt[0] - const file = filt[1] - const dir = filt[2] - this.stat({ entry, file, dir }, then) - }) - } - } - - onstat ({ st, entry, file, dir, isSymbolicLink }, then) { - const abs = this.path + '/' + entry - if (!st.isDirectory()) { - if (file) { - this.result.add(abs.slice(this.root.length + 1)) - } - then() - } else { - // is a directory - if (dir) { - this.walker(entry, { isSymbolicLink, exact: file || this.filterEntry(entry + '/') }, then) - } else { - then() - } - } - } - - stat ({ entry, file, dir }, then) { - const abs = this.path + '/' + entry - fs.lstat(abs, (lstatErr, lstatResult) => { - if (lstatErr) { - this.emit('error', lstatErr) - } else { - const isSymbolicLink = lstatResult.isSymbolicLink() - if (this.follow && isSymbolicLink) { - fs.stat(abs, (statErr, statResult) => { - if (statErr) { - this.emit('error', statErr) - } else { - this.onstat({ st: statResult, entry, file, dir, isSymbolicLink }, then) - } - }) - } else { - this.onstat({ st: lstatResult, entry, file, dir, isSymbolicLink }, then) - } - } - }) - } - - walkerOpt (entry, opts) { - return { - path: this.path + '/' + entry, - parent: this, - ignoreFiles: this.ignoreFiles, - follow: this.follow, - includeEmpty: this.includeEmpty, - ...opts, - } - } - - walker (entry, opts, then) { - new Walker(this.walkerOpt(entry, opts)).on('done', then).start() - } - - filterEntry (entry, partial, entryBasename) { - let included = true - - // this = /a/b/c - // entry = d - // parent /a/b sees c/d - if (this.parent && this.parent.filterEntry) { - const parentEntry = this.basename + '/' + entry - const parentBasename = entryBasename || entry - included = this.parent.filterEntry(parentEntry, partial, parentBasename) - if (!included && !this.exact) { - return false - } - } - - this.ignoreFiles.forEach(f => { - if (this.ignoreRules[f]) { - this.ignoreRules[f].forEach(rule => { - // negation means inclusion - // so if it's negated, and already included, no need to check - // likewise if it's neither negated nor included - if (rule.negate !== included) { - const isRelativeRule = entryBasename && rule.globParts.some(part => - part.length <= (part.slice(-1)[0] ? 1 : 2) - ) - - // first, match against /foo/bar - // then, against foo/bar - // then, in the case of partials, match with a / - // then, if also the rule is relative, match against basename - const match = rule.match('/' + entry) || - rule.match(entry) || - !!partial && ( - rule.match('/' + entry + '/') || - rule.match(entry + '/') || - rule.negate && ( - rule.match('/' + entry, true) || - rule.match(entry, true)) || - isRelativeRule && ( - rule.match('/' + entryBasename + '/') || - rule.match(entryBasename + '/') || - rule.negate && ( - rule.match('/' + entryBasename, true) || - rule.match(entryBasename, true)))) - - if (match) { - included = rule.negate - } - } - }) - } - }) - - return included - } -} - -class WalkerSync extends Walker { - start () { - this.onReaddir(fs.readdirSync(this.path)) - return this - } - - addIgnoreFile (file, then) { - const ig = path.resolve(this.path, file) - this.onReadIgnoreFile(file, fs.readFileSync(ig, 'utf8'), then) - } - - stat ({ entry, file, dir }, then) { - const abs = this.path + '/' + entry - let st = fs.lstatSync(abs) - const isSymbolicLink = st.isSymbolicLink() - if (this.follow && isSymbolicLink) { - st = fs.statSync(abs) - } - - // console.error('STAT SYNC', {st, entry, file, dir, isSymbolicLink, then}) - this.onstat({ st, entry, file, dir, isSymbolicLink }, then) - } - - walker (entry, opts, then) { - new WalkerSync(this.walkerOpt(entry, opts)).start() - then() - } -} - -const walk = (opts, callback) => { - const p = new Promise((resolve, reject) => { - new Walker(opts).on('done', resolve).on('error', reject).start() - }) - return callback ? p.then(res => callback(null, res), callback) : p -} - -const walkSync = opts => new WalkerSync(opts).start().result - -module.exports = walk -walk.sync = walkSync -walk.Walker = Walker -walk.WalkerSync = WalkerSync diff --git a/node_modules/ignore-walk/package.json b/node_modules/ignore-walk/package.json deleted file mode 100644 index f44a7a587a10b..0000000000000 --- a/node_modules/ignore-walk/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "name": "ignore-walk", - "version": "6.0.5", - "description": "Nested/recursive `.gitignore`/`.npmignore` parsing and filtering.", - "main": "lib/index.js", - "devDependencies": { - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.22.0", - "mutate-fs": "^2.1.1", - "tap": "^16.0.1" - }, - "scripts": { - "test": "tap", - "posttest": "npm run lint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force", - "test:windows-coverage": "npm pkg set tap.statements=99 --json && npm pkg set tap.branches=98 --json && npm pkg set tap.lines=99 --json", - "snap": "tap" - }, - "keywords": [ - "ignorefile", - "ignore", - "file", - ".gitignore", - ".npmignore", - "glob" - ], - "author": "GitHub Inc.", - "license": "ISC", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/ignore-walk.git" - }, - "files": [ - "bin/", - "lib/" - ], - "dependencies": { - "minimatch": "^9.0.0" - }, - "tap": { - "test-env": "LC_ALL=sk", - "before": "test/00-setup.js", - "after": "test/zz-cleanup.js", - "timeout": 600, - "jobs": 1, - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ] - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.22.0", - "content": "scripts/template-oss", - "publish": "true" - } -} diff --git a/node_modules/npm-packlist/LICENSE b/node_modules/npm-packlist/LICENSE deleted file mode 100644 index 19129e315fe59..0000000000000 --- a/node_modules/npm-packlist/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/npm-packlist/lib/index.js b/node_modules/npm-packlist/lib/index.js deleted file mode 100644 index 985f11ee3f738..0000000000000 --- a/node_modules/npm-packlist/lib/index.js +++ /dev/null @@ -1,456 +0,0 @@ -'use strict' - -const { Walker: IgnoreWalker } = require('ignore-walk') -const { lstatSync: lstat, readFileSync: readFile } = require('fs') -const { basename, dirname, extname, join, relative, resolve, sep } = require('path') - -// symbols used to represent synthetic rule sets -const defaultRules = Symbol('npm-packlist.rules.default') -const strictRules = Symbol('npm-packlist.rules.strict') - -// There may be others, but :?|<> are handled by node-tar -const nameIsBadForWindows = file => /\*/.test(file) - -// these are the default rules that are applied to everything except for non-link bundled deps -const defaults = [ - '.npmignore', - '.gitignore', - '**/.git', - '**/.svn', - '**/.hg', - '**/CVS', - '**/.git/**', - '**/.svn/**', - '**/.hg/**', - '**/CVS/**', - '/.lock-wscript', - '/.wafpickle-*', - '/build/config.gypi', - 'npm-debug.log', - '**/.npmrc', - '.*.swp', - '.DS_Store', - '**/.DS_Store/**', - '._*', - '**/._*/**', - '*.orig', - '/archived-packages/**', -] - -const strictDefaults = [ - // these are forcibly excluded - '/.git', -] - -const normalizePath = (path) => path.split('\\').join('/') - -const readOutOfTreeIgnoreFiles = (root, rel, result = []) => { - for (const file of ['.npmignore', '.gitignore']) { - try { - const ignoreContent = readFile(join(root, file), { encoding: 'utf8' }) - result.push(ignoreContent) - // break the loop immediately after reading, this allows us to prioritize - // the .npmignore and discard the .gitignore if one is present - break - } catch (err) { - // we ignore ENOENT errors completely because we don't care if the file doesn't exist - // but we throw everything else because failing to read a file that does exist is - // something that the user likely wants to know about - // istanbul ignore next -- we do not need to test a thrown error - if (err.code !== 'ENOENT') { - throw err - } - } - } - - if (!rel) { - return result - } - - const firstRel = rel.split(sep, 1)[0] - const newRoot = join(root, firstRel) - const newRel = relative(newRoot, join(root, rel)) - - return readOutOfTreeIgnoreFiles(newRoot, newRel, result) -} - -class PackWalker extends IgnoreWalker { - constructor (tree, opts) { - const options = { - ...opts, - includeEmpty: false, - follow: false, - // we path.resolve() here because ignore-walk doesn't do it and we want full paths - path: resolve(opts?.path || tree.path).replace(/\\/g, '/'), - ignoreFiles: opts?.ignoreFiles || [ - defaultRules, - 'package.json', - '.npmignore', - '.gitignore', - strictRules, - ], - } - - super(options) - this.isPackage = options.isPackage - this.seen = options.seen || new Set() - this.tree = tree - this.requiredFiles = options.requiredFiles || [] - - const additionalDefaults = [] - if (options.prefix && options.workspaces) { - const path = normalizePath(options.path) - const prefix = normalizePath(options.prefix) - const workspaces = options.workspaces.map((ws) => normalizePath(ws)) - - // istanbul ignore else - this does nothing unless we need it to - if (path !== prefix && workspaces.includes(path)) { - // if path and prefix are not the same directory, and workspaces has path in it - // then we know path is a workspace directory. in order to not drop ignore rules - // from directories between the workspaces root (prefix) and the workspace itself - // (path) we need to find and read those now - const relpath = relative(options.prefix, dirname(options.path)) - additionalDefaults.push(...readOutOfTreeIgnoreFiles(options.prefix, relpath)) - } else if (path === prefix) { - // on the other hand, if the path and prefix are the same, then we ignore workspaces - // so that we don't pack a workspace as part of the root project. append them as - // normalized relative paths from the root - additionalDefaults.push(...workspaces.map((w) => normalizePath(relative(options.path, w)))) - } - } - - // go ahead and inject the default rules now - this.injectRules(defaultRules, [...defaults, ...additionalDefaults]) - - if (!this.isPackage) { - // if this instance is not a package, then place some strict default rules, and append - // known required files for this directory - this.injectRules(strictRules, [ - ...strictDefaults, - ...this.requiredFiles.map((file) => `!${file}`), - ]) - } - } - - // overridden method: we intercept the reading of the package.json file here so that we can - // process it into both the package.json file rules as well as the strictRules synthetic rule set - addIgnoreFile (file, callback) { - // if we're adding anything other than package.json, then let ignore-walk handle it - if (file !== 'package.json' || !this.isPackage) { - return super.addIgnoreFile(file, callback) - } - - return this.processPackage(callback) - } - - // overridden method: if we're done, but we're a package, then we also need to evaluate bundles - // before we actually emit our done event - emit (ev, data) { - if (ev !== 'done' || !this.isPackage) { - return super.emit(ev, data) - } - - // we intentionally delay the done event while keeping the function sync here - // eslint-disable-next-line promise/catch-or-return, promise/always-return - this.gatherBundles().then(() => { - super.emit('done', this.result) - }) - return true - } - - // overridden method: before actually filtering, we make sure that we've removed the rules for - // files that should no longer take effect due to our order of precedence - filterEntries () { - if (this.ignoreRules['package.json']) { - // package.json means no .npmignore or .gitignore - this.ignoreRules['.npmignore'] = null - this.ignoreRules['.gitignore'] = null - } else if (this.ignoreRules['.npmignore']) { - // .npmignore means no .gitignore - this.ignoreRules['.gitignore'] = null - } - - return super.filterEntries() - } - - // overridden method: we never want to include anything that isn't a file or directory - onstat (opts, callback) { - if (!opts.st.isFile() && !opts.st.isDirectory()) { - return callback() - } - - return super.onstat(opts, callback) - } - - // overridden method: we want to refuse to pack files that are invalid, node-tar protects us from - // a lot of them but not all - stat (opts, callback) { - if (nameIsBadForWindows(opts.entry)) { - return callback() - } - - return super.stat(opts, callback) - } - - // overridden method: this is called to create options for a child walker when we step - // in to a normal child directory (this will never be a bundle). the default method here - // copies the root's `ignoreFiles` value, but we don't want to respect package.json for - // subdirectories, so we override it with a list that intentionally omits package.json - walkerOpt (entry, opts) { - let ignoreFiles = null - - // however, if we have a tree, and we have workspaces, and the directory we're about - // to step into is a workspace, then we _do_ want to respect its package.json - if (this.tree.workspaces) { - const workspaceDirs = [...this.tree.workspaces.values()] - .map((dir) => dir.replace(/\\/g, '/')) - - const entryPath = join(this.path, entry).replace(/\\/g, '/') - if (workspaceDirs.includes(entryPath)) { - ignoreFiles = [ - defaultRules, - 'package.json', - '.npmignore', - '.gitignore', - strictRules, - ] - } - } else { - ignoreFiles = [ - defaultRules, - '.npmignore', - '.gitignore', - strictRules, - ] - } - - return { - ...super.walkerOpt(entry, opts), - ignoreFiles, - // we map over our own requiredFiles and pass ones that are within this entry - requiredFiles: this.requiredFiles - .map((file) => { - if (relative(file, entry) === '..') { - return relative(entry, file).replace(/\\/g, '/') - } - return false - }) - .filter(Boolean), - } - } - - // overridden method: we want child walkers to be instances of this class, not ignore-walk - walker (entry, opts, callback) { - new PackWalker(this.tree, this.walkerOpt(entry, opts)).on('done', callback).start() - } - - // overridden method: we use a custom sort method to help compressibility - sort (a, b) { - // optimize for compressibility - // extname, then basename, then locale alphabetically - // https://twitter.com/isntitvacant/status/1131094910923231232 - const exta = extname(a).toLowerCase() - const extb = extname(b).toLowerCase() - const basea = basename(a).toLowerCase() - const baseb = basename(b).toLowerCase() - - return exta.localeCompare(extb, 'en') || - basea.localeCompare(baseb, 'en') || - a.localeCompare(b, 'en') - } - - // convenience method: this joins the given rules with newlines, appends a trailing newline, - // and calls the internal onReadIgnoreFile method - injectRules (filename, rules, callback = () => {}) { - this.onReadIgnoreFile(filename, `${rules.join('\n')}\n`, callback) - } - - // custom method: this is called by addIgnoreFile when we find a package.json, it uses the - // arborist tree to pull both default rules and strict rules for the package - processPackage (callback) { - const { - bin, - browser, - files, - main, - } = this.tree.package - - // rules in these arrays are inverted since they are patterns we want to _not_ ignore - const ignores = [] - const strict = [ - ...strictDefaults, - '!/package.json', - '!/readme{,.*[^~$]}', - '!/copying{,.*[^~$]}', - '!/license{,.*[^~$]}', - '!/licence{,.*[^~$]}', - '/.git', - '/node_modules', - '.npmrc', - '/package-lock.json', - '/yarn.lock', - '/pnpm-lock.yaml', - ] - - // if we have a files array in our package, we need to pull rules from it - if (files) { - for (let file of files) { - // invert the rule because these are things we want to include - if (file.startsWith('./')) { - file = file.slice(1) - } - if (file.endsWith('/*')) { - file += '*' - } - const inverse = `!${file}` - try { - // if an entry in the files array is a specific file, then we need to include it as a - // strict requirement for this package. if it's a directory or a pattern, it's a default - // pattern instead. this is ugly, but we have to stat to find out if it's a file - const stat = lstat(join(this.path, file.replace(/^!+/, '')).replace(/\\/g, '/')) - // if we have a file and we know that, it's strictly required - if (stat.isFile()) { - strict.unshift(inverse) - this.requiredFiles.push(file.startsWith('/') ? file.slice(1) : file) - } else if (stat.isDirectory()) { - // otherwise, it's a default ignore, and since we got here we know it's not a pattern - // so we include the directory contents - ignores.push(inverse) - ignores.push(`${inverse}/**`) - } - // if the thing exists, but is neither a file or a directory, we don't want it at all - } catch (err) { - // if lstat throws, then we assume we're looking at a pattern and treat it as a default - ignores.push(inverse) - } - } - - // we prepend a '*' to exclude everything, followed by our inverted file rules - // which now mean to include those - this.injectRules('package.json', ['*', ...ignores]) - } - - // browser is required - if (browser) { - strict.push(`!/${browser}`) - } - - // main is required - if (main) { - strict.push(`!/${main}`) - } - - // each bin is required - if (bin) { - for (const key in bin) { - strict.push(`!/${bin[key]}`) - } - } - - // and now we add all of the strict rules to our synthetic file - this.injectRules(strictRules, strict, callback) - } - - // custom method: after we've finished gathering the files for the root package, we call this - // before emitting the 'done' event in order to gather all of the files for bundled deps - async gatherBundles () { - if (this.seen.has(this.tree)) { - return - } - - // add this node to our seen tracker - this.seen.add(this.tree) - - // if we're the project root, then we look at our bundleDependencies, otherwise we got here - // because we're a bundled dependency of the root, which means we need to include all prod - // and optional dependencies in the bundle - let toBundle - if (this.tree.isProjectRoot) { - const { bundleDependencies } = this.tree.package - toBundle = bundleDependencies || [] - } else { - const { dependencies, optionalDependencies } = this.tree.package - toBundle = Object.keys(dependencies || {}).concat(Object.keys(optionalDependencies || {})) - } - - for (const dep of toBundle) { - const edge = this.tree.edgesOut.get(dep) - // no edgeOut = missing node, so skip it. we can't pack it if it's not here - // we also refuse to pack peer dependencies and dev dependencies - if (!edge || edge.peer || edge.dev) { - continue - } - - // get a reference to the node we're bundling - const node = this.tree.edgesOut.get(dep).to - // if there's no node, this is most likely an optional dependency that hasn't been - // installed. just skip it. - if (!node) { - continue - } - // we use node.path for the path because we want the location the node was linked to, - // not where it actually lives on disk - const path = node.path - // but link nodes don't have edgesOut, so we need to pass in the target of the node - // in order to make sure we correctly traverse its dependencies - const tree = node.target - - // and start building options to be passed to the walker for this package - const walkerOpts = { - path, - isPackage: true, - ignoreFiles: [], - seen: this.seen, // pass through seen so we can prevent infinite circular loops - } - - // if our node is a link, we apply defaultRules. we don't do this for regular bundled - // deps because their .npmignore and .gitignore files are excluded by default and may - // override defaults - if (node.isLink) { - walkerOpts.ignoreFiles.push(defaultRules) - } - - // _all_ nodes will follow package.json rules from their package root - walkerOpts.ignoreFiles.push('package.json') - - // only link nodes will obey .npmignore or .gitignore - if (node.isLink) { - walkerOpts.ignoreFiles.push('.npmignore') - walkerOpts.ignoreFiles.push('.gitignore') - } - - // _all_ nodes follow strict rules - walkerOpts.ignoreFiles.push(strictRules) - - // create a walker for this dependency and gather its results - const walker = new PackWalker(tree, walkerOpts) - const bundled = await new Promise((pResolve, pReject) => { - walker.on('error', pReject) - walker.on('done', pResolve) - walker.start() - }) - - // now we make sure we have our paths correct from the root, and accumulate everything into - // our own result set to deduplicate - const relativeFrom = relative(this.root, walker.path) - for (const file of bundled) { - this.result.add(join(relativeFrom, file).replace(/\\/g, '/')) - } - } - } -} - -const walk = (tree, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - const p = new Promise((pResolve, pReject) => { - new PackWalker(tree, { ...options, isPackage: true }) - .on('done', pResolve).on('error', pReject).start() - }) - return callback ? p.then(res => callback(null, res), callback) : p -} - -module.exports = walk -walk.Walker = PackWalker diff --git a/node_modules/npm-packlist/package.json b/node_modules/npm-packlist/package.json deleted file mode 100644 index 8c3a16e741ad3..0000000000000 --- a/node_modules/npm-packlist/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "name": "npm-packlist", - "version": "8.0.2", - "description": "Get a list of the files to add from a folder into an npm package", - "directories": { - "test": "test" - }, - "main": "lib/index.js", - "dependencies": { - "ignore-walk": "^6.0.4" - }, - "author": "GitHub Inc.", - "license": "ISC", - "files": [ - "bin/", - "lib/" - ], - "devDependencies": { - "@npmcli/arborist": "^6.0.0 || ^6.0.0-pre.0", - "@npmcli/eslint-config": "^4.0.0", - "@npmcli/template-oss": "4.21.2", - "mutate-fs": "^2.1.1", - "tap": "^16.0.1" - }, - "scripts": { - "test": "tap", - "posttest": "npm run lint", - "snap": "tap", - "postsnap": "npm run lintfix --", - "eslint": "eslint", - "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", - "lintfix": "npm run lint -- --fix", - "npmclilint": "npmcli-lint", - "postlint": "template-oss-check", - "template-oss-apply": "template-oss-apply --force" - }, - "repository": { - "type": "git", - "url": "https://github.com/npm/npm-packlist.git" - }, - "tap": { - "test-env": [ - "LC_ALL=sk" - ], - "nyc-arg": [ - "--exclude", - "tap-snapshots/**" - ], - "files": [ - "test/*.js" - ] - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - }, - "templateOSS": { - "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "4.21.2", - "publish": true - } -} diff --git a/package-lock.json b/package-lock.json index 2e919cb38516f..fb7ba5e6242ff 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1659,411 +1659,19 @@ } }, "node_modules/@npmcli/metavuln-calculator": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-7.1.1.tgz", - "integrity": "sha512-Nkxf96V0lAx3HCpVda7Vw4P23RILgdi/5K1fmj2tZkWIYLpXAN8k2UVVOsW16TsS5F8Ws2I7Cm+PU1/rsVF47g==", - "license": "ISC", - "dependencies": { - "cacache": "^18.0.0", - "json-parse-even-better-errors": "^3.0.0", - "pacote": "^18.0.0", - "proc-log": "^4.1.0", - "semver": "^7.3.5" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/agent": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-2.2.2.tgz", - "integrity": "sha512-OrcNPXdpSl9UX7qPVRWbmWMCSXrcDa2M9DvrbOTj7ao1S4PlqVFYv9/yLKMkrJKZ/V5A/kDBC690or307i26Og==", - "license": "ISC", - "dependencies": { - "agent-base": "^7.1.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.1", - "lru-cache": "^10.0.1", - "socks-proxy-agent": "^8.0.3" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/fs": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-3.1.1.tgz", - "integrity": "sha512-q9CRWjpHCMIh5sVyefoD1cA7PkvILqCZsnSOEUUivORLjxCO/Irmue2DprETiNgEqktDBZaM1Bi+jrarx1XdCg==", - "license": "ISC", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/git": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-5.0.8.tgz", - "integrity": "sha512-liASfw5cqhjNW9UFd+ruwwdEf/lbOAQjLL2XY2dFW/bkJheXDYZgOyul/4gVvEV4BWkTXjYGmDqMw9uegdbJNQ==", - "license": "ISC", - "dependencies": { - "@npmcli/promise-spawn": "^7.0.0", - "ini": "^4.1.3", - "lru-cache": "^10.0.1", - "npm-pick-manifest": "^9.0.0", - "proc-log": "^4.0.0", - "promise-inflight": "^1.0.1", - "promise-retry": "^2.0.1", - "semver": "^7.3.5", - "which": "^4.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/installed-package-contents": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-2.1.0.tgz", - "integrity": "sha512-c8UuGLeZpm69BryRykLuKRyKFZYJsZSCT4aVY5ds4omyZqJ172ApzgfKJ5eV/r3HgLdUYgFVe54KSFVjKoe27w==", - "license": "ISC", - "dependencies": { - "npm-bundled": "^3.0.0", - "npm-normalize-package-bin": "^3.0.0" - }, - "bin": { - "installed-package-contents": "bin/index.js" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/package-json": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-5.2.1.tgz", - "integrity": "sha512-f7zYC6kQautXHvNbLEWgD/uGu1+xCn9izgqBfgItWSx22U0ZDekxN08A1vM8cTxj/cRVe0Q94Ode+tdoYmIOOQ==", - "license": "ISC", - "dependencies": { - "@npmcli/git": "^5.0.0", - "glob": "^10.2.2", - "hosted-git-info": "^7.0.0", - "json-parse-even-better-errors": "^3.0.0", - "normalize-package-data": "^6.0.0", - "proc-log": "^4.0.0", - "semver": "^7.5.3" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/promise-spawn": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-7.0.2.tgz", - "integrity": "sha512-xhfYPXoV5Dy4UkY0D+v2KkwvnDfiA/8Mt3sWCGI/hM03NsYIH8ZaG6QzS9x7pje5vHZBZJ2v6VRFVTWACnqcmQ==", - "license": "ISC", - "dependencies": { - "which": "^4.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/redact": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-2.0.1.tgz", - "integrity": "sha512-YgsR5jCQZhVmTJvjduTOIHph0L73pK8xwMVaDY0PatySqVM9AZj93jpoXYSJqfHFxFkN9dmqTw6OiqExsS3LPw==", - "license": "ISC", - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/@npmcli/run-script": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-8.1.0.tgz", - "integrity": "sha512-y7efHHwghQfk28G2z3tlZ67pLG0XdfYbcVG26r7YIXALRsrVQcTq4/tdenSmdOrEsNahIYA/eh8aEVROWGFUDg==", - "license": "ISC", - "dependencies": { - "@npmcli/node-gyp": "^3.0.0", - "@npmcli/package-json": "^5.0.0", - "@npmcli/promise-spawn": "^7.0.0", - "node-gyp": "^10.0.0", - "proc-log": "^4.0.0", - "which": "^4.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/cacache": { - "version": "18.0.4", - "resolved": "https://registry.npmjs.org/cacache/-/cacache-18.0.4.tgz", - "integrity": "sha512-B+L5iIa9mgcjLbliir2th36yEwPftrzteHYujzsx3dFP/31GCHcIeS8f5MGd80odLOjaOvSpU3EEAmRQptkxLQ==", - "license": "ISC", - "dependencies": { - "@npmcli/fs": "^3.1.0", - "fs-minipass": "^3.0.0", - "glob": "^10.2.2", - "lru-cache": "^10.0.1", - "minipass": "^7.0.3", - "minipass-collect": "^2.0.1", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "p-map": "^4.0.0", - "ssri": "^10.0.0", - "tar": "^6.1.11", - "unique-filename": "^3.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/hosted-git-info": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-7.0.2.tgz", - "integrity": "sha512-puUZAUKT5m8Zzvs72XWy3HtvVbTWljRE66cP60bxJzAqf2DgICo7lYTY2IHUmLnNpjYvw5bvmoHvPc0QO2a62w==", - "license": "ISC", - "dependencies": { - "lru-cache": "^10.0.1" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/ini": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.3.tgz", - "integrity": "sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==", - "license": "ISC", - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/isexe": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.1.tgz", - "integrity": "sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ==", - "license": "ISC", - "engines": { - "node": ">=16" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-3.0.2.tgz", - "integrity": "sha512-fi0NG4bPjCHunUJffmLd0gxssIgkNmArMvis4iNah6Owg1MCJjWhEcDLmsK6iGkJq3tHwbDkTlce70/tmXN4cQ==", - "license": "MIT", - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/make-fetch-happen": { - "version": "13.0.1", - "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-13.0.1.tgz", - "integrity": "sha512-cKTUFc/rbKUd/9meOvgrpJ2WrNzymt6jfRDdwg5UCnVzv9dTpEj9JS5m3wtziXVCjluIXyL8pcaukYqezIzZQA==", - "license": "ISC", - "dependencies": { - "@npmcli/agent": "^2.0.0", - "cacache": "^18.0.0", - "http-cache-semantics": "^4.1.1", - "is-lambda": "^1.0.1", - "minipass": "^7.0.2", - "minipass-fetch": "^3.0.0", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "negotiator": "^0.6.3", - "proc-log": "^4.2.0", - "promise-retry": "^2.0.1", - "ssri": "^10.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/normalize-package-data": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-6.0.2.tgz", - "integrity": "sha512-V6gygoYb/5EmNI+MEGrWkC+e6+Rr7mTmfHrxDbLzxQogBkgzo76rkok0Am6thgSF7Mv2nLOajAJj5vDJZEFn7g==", - "license": "BSD-2-Clause", - "dependencies": { - "hosted-git-info": "^7.0.0", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/npm-bundled": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-3.0.1.tgz", - "integrity": "sha512-+AvaheE/ww1JEwRHOrn4WHNzOxGtVp+adrg2AeZS/7KuxGUYFuBta98wYpfHBbJp6Tg6j1NKSEVHNcfZzJHQwQ==", - "license": "ISC", - "dependencies": { - "npm-normalize-package-bin": "^3.0.0" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/npm-install-checks": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-6.3.0.tgz", - "integrity": "sha512-W29RiK/xtpCGqn6f3ixfRYGk+zRyr+Ew9F2E20BfXxT5/euLdA/Nm7fO7OeTGuAmTs30cpgInyJ0cYe708YTZw==", - "license": "BSD-2-Clause", - "dependencies": { - "semver": "^7.1.1" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/npm-package-arg": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-11.0.3.tgz", - "integrity": "sha512-sHGJy8sOC1YraBywpzQlIKBE4pBbGbiF95U6Auspzyem956E0+FtDtsx1ZxlOJkQCZ1AFXAY/yuvtFYrOxF+Bw==", - "license": "ISC", - "dependencies": { - "hosted-git-info": "^7.0.0", - "proc-log": "^4.0.0", - "semver": "^7.3.5", - "validate-npm-package-name": "^5.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/npm-pick-manifest": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-9.1.0.tgz", - "integrity": "sha512-nkc+3pIIhqHVQr085X9d2JzPzLyjzQS96zbruppqC9aZRm/x8xx6xhI98gHtsfELP2bE+loHq8ZaHFHhe+NauA==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-8.0.0.tgz", + "integrity": "sha512-zR2TGfhR8fH1u4VRz9fuC7r1nI9dweViRDsFnMH8J89OA90lJNwF6idTttEzYSWaOTW4NVoAIB6+ujV+/wI+kg==", "license": "ISC", "dependencies": { - "npm-install-checks": "^6.0.0", - "npm-normalize-package-bin": "^3.0.0", - "npm-package-arg": "^11.0.0", + "cacache": "^19.0.0", + "json-parse-even-better-errors": "^4.0.0", + "pacote": "^19.0.0", + "proc-log": "^5.0.0", "semver": "^7.3.5" }, "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/npm-registry-fetch": { - "version": "17.1.0", - "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-17.1.0.tgz", - "integrity": "sha512-5+bKQRH0J1xG1uZ1zMNvxW0VEyoNWgJpY9UDuluPFLKDfJ9u2JmmjmTJV1srBGQOROfdBMiVvnH2Zvpbm+xkVA==", - "license": "ISC", - "dependencies": { - "@npmcli/redact": "^2.0.0", - "jsonparse": "^1.3.1", - "make-fetch-happen": "^13.0.0", - "minipass": "^7.0.2", - "minipass-fetch": "^3.0.0", - "minizlib": "^2.1.2", - "npm-package-arg": "^11.0.0", - "proc-log": "^4.0.0" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/pacote": { - "version": "18.0.6", - "resolved": "https://registry.npmjs.org/pacote/-/pacote-18.0.6.tgz", - "integrity": "sha512-+eK3G27SMwsB8kLIuj4h1FUhHtwiEUo21Tw8wNjmvdlpOEr613edv+8FUsTj/4F/VN5ywGE19X18N7CC2EJk6A==", - "license": "ISC", - "dependencies": { - "@npmcli/git": "^5.0.0", - "@npmcli/installed-package-contents": "^2.0.1", - "@npmcli/package-json": "^5.1.0", - "@npmcli/promise-spawn": "^7.0.0", - "@npmcli/run-script": "^8.0.0", - "cacache": "^18.0.0", - "fs-minipass": "^3.0.0", - "minipass": "^7.0.2", - "npm-package-arg": "^11.0.0", - "npm-packlist": "^8.0.0", - "npm-pick-manifest": "^9.0.0", - "npm-registry-fetch": "^17.0.0", - "proc-log": "^4.0.0", - "promise-retry": "^2.0.1", - "sigstore": "^2.2.0", - "ssri": "^10.0.0", - "tar": "^6.1.11" - }, - "bin": { - "pacote": "bin/index.js" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/proc-log": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-4.2.0.tgz", - "integrity": "sha512-g8+OnU/L2v+wyiVK+D5fA34J7EH8jZ8DDlvwhRCMxmMj7UCBvxiO1mGeN+36JXIKF4zevU4kRBd8lVgG9vLelA==", - "license": "ISC", - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/ssri": { - "version": "10.0.6", - "resolved": "https://registry.npmjs.org/ssri/-/ssri-10.0.6.tgz", - "integrity": "sha512-MGrFH9Z4NP9Iyhqn16sDtBpRRNJ0Y2hNa6D65h736fVSaPCHr4DM4sWUNvVaSuC+0OBGhwsrydQwmgfg5LncqQ==", - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/unique-filename": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-3.0.0.tgz", - "integrity": "sha512-afXhuC55wkAmZ0P18QsVE6kp8JaxrEokN2HGIoIVv2ijHQd419H0+6EigAFcIzXeMIkcIkNBpB3L/DXB3cTS/g==", - "license": "ISC", - "dependencies": { - "unique-slug": "^4.0.0" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/unique-slug": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-4.0.0.tgz", - "integrity": "sha512-WrcA6AyEfqDX5bWige/4NQfPZMtASNVxdmWR76WESYQVAACSgWcR6e9i0mofqqBxYFtL4oAxPIptY73/0YE1DQ==", - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/validate-npm-package-name": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-5.0.1.tgz", - "integrity": "sha512-OljLrQ9SQdOUqTaQxqL5dEfZWrXExyyWsozYlAWFawPVNuD83igl7uJD2RTkNMbniIYgt8l81eCJGIdQF7avLQ==", - "license": "ISC", - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/@npmcli/metavuln-calculator/node_modules/which": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/which/-/which-4.0.0.tgz", - "integrity": "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==", - "license": "ISC", - "dependencies": { - "isexe": "^3.1.1" - }, - "bin": { - "node-which": "bin/which.js" - }, - "engines": { - "node": "^16.13.0 || >=18.0.0" + "node": "^18.17.0 || >=20.5.0" } }, "node_modules/@npmcli/mock-globals": { @@ -7331,6 +6939,7 @@ "version": "6.0.5", "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-6.0.5.tgz", "integrity": "sha512-VuuG0wCnjhnylG1ABXT3dAuIpTNDs/G8jlpmwXY03fXoXy/8ZK8/T+hMzt8L4WnrLCJgdybqgPagnF/f97cg3A==", + "dev": true, "license": "ISC", "dependencies": { "minimatch": "^9.0.0" @@ -10576,6 +10185,7 @@ "version": "8.0.2", "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-8.0.2.tgz", "integrity": "sha512-shYrPFIS/JLP4oQmAwDyk5HcyysKW8/JLTEA32S0Z5TzvpaeeX2yMFfoK1fjEBnCBvVyIB/Jj/GBFdm0wsgzbA==", + "dev": true, "license": "ISC", "dependencies": { "ignore-walk": "^6.0.4" @@ -17067,7 +16677,7 @@ "@npmcli/fs": "^4.0.0", "@npmcli/installed-package-contents": "^3.0.0", "@npmcli/map-workspaces": "^4.0.1", - "@npmcli/metavuln-calculator": "^7.1.1", + "@npmcli/metavuln-calculator": "^8.0.0", "@npmcli/name-from-folder": "^2.0.0", "@npmcli/node-gyp": "^3.0.0", "@npmcli/package-json": "^6.0.1", diff --git a/workspaces/arborist/package.json b/workspaces/arborist/package.json index bec39143f154f..e16f3b7bf02f9 100644 --- a/workspaces/arborist/package.json +++ b/workspaces/arborist/package.json @@ -7,7 +7,7 @@ "@npmcli/fs": "^4.0.0", "@npmcli/installed-package-contents": "^3.0.0", "@npmcli/map-workspaces": "^4.0.1", - "@npmcli/metavuln-calculator": "^7.1.1", + "@npmcli/metavuln-calculator": "^8.0.0", "@npmcli/name-from-folder": "^2.0.0", "@npmcli/node-gyp": "^3.0.0", "@npmcli/package-json": "^6.0.1",