add autotest

Signed-off-by: bayanxing <bayanxing@kaihongdigi.com>
This commit is contained in:
bayanxing 2022-02-23 11:32:29 +08:00
parent 5ce24f68c7
commit 05ae1d68a5
1671 changed files with 1276782 additions and 20 deletions

1
node_modules/.bin/_mocha generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mocha/bin/_mocha

1
node_modules/.bin/color-support generated vendored Symbolic link
View File

@ -0,0 +1 @@
../color-support/bin.js

1
node_modules/.bin/flat generated vendored Symbolic link
View File

@ -0,0 +1 @@
../flat/cli.js

1
node_modules/.bin/he generated vendored Symbolic link
View File

@ -0,0 +1 @@
../he/bin/he

1
node_modules/.bin/js-yaml generated vendored Symbolic link
View File

@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
node_modules/.bin/mkdirp generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mkdirp/bin/cmd.js

1
node_modules/.bin/mocha generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mocha/bin/mocha

1
node_modules/.bin/nanoid generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nanoid/bin/nanoid.cjs

1
node_modules/.bin/node-gyp generated vendored Symbolic link
View File

@ -0,0 +1 @@
../node-gyp/bin/node-gyp.js

1
node_modules/.bin/node-which generated vendored Symbolic link
View File

@ -0,0 +1 @@
../which/bin/node-which

1
node_modules/.bin/nopt generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nopt/bin/nopt.js

1
node_modules/.bin/rimraf generated vendored Symbolic link
View File

@ -0,0 +1 @@
../rimraf/bin.js

1
node_modules/.bin/semver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../semver/bin/semver.js

1
node_modules/.bin/tsc generated vendored Symbolic link
View File

@ -0,0 +1 @@
../typescript/bin/tsc

1
node_modules/.bin/tsserver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../typescript/bin/tsserver

10
node_modules/@gar/promisify/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,10 @@
The MIT License (MIT)
Copyright © 2020-2022 Michael Garvin
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.

65
node_modules/@gar/promisify/README.md generated vendored Normal file
View File

@ -0,0 +1,65 @@
# @gar/promisify
### Promisify an entire object or class instance
This module leverages es6 Proxy and Reflect to promisify every function in an
object or class instance.
It assumes the callback that the function is expecting is the last
parameter, and that it is an error-first callback with only one value,
i.e. `(err, value) => ...`. This mirrors node's `util.promisify` method.
In order that you can use it as a one-stop-shop for all your promisify
needs, you can also pass it a function. That function will be
promisified as normal using node's built-in `util.promisify` method.
[node's custom promisified
functions](https://nodejs.org/api/util.html#util_custom_promisified_functions)
will also be mirrored, further allowing this to be a drop-in replacement
for the built-in `util.promisify`.
### Examples
Promisify an entire object
```javascript
const promisify = require('@gar/promisify')
class Foo {
constructor (attr) {
this.attr = attr
}
double (input, cb) {
cb(null, input * 2)
}
const foo = new Foo('baz')
const promisified = promisify(foo)
console.log(promisified.attr)
console.log(await promisified.double(1024))
```
Promisify a function
```javascript
const promisify = require('@gar/promisify')
function foo (a, cb) {
if (a !== 'bad') {
return cb(null, 'ok')
}
return cb('not ok')
}
const promisified = promisify(foo)
// This will resolve to 'ok'
promisified('good')
// this will reject
promisified('bad')
```

36
node_modules/@gar/promisify/index.js generated vendored Normal file
View File

@ -0,0 +1,36 @@
'use strict'
const { promisify } = require('util')
const handler = {
get: function (target, prop, receiver) {
if (typeof target[prop] !== 'function') {
return target[prop]
}
if (target[prop][promisify.custom]) {
return function () {
return Reflect.get(target, prop, receiver)[promisify.custom].apply(target, arguments)
}
}
return function () {
return new Promise((resolve, reject) => {
Reflect.get(target, prop, receiver).apply(target, [...arguments, function (err, result) {
if (err) {
return reject(err)
}
resolve(result)
}])
})
}
}
}
module.exports = function (thingToPromisify) {
if (typeof thingToPromisify === 'function') {
return promisify(thingToPromisify)
}
if (typeof thingToPromisify === 'object') {
return new Proxy(thingToPromisify, handler)
}
throw new TypeError('Can only promisify functions or objects')
}

65
node_modules/@gar/promisify/package.json generated vendored Normal file
View File

@ -0,0 +1,65 @@
{
"_from": "@gar/promisify@^1.0.1",
"_id": "@gar/promisify@1.1.3",
"_inBundle": false,
"_integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==",
"_location": "/@gar/promisify",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@gar/promisify@^1.0.1",
"name": "@gar/promisify",
"escapedName": "@gar%2fpromisify",
"scope": "@gar",
"rawSpec": "^1.0.1",
"saveSpec": null,
"fetchSpec": "^1.0.1"
},
"_requiredBy": [
"/@npmcli/fs"
],
"_resolved": "https://registry.npmmirror.com/@gar/promisify/-/promisify-1.1.3.tgz",
"_shasum": "555193ab2e3bb3b6adc3d551c9c030d9e860daf6",
"_spec": "@gar/promisify@^1.0.1",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/@npmcli/fs",
"author": {
"name": "Gar",
"email": "gar+npm@danger.computer"
},
"bugs": {
"url": "https://github.com/wraithgar/gar-promisify/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Promisify an entire class or object",
"devDependencies": {
"@hapi/code": "^8.0.1",
"@hapi/lab": "^24.1.0",
"standard": "^16.0.3"
},
"files": [
"index.js"
],
"homepage": "https://github.com/wraithgar/gar-promisify#readme",
"keywords": [
"promisify",
"all",
"class",
"object"
],
"license": "MIT",
"main": "index.js",
"name": "@gar/promisify",
"repository": {
"type": "git",
"url": "git+https://github.com/wraithgar/gar-promisify.git"
},
"scripts": {
"lint": "standard",
"lint:fix": "standard --fix",
"posttest": "npm run lint",
"test": "lab -a @hapi/code -t 100"
},
"version": "1.1.3"
}

20
node_modules/@npmcli/fs/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,20 @@
<!-- This file is automatically added by @npmcli/template-oss. Do not edit. -->
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.

60
node_modules/@npmcli/fs/README.md generated vendored Normal file
View File

@ -0,0 +1,60 @@
# @npmcli/fs
polyfills, and extensions, of the core `fs` module.
## Features
- all exposed functions return promises
- `fs.rm` polyfill for node versions < 14.14.0
- `fs.mkdir` polyfill adding support for the `recursive` and `force` options in node versions < 10.12.0
- `fs.copyFile` extended to accept an `owner` option
- `fs.mkdir` extended to accept an `owner` option
- `fs.mkdtemp` extended to accept an `owner` option
- `fs.writeFile` extended to accept an `owner` option
- `fs.withTempDir` added
- `fs.cp` polyfill for node < 16.7.0
## The `owner` option
The `copyFile`, `mkdir`, `mkdtemp`, `writeFile`, and `withTempDir` functions
all accept a new `owner` property in their options. It can be used in two ways:
- `{ owner: { uid: 100, gid: 100 } }` - set the `uid` and `gid` explicitly
- `{ owner: 100 }` - use one value, will set both `uid` and `gid` the same
The special string `'inherit'` may be passed instead of a number, which will
cause this module to automatically determine the correct `uid` and/or `gid`
from the nearest existing parent directory of the target.
## `fs.withTempDir(root, fn, options) -> Promise`
### Parameters
- `root`: the directory in which to create the temporary directory
- `fn`: a function that will be called with the path to the temporary directory
- `options`
- `tmpPrefix`: a prefix to be used in the generated directory name
### Usage
The `withTempDir` function creates a temporary directory, runs the provided
function (`fn`), then removes the temporary directory and resolves or rejects
based on the result of `fn`.
```js
const fs = require('@npmcli/fs')
const os = require('os')
// this function will be called with the full path to the temporary directory
// it is called with `await` behind the scenes, so can be async if desired.
const myFunction = async (tempPath) => {
return 'done!'
}
const main = async () => {
const result = await fs.withTempDir(os.tmpdir(), myFunction)
// result === 'done!'
}
main()
```

View File

@ -0,0 +1,17 @@
const url = require('url')
const node = require('../node.js')
const polyfill = require('./polyfill.js')
const useNative = node.satisfies('>=10.12.0')
const fileURLToPath = (path) => {
// 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
? url.fileURLToPath(path)
: polyfill(path)
}
module.exports = fileURLToPath

View File

@ -0,0 +1,121 @@
const { URL, domainToUnicode } = require('url')
const CHAR_LOWERCASE_A = 97
const CHAR_LOWERCASE_Z = 122
const isWindows = process.platform === 'win32'
class ERR_INVALID_FILE_URL_HOST extends TypeError {
constructor (platform) {
super(`File URL host must be "localhost" or empty on ${platform}`)
this.code = 'ERR_INVALID_FILE_URL_HOST'
}
toString () {
return `${this.name} [${this.code}]: ${this.message}`
}
}
class ERR_INVALID_FILE_URL_PATH extends TypeError {
constructor (msg) {
super(`File URL path ${msg}`)
this.code = 'ERR_INVALID_FILE_URL_PATH'
}
toString () {
return `${this.name} [${this.code}]: ${this.message}`
}
}
class ERR_INVALID_ARG_TYPE extends TypeError {
constructor (name, actual) {
super(`The "${name}" argument must be one of type string or an instance ` +
`of URL. Received type ${typeof actual} ${actual}`)
this.code = 'ERR_INVALID_ARG_TYPE'
}
toString () {
return `${this.name} [${this.code}]: ${this.message}`
}
}
class ERR_INVALID_URL_SCHEME extends TypeError {
constructor (expected) {
super(`The URL must be of scheme ${expected}`)
this.code = 'ERR_INVALID_URL_SCHEME'
}
toString () {
return `${this.name} [${this.code}]: ${this.message}`
}
}
const isURLInstance = (input) => {
return input != null && input.href && input.origin
}
const getPathFromURLWin32 = (url) => {
const hostname = url.hostname
let pathname = url.pathname
for (let n = 0; n < pathname.length; n++) {
if (pathname[n] === '%') {
const third = pathname.codePointAt(n + 2) | 0x20
if ((pathname[n + 1] === '2' && third === 102) ||
(pathname[n + 1] === '5' && third === 99)) {
throw new ERR_INVALID_FILE_URL_PATH('must not include encoded \\ or / characters')
}
}
}
pathname = pathname.replace(/\//g, '\\')
pathname = decodeURIComponent(pathname)
if (hostname !== '') {
return `\\\\${domainToUnicode(hostname)}${pathname}`
}
const letter = pathname.codePointAt(1) | 0x20
const sep = pathname[2]
if (letter < CHAR_LOWERCASE_A || letter > CHAR_LOWERCASE_Z ||
(sep !== ':')) {
throw new ERR_INVALID_FILE_URL_PATH('must be absolute')
}
return pathname.slice(1)
}
const getPathFromURLPosix = (url) => {
if (url.hostname !== '') {
throw new ERR_INVALID_FILE_URL_HOST(process.platform)
}
const pathname = url.pathname
for (let n = 0; n < pathname.length; n++) {
if (pathname[n] === '%') {
const third = pathname.codePointAt(n + 2) | 0x20
if (pathname[n + 1] === '2' && third === 102) {
throw new ERR_INVALID_FILE_URL_PATH('must not include encoded / characters')
}
}
}
return decodeURIComponent(pathname)
}
const fileURLToPath = (path) => {
if (typeof path === 'string') {
path = new URL(path)
} else if (!isURLInstance(path)) {
throw new ERR_INVALID_ARG_TYPE('path', ['string', 'URL'], path)
}
if (path.protocol !== 'file:') {
throw new ERR_INVALID_URL_SCHEME('file')
}
return isWindows
? getPathFromURLWin32(path)
: getPathFromURLPosix(path)
}
module.exports = fileURLToPath

20
node_modules/@npmcli/fs/lib/common/get-options.js generated vendored Normal file
View File

@ -0,0 +1,20 @@
// 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

9
node_modules/@npmcli/fs/lib/common/node.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
const semver = require('semver')
const satisfies = (range) => {
return semver.satisfies(process.version, range, { includePrerelease: true })
}
module.exports = {
satisfies,
}

92
node_modules/@npmcli/fs/lib/common/owner.js generated vendored Normal file
View File

@ -0,0 +1,92 @@
const { dirname, resolve } = require('path')
const fileURLToPath = require('./file-url-to-path/index.js')
const fs = require('../fs.js')
// given a path, find the owner of the nearest parent
const find = async (path) => {
// if we have no getuid, permissions are irrelevant on this platform
if (!process.getuid) {
return {}
}
// fs methods accept URL objects with a scheme of file: so we need to unwrap
// those into an actual path string before we can resolve it
const resolved = path != null && path.href && path.origin
? resolve(fileURLToPath(path))
: resolve(path)
let stat
try {
stat = await fs.lstat(resolved)
} finally {
// if we got a stat, return its contents
if (stat) {
return { uid: stat.uid, gid: stat.gid }
}
// try the parent directory
if (resolved !== dirname(resolved)) {
return find(dirname(resolved))
}
// no more parents, never got a stat, just return an empty object
return {}
}
}
// given a path, uid, and gid update the ownership of the path if necessary
const update = async (path, uid, gid) => {
// nothing to update, just exit
if (uid === undefined && gid === undefined) {
return
}
try {
// see if the permissions are already the same, if they are we don't
// need to do anything, so return early
const stat = await fs.stat(path)
if (uid === stat.uid && gid === stat.gid) {
return
}
} catch (err) {}
try {
await fs.chown(path, uid, gid)
} catch (err) {}
}
// accepts a `path` and the `owner` property of an options object and normalizes
// it into an object with numerical `uid` and `gid`
const validate = async (path, input) => {
let uid
let gid
if (typeof input === 'string' || typeof input === 'number') {
uid = input
gid = input
} else if (input && typeof input === 'object') {
uid = input.uid
gid = input.gid
}
if (uid === 'inherit' || gid === 'inherit') {
const owner = await find(path)
if (uid === 'inherit') {
uid = owner.uid
}
if (gid === 'inherit') {
gid = owner.gid
}
}
return { uid, gid }
}
module.exports = {
find,
update,
validate,
}

22
node_modules/@npmcli/fs/lib/copy-file.js generated vendored Normal file
View File

@ -0,0 +1,22 @@
const fs = require('./fs.js')
const getOptions = require('./common/get-options.js')
const owner = require('./common/owner.js')
const copyFile = async (src, dest, opts) => {
const options = getOptions(opts, {
copy: ['mode', 'owner'],
wrap: 'mode',
})
const { uid, gid } = await owner.validate(dest, options.owner)
// the node core method as of 16.5.0 does not support the mode being in an
// object, so we have to pass the mode value directly
const result = await fs.copyFile(src, dest, options.mode)
await owner.update(dest, uid, gid)
return result
}
module.exports = copyFile

15
node_modules/@npmcli/fs/lib/cp/LICENSE generated vendored Normal file
View File

@ -0,0 +1,15 @@
(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.

22
node_modules/@npmcli/fs/lib/cp/index.js generated vendored Normal file
View File

@ -0,0 +1,22 @@
const fs = require('../fs.js')
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

428
node_modules/@npmcli/fs/lib/cp/polyfill.js generated vendored Normal file
View File

@ -0,0 +1,428 @@
// 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.js')
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

129
node_modules/@npmcli/fs/lib/errors.js generated vendored Normal file
View File

@ -0,0 +1,129 @@
'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}`
}
}

8
node_modules/@npmcli/fs/lib/fs.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
const fs = require('fs')
const promisify = require('@gar/promisify')
// this module returns the core fs module wrapped in a proxy that promisifies
// method calls within the getter. we keep it in a separate module so that the
// overridden methods have a consistent way to get to promisified fs methods
// without creating a circular dependency
module.exports = promisify(fs)

10
node_modules/@npmcli/fs/lib/index.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
module.exports = {
...require('./fs.js'),
copyFile: require('./copy-file.js'),
cp: require('./cp/index.js'),
mkdir: require('./mkdir/index.js'),
mkdtemp: require('./mkdtemp.js'),
rm: require('./rm/index.js'),
withTempDir: require('./with-temp-dir.js'),
writeFile: require('./write-file.js'),
}

32
node_modules/@npmcli/fs/lib/mkdir/index.js generated vendored Normal file
View File

@ -0,0 +1,32 @@
const fs = require('../fs.js')
const getOptions = require('../common/get-options.js')
const node = require('../common/node.js')
const owner = require('../common/owner.js')
const polyfill = require('./polyfill.js')
// node 10.12.0 added the options parameter, which allows recursive and mode
// properties to be passed
const useNative = node.satisfies('>=10.12.0')
// extends mkdir with the ability to specify an owner of the new dir
const mkdir = async (path, opts) => {
const options = getOptions(opts, {
copy: ['mode', 'recursive', 'owner'],
wrap: 'mode',
})
const { uid, gid } = await owner.validate(path, options.owner)
// 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
const result = useNative
? await fs.mkdir(path, options)
: await polyfill(path, options)
await owner.update(path, uid, gid)
return result
}
module.exports = mkdir

81
node_modules/@npmcli/fs/lib/mkdir/polyfill.js generated vendored Normal file
View File

@ -0,0 +1,81 @@
const { dirname } = require('path')
const fileURLToPath = require('../common/file-url-to-path/index.js')
const fs = require('../fs.js')
const defaultOptions = {
mode: 0o777,
recursive: false,
}
const mkdir = async (path, opts) => {
const options = { ...defaultOptions, ...opts }
// if we're not in recursive mode, just call the real mkdir with the path and
// the mode option only
if (!options.recursive) {
return fs.mkdir(path, options.mode)
}
const makeDirectory = async (dir, mode) => {
// we can't use dirname directly since these functions support URL
// objects with the file: protocol as the path input, so first we get a
// string path, then we can call dirname on that
const parent = dir != null && dir.href && dir.origin
? dirname(fileURLToPath(dir))
: dirname(dir)
// if the parent is the dir itself, try to create it. anything but EISDIR
// should be rethrown
if (parent === dir) {
try {
await fs.mkdir(dir, opts)
} catch (err) {
if (err.code !== 'EISDIR') {
throw err
}
}
return undefined
}
try {
await fs.mkdir(dir, mode)
return dir
} catch (err) {
// ENOENT means the parent wasn't there, so create that
if (err.code === 'ENOENT') {
const made = await makeDirectory(parent, mode)
await makeDirectory(dir, mode)
// return the shallowest path we created, i.e. the result of creating
// the parent
return made
}
// an EEXIST means there's already something there
// an EROFS means we have a read-only filesystem and can't create a dir
// any other error is fatal and we should give up now
if (err.code !== 'EEXIST' && err.code !== 'EROFS') {
throw err
}
// stat the directory, if the result is a directory, then we successfully
// created this one so return its path. otherwise, we reject with the
// original error by ignoring the error in the catch
try {
const stat = await fs.stat(dir)
if (stat.isDirectory()) {
// if it already existed, we didn't create anything so return
// undefined
return undefined
}
} catch (_) {}
// if the thing that's there isn't a directory, then just re-throw
throw err
}
}
return makeDirectory(path, options.mode)
}
module.exports = mkdir

28
node_modules/@npmcli/fs/lib/mkdtemp.js generated vendored Normal file
View File

@ -0,0 +1,28 @@
const { dirname, sep } = require('path')
const fs = require('./fs.js')
const getOptions = require('./common/get-options.js')
const owner = require('./common/owner.js')
const mkdtemp = async (prefix, opts) => {
const options = getOptions(opts, {
copy: ['encoding', 'owner'],
wrap: 'encoding',
})
// mkdtemp relies on the trailing path separator to indicate if it should
// create a directory inside of the prefix. if that's the case then the root
// we infer ownership from is the prefix itself, otherwise it's the dirname
// /tmp -> /tmpABCDEF, infers from /
// /tmp/ -> /tmp/ABCDEF, infers from /tmp
const root = prefix.endsWith(sep) ? prefix : dirname(prefix)
const { uid, gid } = await owner.validate(root, options.owner)
const result = await fs.mkdtemp(prefix, options)
await owner.update(result, uid, gid)
return result
}
module.exports = mkdtemp

22
node_modules/@npmcli/fs/lib/rm/index.js generated vendored Normal file
View File

@ -0,0 +1,22 @@
const fs = require('../fs.js')
const getOptions = require('../common/get-options.js')
const node = require('../common/node.js')
const polyfill = require('./polyfill.js')
// node 14.14.0 added fs.rm, which allows both the force and recursive options
const useNative = node.satisfies('>=14.14.0')
const rm = async (path, opts) => {
const options = getOptions(opts, {
copy: ['retryDelay', 'maxRetries', 'recursive', 'force'],
})
// 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.rm(path, options)
: polyfill(path, options)
}
module.exports = rm

239
node_modules/@npmcli/fs/lib/rm/polyfill.js generated vendored Normal file
View File

@ -0,0 +1,239 @@
// this file is a modified version of the code in node core >=14.14.0
// which is, in turn, a modified version of the rimraf 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
const errnos = require('os').constants.errno
const { join } = require('path')
const fs = require('../fs.js')
// error codes that mean we need to remove contents
const notEmptyCodes = new Set([
'ENOTEMPTY',
'EEXIST',
'EPERM',
])
// error codes we can retry later
const retryCodes = new Set([
'EBUSY',
'EMFILE',
'ENFILE',
'ENOTEMPTY',
'EPERM',
])
const isWindows = process.platform === 'win32'
const defaultOptions = {
retryDelay: 100,
maxRetries: 0,
recursive: false,
force: false,
}
// this is drastically simplified, but should be roughly equivalent to what
// node core throws
class ERR_FS_EISDIR extends Error {
constructor (path) {
super()
this.info = {
code: 'EISDIR',
message: 'is a directory',
path,
syscall: 'rm',
errno: errnos.EISDIR,
}
this.name = 'SystemError'
this.code = 'ERR_FS_EISDIR'
this.errno = errnos.EISDIR
this.syscall = 'rm'
this.path = path
this.message = `Path is a directory: ${this.syscall} returned ` +
`${this.info.code} (is a directory) ${path}`
}
toString () {
return `${this.name} [${this.code}]: ${this.message}`
}
}
class ENOTDIR extends Error {
constructor (path) {
super()
this.name = 'Error'
this.code = 'ENOTDIR'
this.errno = errnos.ENOTDIR
this.syscall = 'rmdir'
this.path = path
this.message = `not a directory, ${this.syscall} '${this.path}'`
}
toString () {
return `${this.name}: ${this.code}: ${this.message}`
}
}
// force is passed separately here because we respect it for the first entry
// into rimraf only, any further calls that are spawned as a result (i.e. to
// delete content within the target) will ignore ENOENT errors
const rimraf = async (path, options, isTop = false) => {
const force = isTop ? options.force : true
const stat = await fs.lstat(path)
.catch((err) => {
// we only ignore ENOENT if we're forcing this call
if (err.code === 'ENOENT' && force) {
return
}
if (isWindows && err.code === 'EPERM') {
return fixEPERM(path, options, err, isTop)
}
throw err
})
// no stat object here means either lstat threw an ENOENT, or lstat threw
// an EPERM and the fixPERM function took care of things. either way, we're
// already done, so return early
if (!stat) {
return
}
if (stat.isDirectory()) {
return rmdir(path, options, null, isTop)
}
return fs.unlink(path)
.catch((err) => {
if (err.code === 'ENOENT' && force) {
return
}
if (err.code === 'EISDIR') {
return rmdir(path, options, err, isTop)
}
if (err.code === 'EPERM') {
// in windows, we handle this through fixEPERM which will also try to
// delete things again. everywhere else since deleting the target as a
// file didn't work we go ahead and try to delete it as a directory
return isWindows
? fixEPERM(path, options, err, isTop)
: rmdir(path, options, err, isTop)
}
throw err
})
}
const fixEPERM = async (path, options, originalErr, isTop) => {
const force = isTop ? options.force : true
const targetMissing = await fs.chmod(path, 0o666)
.catch((err) => {
if (err.code === 'ENOENT' && force) {
return true
}
throw originalErr
})
// got an ENOENT above, return now. no file = no problem
if (targetMissing) {
return
}
// this function does its own lstat rather than calling rimraf again to avoid
// infinite recursion for a repeating EPERM
const stat = await fs.lstat(path)
.catch((err) => {
if (err.code === 'ENOENT' && force) {
return
}
throw originalErr
})
if (!stat) {
return
}
if (stat.isDirectory()) {
return rmdir(path, options, originalErr, isTop)
}
return fs.unlink(path)
}
const rmdir = async (path, options, originalErr, isTop) => {
if (!options.recursive && isTop) {
throw originalErr || new ERR_FS_EISDIR(path)
}
const force = isTop ? options.force : true
return fs.rmdir(path)
.catch(async (err) => {
// in Windows, calling rmdir on a file path will fail with ENOENT rather
// than ENOTDIR. to determine if that's what happened, we have to do
// another lstat on the path. if the path isn't actually gone, we throw
// away the ENOENT and replace it with our own ENOTDIR
if (isWindows && err.code === 'ENOENT') {
const stillExists = await fs.lstat(path).then(() => true, () => false)
if (stillExists) {
err = new ENOTDIR(path)
}
}
// not there, not a problem
if (err.code === 'ENOENT' && force) {
return
}
// we may not have originalErr if lstat tells us our target is a
// directory but that changes before we actually remove it, so
// only throw it here if it's set
if (originalErr && err.code === 'ENOTDIR') {
throw originalErr
}
// the directory isn't empty, remove the contents and try again
if (notEmptyCodes.has(err.code)) {
const files = await fs.readdir(path)
await Promise.all(files.map((file) => {
const target = join(path, file)
return rimraf(target, options)
}))
return fs.rmdir(path)
}
throw err
})
}
const rm = async (path, opts) => {
const options = { ...defaultOptions, ...opts }
let retries = 0
const errHandler = async (err) => {
if (retryCodes.has(err.code) && ++retries < options.maxRetries) {
const delay = retries * options.retryDelay
await promiseTimeout(delay)
return rimraf(path, options, true).catch(errHandler)
}
throw err
}
return rimraf(path, options, true).catch(errHandler)
}
const promiseTimeout = (ms) => new Promise((r) => setTimeout(r, ms))
module.exports = rm

39
node_modules/@npmcli/fs/lib/with-temp-dir.js generated vendored Normal file
View File

@ -0,0 +1,39 @@
const { join, sep } = require('path')
const getOptions = require('./common/get-options.js')
const mkdir = require('./mkdir/index.js')
const mkdtemp = require('./mkdtemp.js')
const rm = require('./rm/index.js')
// 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, and fix its ownership
await mkdir(root, { recursive: true, owner: 'inherit' })
const target = await mkdtemp(join(`${root}${sep}`, options.tmpPrefix || ''), { owner: 'inherit' })
let err
let result
try {
result = await fn(target)
} catch (_err) {
err = _err
}
try {
await rm(target, { force: true, recursive: true })
} catch (err) {}
if (err) {
throw err
}
return result
}
module.exports = withTempDir

19
node_modules/@npmcli/fs/lib/write-file.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
const fs = require('./fs.js')
const getOptions = require('./common/get-options.js')
const owner = require('./common/owner.js')
const writeFile = async (file, data, opts) => {
const options = getOptions(opts, {
copy: ['encoding', 'mode', 'flag', 'signal', 'owner'],
wrap: 'encoding',
})
const { uid, gid } = await owner.validate(file, options.owner)
const result = await fs.writeFile(file, data, options)
await owner.update(file, uid, gid)
return result
}
module.exports = writeFile

66
node_modules/@npmcli/fs/package.json generated vendored Normal file
View File

@ -0,0 +1,66 @@
{
"_from": "@npmcli/fs@^1.0.0",
"_id": "@npmcli/fs@1.1.1",
"_inBundle": false,
"_integrity": "sha512-8KG5RD0GVP4ydEzRn/I4BNDuxDtqVbOdm8675T49OIG/NGhaK0pjPX7ZcDlvKYbA+ulvVK3ztfcF4uBdOxuJbQ==",
"_location": "/@npmcli/fs",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@npmcli/fs@^1.0.0",
"name": "@npmcli/fs",
"escapedName": "@npmcli%2ffs",
"scope": "@npmcli",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/cacache"
],
"_resolved": "https://registry.npmmirror.com/@npmcli/fs/-/fs-1.1.1.tgz",
"_shasum": "72f719fe935e687c56a4faecf3c03d06ba593257",
"_spec": "@npmcli/fs@^1.0.0",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/cacache",
"author": {
"name": "GitHub Inc."
},
"bundleDependencies": false,
"dependencies": {
"@gar/promisify": "^1.0.1",
"semver": "^7.3.5"
},
"deprecated": false,
"description": "filesystem utilities for the npm cli",
"devDependencies": {
"@npmcli/template-oss": "^2.3.1",
"tap": "^15.0.9"
},
"files": [
"bin",
"lib"
],
"keywords": [
"npm",
"oss"
],
"license": "ISC",
"main": "lib/index.js",
"name": "@npmcli/fs",
"scripts": {
"lint": "eslint '**/*.js'",
"lintfix": "npm run lint -- --fix",
"npmclilint": "npmcli-lint",
"postlint": "npm-template-check",
"postsnap": "npm run lintfix --",
"posttest": "npm run lint",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"preversion": "npm test",
"snap": "tap",
"test": "tap"
},
"templateVersion": "2.3.1",
"version": "1.1.1"
}

22
node_modules/@npmcli/move-file/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Copyright (c) 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.

69
node_modules/@npmcli/move-file/README.md generated vendored Normal file
View File

@ -0,0 +1,69 @@
# @npmcli/move-file
A fork of [move-file](https://github.com/sindresorhus/move-file) with
compatibility with all node 10.x versions.
> Move a file (or directory)
The built-in
[`fs.rename()`](https://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback)
is just a JavaScript wrapper for the C `rename(2)` function, which doesn't
support moving files across partitions or devices. This module is what you
would have expected `fs.rename()` to be.
## Highlights
- Promise API.
- Supports moving a file across partitions and devices.
- Optionally prevent overwriting an existing file.
- Creates non-existent destination directories for you.
- Support for Node versions that lack built-in recursive `fs.mkdir()`
- Automatically recurses when source is a directory.
## Install
```
$ npm install @npmcli/move-file
```
## Usage
```js
const moveFile = require('@npmcli/move-file');
(async () => {
await moveFile('source/unicorn.png', 'destination/unicorn.png');
console.log('The file has been moved');
})();
```
## API
### moveFile(source, destination, options?)
Returns a `Promise` that resolves when the file has been moved.
### moveFile.sync(source, destination, options?)
#### source
Type: `string`
File, or directory, you want to move.
#### destination
Type: `string`
Where you want the file or directory moved.
#### options
Type: `object`
##### overwrite
Type: `boolean`\
Default: `true`
Overwrite existing destination file(s).

162
node_modules/@npmcli/move-file/index.js generated vendored Normal file
View File

@ -0,0 +1,162 @@
const { dirname, join, resolve, relative, isAbsolute } = require('path')
const rimraf_ = require('rimraf')
const { promisify } = require('util')
const {
access: access_,
accessSync,
copyFile: copyFile_,
copyFileSync,
unlink: unlink_,
unlinkSync,
readdir: readdir_,
readdirSync,
rename: rename_,
renameSync,
stat: stat_,
statSync,
lstat: lstat_,
lstatSync,
symlink: symlink_,
symlinkSync,
readlink: readlink_,
readlinkSync
} = require('fs')
const access = promisify(access_)
const copyFile = promisify(copyFile_)
const unlink = promisify(unlink_)
const readdir = promisify(readdir_)
const rename = promisify(rename_)
const stat = promisify(stat_)
const lstat = promisify(lstat_)
const symlink = promisify(symlink_)
const readlink = promisify(readlink_)
const rimraf = promisify(rimraf_)
const rimrafSync = rimraf_.sync
const mkdirp = require('mkdirp')
const pathExists = async path => {
try {
await access(path)
return true
} catch (er) {
return er.code !== 'ENOENT'
}
}
const pathExistsSync = path => {
try {
accessSync(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 mkdirp(dirname(destination))
try {
await rename(source, destination)
} catch (error) {
if (error.code === 'EXDEV' || error.code === 'EPERM') {
const sourceStat = await lstat(source)
if (sourceStat.isDirectory()) {
const files = await 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 copyFile(source, destination)
}
} else {
throw error
}
}
if (root) {
await Promise.all(symlinks.map(async ({ source, destination }) => {
let target = await readlink(source)
// junction symlinks in windows will be absolute paths, so we need to make sure they point to the destination
if (isAbsolute(target))
target = resolve(destination, relative(source, target))
// try to determine what the actual file is so we can create the correct type of symlink in windows
let targetStat
try {
targetStat = await stat(resolve(dirname(source), target))
} catch (err) {}
await symlink(target, destination, targetStat && targetStat.isDirectory() ? 'junction' : 'file')
}))
await rimraf(source)
}
}
const moveFileSync = (source, destination, options = {}, root = true, symlinks = []) => {
if (!source || !destination) {
throw new TypeError('`source` and `destination` file required')
}
options = {
overwrite: true,
...options
}
if (!options.overwrite && pathExistsSync(destination)) {
throw new Error(`The destination file exists: ${destination}`)
}
mkdirp.sync(dirname(destination))
try {
renameSync(source, destination)
} catch (error) {
if (error.code === 'EXDEV' || error.code === 'EPERM') {
const sourceStat = lstatSync(source)
if (sourceStat.isDirectory()) {
const files = readdirSync(source)
for (const file of files) {
moveFileSync(join(source, file), join(destination, file), options, false, symlinks)
}
} else if (sourceStat.isSymbolicLink()) {
symlinks.push({ source, destination })
} else {
copyFileSync(source, destination)
}
} else {
throw error
}
}
if (root) {
for (const { source, destination } of symlinks) {
let target = readlinkSync(source)
// junction symlinks in windows will be absolute paths, so we need to make sure they point to the destination
if (isAbsolute(target))
target = resolve(destination, relative(source, target))
// try to determine what the actual file is so we can create the correct type of symlink in windows
let targetStat
try {
targetStat = statSync(resolve(dirname(source), target))
} catch (err) {}
symlinkSync(target, destination, targetStat && targetStat.isDirectory() ? 'junction' : 'file')
}
rimrafSync(source)
}
}
module.exports = moveFile
module.exports.sync = moveFileSync

64
node_modules/@npmcli/move-file/package.json generated vendored Normal file
View File

@ -0,0 +1,64 @@
{
"_from": "@npmcli/move-file@^1.0.1",
"_id": "@npmcli/move-file@1.1.2",
"_inBundle": false,
"_integrity": "sha512-1SUf/Cg2GzGDyaf15aR9St9TWlb+XvbZXWpDx8YKs7MLzMH/BCeopv+y9vzrzgkfykCGuWOlSu3mZhj2+FQcrg==",
"_location": "/@npmcli/move-file",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@npmcli/move-file@^1.0.1",
"name": "@npmcli/move-file",
"escapedName": "@npmcli%2fmove-file",
"scope": "@npmcli",
"rawSpec": "^1.0.1",
"saveSpec": null,
"fetchSpec": "^1.0.1"
},
"_requiredBy": [
"/cacache"
],
"_resolved": "https://registry.npmmirror.com/@npmcli/move-file/-/move-file-1.1.2.tgz",
"_shasum": "1a82c3e372f7cae9253eb66d72543d6b8685c674",
"_spec": "@npmcli/move-file@^1.0.1",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/cacache",
"bugs": {
"url": "https://github.com/npm/move-file/issues"
},
"bundleDependencies": false,
"dependencies": {
"mkdirp": "^1.0.4",
"rimraf": "^3.0.2"
},
"deprecated": false,
"description": "move a file (fork of move-file)",
"devDependencies": {
"require-inject": "^1.4.4",
"tap": "^14.10.7"
},
"engines": {
"node": ">=10"
},
"files": [
"index.js"
],
"homepage": "https://github.com/npm/move-file#readme",
"license": "MIT",
"name": "@npmcli/move-file",
"repository": {
"type": "git",
"url": "git+https://github.com/npm/move-file.git"
},
"scripts": {
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"preversion": "npm test",
"snap": "tap",
"test": "tap"
},
"tap": {
"check-coverage": true
},
"version": "1.1.2"
}

14
node_modules/@tootallnate/once/dist/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,14 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
declare function once<T>(emitter: EventEmitter, name: string): once.CancelablePromise<T>;
declare namespace once {
interface CancelFunction {
(): void;
}
interface CancelablePromise<T> extends Promise<T> {
cancel: CancelFunction;
}
type CancellablePromise<T> = CancelablePromise<T>;
function spread<T extends any[]>(emitter: EventEmitter, name: string): once.CancelablePromise<T>;
}
export = once;

39
node_modules/@tootallnate/once/dist/index.js generated vendored Normal file
View File

@ -0,0 +1,39 @@
"use strict";
function noop() { }
function once(emitter, name) {
const o = once.spread(emitter, name);
const r = o.then((args) => args[0]);
r.cancel = o.cancel;
return r;
}
(function (once) {
function spread(emitter, name) {
let c = null;
const p = new Promise((resolve, reject) => {
function cancel() {
emitter.removeListener(name, onEvent);
emitter.removeListener('error', onError);
p.cancel = noop;
}
function onEvent(...args) {
cancel();
resolve(args);
}
function onError(err) {
cancel();
reject(err);
}
c = cancel;
emitter.on(name, onEvent);
emitter.on('error', onError);
});
if (!c) {
throw new TypeError('Could not get `cancel()` function');
}
p.cancel = c;
return p;
}
once.spread = spread;
})(once || (once = {}));
module.exports = once;
//# sourceMappingURL=index.js.map

1
node_modules/@tootallnate/once/dist/index.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA,SAAS,IAAI,KAAI,CAAC;AAElB,SAAS,IAAI,CACZ,OAAqB,EACrB,IAAY;IAEZ,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAM,OAAO,EAAE,IAAI,CAAC,CAAC;IAC1C,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,IAAS,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAA8B,CAAC;IACtE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC;IACpB,OAAO,CAAC,CAAC;AACV,CAAC;AAED,WAAU,IAAI;IAWb,SAAgB,MAAM,CACrB,OAAqB,EACrB,IAAY;QAEZ,IAAI,CAAC,GAA+B,IAAI,CAAC;QACzC,MAAM,CAAC,GAAG,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC5C,SAAS,MAAM;gBACd,OAAO,CAAC,cAAc,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;gBACtC,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;gBACzC,CAAC,CAAC,MAAM,GAAG,IAAI,CAAC;YACjB,CAAC;YACD,SAAS,OAAO,CAAC,GAAG,IAAW;gBAC9B,MAAM,EAAE,CAAC;gBACT,OAAO,CAAC,IAAS,CAAC,CAAC;YACpB,CAAC;YACD,SAAS,OAAO,CAAC,GAAU;gBAC1B,MAAM,EAAE,CAAC;gBACT,MAAM,CAAC,GAAG,CAAC,CAAC;YACb,CAAC;YACD,CAAC,GAAG,MAAM,CAAC;YACX,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAC1B,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9B,CAAC,CAA8B,CAAC;QAChC,IAAI,CAAC,CAAC,EAAE;YACP,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;SACzD;QACD,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;QACb,OAAO,CAAC,CAAC;IACV,CAAC;IA5Be,WAAM,SA4BrB,CAAA;AACF,CAAC,EAxCS,IAAI,KAAJ,IAAI,QAwCb;AAED,iBAAS,IAAI,CAAC"}

76
node_modules/@tootallnate/once/package.json generated vendored Normal file
View File

@ -0,0 +1,76 @@
{
"_from": "@tootallnate/once@1",
"_id": "@tootallnate/once@1.1.2",
"_inBundle": false,
"_integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==",
"_location": "/@tootallnate/once",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@tootallnate/once@1",
"name": "@tootallnate/once",
"escapedName": "@tootallnate%2fonce",
"scope": "@tootallnate",
"rawSpec": "1",
"saveSpec": null,
"fetchSpec": "1"
},
"_requiredBy": [
"/http-proxy-agent"
],
"_resolved": "https://registry.npmmirror.com/@tootallnate/once/-/once-1.1.2.tgz",
"_shasum": "ccb91445360179a04e7fe6aff78c00ffc1eeaf82",
"_spec": "@tootallnate/once@1",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/http-proxy-agent",
"author": {
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://n8.io/"
},
"bugs": {
"url": "https://github.com/TooTallNate/once/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Creates a Promise that waits for a single event",
"devDependencies": {
"@types/node": "^12.12.11",
"@typescript-eslint/eslint-plugin": "1.6.0",
"@typescript-eslint/parser": "1.1.0",
"eslint": "5.16.0",
"eslint-config-airbnb": "17.1.0",
"eslint-config-prettier": "4.1.0",
"eslint-import-resolver-typescript": "1.1.1",
"eslint-plugin-import": "2.16.0",
"eslint-plugin-jsx-a11y": "6.2.1",
"eslint-plugin-react": "7.12.4",
"mocha": "^6.2.2",
"rimraf": "^3.0.0",
"typescript": "^3.7.3"
},
"engines": {
"node": ">= 6"
},
"files": [
"dist"
],
"homepage": "https://github.com/TooTallNate/once#readme",
"keywords": [],
"license": "MIT",
"main": "./dist/index.js",
"name": "@tootallnate/once",
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/once.git"
},
"scripts": {
"build": "tsc",
"prebuild": "rimraf dist",
"prepublishOnly": "npm run build",
"test": "mocha --reporter spec",
"test-lint": "eslint src --ext .js,.ts"
},
"types": "./dist/index.d.ts",
"version": "1.1.2"
}

15
node_modules/@ungap/promise-all-settled/LICENSE generated vendored Normal file
View File

@ -0,0 +1,15 @@
ISC License
Copyright (c) 2019, Andrea Giammarchi, @WebReflection
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.

26
node_modules/@ungap/promise-all-settled/README.md generated vendored Normal file
View File

@ -0,0 +1,26 @@
# Promise.allSettled
[![Build Status](https://travis-ci.com/ungap/promise-all-settled.svg?branch=master)](https://travis-ci.com/ungap/promise-all-settled) [![Coverage Status](https://coveralls.io/repos/github/ungap/promise-all-settled/badge.svg?branch=master)](https://coveralls.io/github/ungap/promise-all-settled?branch=master) [![Greenkeeper badge](https://badges.greenkeeper.io/ungap/promise-all-settled.svg)](https://greenkeeper.io/) ![WebReflection status](https://offline.report/status/webreflection.svg)
A cross platform [Promise.allSettled](https://github.com/tc39/proposal-promise-allSettled) polyfill.
* CDN global utility via https://unpkg.com/@ungap/promise-all-settled
* ESM via `import allSettled from '@ungap/promise-all-settled'`
* CJS via `const allSettled = require('@ungap/promise-all-settled')`
### Example
```js
const allSettled = require("@ungap/promise-all-settled");
// use it via call
allSettled.call(Promise, []);
// or bind it:
const $settled = allSettled.bind(Promise);
// or put it in the Promise class
if (!Promise.allSettled)
Promise.allSettled = allSettled;
```

19
node_modules/@ungap/promise-all-settled/cjs/index.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
var allSettled = Promise.allSettled || function ($) {'use strict';
var self = this;
return self.all(
$.map(
function (value) {
return self.resolve(value).then(this.$, this._);
},
{
$: function (value) {
return {status: 'fulfilled', value: value};
},
_: function (reason) {
return {status: 'rejected', reason: reason};
}
}
)
);
};
module.exports = allSettled;

View File

@ -0,0 +1 @@
{"type":"commonjs"}

19
node_modules/@ungap/promise-all-settled/esm/index.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
var allSettled = Promise.allSettled || function ($) {'use strict';
var self = this;
return self.all(
$.map(
function (value) {
return self.resolve(value).then(this.$, this._);
},
{
$: function (value) {
return {status: 'fulfilled', value: value};
},
_: function (reason) {
return {status: 'rejected', reason: reason};
}
}
)
);
};
export default allSettled;

18
node_modules/@ungap/promise-all-settled/index.js generated vendored Normal file
View File

@ -0,0 +1,18 @@
var allSettled = Promise.allSettled || function ($) {'use strict';
var self = this;
return self.all(
$.map(
function (value) {
return self.resolve(value).then(this.$, this._);
},
{
$: function (value) {
return {status: 'fulfilled', value: value};
},
_: function (reason) {
return {status: 'rejected', reason: reason};
}
}
)
);
};

1
node_modules/@ungap/promise-all-settled/min.js generated vendored Normal file
View File

@ -0,0 +1 @@
var allSettled=Promise.allSettled||function(t){"use strict";var e=this;return e.all(t.map(function(t){return e.resolve(t).then(this.$,this._)},{$:function(t){return{status:"fulfilled",value:t}},_:function(t){return{status:"rejected",reason:t}}}))};

72
node_modules/@ungap/promise-all-settled/package.json generated vendored Normal file
View File

@ -0,0 +1,72 @@
{
"_from": "@ungap/promise-all-settled@1.1.2",
"_id": "@ungap/promise-all-settled@1.1.2",
"_inBundle": false,
"_integrity": "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==",
"_location": "/@ungap/promise-all-settled",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@ungap/promise-all-settled@1.1.2",
"name": "@ungap/promise-all-settled",
"escapedName": "@ungap%2fpromise-all-settled",
"scope": "@ungap",
"rawSpec": "1.1.2",
"saveSpec": null,
"fetchSpec": "1.1.2"
},
"_requiredBy": [
"/mocha"
],
"_resolved": "https://registry.npmmirror.com/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz",
"_shasum": "aa58042711d6e3275dd37dc597e5d31e8c290a44",
"_spec": "@ungap/promise-all-settled@1.1.2",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/mocha",
"author": {
"name": "Andrea Giammarchi"
},
"bugs": {
"url": "https://github.com/ungap/promise-all-settled/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "A cross platform Promise.allSettled polyfill",
"devDependencies": {
"coveralls": "^3.1.0",
"nyc": "^15.0.1",
"uglify-js": "^3.9.1"
},
"exports": {
"import": "./esm/index.js",
"default": "./cjs/index.js"
},
"homepage": "https://github.com/ungap/promise-all-settled#readme",
"keywords": [
"Promise",
"allSettled",
"polyfill",
"utility",
"ungap"
],
"license": "ISC",
"main": "./cjs/index.js",
"module": "./esm/index.js",
"name": "@ungap/promise-all-settled",
"repository": {
"type": "git",
"url": "git+https://github.com/ungap/promise-all-settled.git"
},
"scripts": {
"build": "npm run cjs && npm run esm && npm run min && npm run test && npm run size",
"cjs": "cp index.js cjs/ && echo 'module.exports = allSettled;' >> cjs/index.js",
"coveralls": "nyc report --reporter=text-lcov | coveralls",
"esm": "cp index.js esm/ && echo 'export default allSettled;' >> esm/index.js",
"min": "uglifyjs index.js --support-ie8 --comments=/^!/ -c -m -o min.js",
"size": "cat index.js | wc -c && cat min.js | wc -c && gzip -c9 min.js | wc -c && cat min.js | brotli | wc -c",
"test": "nyc node test/index.js"
},
"type": "module",
"unpkg": "min.js",
"version": "1.1.2"
}

46
node_modules/abbrev/LICENSE generated vendored Normal file
View File

@ -0,0 +1,46 @@
This software is dual-licensed under the ISC and MIT licenses.
You may use this software under EITHER of the following licenses.
----------
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.
----------
Copyright Isaac Z. Schlueter and Contributors
All rights reserved.
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.

23
node_modules/abbrev/README.md generated vendored Normal file
View File

@ -0,0 +1,23 @@
# abbrev-js
Just like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).
Usage:
var abbrev = require("abbrev");
abbrev("foo", "fool", "folding", "flop");
// returns:
{ fl: 'flop'
, flo: 'flop'
, flop: 'flop'
, fol: 'folding'
, fold: 'folding'
, foldi: 'folding'
, foldin: 'folding'
, folding: 'folding'
, foo: 'foo'
, fool: 'fool'
}
This is handy for command-line scripts, or other cases where you want to be able to accept shorthands.

61
node_modules/abbrev/abbrev.js generated vendored Normal file
View File

@ -0,0 +1,61 @@
module.exports = exports = abbrev.abbrev = abbrev
abbrev.monkeyPatch = monkeyPatch
function monkeyPatch () {
Object.defineProperty(Array.prototype, 'abbrev', {
value: function () { return abbrev(this) },
enumerable: false, configurable: true, writable: true
})
Object.defineProperty(Object.prototype, 'abbrev', {
value: function () { return abbrev(Object.keys(this)) },
enumerable: false, configurable: true, writable: true
})
}
function abbrev (list) {
if (arguments.length !== 1 || !Array.isArray(list)) {
list = Array.prototype.slice.call(arguments, 0)
}
for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
}
// sort them lexicographically, so that they're next to their nearest kin
args = args.sort(lexSort)
// walk through each, seeing how much it has in common with the next and previous
var abbrevs = {}
, prev = ""
for (var i = 0, l = args.length ; i < l ; i ++) {
var current = args[i]
, next = args[i + 1] || ""
, nextMatches = true
, prevMatches = true
if (current === next) continue
for (var j = 0, cl = current.length ; j < cl ; j ++) {
var curChar = current.charAt(j)
nextMatches = nextMatches && curChar === next.charAt(j)
prevMatches = prevMatches && curChar === prev.charAt(j)
if (!nextMatches && !prevMatches) {
j ++
break
}
}
prev = current
if (j === cl) {
abbrevs[current] = current
continue
}
for (var a = current.substr(0, j) ; j <= cl ; j ++) {
abbrevs[a] = current
a += current.charAt(j)
}
}
return abbrevs
}
function lexSort (a, b) {
return a === b ? 0 : a > b ? 1 : -1
}

56
node_modules/abbrev/package.json generated vendored Normal file
View File

@ -0,0 +1,56 @@
{
"_from": "abbrev@1",
"_id": "abbrev@1.1.1",
"_inBundle": false,
"_integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
"_location": "/abbrev",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "abbrev@1",
"name": "abbrev",
"escapedName": "abbrev",
"rawSpec": "1",
"saveSpec": null,
"fetchSpec": "1"
},
"_requiredBy": [
"/nopt"
],
"_resolved": "https://registry.npmmirror.com/abbrev/-/abbrev-1.1.1.tgz",
"_shasum": "f8f2c887ad10bf67f634f005b6987fed3179aac8",
"_spec": "abbrev@1",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/nopt",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me"
},
"bugs": {
"url": "https://github.com/isaacs/abbrev-js/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Like ruby's abbrev module, but in js",
"devDependencies": {
"tap": "^10.1"
},
"files": [
"abbrev.js"
],
"homepage": "https://github.com/isaacs/abbrev-js#readme",
"license": "ISC",
"main": "abbrev.js",
"name": "abbrev",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/isaacs/abbrev-js.git"
},
"scripts": {
"postpublish": "git push origin --all; git push origin --tags",
"postversion": "npm publish",
"preversion": "npm test",
"test": "tap test.js --100"
},
"version": "1.1.1"
}

145
node_modules/agent-base/README.md generated vendored Normal file
View File

@ -0,0 +1,145 @@
agent-base
==========
### Turn a function into an [`http.Agent`][http.Agent] instance
[![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI)
This module provides an `http.Agent` generator. That is, you pass it an async
callback function, and it returns a new `http.Agent` instance that will invoke the
given callback function when sending outbound HTTP requests.
#### Some subclasses:
Here's some more interesting uses of `agent-base`.
Send a pull request to list yours!
* [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints
* [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints
* [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS
* [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS
Installation
------------
Install with `npm`:
``` bash
$ npm install agent-base
```
Example
-------
Here's a minimal example that creates a new `net.Socket` connection to the server
for every HTTP request (i.e. the equivalent of `agent: false` option):
```js
var net = require('net');
var tls = require('tls');
var url = require('url');
var http = require('http');
var agent = require('agent-base');
var endpoint = 'http://nodejs.org/api/';
var parsed = url.parse(endpoint);
// This is the important part!
parsed.agent = agent(function (req, opts) {
var socket;
// `secureEndpoint` is true when using the https module
if (opts.secureEndpoint) {
socket = tls.connect(opts);
} else {
socket = net.connect(opts);
}
return socket;
});
// Everything else works just like normal...
http.get(parsed, function (res) {
console.log('"response" event!', res.headers);
res.pipe(process.stdout);
});
```
Returning a Promise or using an `async` function is also supported:
```js
agent(async function (req, opts) {
await sleep(1000);
// etc…
});
```
Return another `http.Agent` instance to "pass through" the responsibility
for that HTTP request to that agent:
```js
agent(function (req, opts) {
return opts.secureEndpoint ? https.globalAgent : http.globalAgent;
});
```
API
---
## Agent(Function callback[, Object options]) → [http.Agent][]
Creates a base `http.Agent` that will execute the callback function `callback`
for every HTTP request that it is used as the `agent` for. The callback function
is responsible for creating a `stream.Duplex` instance of some kind that will be
used as the underlying socket in the HTTP request.
The `options` object accepts the following properties:
* `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional).
The callback function should have the following signature:
### callback(http.ClientRequest req, Object options, Function cb) → undefined
The ClientRequest `req` can be accessed to read request headers and
and the path, etc. The `options` object contains the options passed
to the `http.request()`/`https.request()` function call, and is formatted
to be directly passed to `net.connect()`/`tls.connect()`, or however
else you want a Socket to be created. Pass the created socket to
the callback function `cb` once created, and the HTTP request will
continue to proceed.
If the `https` module is used to invoke the HTTP request, then the
`secureEndpoint` property on `options` _will be set to `true`_.
License
-------
(The MIT License)
Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
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.
[http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent
[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
[pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent
[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent

78
node_modules/agent-base/dist/src/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,78 @@
/// <reference types="node" />
import net from 'net';
import http from 'http';
import https from 'https';
import { Duplex } from 'stream';
import { EventEmitter } from 'events';
declare function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent;
declare function createAgent(callback: createAgent.AgentCallback, opts?: createAgent.AgentOptions): createAgent.Agent;
declare namespace createAgent {
interface ClientRequest extends http.ClientRequest {
_last?: boolean;
_hadError?: boolean;
method: string;
}
interface AgentRequestOptions {
host?: string;
path?: string;
port: number;
}
interface HttpRequestOptions extends AgentRequestOptions, Omit<http.RequestOptions, keyof AgentRequestOptions> {
secureEndpoint: false;
}
interface HttpsRequestOptions extends AgentRequestOptions, Omit<https.RequestOptions, keyof AgentRequestOptions> {
secureEndpoint: true;
}
type RequestOptions = HttpRequestOptions | HttpsRequestOptions;
type AgentLike = Pick<createAgent.Agent, 'addRequest'> | http.Agent;
type AgentCallbackReturn = Duplex | AgentLike;
type AgentCallbackCallback = (err?: Error | null, socket?: createAgent.AgentCallbackReturn) => void;
type AgentCallbackPromise = (req: createAgent.ClientRequest, opts: createAgent.RequestOptions) => createAgent.AgentCallbackReturn | Promise<createAgent.AgentCallbackReturn>;
type AgentCallback = typeof Agent.prototype.callback;
type AgentOptions = {
timeout?: number;
};
/**
* Base `http.Agent` implementation.
* No pooling/keep-alive is implemented by default.
*
* @param {Function} callback
* @api public
*/
class Agent extends EventEmitter {
timeout: number | null;
maxFreeSockets: number;
maxTotalSockets: number;
maxSockets: number;
sockets: {
[key: string]: net.Socket[];
};
freeSockets: {
[key: string]: net.Socket[];
};
requests: {
[key: string]: http.IncomingMessage[];
};
options: https.AgentOptions;
private promisifiedCallback?;
private explicitDefaultPort?;
private explicitProtocol?;
constructor(callback?: createAgent.AgentCallback | createAgent.AgentOptions, _opts?: createAgent.AgentOptions);
get defaultPort(): number;
set defaultPort(v: number);
get protocol(): string;
set protocol(v: string);
callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions, fn: createAgent.AgentCallbackCallback): void;
callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions): createAgent.AgentCallbackReturn | Promise<createAgent.AgentCallbackReturn>;
/**
* Called by node-core's "_http_client.js" module when creating
* a new HTTP request with this Agent instance.
*
* @api public
*/
addRequest(req: ClientRequest, _opts: RequestOptions): void;
freeSocket(socket: net.Socket, opts: AgentOptions): void;
destroy(): void;
}
}
export = createAgent;

203
node_modules/agent-base/dist/src/index.js generated vendored Normal file
View File

@ -0,0 +1,203 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const events_1 = require("events");
const debug_1 = __importDefault(require("debug"));
const promisify_1 = __importDefault(require("./promisify"));
const debug = debug_1.default('agent-base');
function isAgent(v) {
return Boolean(v) && typeof v.addRequest === 'function';
}
function isSecureEndpoint() {
const { stack } = new Error();
if (typeof stack !== 'string')
return false;
return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);
}
function createAgent(callback, opts) {
return new createAgent.Agent(callback, opts);
}
(function (createAgent) {
/**
* Base `http.Agent` implementation.
* No pooling/keep-alive is implemented by default.
*
* @param {Function} callback
* @api public
*/
class Agent extends events_1.EventEmitter {
constructor(callback, _opts) {
super();
let opts = _opts;
if (typeof callback === 'function') {
this.callback = callback;
}
else if (callback) {
opts = callback;
}
// Timeout for the socket to be returned from the callback
this.timeout = null;
if (opts && typeof opts.timeout === 'number') {
this.timeout = opts.timeout;
}
// These aren't actually used by `agent-base`, but are required
// for the TypeScript definition files in `@types/node` :/
this.maxFreeSockets = 1;
this.maxSockets = 1;
this.maxTotalSockets = Infinity;
this.sockets = {};
this.freeSockets = {};
this.requests = {};
this.options = {};
}
get defaultPort() {
if (typeof this.explicitDefaultPort === 'number') {
return this.explicitDefaultPort;
}
return isSecureEndpoint() ? 443 : 80;
}
set defaultPort(v) {
this.explicitDefaultPort = v;
}
get protocol() {
if (typeof this.explicitProtocol === 'string') {
return this.explicitProtocol;
}
return isSecureEndpoint() ? 'https:' : 'http:';
}
set protocol(v) {
this.explicitProtocol = v;
}
callback(req, opts, fn) {
throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`');
}
/**
* Called by node-core's "_http_client.js" module when creating
* a new HTTP request with this Agent instance.
*
* @api public
*/
addRequest(req, _opts) {
const opts = Object.assign({}, _opts);
if (typeof opts.secureEndpoint !== 'boolean') {
opts.secureEndpoint = isSecureEndpoint();
}
if (opts.host == null) {
opts.host = 'localhost';
}
if (opts.port == null) {
opts.port = opts.secureEndpoint ? 443 : 80;
}
if (opts.protocol == null) {
opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';
}
if (opts.host && opts.path) {
// If both a `host` and `path` are specified then it's most
// likely the result of a `url.parse()` call... we need to
// remove the `path` portion so that `net.connect()` doesn't
// attempt to open that as a unix socket file.
delete opts.path;
}
delete opts.agent;
delete opts.hostname;
delete opts._defaultAgent;
delete opts.defaultPort;
delete opts.createConnection;
// Hint to use "Connection: close"
// XXX: non-documented `http` module API :(
req._last = true;
req.shouldKeepAlive = false;
let timedOut = false;
let timeoutId = null;
const timeoutMs = opts.timeout || this.timeout;
const onerror = (err) => {
if (req._hadError)
return;
req.emit('error', err);
// For Safety. Some additional errors might fire later on
// and we need to make sure we don't double-fire the error event.
req._hadError = true;
};
const ontimeout = () => {
timeoutId = null;
timedOut = true;
const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`);
err.code = 'ETIMEOUT';
onerror(err);
};
const callbackError = (err) => {
if (timedOut)
return;
if (timeoutId !== null) {
clearTimeout(timeoutId);
timeoutId = null;
}
onerror(err);
};
const onsocket = (socket) => {
if (timedOut)
return;
if (timeoutId != null) {
clearTimeout(timeoutId);
timeoutId = null;
}
if (isAgent(socket)) {
// `socket` is actually an `http.Agent` instance, so
// relinquish responsibility for this `req` to the Agent
// from here on
debug('Callback returned another Agent instance %o', socket.constructor.name);
socket.addRequest(req, opts);
return;
}
if (socket) {
socket.once('free', () => {
this.freeSocket(socket, opts);
});
req.onSocket(socket);
return;
}
const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``);
onerror(err);
};
if (typeof this.callback !== 'function') {
onerror(new Error('`callback` is not defined'));
return;
}
if (!this.promisifiedCallback) {
if (this.callback.length >= 3) {
debug('Converting legacy callback function to promise');
this.promisifiedCallback = promisify_1.default(this.callback);
}
else {
this.promisifiedCallback = this.callback;
}
}
if (typeof timeoutMs === 'number' && timeoutMs > 0) {
timeoutId = setTimeout(ontimeout, timeoutMs);
}
if ('port' in opts && typeof opts.port !== 'number') {
opts.port = Number(opts.port);
}
try {
debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`);
Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError);
}
catch (err) {
Promise.reject(err).catch(callbackError);
}
}
freeSocket(socket, opts) {
debug('Freeing socket %o %o', socket.constructor.name, opts);
socket.destroy();
}
destroy() {
debug('Destroying agent %o', this.constructor.name);
}
}
createAgent.Agent = Agent;
// So that `instanceof` works correctly
createAgent.prototype = createAgent.Agent.prototype;
})(createAgent || (createAgent = {}));
module.exports = createAgent;
//# sourceMappingURL=index.js.map

1
node_modules/agent-base/dist/src/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

4
node_modules/agent-base/dist/src/promisify.d.ts generated vendored Normal file
View File

@ -0,0 +1,4 @@
import { ClientRequest, RequestOptions, AgentCallbackCallback, AgentCallbackPromise } from './index';
declare type LegacyCallback = (req: ClientRequest, opts: RequestOptions, fn: AgentCallbackCallback) => void;
export default function promisify(fn: LegacyCallback): AgentCallbackPromise;
export {};

18
node_modules/agent-base/dist/src/promisify.js generated vendored Normal file
View File

@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function promisify(fn) {
return function (req, opts) {
return new Promise((resolve, reject) => {
fn.call(this, req, opts, (err, rtn) => {
if (err) {
reject(err);
}
else {
resolve(rtn);
}
});
});
};
}
exports.default = promisify;
//# sourceMappingURL=promisify.js.map

1
node_modules/agent-base/dist/src/promisify.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"promisify.js","sourceRoot":"","sources":["../../src/promisify.ts"],"names":[],"mappings":";;AAeA,SAAwB,SAAS,CAAC,EAAkB;IACnD,OAAO,UAAsB,GAAkB,EAAE,IAAoB;QACpE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtC,EAAE,CAAC,IAAI,CACN,IAAI,EACJ,GAAG,EACH,IAAI,EACJ,CAAC,GAA6B,EAAE,GAAyB,EAAE,EAAE;gBAC5D,IAAI,GAAG,EAAE;oBACR,MAAM,CAAC,GAAG,CAAC,CAAC;iBACZ;qBAAM;oBACN,OAAO,CAAC,GAAG,CAAC,CAAC;iBACb;YACF,CAAC,CACD,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC;AAjBD,4BAiBC"}

96
node_modules/agent-base/package.json generated vendored Normal file
View File

@ -0,0 +1,96 @@
{
"_from": "agent-base@6",
"_id": "agent-base@6.0.2",
"_inBundle": false,
"_integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
"_location": "/agent-base",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "agent-base@6",
"name": "agent-base",
"escapedName": "agent-base",
"rawSpec": "6",
"saveSpec": null,
"fetchSpec": "6"
},
"_requiredBy": [
"/http-proxy-agent",
"/https-proxy-agent",
"/socks-proxy-agent"
],
"_resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-6.0.2.tgz",
"_shasum": "49fff58577cfee3f37176feab4c22e00f86d7f77",
"_spec": "agent-base@6",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/http-proxy-agent",
"author": {
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://n8.io/"
},
"bugs": {
"url": "https://github.com/TooTallNate/node-agent-base/issues"
},
"bundleDependencies": false,
"dependencies": {
"debug": "4"
},
"deprecated": false,
"description": "Turn a function into an `http.Agent` instance",
"devDependencies": {
"@types/debug": "4",
"@types/mocha": "^5.2.7",
"@types/node": "^14.0.20",
"@types/semver": "^7.1.0",
"@types/ws": "^6.0.3",
"@typescript-eslint/eslint-plugin": "1.6.0",
"@typescript-eslint/parser": "1.1.0",
"async-listen": "^1.2.0",
"cpy-cli": "^2.0.0",
"eslint": "5.16.0",
"eslint-config-airbnb": "17.1.0",
"eslint-config-prettier": "4.1.0",
"eslint-import-resolver-typescript": "1.1.1",
"eslint-plugin-import": "2.16.0",
"eslint-plugin-jsx-a11y": "6.2.1",
"eslint-plugin-react": "7.12.4",
"mocha": "^6.2.0",
"rimraf": "^3.0.0",
"semver": "^7.1.2",
"typescript": "^3.5.3",
"ws": "^3.0.0"
},
"engines": {
"node": ">= 6.0.0"
},
"files": [
"dist/src",
"src"
],
"homepage": "https://github.com/TooTallNate/node-agent-base#readme",
"keywords": [
"http",
"agent",
"base",
"barebones",
"https"
],
"license": "MIT",
"main": "dist/src/index",
"name": "agent-base",
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-agent-base.git"
},
"scripts": {
"build": "tsc",
"postbuild": "cpy --parents src test '!**/*.ts' dist",
"prebuild": "rimraf dist",
"prepublishOnly": "npm run build",
"test": "mocha --reporter spec dist/test/*.js",
"test-lint": "eslint src --ext .js,.ts"
},
"typings": "dist/src/index",
"version": "6.0.2"
}

345
node_modules/agent-base/src/index.ts generated vendored Normal file
View File

@ -0,0 +1,345 @@
import net from 'net';
import http from 'http';
import https from 'https';
import { Duplex } from 'stream';
import { EventEmitter } from 'events';
import createDebug from 'debug';
import promisify from './promisify';
const debug = createDebug('agent-base');
function isAgent(v: any): v is createAgent.AgentLike {
return Boolean(v) && typeof v.addRequest === 'function';
}
function isSecureEndpoint(): boolean {
const { stack } = new Error();
if (typeof stack !== 'string') return false;
return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);
}
function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent;
function createAgent(
callback: createAgent.AgentCallback,
opts?: createAgent.AgentOptions
): createAgent.Agent;
function createAgent(
callback?: createAgent.AgentCallback | createAgent.AgentOptions,
opts?: createAgent.AgentOptions
) {
return new createAgent.Agent(callback, opts);
}
namespace createAgent {
export interface ClientRequest extends http.ClientRequest {
_last?: boolean;
_hadError?: boolean;
method: string;
}
export interface AgentRequestOptions {
host?: string;
path?: string;
// `port` on `http.RequestOptions` can be a string or undefined,
// but `net.TcpNetConnectOpts` expects only a number
port: number;
}
export interface HttpRequestOptions
extends AgentRequestOptions,
Omit<http.RequestOptions, keyof AgentRequestOptions> {
secureEndpoint: false;
}
export interface HttpsRequestOptions
extends AgentRequestOptions,
Omit<https.RequestOptions, keyof AgentRequestOptions> {
secureEndpoint: true;
}
export type RequestOptions = HttpRequestOptions | HttpsRequestOptions;
export type AgentLike = Pick<createAgent.Agent, 'addRequest'> | http.Agent;
export type AgentCallbackReturn = Duplex | AgentLike;
export type AgentCallbackCallback = (
err?: Error | null,
socket?: createAgent.AgentCallbackReturn
) => void;
export type AgentCallbackPromise = (
req: createAgent.ClientRequest,
opts: createAgent.RequestOptions
) =>
| createAgent.AgentCallbackReturn
| Promise<createAgent.AgentCallbackReturn>;
export type AgentCallback = typeof Agent.prototype.callback;
export type AgentOptions = {
timeout?: number;
};
/**
* Base `http.Agent` implementation.
* No pooling/keep-alive is implemented by default.
*
* @param {Function} callback
* @api public
*/
export class Agent extends EventEmitter {
public timeout: number | null;
public maxFreeSockets: number;
public maxTotalSockets: number;
public maxSockets: number;
public sockets: {
[key: string]: net.Socket[];
};
public freeSockets: {
[key: string]: net.Socket[];
};
public requests: {
[key: string]: http.IncomingMessage[];
};
public options: https.AgentOptions;
private promisifiedCallback?: createAgent.AgentCallbackPromise;
private explicitDefaultPort?: number;
private explicitProtocol?: string;
constructor(
callback?: createAgent.AgentCallback | createAgent.AgentOptions,
_opts?: createAgent.AgentOptions
) {
super();
let opts = _opts;
if (typeof callback === 'function') {
this.callback = callback;
} else if (callback) {
opts = callback;
}
// Timeout for the socket to be returned from the callback
this.timeout = null;
if (opts && typeof opts.timeout === 'number') {
this.timeout = opts.timeout;
}
// These aren't actually used by `agent-base`, but are required
// for the TypeScript definition files in `@types/node` :/
this.maxFreeSockets = 1;
this.maxSockets = 1;
this.maxTotalSockets = Infinity;
this.sockets = {};
this.freeSockets = {};
this.requests = {};
this.options = {};
}
get defaultPort(): number {
if (typeof this.explicitDefaultPort === 'number') {
return this.explicitDefaultPort;
}
return isSecureEndpoint() ? 443 : 80;
}
set defaultPort(v: number) {
this.explicitDefaultPort = v;
}
get protocol(): string {
if (typeof this.explicitProtocol === 'string') {
return this.explicitProtocol;
}
return isSecureEndpoint() ? 'https:' : 'http:';
}
set protocol(v: string) {
this.explicitProtocol = v;
}
callback(
req: createAgent.ClientRequest,
opts: createAgent.RequestOptions,
fn: createAgent.AgentCallbackCallback
): void;
callback(
req: createAgent.ClientRequest,
opts: createAgent.RequestOptions
):
| createAgent.AgentCallbackReturn
| Promise<createAgent.AgentCallbackReturn>;
callback(
req: createAgent.ClientRequest,
opts: createAgent.AgentOptions,
fn?: createAgent.AgentCallbackCallback
):
| createAgent.AgentCallbackReturn
| Promise<createAgent.AgentCallbackReturn>
| void {
throw new Error(
'"agent-base" has no default implementation, you must subclass and override `callback()`'
);
}
/**
* Called by node-core's "_http_client.js" module when creating
* a new HTTP request with this Agent instance.
*
* @api public
*/
addRequest(req: ClientRequest, _opts: RequestOptions): void {
const opts: RequestOptions = { ..._opts };
if (typeof opts.secureEndpoint !== 'boolean') {
opts.secureEndpoint = isSecureEndpoint();
}
if (opts.host == null) {
opts.host = 'localhost';
}
if (opts.port == null) {
opts.port = opts.secureEndpoint ? 443 : 80;
}
if (opts.protocol == null) {
opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';
}
if (opts.host && opts.path) {
// If both a `host` and `path` are specified then it's most
// likely the result of a `url.parse()` call... we need to
// remove the `path` portion so that `net.connect()` doesn't
// attempt to open that as a unix socket file.
delete opts.path;
}
delete opts.agent;
delete opts.hostname;
delete opts._defaultAgent;
delete opts.defaultPort;
delete opts.createConnection;
// Hint to use "Connection: close"
// XXX: non-documented `http` module API :(
req._last = true;
req.shouldKeepAlive = false;
let timedOut = false;
let timeoutId: ReturnType<typeof setTimeout> | null = null;
const timeoutMs = opts.timeout || this.timeout;
const onerror = (err: NodeJS.ErrnoException) => {
if (req._hadError) return;
req.emit('error', err);
// For Safety. Some additional errors might fire later on
// and we need to make sure we don't double-fire the error event.
req._hadError = true;
};
const ontimeout = () => {
timeoutId = null;
timedOut = true;
const err: NodeJS.ErrnoException = new Error(
`A "socket" was not created for HTTP request before ${timeoutMs}ms`
);
err.code = 'ETIMEOUT';
onerror(err);
};
const callbackError = (err: NodeJS.ErrnoException) => {
if (timedOut) return;
if (timeoutId !== null) {
clearTimeout(timeoutId);
timeoutId = null;
}
onerror(err);
};
const onsocket = (socket: AgentCallbackReturn) => {
if (timedOut) return;
if (timeoutId != null) {
clearTimeout(timeoutId);
timeoutId = null;
}
if (isAgent(socket)) {
// `socket` is actually an `http.Agent` instance, so
// relinquish responsibility for this `req` to the Agent
// from here on
debug(
'Callback returned another Agent instance %o',
socket.constructor.name
);
(socket as createAgent.Agent).addRequest(req, opts);
return;
}
if (socket) {
socket.once('free', () => {
this.freeSocket(socket as net.Socket, opts);
});
req.onSocket(socket as net.Socket);
return;
}
const err = new Error(
`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``
);
onerror(err);
};
if (typeof this.callback !== 'function') {
onerror(new Error('`callback` is not defined'));
return;
}
if (!this.promisifiedCallback) {
if (this.callback.length >= 3) {
debug('Converting legacy callback function to promise');
this.promisifiedCallback = promisify(this.callback);
} else {
this.promisifiedCallback = this.callback;
}
}
if (typeof timeoutMs === 'number' && timeoutMs > 0) {
timeoutId = setTimeout(ontimeout, timeoutMs);
}
if ('port' in opts && typeof opts.port !== 'number') {
opts.port = Number(opts.port);
}
try {
debug(
'Resolving socket for %o request: %o',
opts.protocol,
`${req.method} ${req.path}`
);
Promise.resolve(this.promisifiedCallback(req, opts)).then(
onsocket,
callbackError
);
} catch (err) {
Promise.reject(err).catch(callbackError);
}
}
freeSocket(socket: net.Socket, opts: AgentOptions) {
debug('Freeing socket %o %o', socket.constructor.name, opts);
socket.destroy();
}
destroy() {
debug('Destroying agent %o', this.constructor.name);
}
}
// So that `instanceof` works correctly
createAgent.prototype = createAgent.Agent.prototype;
}
export = createAgent;

33
node_modules/agent-base/src/promisify.ts generated vendored Normal file
View File

@ -0,0 +1,33 @@
import {
Agent,
ClientRequest,
RequestOptions,
AgentCallbackCallback,
AgentCallbackPromise,
AgentCallbackReturn
} from './index';
type LegacyCallback = (
req: ClientRequest,
opts: RequestOptions,
fn: AgentCallbackCallback
) => void;
export default function promisify(fn: LegacyCallback): AgentCallbackPromise {
return function(this: Agent, req: ClientRequest, opts: RequestOptions) {
return new Promise((resolve, reject) => {
fn.call(
this,
req,
opts,
(err: Error | null | undefined, rtn?: AgentCallbackReturn) => {
if (err) {
reject(err);
} else {
resolve(rtn);
}
}
);
});
};
}

248
node_modules/agentkeepalive/History.md generated vendored Normal file
View File

@ -0,0 +1,248 @@
4.2.1 / 2022-02-21
==================
**fixes**
* [[`8b13b5c`](http://github.com/node-modules/agentkeepalive/commit/8b13b5ca797f4779a0a8d393ad8ecb622cd27987)] - fix: explicitly set `| undefined` in type definitions (#99) (Benoit Lemoine <<lemoine.benoit@gmail.com>>)
4.2.0 / 2021-12-31
==================
**fixes**
* [[`f418c67`](http://github.com/node-modules/agentkeepalive/commit/f418c67a63c061c7261592d4553bc455e0b0d306)] - fix: change `freeSocketTimeout` default value to 4000 (#102) (fengmk2 <<fengmk2@gmail.com>>)
**others**
* [[`bc2a1ce`](http://github.com/node-modules/agentkeepalive/commit/bc2a1cea0884b4d18b0d244bf00006d9107963df)] - doc(readme): making `timeout`'s default clear (#100) (Aaron <<aaronarinder@gmail.com>>)
4.1.4 / 2021-02-05
==================
**fixes**
* [[`4d04794`](http://github.com/node-modules/agentkeepalive/commit/4d047946b1547b4edff92ea40205aee4f0c8aa46)] - fix(types): correct `Https` constructor argument (#89) (Simen Bekkhus <<sbekkhus91@gmail.com>>)
4.1.3 / 2020-06-15
==================
**fixes**
* [[`4ba9f9c`](http://github.com/node-modules/agentkeepalive/commit/4ba9f9c844f2a6b8037ce56599d25c69ef054d91)] - fix: compatible with node v12.16.3 (#91) (killa <<killa123@126.com>>)
4.1.2 / 2020-04-25
==================
**fixes**
* [[`de66b02`](http://github.com/node-modules/agentkeepalive/commit/de66b0206d064a97129c2c31bcdabd4d64557b91)] - fix: detect http request timeout handler (#88) (fengmk2 <<fengmk2@gmail.com>>)
4.1.1 / 2020-04-25
==================
**fixes**
* [[`bbd20c0`](http://github.com/node-modules/agentkeepalive/commit/bbd20c03b8cf7dfb00b3aad1ada26d4ab90d2d6e)] - fix: definition error (#87) (吖猩 <<whxaxes@qq.com>>)
**others**
* [[`3b01699`](http://github.com/node-modules/agentkeepalive/commit/3b01699b8e90022d5f56898dd709e4fe7ee7cdaa)] - test: run test on node 12 (#84) (Igor Savin <<iselwin@gmail.com>>)
4.1.0 / 2019-10-12
==================
**features**
* [[`fe33b80`](http://github.com/node-modules/agentkeepalive/commit/fe33b800acc09109388bfe65107550952b6fc7b0)] - feat: Add `reusedSocket` property on client request (#82) (Weijia Wang <<starkwang@126.com>>)
**others**
* [[`77ba744`](http://github.com/node-modules/agentkeepalive/commit/77ba744667bb6b9e5986a53e5222f62094db12b9)] - docs: fix grammar in readme (#81) (Herrington Darkholme <<2883231+HerringtonDarkholme@users.noreply.github.com>>)
4.0.2 / 2019-02-19
==================
**fixes**
* [[`56d4a9b`](http://github.com/node-modules/agentkeepalive/commit/56d4a9b2a4499ea28943ddb590358d7831a02cb1)] - fix: HttpAgent export = internal (#74) (Andrew Leedham <<AndrewLeedham@outlook.com>>)
4.0.1 / 2019-02-19
==================
**fixes**
* [[`bad1ac0`](http://github.com/node-modules/agentkeepalive/commit/bad1ac0e710fbc486717e14e68c59266d35df6a8)] - fix: HttpsAgent Type Definition (#71) (#72) (Andrew Leedham <<AndrewLeedham@outlook.com>>)
* [[`f48a4a7`](http://github.com/node-modules/agentkeepalive/commit/f48a4a701ea6fbe43781c91e1c0aaad6e328ac7f)] - fix: export interface (#70) (Vinay <<vinaybedre@gmail.com>>)
**others**
* [[`9124343`](http://github.com/node-modules/agentkeepalive/commit/91243437cfdd324cb97f39dee76746d5e5f4cd72)] - chore: add agent.options.keepAlive instead agent.keepAlive (fengmk2 <<fengmk2@gmail.com>>)
* [[`d177d40`](http://github.com/node-modules/agentkeepalive/commit/d177d40422fe7296990b4e270cf498e3f33c18fa)] - test: add request timeout bigger than agent timeout cases (fengmk2 <<fengmk2@gmail.com>>)
4.0.0 / 2018-10-23
==================
**features**
* [[`5c9f3bb`](http://github.com/node-modules/agentkeepalive/commit/5c9f3bbd60555744edcf777105b148982a1a42b6)] - feat: impl the new Agent extend http.Agent (fengmk2 <<fengmk2@gmail.com>>)
**others**
* [[`498c8f1`](http://github.com/node-modules/agentkeepalive/commit/498c8f13cf76600d3dd6e1c91cdf2d8292355dff)] - chore: move LICENSE from readme to file (fengmk2 <<fengmk2@gmail.com>>)
* [[`4f39894`](http://github.com/node-modules/agentkeepalive/commit/4f398942ba2f90cf4501239e56ac4e6344931a01)] - bugfix: support agent.options.timeout on https agent (fengmk2 <<fengmk2@gmail.com>>)
3.5.2 / 2018-10-19
==================
**fixes**
* [[`5751fc1`](http://github.com/node-modules/agentkeepalive/commit/5751fc1180ed6544602c681ffbd08ca66a0cb12c)] - fix: sockLen being miscalculated when removing sockets (#60) (Ehden Sinai <<cixel@users.noreply.github.com>>)
3.5.1 / 2018-07-31
==================
**fixes**
* [[`495f1ab`](http://github.com/node-modules/agentkeepalive/commit/495f1ab625d43945d72f68096b97db723d4f0657)] - fix: add the lost npm files (#66) (Henry Zhuang <<zhuanghengfei@gmail.com>>)
3.5.0 / 2018-07-31
==================
**features**
* [[`16f5aea`](http://github.com/node-modules/agentkeepalive/commit/16f5aeadfda57f1c602652f1472a63cc83cd05bf)] - feat: add typing define. (#65) (Henry Zhuang <<zhuanghengfei@gmail.com>>)
**others**
* [[`28fa062`](http://github.com/node-modules/agentkeepalive/commit/28fa06246fb5103f88ebeeb8563757a9078b8157)] - docs: add "per host" to description of maxFreeSockets (tony-gutierrez <<tony.gutierrez@bluefletch.com>>)
* [[`7df2577`](http://github.com/node-modules/agentkeepalive/commit/7df25774f00a1031ca4daad2878a17e0539072a2)] - test: run test on node 10 (#63) (fengmk2 <<fengmk2@gmail.com>>)
3.4.1 / 2018-03-08
==================
**fixes**
* [[`4d3a3b1`](http://github.com/node-modules/agentkeepalive/commit/4d3a3b1f7b16595febbbd39eeed72b2663549014)] - fix: Handle ipv6 addresses in host-header correctly with TLS (#53) (Mattias Holmlund <<u376@m1.holmlund.se>>)
**others**
* [[`55a7a5c`](http://github.com/node-modules/agentkeepalive/commit/55a7a5cd33e97f9a8370083dcb041c5552f10ac9)] - test: stop timer after test end (fengmk2 <<fengmk2@gmail.com>>)
3.4.0 / 2018-02-27
==================
**features**
* [[`bc7cadb`](http://github.com/node-modules/agentkeepalive/commit/bc7cadb30ecd2071e2b341ac53ae1a2b8155c43d)] - feat: use socket custom freeSocketKeepAliveTimeout first (#59) (fengmk2 <<fengmk2@gmail.com>>)
**others**
* [[`138eda8`](http://github.com/node-modules/agentkeepalive/commit/138eda81e10b632aaa87bea0cb66d8667124c4e8)] - doc: fix `keepAliveMsecs` params description (#55) (Hongcai Deng <<admin@dhchouse.com>>)
3.3.0 / 2017-06-20
==================
* feat: add statusChanged getter (#51)
* chore: format License
3.2.0 / 2017-06-10
==================
* feat: add expiring active sockets
* test: add node 8 (#49)
3.1.0 / 2017-02-20
==================
* feat: timeout support humanize ms (#48)
3.0.0 / 2016-12-20
==================
* fix: emit agent socket close event
* test: add remove excess calls to removeSocket
* test: use egg-ci
* test: refactor test with eslint rules
* feat: merge _http_agent.js from 7.2.1
2.2.0 / 2016-06-26
==================
* feat: Add browser shim (noop) for isomorphic use. (#39)
* chore: add security check badge
2.1.1 / 2016-04-06
==================
* https: fix ssl socket leak when keepalive is used
* chore: remove circle ci image
2.1.0 / 2016-04-02
==================
* fix: opened sockets number overflow maxSockets
2.0.5 / 2016-03-16
==================
* fix: pick _evictSession to httpsAgent
2.0.4 / 2016-03-13
==================
* test: add Circle ci
* test: add appveyor ci build
* refactor: make sure only one error listener
* chore: use codecov
* fix: handle idle socket error
* test: run on more node versions
2.0.3 / 2015-08-03
==================
* fix: add default error handler to avoid Unhandled error event throw
2.0.2 / 2015-04-25
==================
* fix: remove socket from freeSockets on 'timeout' (@pmalouin)
2.0.1 / 2015-04-19
==================
* fix: add timeoutSocketCount to getCurrentStatus()
* feat(getCurrentStatus): add getCurrentStatus
2.0.0 / 2015-04-01
==================
* fix: socket.destroyed always be undefined on 0.10.x
* Make it compatible with node v0.10.x (@lattmann)
1.2.1 / 2015-03-23
==================
* patch from iojs: don't overwrite servername option
* patch commits from joyent/node
* add max sockets test case
* add nagle algorithm delayed link
1.2.0 / 2014-09-02
==================
* allow set keepAliveTimeout = 0
* support timeout on working socket. fixed #6
1.1.0 / 2014-08-28
==================
* add some socket counter for deep monitor
1.0.0 / 2014-08-13
==================
* update _http_agent, only support 0.11+, only support node 0.11.0+
0.2.2 / 2013-11-19
==================
* support node 0.8 and node 0.10
0.2.1 / 2013-11-08
==================
* fix socket does not timeout bug, it will hang on life, must use 0.2.x on node 0.11
0.2.0 / 2013-11-06
==================
* use keepalive agent on node 0.11+ impl
0.1.5 / 2013-06-24
==================
* support coveralls
* add node 0.10 test
* add 0.8.22 original https.js
* add original http.js module to diff
* update jscover
* mv pem to fixtures
* add https agent usage

23
node_modules/agentkeepalive/LICENSE generated vendored Normal file
View File

@ -0,0 +1,23 @@
The MIT License
Copyright(c) node-modules and other contributors.
Copyright(c) 2012 - 2015 fengmk2 <fengmk2@gmail.com>
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.

246
node_modules/agentkeepalive/README.md generated vendored Normal file
View File

@ -0,0 +1,246 @@
# agentkeepalive
[![NPM version][npm-image]][npm-url]
[![Known Vulnerabilities][snyk-image]][snyk-url]
[![Node.js CI](https://github.com/node-modules/agentkeepalive/actions/workflows/nodejs.yml/badge.svg)](https://github.com/node-modules/agentkeepalive/actions/workflows/nodejs.yml)
[![npm download][download-image]][download-url]
[npm-image]: https://img.shields.io/npm/v/agentkeepalive.svg?style=flat
[npm-url]: https://npmjs.org/package/agentkeepalive
[snyk-image]: https://snyk.io/test/npm/agentkeepalive/badge.svg?style=flat-square
[snyk-url]: https://snyk.io/test/npm/agentkeepalive
[download-image]: https://img.shields.io/npm/dm/agentkeepalive.svg?style=flat-square
[download-url]: https://npmjs.org/package/agentkeepalive
The enhancement features `keep alive` `http.Agent`. Support `http` and `https`.
## What's different from original `http.Agent`?
- `keepAlive=true` by default
- Disable Nagle's algorithm: `socket.setNoDelay(true)`
- Add free socket timeout: avoid long time inactivity socket leak in the free-sockets queue.
- Add active socket timeout: avoid long time inactivity socket leak in the active-sockets queue.
- TTL for active socket.
## Node.js version required
Support Node.js >= `8.0.0`
## Install
```bash
$ npm install agentkeepalive --save
```
## new Agent([options])
* `options` {Object} Set of configurable options to set on the agent.
Can have the following fields:
* `keepAlive` {Boolean} Keep sockets around in a pool to be used by
other requests in the future. Default = `true`.
* `keepAliveMsecs` {Number} When using the keepAlive option, specifies the initial delay
for TCP Keep-Alive packets. Ignored when the keepAlive option is false or undefined. Defaults to 1000.
Default = `1000`. Only relevant if `keepAlive` is set to `true`.
* `freeSocketTimeout`: {Number} Sets the free socket to timeout
after `freeSocketTimeout` milliseconds of inactivity on the free socket.
The default [server-side timeout](https://nodejs.org/api/http.html#serverkeepalivetimeout) is 5000 milliseconds, to [avoid ECONNRESET exceptions](https://medium.com/ssense-tech/reduce-networking-errors-in-nodejs-23b4eb9f2d83), we set the default value to `4000` milliseconds.
Only relevant if `keepAlive` is set to `true`.
* `timeout`: {Number} Sets the working socket to timeout
after `timeout` milliseconds of inactivity on the working socket.
Default is `freeSocketTimeout * 2` so long as that value is greater than or equal to 8 seconds, otherwise the default is 8 seconds.
* `maxSockets` {Number} Maximum number of sockets to allow per
host. Default = `Infinity`.
* `maxFreeSockets` {Number} Maximum number of sockets (per host) to leave open
in a free state. Only relevant if `keepAlive` is set to `true`.
Default = `256`.
* `socketActiveTTL` {Number} Sets the socket active time to live, even if it's in use.
If not set, the behaviour keeps the same (the socket will be released only when free)
Default = `null`.
## Usage
```js
const http = require('http');
const Agent = require('agentkeepalive');
const keepaliveAgent = new Agent({
maxSockets: 100,
maxFreeSockets: 10,
timeout: 60000, // active socket keepalive for 60 seconds
freeSocketTimeout: 30000, // free socket keepalive for 30 seconds
});
const options = {
host: 'cnodejs.org',
port: 80,
path: '/',
method: 'GET',
agent: keepaliveAgent,
};
const req = http.request(options, res => {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', e => {
console.log('problem with request: ' + e.message);
});
req.end();
setTimeout(() => {
if (keepaliveAgent.statusChanged) {
console.log('[%s] agent status changed: %j', Date(), keepaliveAgent.getCurrentStatus());
}
}, 2000);
```
### `getter agent.statusChanged`
counters have change or not after last checkpoint.
### `agent.getCurrentStatus()`
`agent.getCurrentStatus()` will return a object to show the status of this agent:
```js
{
createSocketCount: 10,
closeSocketCount: 5,
timeoutSocketCount: 0,
requestCount: 5,
freeSockets: { 'localhost:57479:': 3 },
sockets: { 'localhost:57479:': 5 },
requests: {}
}
```
### Support `https`
```js
const https = require('https');
const HttpsAgent = require('agentkeepalive').HttpsAgent;
const keepaliveAgent = new HttpsAgent();
// https://www.google.com/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8
const options = {
host: 'www.google.com',
port: 443,
path: '/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8',
method: 'GET',
agent: keepaliveAgent,
};
const req = https.request(options, res => {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', chunk => {
console.log('BODY: ' + chunk);
});
});
req.on('error', e => {
console.log('problem with request: ' + e.message);
});
req.end();
setTimeout(() => {
console.log('agent status: %j', keepaliveAgent.getCurrentStatus());
}, 2000);
```
### Support `req.reusedSocket`
This agent implements the `req.reusedSocket` to determine whether a request is send through a reused socket.
When server closes connection at unfortunate time ([keep-alive race](https://code-examples.net/en/q/28a8069)), the http client will throw a `ECONNRESET` error. Under this circumstance, `req.reusedSocket` is useful when we want to retry the request automatically.
```js
const http = require('http');
const Agent = require('agentkeepalive');
const agent = new Agent();
const req = http
.get('http://localhost:3000', { agent }, (res) => {
// ...
})
.on('error', (err) => {
if (req.reusedSocket && err.code === 'ECONNRESET') {
// retry the request or anything else...
}
})
```
This behavior is consistent with Node.js core. But through `agentkeepalive`, you can use this feature in older Node.js version.
## [Benchmark](https://github.com/node-modules/agentkeepalive/tree/master/benchmark)
run the benchmark:
```bash
cd benchmark
sh start.sh
```
Intel(R) Core(TM)2 Duo CPU P8600 @ 2.40GHz
node@v0.8.9
50 maxSockets, 60 concurrent, 1000 requests per concurrent, 5ms delay
Keep alive agent (30 seconds):
```js
Transactions: 60000 hits
Availability: 100.00 %
Elapsed time: 29.70 secs
Data transferred: 14.88 MB
Response time: 0.03 secs
Transaction rate: 2020.20 trans/sec
Throughput: 0.50 MB/sec
Concurrency: 59.84
Successful transactions: 60000
Failed transactions: 0
Longest transaction: 0.15
Shortest transaction: 0.01
```
Normal agent:
```js
Transactions: 60000 hits
Availability: 100.00 %
Elapsed time: 46.53 secs
Data transferred: 14.88 MB
Response time: 0.05 secs
Transaction rate: 1289.49 trans/sec
Throughput: 0.32 MB/sec
Concurrency: 59.81
Successful transactions: 60000
Failed transactions: 0
Longest transaction: 0.45
Shortest transaction: 0.00
```
Socket created:
```bash
[proxy.js:120000] keepalive, 50 created, 60000 requestFinished, 1200 req/socket, 0 requests, 0 sockets, 0 unusedSockets, 50 timeout
{" <10ms":662," <15ms":17825," <20ms":20552," <30ms":17646," <40ms":2315," <50ms":567," <100ms":377," <150ms":56," <200ms":0," >=200ms+":0}
----------------------------------------------------------------
[proxy.js:120000] normal , 53866 created, 84260 requestFinished, 1.56 req/socket, 0 requests, 0 sockets
{" <10ms":75," <15ms":1112," <20ms":10947," <30ms":32130," <40ms":8228," <50ms":3002," <100ms":4274," <150ms":181," <200ms":18," >=200ms+":33}
```
## License
[MIT](LICENSE)
## Contributors
[![](https://ergatejs.implements.io/badges/contributors/node-modules/agentkeepalive.svg?size=96)](https://github.com/node-modules/agentkeepalive/graphs/contributors)

5
node_modules/agentkeepalive/browser.js generated vendored Normal file
View File

@ -0,0 +1,5 @@
module.exports = noop;
module.exports.HttpsAgent = noop;
// Noop function for browser since native api's don't use agents.
function noop () {}

62
node_modules/agentkeepalive/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,62 @@
import * as http from 'http';
import * as https from 'https';
interface PlainObject {
[key: string]: any;
}
declare class HttpAgent extends http.Agent {
constructor(opts?: AgentKeepAlive.HttpOptions);
readonly statusChanged: boolean;
createSocket(req: http.IncomingMessage, options: http.RequestOptions, cb: Function): void;
getCurrentStatus(): AgentKeepAlive.AgentStatus;
}
interface Constants {
CURRENT_ID: Symbol;
CREATE_ID: Symbol;
INIT_SOCKET: Symbol;
CREATE_HTTPS_CONNECTION: Symbol;
SOCKET_CREATED_TIME: Symbol;
SOCKET_NAME: Symbol;
SOCKET_REQUEST_COUNT: Symbol;
SOCKET_REQUEST_FINISHED_COUNT: Symbol;
}
declare class AgentKeepAlive extends HttpAgent {}
declare namespace AgentKeepAlive {
export interface AgentStatus {
createSocketCount: number;
createSocketErrorCount: number;
closeSocketCount: number;
errorSocketCount: number;
timeoutSocketCount: number;
requestCount: number;
freeSockets: PlainObject;
sockets: PlainObject;
requests: PlainObject;
}
interface CommonHttpOption {
keepAlive?: boolean | undefined;
freeSocketTimeout?: number | undefined;
freeSocketKeepAliveTimeout?: number | undefined;
timeout?: number | undefined;
socketActiveTTL?: number | undefined;
}
export interface HttpOptions extends http.AgentOptions, CommonHttpOption { }
export interface HttpsOptions extends https.AgentOptions, CommonHttpOption { }
export class HttpsAgent extends https.Agent {
constructor(opts?: HttpsOptions);
readonly statusChanged: boolean;
createSocket(req: http.IncomingMessage, options: http.RequestOptions, cb: Function): void;
getCurrentStatus(): AgentStatus;
}
export const constants: Constants;
}
export = AgentKeepAlive;

5
node_modules/agentkeepalive/index.js generated vendored Normal file
View File

@ -0,0 +1,5 @@
'use strict';
module.exports = require('./lib/agent');
module.exports.HttpsAgent = require('./lib/https_agent');
module.exports.constants = require('./lib/constants');

398
node_modules/agentkeepalive/lib/agent.js generated vendored Normal file
View File

@ -0,0 +1,398 @@
'use strict';
const OriginalAgent = require('http').Agent;
const ms = require('humanize-ms');
const debug = require('debug')('agentkeepalive');
const deprecate = require('depd')('agentkeepalive');
const {
INIT_SOCKET,
CURRENT_ID,
CREATE_ID,
SOCKET_CREATED_TIME,
SOCKET_NAME,
SOCKET_REQUEST_COUNT,
SOCKET_REQUEST_FINISHED_COUNT,
} = require('./constants');
// OriginalAgent come from
// - https://github.com/nodejs/node/blob/v8.12.0/lib/_http_agent.js
// - https://github.com/nodejs/node/blob/v10.12.0/lib/_http_agent.js
// node <= 10
let defaultTimeoutListenerCount = 1;
const majorVersion = parseInt(process.version.split('.', 1)[0].substring(1));
if (majorVersion >= 11 && majorVersion <= 12) {
defaultTimeoutListenerCount = 2;
} else if (majorVersion >= 13) {
defaultTimeoutListenerCount = 3;
}
class Agent extends OriginalAgent {
constructor(options) {
options = options || {};
options.keepAlive = options.keepAlive !== false;
// default is keep-alive and 4s free socket timeout
// see https://medium.com/ssense-tech/reduce-networking-errors-in-nodejs-23b4eb9f2d83
if (options.freeSocketTimeout === undefined) {
options.freeSocketTimeout = 4000;
}
// Legacy API: keepAliveTimeout should be rename to `freeSocketTimeout`
if (options.keepAliveTimeout) {
deprecate('options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
options.freeSocketTimeout = options.keepAliveTimeout;
delete options.keepAliveTimeout;
}
// Legacy API: freeSocketKeepAliveTimeout should be rename to `freeSocketTimeout`
if (options.freeSocketKeepAliveTimeout) {
deprecate('options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
options.freeSocketTimeout = options.freeSocketKeepAliveTimeout;
delete options.freeSocketKeepAliveTimeout;
}
// Sets the socket to timeout after timeout milliseconds of inactivity on the socket.
// By default is double free socket timeout.
if (options.timeout === undefined) {
// make sure socket default inactivity timeout >= 8s
options.timeout = Math.max(options.freeSocketTimeout * 2, 8000);
}
// support humanize format
options.timeout = ms(options.timeout);
options.freeSocketTimeout = ms(options.freeSocketTimeout);
options.socketActiveTTL = options.socketActiveTTL ? ms(options.socketActiveTTL) : 0;
super(options);
this[CURRENT_ID] = 0;
// create socket success counter
this.createSocketCount = 0;
this.createSocketCountLastCheck = 0;
this.createSocketErrorCount = 0;
this.createSocketErrorCountLastCheck = 0;
this.closeSocketCount = 0;
this.closeSocketCountLastCheck = 0;
// socket error event count
this.errorSocketCount = 0;
this.errorSocketCountLastCheck = 0;
// request finished counter
this.requestCount = 0;
this.requestCountLastCheck = 0;
// including free socket timeout counter
this.timeoutSocketCount = 0;
this.timeoutSocketCountLastCheck = 0;
this.on('free', socket => {
// https://github.com/nodejs/node/pull/32000
// Node.js native agent will check socket timeout eqs agent.options.timeout.
// Use the ttl or freeSocketTimeout to overwrite.
const timeout = this.calcSocketTimeout(socket);
if (timeout > 0 && socket.timeout !== timeout) {
socket.setTimeout(timeout);
}
});
}
get freeSocketKeepAliveTimeout() {
deprecate('agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead');
return this.options.freeSocketTimeout;
}
get timeout() {
deprecate('agent.timeout is deprecated, please use agent.options.timeout instead');
return this.options.timeout;
}
get socketActiveTTL() {
deprecate('agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead');
return this.options.socketActiveTTL;
}
calcSocketTimeout(socket) {
/**
* return <= 0: should free socket
* return > 0: should update socket timeout
* return undefined: not find custom timeout
*/
let freeSocketTimeout = this.options.freeSocketTimeout;
const socketActiveTTL = this.options.socketActiveTTL;
if (socketActiveTTL) {
// check socketActiveTTL
const aliveTime = Date.now() - socket[SOCKET_CREATED_TIME];
const diff = socketActiveTTL - aliveTime;
if (diff <= 0) {
return diff;
}
if (freeSocketTimeout && diff < freeSocketTimeout) {
freeSocketTimeout = diff;
}
}
// set freeSocketTimeout
if (freeSocketTimeout) {
// set free keepalive timer
// try to use socket custom freeSocketTimeout first, support headers['keep-alive']
// https://github.com/node-modules/urllib/blob/b76053020923f4d99a1c93cf2e16e0c5ba10bacf/lib/urllib.js#L498
const customFreeSocketTimeout = socket.freeSocketTimeout || socket.freeSocketKeepAliveTimeout;
return customFreeSocketTimeout || freeSocketTimeout;
}
}
keepSocketAlive(socket) {
const result = super.keepSocketAlive(socket);
// should not keepAlive, do nothing
if (!result) return result;
const customTimeout = this.calcSocketTimeout(socket);
if (typeof customTimeout === 'undefined') {
return true;
}
if (customTimeout <= 0) {
debug('%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s',
socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], customTimeout);
return false;
}
if (socket.timeout !== customTimeout) {
socket.setTimeout(customTimeout);
}
return true;
}
// only call on addRequest
reuseSocket(...args) {
// reuseSocket(socket, req)
super.reuseSocket(...args);
const socket = args[0];
const req = args[1];
req.reusedSocket = true;
const agentTimeout = this.options.timeout;
if (getSocketTimeout(socket) !== agentTimeout) {
// reset timeout before use
socket.setTimeout(agentTimeout);
debug('%s reset timeout to %sms', socket[SOCKET_NAME], agentTimeout);
}
socket[SOCKET_REQUEST_COUNT]++;
debug('%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms',
socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
getSocketTimeout(socket));
}
[CREATE_ID]() {
const id = this[CURRENT_ID]++;
if (this[CURRENT_ID] === Number.MAX_SAFE_INTEGER) this[CURRENT_ID] = 0;
return id;
}
[INIT_SOCKET](socket, options) {
// bugfix here.
// https on node 8, 10 won't set agent.options.timeout by default
// TODO: need to fix on node itself
if (options.timeout) {
const timeout = getSocketTimeout(socket);
if (!timeout) {
socket.setTimeout(options.timeout);
}
}
if (this.options.keepAlive) {
// Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/
// https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html
socket.setNoDelay(true);
}
this.createSocketCount++;
if (this.options.socketActiveTTL) {
socket[SOCKET_CREATED_TIME] = Date.now();
}
// don't show the hole '-----BEGIN CERTIFICATE----' key string
socket[SOCKET_NAME] = `sock[${this[CREATE_ID]()}#${options._agentKey}]`.split('-----BEGIN', 1)[0];
socket[SOCKET_REQUEST_COUNT] = 1;
socket[SOCKET_REQUEST_FINISHED_COUNT] = 0;
installListeners(this, socket, options);
}
createConnection(options, oncreate) {
let called = false;
const onNewCreate = (err, socket) => {
if (called) return;
called = true;
if (err) {
this.createSocketErrorCount++;
return oncreate(err);
}
this[INIT_SOCKET](socket, options);
oncreate(err, socket);
};
const newSocket = super.createConnection(options, onNewCreate);
if (newSocket) onNewCreate(null, newSocket);
}
get statusChanged() {
const changed = this.createSocketCount !== this.createSocketCountLastCheck ||
this.createSocketErrorCount !== this.createSocketErrorCountLastCheck ||
this.closeSocketCount !== this.closeSocketCountLastCheck ||
this.errorSocketCount !== this.errorSocketCountLastCheck ||
this.timeoutSocketCount !== this.timeoutSocketCountLastCheck ||
this.requestCount !== this.requestCountLastCheck;
if (changed) {
this.createSocketCountLastCheck = this.createSocketCount;
this.createSocketErrorCountLastCheck = this.createSocketErrorCount;
this.closeSocketCountLastCheck = this.closeSocketCount;
this.errorSocketCountLastCheck = this.errorSocketCount;
this.timeoutSocketCountLastCheck = this.timeoutSocketCount;
this.requestCountLastCheck = this.requestCount;
}
return changed;
}
getCurrentStatus() {
return {
createSocketCount: this.createSocketCount,
createSocketErrorCount: this.createSocketErrorCount,
closeSocketCount: this.closeSocketCount,
errorSocketCount: this.errorSocketCount,
timeoutSocketCount: this.timeoutSocketCount,
requestCount: this.requestCount,
freeSockets: inspect(this.freeSockets),
sockets: inspect(this.sockets),
requests: inspect(this.requests),
};
}
}
// node 8 don't has timeout attribute on socket
// https://github.com/nodejs/node/pull/21204/files#diff-e6ef024c3775d787c38487a6309e491dR408
function getSocketTimeout(socket) {
return socket.timeout || socket._idleTimeout;
}
function installListeners(agent, socket, options) {
debug('%s create, timeout %sms', socket[SOCKET_NAME], getSocketTimeout(socket));
// listener socket events: close, timeout, error, free
function onFree() {
// create and socket.emit('free') logic
// https://github.com/nodejs/node/blob/master/lib/_http_agent.js#L311
// no req on the socket, it should be the new socket
if (!socket._httpMessage && socket[SOCKET_REQUEST_COUNT] === 1) return;
socket[SOCKET_REQUEST_FINISHED_COUNT]++;
agent.requestCount++;
debug('%s(requests: %s, finished: %s) free',
socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
// should reuse on pedding requests?
const name = agent.getName(options);
if (socket.writable && agent.requests[name] && agent.requests[name].length) {
// will be reuse on agent free listener
socket[SOCKET_REQUEST_COUNT]++;
debug('%s(requests: %s, finished: %s) will be reuse on agent free event',
socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
}
}
socket.on('free', onFree);
function onClose(isError) {
debug('%s(requests: %s, finished: %s) close, isError: %s',
socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], isError);
agent.closeSocketCount++;
}
socket.on('close', onClose);
// start socket timeout handler
function onTimeout() {
// onTimeout and emitRequestTimeout(_http_client.js)
// https://github.com/nodejs/node/blob/v12.x/lib/_http_client.js#L711
const listenerCount = socket.listeners('timeout').length;
// node <= 10, default listenerCount is 1, onTimeout
// 11 < node <= 12, default listenerCount is 2, onTimeout and emitRequestTimeout
// node >= 13, default listenerCount is 3, onTimeout,
// onTimeout(https://github.com/nodejs/node/pull/32000/files#diff-5f7fb0850412c6be189faeddea6c5359R333)
// and emitRequestTimeout
const timeout = getSocketTimeout(socket);
const req = socket._httpMessage;
const reqTimeoutListenerCount = req && req.listeners('timeout').length || 0;
debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s',
socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
timeout, listenerCount, defaultTimeoutListenerCount, !!req, reqTimeoutListenerCount);
if (debug.enabled) {
debug('timeout listeners: %s', socket.listeners('timeout').map(f => f.name).join(', '));
}
agent.timeoutSocketCount++;
const name = agent.getName(options);
if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) {
// free socket timeout, destroy quietly
socket.destroy();
// Remove it from freeSockets list immediately to prevent new requests
// from being sent through this socket.
agent.removeSocket(socket, options);
debug('%s is free, destroy quietly', socket[SOCKET_NAME]);
} else {
// if there is no any request socket timeout handler,
// agent need to handle socket timeout itself.
//
// custom request socket timeout handle logic must follow these rules:
// 1. Destroy socket first
// 2. Must emit socket 'agentRemove' event tell agent remove socket
// from freeSockets list immediately.
// Otherise you may be get 'socket hang up' error when reuse
// free socket and timeout happen in the same time.
if (reqTimeoutListenerCount === 0) {
const error = new Error('Socket timeout');
error.code = 'ERR_SOCKET_TIMEOUT';
error.timeout = timeout;
// must manually call socket.end() or socket.destroy() to end the connection.
// https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback
socket.destroy(error);
agent.removeSocket(socket, options);
debug('%s destroy with timeout error', socket[SOCKET_NAME]);
}
}
}
socket.on('timeout', onTimeout);
function onError(err) {
const listenerCount = socket.listeners('error').length;
debug('%s(requests: %s, finished: %s) error: %s, listenerCount: %s',
socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
err, listenerCount);
agent.errorSocketCount++;
if (listenerCount === 1) {
// if socket don't contain error event handler, don't catch it, emit it again
debug('%s emit uncaught error event', socket[SOCKET_NAME]);
socket.removeListener('error', onError);
socket.emit('error', err);
}
}
socket.on('error', onError);
function onRemove() {
debug('%s(requests: %s, finished: %s) agentRemove',
socket[SOCKET_NAME],
socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
// We need this function for cases like HTTP 'upgrade'
// (defined by WebSockets) where we need to remove a socket from the
// pool because it'll be locked up indefinitely
socket.removeListener('close', onClose);
socket.removeListener('error', onError);
socket.removeListener('free', onFree);
socket.removeListener('timeout', onTimeout);
socket.removeListener('agentRemove', onRemove);
}
socket.on('agentRemove', onRemove);
}
module.exports = Agent;
function inspect(obj) {
const res = {};
for (const key in obj) {
res[key] = obj[key].length;
}
return res;
}

14
node_modules/agentkeepalive/lib/constants.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
'use strict';
module.exports = {
// agent
CURRENT_ID: Symbol('agentkeepalive#currentId'),
CREATE_ID: Symbol('agentkeepalive#createId'),
INIT_SOCKET: Symbol('agentkeepalive#initSocket'),
CREATE_HTTPS_CONNECTION: Symbol('agentkeepalive#createHttpsConnection'),
// socket
SOCKET_CREATED_TIME: Symbol('agentkeepalive#socketCreatedTime'),
SOCKET_NAME: Symbol('agentkeepalive#socketName'),
SOCKET_REQUEST_COUNT: Symbol('agentkeepalive#socketRequestCount'),
SOCKET_REQUEST_FINISHED_COUNT: Symbol('agentkeepalive#socketRequestFinishedCount'),
};

51
node_modules/agentkeepalive/lib/https_agent.js generated vendored Normal file
View File

@ -0,0 +1,51 @@
'use strict';
const OriginalHttpsAgent = require('https').Agent;
const HttpAgent = require('./agent');
const {
INIT_SOCKET,
CREATE_HTTPS_CONNECTION,
} = require('./constants');
class HttpsAgent extends HttpAgent {
constructor(options) {
super(options);
this.defaultPort = 443;
this.protocol = 'https:';
this.maxCachedSessions = this.options.maxCachedSessions;
/* istanbul ignore next */
if (this.maxCachedSessions === undefined) {
this.maxCachedSessions = 100;
}
this._sessionCache = {
map: {},
list: [],
};
}
createConnection(options) {
const socket = this[CREATE_HTTPS_CONNECTION](options);
this[INIT_SOCKET](socket, options);
return socket;
}
}
// https://github.com/nodejs/node/blob/master/lib/https.js#L89
HttpsAgent.prototype[CREATE_HTTPS_CONNECTION] = OriginalHttpsAgent.prototype.createConnection;
[
'getName',
'_getSession',
'_cacheSession',
// https://github.com/nodejs/node/pull/4982
'_evictSession',
].forEach(function(method) {
/* istanbul ignore next */
if (typeof OriginalHttpsAgent.prototype[method] === 'function') {
HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method];
}
});
module.exports = HttpsAgent;

96
node_modules/agentkeepalive/package.json generated vendored Normal file
View File

@ -0,0 +1,96 @@
{
"_from": "agentkeepalive@^4.1.3",
"_id": "agentkeepalive@4.2.1",
"_inBundle": false,
"_integrity": "sha512-Zn4cw2NEqd+9fiSVWMscnjyQ1a8Yfoc5oBajLeo5w+YBHgDUcEBY2hS4YpTz6iN5f/2zQiktcuM6tS8x1p9dpA==",
"_location": "/agentkeepalive",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "agentkeepalive@^4.1.3",
"name": "agentkeepalive",
"escapedName": "agentkeepalive",
"rawSpec": "^4.1.3",
"saveSpec": null,
"fetchSpec": "^4.1.3"
},
"_requiredBy": [
"/make-fetch-happen"
],
"_resolved": "https://registry.npmmirror.com/agentkeepalive/-/agentkeepalive-4.2.1.tgz",
"_shasum": "a7975cbb9f83b367f06c90cc51ff28fe7d499717",
"_spec": "agentkeepalive@^4.1.3",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/make-fetch-happen",
"author": {
"name": "fengmk2",
"email": "fengmk2@gmail.com",
"url": "https://fengmk2.com"
},
"browser": "browser.js",
"bugs": {
"url": "https://github.com/node-modules/agentkeepalive/issues"
},
"bundleDependencies": false,
"ci": {
"type": "github",
"os": {
"github": "linux"
},
"version": "8, 10, 12, 14, 16"
},
"dependencies": {
"debug": "^4.1.0",
"depd": "^1.1.2",
"humanize-ms": "^1.2.1"
},
"deprecated": false,
"description": "Missing keepalive http.Agent",
"devDependencies": {
"autod": "^3.0.1",
"coffee": "^5.3.0",
"cross-env": "^6.0.3",
"egg-bin": "^4.9.0",
"egg-ci": "^1.10.0",
"eslint": "^5.7.0",
"eslint-config-egg": "^7.1.0",
"mm": "^2.4.1",
"pedding": "^1.1.0",
"typescript": "^3.8.3"
},
"engines": {
"node": ">= 8.0.0"
},
"files": [
"index.js",
"index.d.ts",
"browser.js",
"lib"
],
"homepage": "https://github.com/node-modules/agentkeepalive#readme",
"keywords": [
"http",
"https",
"agent",
"keepalive",
"agentkeepalive",
"HttpAgent",
"HttpsAgent"
],
"license": "MIT",
"main": "index.js",
"name": "agentkeepalive",
"repository": {
"type": "git",
"url": "git://github.com/node-modules/agentkeepalive.git"
},
"scripts": {
"autod": "autod",
"ci": "npm run lint && npm run cov",
"cov": "cross-env DEBUG=agentkeepalive egg-bin cov --full-trace",
"lint": "eslint lib test index.js",
"test": "npm run lint && egg-bin test --full-trace",
"test-local": "egg-bin test --full-trace"
},
"version": "4.2.1"
}

51
node_modules/aggregate-error/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,51 @@
/**
Create an error from multiple errors.
*/
declare class AggregateError<T extends Error = Error> extends Error implements Iterable<T> {
readonly name: 'AggregateError';
/**
@param errors - If a string, a new `Error` is created with the string as the error message. If a non-Error object, a new `Error` is created with all properties from the object copied over.
@returns An Error that is also an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables) for the individual errors.
@example
```
import AggregateError = require('aggregate-error');
const error = new AggregateError([new Error('foo'), 'bar', {message: 'baz'}]);
throw error;
// AggregateError:
// Error: foo
// at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:33)
// Error: bar
// at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13)
// Error: baz
// at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13)
// at AggregateError (/Users/sindresorhus/dev/aggregate-error/index.js:19:3)
// at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13)
// at Module._compile (module.js:556:32)
// at Object.Module._extensions..js (module.js:565:10)
// at Module.load (module.js:473:32)
// at tryModuleLoad (module.js:432:12)
// at Function.Module._load (module.js:424:3)
// at Module.runMain (module.js:590:10)
// at run (bootstrap_node.js:394:7)
// at startup (bootstrap_node.js:149:9)
for (const individualError of error) {
console.log(individualError);
}
//=> [Error: foo]
//=> [Error: bar]
//=> [Error: baz]
```
*/
constructor(errors: ReadonlyArray<T | {[key: string]: any} | string>);
[Symbol.iterator](): IterableIterator<T>;
}
export = AggregateError;

47
node_modules/aggregate-error/index.js generated vendored Normal file
View File

@ -0,0 +1,47 @@
'use strict';
const indentString = require('indent-string');
const cleanStack = require('clean-stack');
const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, '');
class AggregateError extends Error {
constructor(errors) {
if (!Array.isArray(errors)) {
throw new TypeError(`Expected input to be an Array, got ${typeof errors}`);
}
errors = [...errors].map(error => {
if (error instanceof Error) {
return error;
}
if (error !== null && typeof error === 'object') {
// Handle plain error objects with message property and/or possibly other metadata
return Object.assign(new Error(error.message), error);
}
return new Error(error);
});
let message = errors
.map(error => {
// The `stack` property is not standardized, so we can't assume it exists
return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error);
})
.join('\n');
message = '\n' + indentString(message, 4);
super(message);
this.name = 'AggregateError';
Object.defineProperty(this, '_errors', {value: errors});
}
* [Symbol.iterator]() {
for (const error of this._errors) {
yield error;
}
}
}
module.exports = AggregateError;

9
node_modules/aggregate-error/license generated vendored Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.

73
node_modules/aggregate-error/package.json generated vendored Normal file
View File

@ -0,0 +1,73 @@
{
"_from": "aggregate-error@^3.0.0",
"_id": "aggregate-error@3.1.0",
"_inBundle": false,
"_integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==",
"_location": "/aggregate-error",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "aggregate-error@^3.0.0",
"name": "aggregate-error",
"escapedName": "aggregate-error",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/p-map"
],
"_resolved": "https://registry.npmmirror.com/aggregate-error/-/aggregate-error-3.1.0.tgz",
"_shasum": "92670ff50f5359bdb7a3e0d40d0ec30c5737687a",
"_spec": "aggregate-error@^3.0.0",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/p-map",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/aggregate-error/issues"
},
"bundleDependencies": false,
"dependencies": {
"clean-stack": "^2.0.0",
"indent-string": "^4.0.0"
},
"deprecated": false,
"description": "Create an error from multiple errors",
"devDependencies": {
"ava": "^2.4.0",
"tsd": "^0.7.1",
"xo": "^0.25.3"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/aggregate-error#readme",
"keywords": [
"aggregate",
"error",
"combine",
"multiple",
"many",
"collection",
"iterable",
"iterator"
],
"license": "MIT",
"name": "aggregate-error",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/aggregate-error.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "3.1.0"
}

61
node_modules/aggregate-error/readme.md generated vendored Normal file
View File

@ -0,0 +1,61 @@
# aggregate-error [![Build Status](https://travis-ci.org/sindresorhus/aggregate-error.svg?branch=master)](https://travis-ci.org/sindresorhus/aggregate-error)
> Create an error from multiple errors
## Install
```
$ npm install aggregate-error
```
## Usage
```js
const AggregateError = require('aggregate-error');
const error = new AggregateError([new Error('foo'), 'bar', {message: 'baz'}]);
throw error;
/*
AggregateError:
Error: foo
at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:33)
Error: bar
at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13)
Error: baz
at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13)
at AggregateError (/Users/sindresorhus/dev/aggregate-error/index.js:19:3)
at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
*/
for (const individualError of error) {
console.log(individualError);
}
//=> [Error: foo]
//=> [Error: bar]
//=> [Error: baz]
```
## API
### AggregateError(errors)
Returns an `Error` that is also an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables) for the individual errors.
#### errors
Type: `Array<Error|Object|string>`
If a string, a new `Error` is created with the string as the error message.<br>
If a non-Error object, a new `Error` is created with all properties from the object copied over.

21
node_modules/ansi-colors/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015-present, Brian Woodward.
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.

315
node_modules/ansi-colors/README.md generated vendored Normal file
View File

@ -0,0 +1,315 @@
# ansi-colors [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/ansi-colors.svg?style=flat)](https://www.npmjs.com/package/ansi-colors) [![NPM monthly downloads](https://img.shields.io/npm/dm/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![NPM total downloads](https://img.shields.io/npm/dt/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![Linux Build Status](https://img.shields.io/travis/doowb/ansi-colors.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/ansi-colors)
> Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs).
Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save ansi-colors
```
![image](https://user-images.githubusercontent.com/383994/39635445-8a98a3a6-4f8b-11e8-89c1-068c45d4fff8.png)
## Why use this?
ansi-colors is _the fastest Node.js library for terminal styling_. A more performant drop-in replacement for chalk, with no dependencies.
* _Blazing fast_ - Fastest terminal styling library in node.js, 10-20x faster than chalk!
* _Drop-in replacement_ for [chalk](https://github.com/chalk/chalk).
* _No dependencies_ (Chalk has 7 dependencies in its tree!)
* _Safe_ - Does not modify the `String.prototype` like [colors](https://github.com/Marak/colors.js).
* Supports [nested colors](#nested-colors), **and does not have the [nested styling bug](#nested-styling-bug) that is present in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur)**.
* Supports [chained colors](#chained-colors).
* [Toggle color support](#toggle-color-support) on or off.
## Usage
```js
const c = require('ansi-colors');
console.log(c.red('This is a red string!'));
console.log(c.green('This is a red string!'));
console.log(c.cyan('This is a cyan string!'));
console.log(c.yellow('This is a yellow string!'));
```
![image](https://user-images.githubusercontent.com/383994/39653848-a38e67da-4fc0-11e8-89ae-98c65ebe9dcf.png)
## Chained colors
```js
console.log(c.bold.red('this is a bold red message'));
console.log(c.bold.yellow.italic('this is a bold yellow italicized message'));
console.log(c.green.bold.underline('this is a bold green underlined message'));
```
![image](https://user-images.githubusercontent.com/383994/39635780-7617246a-4f8c-11e8-89e9-05216cc54e38.png)
## Nested colors
```js
console.log(c.yellow(`foo ${c.red.bold('red')} bar ${c.cyan('cyan')} baz`));
```
![image](https://user-images.githubusercontent.com/383994/39635817-8ed93d44-4f8c-11e8-8afd-8c3ea35f5fbe.png)
### Nested styling bug
`ansi-colors` does not have the nested styling bug found in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur).
```js
const { bold, red } = require('ansi-styles');
console.log(bold(`foo ${red.dim('bar')} baz`));
const colorette = require('colorette');
console.log(colorette.bold(`foo ${colorette.red(colorette.dim('bar'))} baz`));
const kleur = require('kleur');
console.log(kleur.bold(`foo ${kleur.red.dim('bar')} baz`));
const chalk = require('chalk');
console.log(chalk.bold(`foo ${chalk.red.dim('bar')} baz`));
```
**Results in the following**
(sans icons and labels)
![image](https://user-images.githubusercontent.com/383994/47280326-d2ee0580-d5a3-11e8-9611-ea6010f0a253.png)
## Toggle color support
Easily enable/disable colors.
```js
const c = require('ansi-colors');
// disable colors manually
c.enabled = false;
// or use a library to automatically detect support
c.enabled = require('color-support').hasBasic;
console.log(c.red('I will only be colored red if the terminal supports colors'));
```
## Strip ANSI codes
Use the `.unstyle` method to strip ANSI codes from a string.
```js
console.log(c.unstyle(c.blue.bold('foo bar baz')));
//=> 'foo bar baz'
```
## Available styles
**Note** that bright and bright-background colors are not always supported.
| Colors | Background Colors | Bright Colors | Bright Background Colors |
| ------- | ----------------- | ------------- | ------------------------ |
| black | bgBlack | blackBright | bgBlackBright |
| red | bgRed | redBright | bgRedBright |
| green | bgGreen | greenBright | bgGreenBright |
| yellow | bgYellow | yellowBright | bgYellowBright |
| blue | bgBlue | blueBright | bgBlueBright |
| magenta | bgMagenta | magentaBright | bgMagentaBright |
| cyan | bgCyan | cyanBright | bgCyanBright |
| white | bgWhite | whiteBright | bgWhiteBright |
| gray | | | |
| grey | | | |
_(`gray` is the U.S. spelling, `grey` is more commonly used in the Canada and U.K.)_
### Style modifiers
* dim
* **bold**
* hidden
* _italic_
* underline
* inverse
* ~~strikethrough~~
* reset
## Aliases
Create custom aliases for styles.
```js
const colors = require('ansi-colors');
colors.alias('primary', colors.yellow);
colors.alias('secondary', colors.bold);
console.log(colors.primary.secondary('Foo'));
```
## Themes
A theme is an object of custom aliases.
```js
const colors = require('ansi-colors');
colors.theme({
danger: colors.red,
dark: colors.dim.gray,
disabled: colors.gray,
em: colors.italic,
heading: colors.bold.underline,
info: colors.cyan,
muted: colors.dim,
primary: colors.blue,
strong: colors.bold,
success: colors.green,
underline: colors.underline,
warning: colors.yellow
});
// Now, we can use our custom styles alongside the built-in styles!
console.log(colors.danger.strong.em('Error!'));
console.log(colors.warning('Heads up!'));
console.log(colors.info('Did you know...'));
console.log(colors.success.bold('It worked!'));
```
## Performance
**Libraries tested**
* ansi-colors v3.0.4
* chalk v2.4.1
### Mac
> MacBook Pro, Intel Core i7, 2.3 GHz, 16 GB.
**Load time**
Time it takes to load the first time `require()` is called:
* ansi-colors - `1.915ms`
* chalk - `12.437ms`
**Benchmarks**
```
# All Colors
ansi-colors x 173,851 ops/sec ±0.42% (91 runs sampled)
chalk x 9,944 ops/sec ±2.53% (81 runs sampled)))
# Chained colors
ansi-colors x 20,791 ops/sec ±0.60% (88 runs sampled)
chalk x 2,111 ops/sec ±2.34% (83 runs sampled)
# Nested colors
ansi-colors x 59,304 ops/sec ±0.98% (92 runs sampled)
chalk x 4,590 ops/sec ±2.08% (82 runs sampled)
```
### Windows
> Windows 10, Intel Core i7-7700k CPU @ 4.2 GHz, 32 GB
**Load time**
Time it takes to load the first time `require()` is called:
* ansi-colors - `1.494ms`
* chalk - `11.523ms`
**Benchmarks**
```
# All Colors
ansi-colors x 193,088 ops/sec ±0.51% (95 runs sampled))
chalk x 9,612 ops/sec ±3.31% (77 runs sampled)))
# Chained colors
ansi-colors x 26,093 ops/sec ±1.13% (94 runs sampled)
chalk x 2,267 ops/sec ±2.88% (80 runs sampled))
# Nested colors
ansi-colors x 67,747 ops/sec ±0.49% (93 runs sampled)
chalk x 4,446 ops/sec ±3.01% (82 runs sampled))
```
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Related projects
You might also be interested in these projects:
* [ansi-wrap](https://www.npmjs.com/package/ansi-wrap): Create ansi colors by passing the open and close codes. | [homepage](https://github.com/jonschlinkert/ansi-wrap "Create ansi colors by passing the open and close codes.")
* [strip-color](https://www.npmjs.com/package/strip-color): Strip ANSI color codes from a string. No dependencies. | [homepage](https://github.com/jonschlinkert/strip-color "Strip ANSI color codes from a string. No dependencies.")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 48 | [jonschlinkert](https://github.com/jonschlinkert) |
| 42 | [doowb](https://github.com/doowb) |
| 6 | [lukeed](https://github.com/lukeed) |
| 2 | [Silic0nS0ldier](https://github.com/Silic0nS0ldier) |
| 1 | [dwieeb](https://github.com/dwieeb) |
| 1 | [jorgebucaran](https://github.com/jorgebucaran) |
| 1 | [madhavarshney](https://github.com/madhavarshney) |
| 1 | [chapterjason](https://github.com/chapterjason) |
### Author
**Brian Woodward**
* [GitHub Profile](https://github.com/doowb)
* [Twitter Profile](https://twitter.com/doowb)
* [LinkedIn Profile](https://linkedin.com/in/woodwardbrian)
### License
Copyright © 2019, [Brian Woodward](https://github.com/doowb).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on July 01, 2019._

177
node_modules/ansi-colors/index.js generated vendored Normal file
View File

@ -0,0 +1,177 @@
'use strict';
const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
const identity = val => val;
/* eslint-disable no-control-regex */
// this is a modified version of https://github.com/chalk/ansi-regex (MIT License)
const ANSI_REGEX = /[\u001b\u009b][[\]#;?()]*(?:(?:(?:[^\W_]*;?[^\W_]*)\u0007)|(?:(?:[0-9]{1,4}(;[0-9]{0,4})*)?[~0-9=<>cf-nqrtyA-PRZ]))/g;
const create = () => {
const colors = { enabled: true, visible: true, styles: {}, keys: {} };
if ('FORCE_COLOR' in process.env) {
colors.enabled = process.env.FORCE_COLOR !== '0';
}
const ansi = style => {
let open = style.open = `\u001b[${style.codes[0]}m`;
let close = style.close = `\u001b[${style.codes[1]}m`;
let regex = style.regex = new RegExp(`\\u001b\\[${style.codes[1]}m`, 'g');
style.wrap = (input, newline) => {
if (input.includes(close)) input = input.replace(regex, close + open);
let output = open + input + close;
// see https://github.com/chalk/chalk/pull/92, thanks to the
// chalk contributors for this fix. However, we've confirmed that
// this issue is also present in Windows terminals
return newline ? output.replace(/\r*\n/g, `${close}$&${open}`) : output;
};
return style;
};
const wrap = (style, input, newline) => {
return typeof style === 'function' ? style(input) : style.wrap(input, newline);
};
const style = (input, stack) => {
if (input === '' || input == null) return '';
if (colors.enabled === false) return input;
if (colors.visible === false) return '';
let str = '' + input;
let nl = str.includes('\n');
let n = stack.length;
if (n > 0 && stack.includes('unstyle')) {
stack = [...new Set(['unstyle', ...stack])].reverse();
}
while (n-- > 0) str = wrap(colors.styles[stack[n]], str, nl);
return str;
};
const define = (name, codes, type) => {
colors.styles[name] = ansi({ name, codes });
let keys = colors.keys[type] || (colors.keys[type] = []);
keys.push(name);
Reflect.defineProperty(colors, name, {
configurable: true,
enumerable: true,
set(value) {
colors.alias(name, value);
},
get() {
let color = input => style(input, color.stack);
Reflect.setPrototypeOf(color, colors);
color.stack = this.stack ? this.stack.concat(name) : [name];
return color;
}
});
};
define('reset', [0, 0], 'modifier');
define('bold', [1, 22], 'modifier');
define('dim', [2, 22], 'modifier');
define('italic', [3, 23], 'modifier');
define('underline', [4, 24], 'modifier');
define('inverse', [7, 27], 'modifier');
define('hidden', [8, 28], 'modifier');
define('strikethrough', [9, 29], 'modifier');
define('black', [30, 39], 'color');
define('red', [31, 39], 'color');
define('green', [32, 39], 'color');
define('yellow', [33, 39], 'color');
define('blue', [34, 39], 'color');
define('magenta', [35, 39], 'color');
define('cyan', [36, 39], 'color');
define('white', [37, 39], 'color');
define('gray', [90, 39], 'color');
define('grey', [90, 39], 'color');
define('bgBlack', [40, 49], 'bg');
define('bgRed', [41, 49], 'bg');
define('bgGreen', [42, 49], 'bg');
define('bgYellow', [43, 49], 'bg');
define('bgBlue', [44, 49], 'bg');
define('bgMagenta', [45, 49], 'bg');
define('bgCyan', [46, 49], 'bg');
define('bgWhite', [47, 49], 'bg');
define('blackBright', [90, 39], 'bright');
define('redBright', [91, 39], 'bright');
define('greenBright', [92, 39], 'bright');
define('yellowBright', [93, 39], 'bright');
define('blueBright', [94, 39], 'bright');
define('magentaBright', [95, 39], 'bright');
define('cyanBright', [96, 39], 'bright');
define('whiteBright', [97, 39], 'bright');
define('bgBlackBright', [100, 49], 'bgBright');
define('bgRedBright', [101, 49], 'bgBright');
define('bgGreenBright', [102, 49], 'bgBright');
define('bgYellowBright', [103, 49], 'bgBright');
define('bgBlueBright', [104, 49], 'bgBright');
define('bgMagentaBright', [105, 49], 'bgBright');
define('bgCyanBright', [106, 49], 'bgBright');
define('bgWhiteBright', [107, 49], 'bgBright');
colors.ansiRegex = ANSI_REGEX;
colors.hasColor = colors.hasAnsi = str => {
colors.ansiRegex.lastIndex = 0;
return typeof str === 'string' && str !== '' && colors.ansiRegex.test(str);
};
colors.alias = (name, color) => {
let fn = typeof color === 'string' ? colors[color] : color;
if (typeof fn !== 'function') {
throw new TypeError('Expected alias to be the name of an existing color (string) or a function');
}
if (!fn.stack) {
Reflect.defineProperty(fn, 'name', { value: name });
colors.styles[name] = fn;
fn.stack = [name];
}
Reflect.defineProperty(colors, name, {
configurable: true,
enumerable: true,
set(value) {
colors.alias(name, value);
},
get() {
let color = input => style(input, color.stack);
Reflect.setPrototypeOf(color, colors);
color.stack = this.stack ? this.stack.concat(fn.stack) : fn.stack;
return color;
}
});
};
colors.theme = custom => {
if (!isObject(custom)) throw new TypeError('Expected theme to be an object');
for (let name of Object.keys(custom)) {
colors.alias(name, custom[name]);
}
return colors;
};
colors.alias('unstyle', str => {
if (typeof str === 'string' && str !== '') {
colors.ansiRegex.lastIndex = 0;
return str.replace(colors.ansiRegex, '');
}
return '';
});
colors.alias('noop', str => str);
colors.none = colors.clear = colors.noop;
colors.stripColor = colors.unstyle;
colors.symbols = require('./symbols');
colors.define = define;
return colors;
};
module.exports = create();
module.exports.create = create;

152
node_modules/ansi-colors/package.json generated vendored Normal file
View File

@ -0,0 +1,152 @@
{
"_from": "ansi-colors@4.1.1",
"_id": "ansi-colors@4.1.1",
"_inBundle": false,
"_integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==",
"_location": "/ansi-colors",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "ansi-colors@4.1.1",
"name": "ansi-colors",
"escapedName": "ansi-colors",
"rawSpec": "4.1.1",
"saveSpec": null,
"fetchSpec": "4.1.1"
},
"_requiredBy": [
"/mocha"
],
"_resolved": "https://registry.npmmirror.com/ansi-colors/-/ansi-colors-4.1.1.tgz",
"_shasum": "cbb9ae256bf750af1eab344f229aa27fe94ba348",
"_spec": "ansi-colors@4.1.1",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/mocha",
"author": {
"name": "Brian Woodward",
"url": "https://github.com/doowb"
},
"bugs": {
"url": "https://github.com/doowb/ansi-colors/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Brian Woodward",
"url": "https://twitter.com/doowb"
},
{
"name": "Jason Schilling",
"url": "https://sourecode.de"
},
{
"name": "Jon Schlinkert",
"url": "http://twitter.com/jonschlinkert"
},
{
"name": "Jordan",
"url": "https://github.com/Silic0nS0ldier"
}
],
"deprecated": false,
"description": "Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs).",
"devDependencies": {
"decache": "^4.5.1",
"gulp-format-md": "^2.0.0",
"justified": "^1.0.1",
"mocha": "^6.1.4",
"text-table": "^0.2.0"
},
"engines": {
"node": ">=6"
},
"files": [
"index.js",
"symbols.js",
"types/index.d.ts"
],
"homepage": "https://github.com/doowb/ansi-colors",
"keywords": [
"ansi",
"bgblack",
"bgBlack",
"bgblue",
"bgBlue",
"bgcyan",
"bgCyan",
"bggreen",
"bgGreen",
"bgmagenta",
"bgMagenta",
"bgred",
"bgRed",
"bgwhite",
"bgWhite",
"bgyellow",
"bgYellow",
"black",
"blue",
"bold",
"clorox",
"colors",
"cyan",
"dim",
"gray",
"green",
"grey",
"hidden",
"inverse",
"italic",
"kleur",
"magenta",
"red",
"reset",
"strikethrough",
"underline",
"white",
"yellow"
],
"license": "MIT",
"main": "index.js",
"name": "ansi-colors",
"repository": {
"type": "git",
"url": "git+https://github.com/doowb/ansi-colors.git"
},
"scripts": {
"test": "mocha"
},
"types": "./types/index.d.ts",
"verb": {
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"data": {
"author": {
"linkedin": "woodwardbrian",
"twitter": "doowb"
}
},
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
},
"related": {
"list": [
"ansi-wrap",
"strip-color"
]
},
"reflinks": [
"chalk",
"colorette",
"colors",
"kleur"
]
},
"version": "4.1.1"
}

70
node_modules/ansi-colors/symbols.js generated vendored Normal file
View File

@ -0,0 +1,70 @@
'use strict';
const isHyper = process.env.TERM_PROGRAM === 'Hyper';
const isWindows = process.platform === 'win32';
const isLinux = process.platform === 'linux';
const common = {
ballotDisabled: '☒',
ballotOff: '☐',
ballotOn: '☑',
bullet: '•',
bulletWhite: '◦',
fullBlock: '█',
heart: '❤',
identicalTo: '≡',
line: '─',
mark: '※',
middot: '·',
minus: '',
multiplication: '×',
obelus: '÷',
pencilDownRight: '✎',
pencilRight: '✏',
pencilUpRight: '✐',
percent: '%',
pilcrow2: '❡',
pilcrow: '¶',
plusMinus: '±',
section: '§',
starsOff: '☆',
starsOn: '★',
upDownArrow: '↕'
};
const windows = Object.assign({}, common, {
check: '√',
cross: '×',
ellipsisLarge: '...',
ellipsis: '...',
info: 'i',
question: '?',
questionSmall: '?',
pointer: '>',
pointerSmall: '»',
radioOff: '( )',
radioOn: '(*)',
warning: '‼'
});
const other = Object.assign({}, common, {
ballotCross: '✘',
check: '✔',
cross: '✖',
ellipsisLarge: '⋯',
ellipsis: '…',
info: '',
question: '?',
questionFull: '',
questionSmall: '﹖',
pointer: isLinux ? '▸' : '',
pointerSmall: isLinux ? '‣' : '',
radioOff: '◯',
radioOn: '◉',
warning: '⚠'
});
module.exports = (isWindows && !isHyper) ? windows : other;
Reflect.defineProperty(module.exports, 'common', { enumerable: false, value: common });
Reflect.defineProperty(module.exports, 'windows', { enumerable: false, value: windows });
Reflect.defineProperty(module.exports, 'other', { enumerable: false, value: other });

161
node_modules/ansi-colors/types/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,161 @@
// Imported from DefinitelyTyped project.
// TypeScript definitions for ansi-colors
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Integrated by: Jordan Mele <https://github.com/Silic0nS0ldier>
interface SymbolsType {
check: string;
cross: string;
info: string;
line: string;
pointer: string;
pointerSmall: string;
question: string;
warning: string;
}
type StyleArrayStructure = [number, number];
interface StyleArrayProperties {
open: string;
close: string;
closeRe: string;
}
type StyleType = StyleArrayStructure & StyleArrayProperties;
export interface StyleFunction extends StylesType<StyleFunction> {
(s: string): string;
}
interface StylesType<T> {
// modifiers
reset: T;
bold: T;
dim: T;
italic: T;
underline: T;
inverse: T;
hidden: T;
strikethrough: T;
// colors
black: T;
red: T;
green: T;
yellow: T;
blue: T;
magenta: T;
cyan: T;
white: T;
gray: T;
grey: T;
// bright colors
blackBright: T;
redBright: T;
greenBright: T;
yellowBright: T;
blueBright: T;
magentaBright: T;
cyanBright: T;
whiteBright: T;
// background colors
bgBlack: T;
bgRed: T;
bgGreen: T;
bgYellow: T;
bgBlue: T;
bgMagenta: T;
bgCyan: T;
bgWhite: T;
// bright background colors
bgBlackBright: T;
bgRedBright: T;
bgGreenBright: T;
bgYellowBright: T;
bgBlueBright: T;
bgMagentaBright: T;
bgCyanBright: T;
bgWhiteBright: T;
}
// modifiers
export const reset: StyleFunction;
export const bold: StyleFunction;
export const dim: StyleFunction;
export const italic: StyleFunction;
export const underline: StyleFunction;
export const inverse: StyleFunction;
export const hidden: StyleFunction;
export const strikethrough: StyleFunction;
// colors
export const black: StyleFunction;
export const red: StyleFunction;
export const green: StyleFunction;
export const yellow: StyleFunction;
export const blue: StyleFunction;
export const magenta: StyleFunction;
export const cyan: StyleFunction;
export const white: StyleFunction;
export const gray: StyleFunction;
export const grey: StyleFunction;
// bright colors
export const blackBright: StyleFunction;
export const redBright: StyleFunction;
export const greenBright: StyleFunction;
export const yellowBright: StyleFunction;
export const blueBright: StyleFunction;
export const magentaBright: StyleFunction;
export const cyanBright: StyleFunction;
export const whiteBright: StyleFunction;
// background colors
export const bgBlack: StyleFunction;
export const bgRed: StyleFunction;
export const bgGreen: StyleFunction;
export const bgYellow: StyleFunction;
export const bgBlue: StyleFunction;
export const bgMagenta: StyleFunction;
export const bgCyan: StyleFunction;
export const bgWhite: StyleFunction;
// bright background colors
export const bgBlackBright: StyleFunction;
export const bgRedBright: StyleFunction;
export const bgGreenBright: StyleFunction;
export const bgYellowBright: StyleFunction;
export const bgBlueBright: StyleFunction;
export const bgMagentaBright: StyleFunction;
export const bgCyanBright: StyleFunction;
export const bgWhiteBright: StyleFunction;
export let enabled: boolean;
export let visible: boolean;
export const ansiRegex: RegExp;
/**
* Remove styles from string
*/
export function stripColor(s: string): string;
/**
* Remove styles from string
*/
export function strip(s: string): string;
/**
* Remove styles from string
*/
export function unstyle(s: string): string;
export const styles: StylesType<StyleType>;
export const symbols: SymbolsType;
/**
* Outputs a string with check-symbol as prefix
*/
export function ok(...args: string[]): string;

37
node_modules/ansi-regex/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,37 @@
declare namespace ansiRegex {
interface Options {
/**
Match only the first ANSI escape.
@default false
*/
onlyFirst: boolean;
}
}
/**
Regular expression for matching ANSI escape codes.
@example
```
import ansiRegex = require('ansi-regex');
ansiRegex().test('\u001B[4mcake\u001B[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
//=> ['\u001B[4m', '\u001B[0m']
'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true}));
//=> ['\u001B[4m']
'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex());
//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007']
```
*/
declare function ansiRegex(options?: ansiRegex.Options): RegExp;
export = ansiRegex;

10
node_modules/ansi-regex/index.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
'use strict';
module.exports = ({onlyFirst = false} = {}) => {
const pattern = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
].join('|');
return new RegExp(pattern, onlyFirst ? undefined : 'g');
};

9
node_modules/ansi-regex/license generated vendored Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.

88
node_modules/ansi-regex/package.json generated vendored Normal file
View File

@ -0,0 +1,88 @@
{
"_from": "ansi-regex@^5.0.1",
"_id": "ansi-regex@5.0.1",
"_inBundle": false,
"_integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"_location": "/ansi-regex",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "ansi-regex@^5.0.1",
"name": "ansi-regex",
"escapedName": "ansi-regex",
"rawSpec": "^5.0.1",
"saveSpec": null,
"fetchSpec": "^5.0.1"
},
"_requiredBy": [
"/gauge",
"/strip-ansi"
],
"_resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz",
"_shasum": "082cb2c89c9fe8659a311a53bd6a4dc5301db304",
"_spec": "ansi-regex@^5.0.1",
"_where": "/home/harmony/hhhh/napi_generator/node_modules/gauge",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-regex/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Regular expression for matching ANSI escape codes",
"devDependencies": {
"ava": "^2.4.0",
"tsd": "^0.9.0",
"xo": "^0.25.3"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/chalk/ansi-regex#readme",
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"text",
"regex",
"regexp",
"re",
"match",
"test",
"find",
"pattern"
],
"license": "MIT",
"name": "ansi-regex",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-regex.git"
},
"scripts": {
"test": "xo && ava && tsd",
"view-supported": "node fixtures/view-codes.js"
},
"version": "5.0.1"
}

78
node_modules/ansi-regex/readme.md generated vendored Normal file
View File

@ -0,0 +1,78 @@
# ansi-regex
> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install ansi-regex
```
## Usage
```js
const ansiRegex = require('ansi-regex');
ansiRegex().test('\u001B[4mcake\u001B[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
//=> ['\u001B[4m', '\u001B[0m']
'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true}));
//=> ['\u001B[4m']
'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex());
//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007']
```
## API
### ansiRegex(options?)
Returns a regex for matching ANSI escape codes.
#### options
Type: `object`
##### onlyFirst
Type: `boolean`<br>
Default: `false` *(Matches any ANSI escape codes in a string)*
Match only the first ANSI escape.
## FAQ
### Why do you test for codes not in the ECMA 48 standard?
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-ansi-regex?utm_source=npm-ansi-regex&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

345
node_modules/ansi-styles/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,345 @@
declare type CSSColor =
| 'aliceblue'
| 'antiquewhite'
| 'aqua'
| 'aquamarine'
| 'azure'
| 'beige'
| 'bisque'
| 'black'
| 'blanchedalmond'
| 'blue'
| 'blueviolet'
| 'brown'
| 'burlywood'
| 'cadetblue'
| 'chartreuse'
| 'chocolate'
| 'coral'
| 'cornflowerblue'
| 'cornsilk'
| 'crimson'
| 'cyan'
| 'darkblue'
| 'darkcyan'
| 'darkgoldenrod'
| 'darkgray'
| 'darkgreen'
| 'darkgrey'
| 'darkkhaki'
| 'darkmagenta'
| 'darkolivegreen'
| 'darkorange'
| 'darkorchid'
| 'darkred'
| 'darksalmon'
| 'darkseagreen'
| 'darkslateblue'
| 'darkslategray'
| 'darkslategrey'
| 'darkturquoise'
| 'darkviolet'
| 'deeppink'
| 'deepskyblue'
| 'dimgray'
| 'dimgrey'
| 'dodgerblue'
| 'firebrick'
| 'floralwhite'
| 'forestgreen'
| 'fuchsia'
| 'gainsboro'
| 'ghostwhite'
| 'gold'
| 'goldenrod'
| 'gray'
| 'green'
| 'greenyellow'
| 'grey'
| 'honeydew'
| 'hotpink'
| 'indianred'
| 'indigo'
| 'ivory'
| 'khaki'
| 'lavender'
| 'lavenderblush'
| 'lawngreen'
| 'lemonchiffon'
| 'lightblue'
| 'lightcoral'
| 'lightcyan'
| 'lightgoldenrodyellow'
| 'lightgray'
| 'lightgreen'
| 'lightgrey'
| 'lightpink'
| 'lightsalmon'
| 'lightseagreen'
| 'lightskyblue'
| 'lightslategray'
| 'lightslategrey'
| 'lightsteelblue'
| 'lightyellow'
| 'lime'
| 'limegreen'
| 'linen'
| 'magenta'
| 'maroon'
| 'mediumaquamarine'
| 'mediumblue'
| 'mediumorchid'
| 'mediumpurple'
| 'mediumseagreen'
| 'mediumslateblue'
| 'mediumspringgreen'
| 'mediumturquoise'
| 'mediumvioletred'
| 'midnightblue'
| 'mintcream'
| 'mistyrose'
| 'moccasin'
| 'navajowhite'
| 'navy'
| 'oldlace'
| 'olive'
| 'olivedrab'
| 'orange'
| 'orangered'
| 'orchid'
| 'palegoldenrod'
| 'palegreen'
| 'paleturquoise'
| 'palevioletred'
| 'papayawhip'
| 'peachpuff'
| 'peru'
| 'pink'
| 'plum'
| 'powderblue'
| 'purple'
| 'rebeccapurple'
| 'red'
| 'rosybrown'
| 'royalblue'
| 'saddlebrown'
| 'salmon'
| 'sandybrown'
| 'seagreen'
| 'seashell'
| 'sienna'
| 'silver'
| 'skyblue'
| 'slateblue'
| 'slategray'
| 'slategrey'
| 'snow'
| 'springgreen'
| 'steelblue'
| 'tan'
| 'teal'
| 'thistle'
| 'tomato'
| 'turquoise'
| 'violet'
| 'wheat'
| 'white'
| 'whitesmoke'
| 'yellow'
| 'yellowgreen';
declare namespace ansiStyles {
interface ColorConvert {
/**
The RGB color space.
@param red - (`0`-`255`)
@param green - (`0`-`255`)
@param blue - (`0`-`255`)
*/
rgb(red: number, green: number, blue: number): string;
/**
The RGB HEX color space.
@param hex - A hexadecimal string containing RGB data.
*/
hex(hex: string): string;
/**
@param keyword - A CSS color name.
*/
keyword(keyword: CSSColor): string;
/**
The HSL color space.
@param hue - (`0`-`360`)
@param saturation - (`0`-`100`)
@param lightness - (`0`-`100`)
*/
hsl(hue: number, saturation: number, lightness: number): string;
/**
The HSV color space.
@param hue - (`0`-`360`)
@param saturation - (`0`-`100`)
@param value - (`0`-`100`)
*/
hsv(hue: number, saturation: number, value: number): string;
/**
The HSV color space.
@param hue - (`0`-`360`)
@param whiteness - (`0`-`100`)
@param blackness - (`0`-`100`)
*/
hwb(hue: number, whiteness: number, blackness: number): string;
/**
Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color.
*/
ansi(ansi: number): string;
/**
Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
*/
ansi256(ansi: number): string;
}
interface CSPair {
/**
The ANSI terminal control sequence for starting this style.
*/
readonly open: string;
/**
The ANSI terminal control sequence for ending this style.
*/
readonly close: string;
}
interface ColorBase {
readonly ansi: ColorConvert;
readonly ansi256: ColorConvert;
readonly ansi16m: ColorConvert;
/**
The ANSI terminal control sequence for ending this color.
*/
readonly close: string;
}
interface Modifier {
/**
Resets the current color chain.
*/
readonly reset: CSPair;
/**
Make text bold.
*/
readonly bold: CSPair;
/**
Emitting only a small amount of light.
*/
readonly dim: CSPair;
/**
Make text italic. (Not widely supported)
*/
readonly italic: CSPair;
/**
Make text underline. (Not widely supported)
*/
readonly underline: CSPair;
/**
Inverse background and foreground colors.
*/
readonly inverse: CSPair;
/**
Prints the text, but makes it invisible.
*/
readonly hidden: CSPair;
/**
Puts a horizontal line through the center of the text. (Not widely supported)
*/
readonly strikethrough: CSPair;
}
interface ForegroundColor {
readonly black: CSPair;
readonly red: CSPair;
readonly green: CSPair;
readonly yellow: CSPair;
readonly blue: CSPair;
readonly cyan: CSPair;
readonly magenta: CSPair;
readonly white: CSPair;
/**
Alias for `blackBright`.
*/
readonly gray: CSPair;
/**
Alias for `blackBright`.
*/
readonly grey: CSPair;
readonly blackBright: CSPair;
readonly redBright: CSPair;
readonly greenBright: CSPair;
readonly yellowBright: CSPair;
readonly blueBright: CSPair;
readonly cyanBright: CSPair;
readonly magentaBright: CSPair;
readonly whiteBright: CSPair;
}
interface BackgroundColor {
readonly bgBlack: CSPair;
readonly bgRed: CSPair;
readonly bgGreen: CSPair;
readonly bgYellow: CSPair;
readonly bgBlue: CSPair;
readonly bgCyan: CSPair;
readonly bgMagenta: CSPair;
readonly bgWhite: CSPair;
/**
Alias for `bgBlackBright`.
*/
readonly bgGray: CSPair;
/**
Alias for `bgBlackBright`.
*/
readonly bgGrey: CSPair;
readonly bgBlackBright: CSPair;
readonly bgRedBright: CSPair;
readonly bgGreenBright: CSPair;
readonly bgYellowBright: CSPair;
readonly bgBlueBright: CSPair;
readonly bgCyanBright: CSPair;
readonly bgMagentaBright: CSPair;
readonly bgWhiteBright: CSPair;
}
}
declare const ansiStyles: {
readonly modifier: ansiStyles.Modifier;
readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase;
readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase;
readonly codes: ReadonlyMap<number, number>;
} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier;
export = ansiStyles;

163
node_modules/ansi-styles/index.js generated vendored Normal file
View File

@ -0,0 +1,163 @@
'use strict';
const wrapAnsi16 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\u001B[${code + offset}m`;
};
const wrapAnsi256 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\u001B[${38 + offset};5;${code}m`;
};
const wrapAnsi16m = (fn, offset) => (...args) => {
const rgb = fn(...args);
return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
};
const ansi2ansi = n => n;
const rgb2rgb = (r, g, b) => [r, g, b];
const setLazyProperty = (object, property, get) => {
Object.defineProperty(object, property, {
get: () => {
const value = get();
Object.defineProperty(object, property, {
value,
enumerable: true,
configurable: true
});
return value;
},
enumerable: true,
configurable: true
});
};
/** @type {typeof import('color-convert')} */
let colorConvert;
const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
if (colorConvert === undefined) {
colorConvert = require('color-convert');
}
const offset = isBackground ? 10 : 0;
const styles = {};
for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
if (sourceSpace === targetSpace) {
styles[name] = wrap(identity, offset);
} else if (typeof suite === 'object') {
styles[name] = wrap(suite[targetSpace], offset);
}
}
return styles;
};
function assembleStyles() {
const codes = new Map();
const styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
// Alias bright black as gray (and grey)
styles.color.gray = styles.color.blackBright;
styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
styles.color.grey = styles.color.blackBright;
styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\u001B[${style[0]}m`,
close: `\u001B[${style[1]}m`
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles, 'codes', {
value: codes,
enumerable: false
});
styles.color.close = '\u001B[39m';
styles.bgColor.close = '\u001B[49m';
setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
return styles;
}
// Make the export immutable
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});

9
node_modules/ansi-styles/license generated vendored Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.

Some files were not shown because too many files have changed in this diff Show More