diff --git a/bin/index.js b/bin/index.js index ec2289b..026a0b8 100644 --- a/bin/index.js +++ b/bin/index.js @@ -1,11 +1,10 @@ #!/usr/bin/env node -import require$$5$1, { notStrictEqual, strictEqual } from 'assert'; -import require$$1$1, { resolve, dirname, normalize, basename, extname, relative } from 'path'; import require$$0$5, { statSync, readdirSync, readFileSync as readFileSync$1, writeFile as writeFile$1 } from 'fs'; -import require$$0$6, { format, inspect } from 'util'; -import { fileURLToPath } from 'url'; import require$$0$3 from 'constants'; import require$$0$4 from 'stream'; +import require$$0$6, { format, inspect } from 'util'; +import require$$5$1, { notStrictEqual, strictEqual } from 'assert'; +import require$$1$1, { resolve, dirname, normalize, basename, extname, relative } from 'path'; import require$$0$7 from 'os'; import process$2 from 'node:process'; import os$j, { constants as constants$1 } from 'node:os'; @@ -23,7662 +22,2360 @@ import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks'; import * as readline$1 from 'node:readline'; import require$$2$1 from 'crypto'; import require$$0$8 from 'net'; +import { fileURLToPath } from 'url'; -const align = { - right: alignRight, - center: alignCenter -}; -const top = 0; -const right = 1; -const bottom = 2; -const left = 3; -class UI { - constructor(opts) { - var _a; - this.width = opts.width; - this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; - this.rows = []; - } - span(...args) { - const cols = this.div(...args); - cols.span = true; - } - resetOutput() { - this.rows = []; - } - div(...args) { - if (args.length === 0) { - this.div(''); - } - if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { - return this.applyLayoutDSL(args[0]); - } - const cols = args.map(arg => { - if (typeof arg === 'string') { - return this.colFromString(arg); - } - return arg; - }); - this.rows.push(cols); - return cols; - } - shouldApplyLayoutDSL(...args) { - return args.length === 1 && typeof args[0] === 'string' && - /[\t\n]/.test(args[0]); - } - applyLayoutDSL(str) { - const rows = str.split('\n').map(row => row.split('\t')); - let leftColumnWidth = 0; - // simple heuristic for layout, make sure the - // second column lines up along the left-hand. - // don't allow the first column to take up more - // than 50% of the screen. - rows.forEach(columns => { - if (columns.length > 1 && mixin$1.stringWidth(columns[0]) > leftColumnWidth) { - leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin$1.stringWidth(columns[0])); - } - }); - // generate a table: - // replacing ' ' with padding calculations. - // using the algorithmically generated width. - rows.forEach(columns => { - this.div(...columns.map((r, i) => { - return { - text: r.trim(), - padding: this.measurePadding(r), - width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined - }; - })); - }); - return this.rows[this.rows.length - 1]; - } - colFromString(text) { - return { - text, - padding: this.measurePadding(text) - }; - } - measurePadding(str) { - // measure padding without ansi escape codes - const noAnsi = mixin$1.stripAnsi(str); - return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; - } - toString() { - const lines = []; - this.rows.forEach(row => { - this.rowToString(row, lines); - }); - // don't display any lines with the - // hidden flag set. - return lines - .filter(line => !line.hidden) - .map(line => line.text) - .join('\n'); - } - rowToString(row, lines) { - this.rasterize(row).forEach((rrow, r) => { - let str = ''; - rrow.forEach((col, c) => { - const { width } = row[c]; // the width with padding. - const wrapWidth = this.negatePadding(row[c]); // the width without padding. - let ts = col; // temporary string used during alignment/padding. - if (wrapWidth > mixin$1.stringWidth(col)) { - ts += ' '.repeat(wrapWidth - mixin$1.stringWidth(col)); - } - // align the string within its column. - if (row[c].align && row[c].align !== 'left' && this.wrap) { - const fn = align[row[c].align]; - ts = fn(ts, wrapWidth); - if (mixin$1.stringWidth(ts) < wrapWidth) { - ts += ' '.repeat((width || 0) - mixin$1.stringWidth(ts) - 1); - } - } - // apply border and padding to string. - const padding = row[c].padding || [0, 0, 0, 0]; - if (padding[left]) { - str += ' '.repeat(padding[left]); - } - str += addBorder(row[c], ts, '| '); - str += ts; - str += addBorder(row[c], ts, ' |'); - if (padding[right]) { - str += ' '.repeat(padding[right]); - } - // if prior row is span, try to render the - // current row on the prior line. - if (r === 0 && lines.length > 0) { - str = this.renderInline(str, lines[lines.length - 1]); - } - }); - // remove trailing whitespace. - lines.push({ - text: str.replace(/ +$/, ''), - span: row.span - }); - }); - return lines; - } - // if the full 'source' can render in - // the target line, do so. - renderInline(source, previousLine) { - const match = source.match(/^ */); - const leadingWhitespace = match ? match[0].length : 0; - const target = previousLine.text; - const targetTextWidth = mixin$1.stringWidth(target.trimRight()); - if (!previousLine.span) { - return source; - } - // if we're not applying wrapping logic, - // just always append to the span. - if (!this.wrap) { - previousLine.hidden = true; - return target + source; - } - if (leadingWhitespace < targetTextWidth) { - return source; - } - previousLine.hidden = true; - return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft(); - } - rasterize(row) { - const rrows = []; - const widths = this.columnWidths(row); - let wrapped; - // word wrap all columns, and create - // a data-structure that is easy to rasterize. - row.forEach((col, c) => { - // leave room for left and right padding. - col.width = widths[c]; - if (this.wrap) { - wrapped = mixin$1.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); - } - else { - wrapped = col.text.split('\n'); - } - if (col.border) { - wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); - wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); - } - // add top and bottom padding. - if (col.padding) { - wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); - wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); - } - wrapped.forEach((str, r) => { - if (!rrows[r]) { - rrows.push([]); - } - const rrow = rrows[r]; - for (let i = 0; i < c; i++) { - if (rrow[i] === undefined) { - rrow.push(''); - } - } - rrow.push(str); - }); - }); - return rrows; - } - negatePadding(col) { - let wrapWidth = col.width || 0; - if (col.padding) { - wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); - } - if (col.border) { - wrapWidth -= 4; - } - return wrapWidth; - } - columnWidths(row) { - if (!this.wrap) { - return row.map(col => { - return col.width || mixin$1.stringWidth(col.text); - }); - } - let unset = row.length; - let remainingWidth = this.width; - // column widths can be set in config. - const widths = row.map(col => { - if (col.width) { - unset--; - remainingWidth -= col.width; - return col.width; - } - return undefined; - }); - // any unset widths should be calculated. - const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; - return widths.map((w, i) => { - if (w === undefined) { - return Math.max(unsetWidth, _minWidth(row[i])); - } - return w; - }); - } -} -function addBorder(col, ts, style) { - if (col.border) { - if (/[.']-+[.']/.test(ts)) { - return ''; - } - if (ts.trim().length !== 0) { - return style; - } - return ' '; - } - return ''; -} -// calculates the minimum width of -// a column, based on padding preferences. -function _minWidth(col) { - const padding = col.padding || []; - const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); - if (col.border) { - return minWidth + 4; - } - return minWidth; -} -function getWindowWidth() { - /* istanbul ignore next: depends on terminal */ - if (typeof process === 'object' && process.stdout && process.stdout.columns) { - return process.stdout.columns; - } - return 80; -} -function alignRight(str, width) { - str = str.trim(); - const strWidth = mixin$1.stringWidth(str); - if (strWidth < width) { - return ' '.repeat(width - strWidth) + str; - } - return str; -} -function alignCenter(str, width) { - str = str.trim(); - const strWidth = mixin$1.stringWidth(str); - /* istanbul ignore next */ - if (strWidth >= width) { - return str; - } - return ' '.repeat((width - strWidth) >> 1) + str; -} -let mixin$1; -function cliui(opts, _mixin) { - mixin$1 = _mixin; - return new UI({ - width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), - wrap: opts === null || opts === void 0 ? void 0 : opts.wrap - }); -} +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; -// Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi". -// to facilitate ESM and Deno modules. -// TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM. -// The npm application -// Copyright (c) npm, Inc. and Contributors -// Licensed on the terms of The Artistic License 2.0 -// See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js -const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' + - '\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g'); -function stripAnsi$4(str) { - return str.replace(ansi, ''); +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } -function wrap(str, width) { - const [start, end] = str.match(ansi) || ['', '']; - str = stripAnsi$4(str); - let wrapped = ''; - for (let i = 0; i < str.length; i++) { - if (i !== 0 && (i % width) === 0) { - wrapped += '\n'; - } - wrapped += str.charAt(i); + +var fs$w = {}; + +var universalify$1 = {}; + +universalify$1.fromCallback = function (fn) { + return Object.defineProperty(function (...args) { + if (typeof args[args.length - 1] === 'function') fn.apply(this, args); + else { + return new Promise((resolve, reject) => { + args.push((err, res) => (err != null) ? reject(err) : resolve(res)); + fn.apply(this, args); + }) } - if (start && end) { - wrapped = `${start}${wrapped}${end}`; + }, 'name', { value: fn.name }) +}; + +universalify$1.fromPromise = function (fn) { + return Object.defineProperty(function (...args) { + const cb = args[args.length - 1]; + if (typeof cb !== 'function') return fn.apply(this, args) + else { + args.pop(); + fn.apply(this, args).then(r => cb(null, r), cb); } - return wrapped; -} + }, 'name', { value: fn.name }) +}; -// Bootstrap cliui with CommonJS dependencies: +var constants = require$$0$3; -function ui (opts) { - return cliui(opts, { - stringWidth: (str) => { - return [...str].length - }, - stripAnsi: stripAnsi$4, - wrap - }) -} +var origCwd = process.cwd; +var cwd = null; -function escalade (start, callback) { - let dir = resolve('.', start); - let tmp, stats = statSync(dir); +var platform$1 = process.env.GRACEFUL_FS_PLATFORM || process.platform; - if (!stats.isDirectory()) { - dir = dirname(dir); - } +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process); + return cwd +}; +try { + process.cwd(); +} catch (er) {} - while (true) { - tmp = callback(dir, readdirSync(dir)); - if (tmp) return resolve(dir, tmp); - dir = dirname(tmp = dir); - if (tmp === dir) break; - } +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir; + process.chdir = function (d) { + cwd = null; + chdir.call(process, d); + }; + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir); } -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -function camelCase(str) { - // Handle the case where an argument is provided as camel case, e.g., fooBar. - // by ensuring that the string isn't already mixed case: - const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); - if (!isCamelCase) { - str = str.toLowerCase(); - } - if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { - return str; - } - else { - let camelcase = ''; - let nextChrUpper = false; - const leadingHyphens = str.match(/^-+/); - for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { - let chr = str.charAt(i); - if (nextChrUpper) { - nextChrUpper = false; - chr = chr.toUpperCase(); - } - if (i !== 0 && (chr === '-' || chr === '_')) { - nextChrUpper = true; - } - else if (chr !== '-' && chr !== '_') { - camelcase += chr; - } - } - return camelcase; - } -} -function decamelize(str, joinString) { - const lowercase = str.toLowerCase(); - joinString = joinString || '-'; - let notCamelcase = ''; - for (let i = 0; i < str.length; i++) { - const chrLower = lowercase.charAt(i); - const chrString = str.charAt(i); - if (chrLower !== chrString && i > 0) { - notCamelcase += `${joinString}${lowercase.charAt(i)}`; - } - else { - notCamelcase += chrString; - } - } - return notCamelcase; -} -function looksLikeNumber(x) { - if (x === null || x === undefined) - return false; - // if loaded from config, may already be a number. - if (typeof x === 'number') - return true; - // hexadecimal. - if (/^0x[0-9a-f]+$/i.test(x)) - return true; - // don't treat 0123 as a number; as it drops the leading '0'. - if (/^0[^.]/.test(x)) - return false; - return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); -} +var polyfills$1 = patch$1; -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -// take an un-split argv string and tokenize it. -function tokenizeArgString(argString) { - if (Array.isArray(argString)) { - return argString.map(e => typeof e !== 'string' ? e + '' : e); - } - argString = argString.trim(); - let i = 0; - let prevC = null; - let c = null; - let opening = null; - const args = []; - for (let ii = 0; ii < argString.length; ii++) { - prevC = c; - c = argString.charAt(ii); - // split on spaces unless we're in quotes. - if (c === ' ' && !opening) { - if (!(prevC === ' ')) { - i++; - } - continue; - } - // don't split the string if we're in matching - // opening or closing single and double quotes. - if (c === opening) { - opening = null; - } - else if ((c === "'" || c === '"') && !opening) { - opening = c; - } - if (!args[i]) - args[i] = ''; - args[i] += c; - } - return args; -} +function patch$1 (fs) { + // (re-)implement some things that are known busted or missing. -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -var DefaultValuesForTypeKey; -(function (DefaultValuesForTypeKey) { - DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; - DefaultValuesForTypeKey["STRING"] = "string"; - DefaultValuesForTypeKey["NUMBER"] = "number"; - DefaultValuesForTypeKey["ARRAY"] = "array"; -})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs); + } -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -let mixin; -class YargsParser { - constructor(_mixin) { - mixin = _mixin; - } - parse(argsInput, options) { - const opts = Object.assign({ - alias: undefined, - array: undefined, - boolean: undefined, - config: undefined, - configObjects: undefined, - configuration: undefined, - coerce: undefined, - count: undefined, - default: undefined, - envPrefix: undefined, - narg: undefined, - normalize: undefined, - string: undefined, - number: undefined, - __: undefined, - key: undefined - }, options); - // allow a string argument to be passed in rather - // than an argv array. - const args = tokenizeArgString(argsInput); - // tokenizeArgString adds extra quotes to args if argsInput is a string - // only strip those extra quotes in processValue if argsInput is a string - const inputIsString = typeof argsInput === 'string'; - // aliases might have transitive relationships, normalize this. - const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); - const configuration = Object.assign({ - 'boolean-negation': true, - 'camel-case-expansion': true, - 'combine-arrays': false, - 'dot-notation': true, - 'duplicate-arguments-array': true, - 'flatten-duplicate-arrays': true, - 'greedy-arrays': true, - 'halt-at-non-option': false, - 'nargs-eats-options': false, - 'negation-prefix': 'no-', - 'parse-numbers': true, - 'parse-positional-numbers': true, - 'populate--': false, - 'set-placeholder-key': false, - 'short-option-groups': true, - 'strip-aliased': false, - 'strip-dashed': false, - 'unknown-options-as-args': false - }, opts.configuration); - const defaults = Object.assign(Object.create(null), opts.default); - const configObjects = opts.configObjects || []; - const envPrefix = opts.envPrefix; - const notFlagsOption = configuration['populate--']; - const notFlagsArgv = notFlagsOption ? '--' : '_'; - const newAliases = Object.create(null); - const defaulted = Object.create(null); - // allow a i18n handler to be passed in, default to a fake one (util.format). - const __ = opts.__ || mixin.format; - const flags = { - aliases: Object.create(null), - arrays: Object.create(null), - bools: Object.create(null), - strings: Object.create(null), - numbers: Object.create(null), - counts: Object.create(null), - normalize: Object.create(null), - configs: Object.create(null), - nargs: Object.create(null), - coercions: Object.create(null), - keys: [] - }; - const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; - const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); - [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { - const key = typeof opt === 'object' ? opt.key : opt; - // assign to flags[bools|strings|numbers] - const assignment = Object.keys(opt).map(function (key) { - const arrayFlagKeys = { - boolean: 'bools', - string: 'strings', - number: 'numbers' - }; - return arrayFlagKeys[key]; - }).filter(Boolean).pop(); - // assign key to be coerced - if (assignment) { - flags[assignment][key] = true; - } - flags.arrays[key] = true; - flags.keys.push(key); - }); - [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - flags.keys.push(key); - }); - [].concat(opts.string || []).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - flags.keys.push(key); - }); - [].concat(opts.number || []).filter(Boolean).forEach(function (key) { - flags.numbers[key] = true; - flags.keys.push(key); - }); - [].concat(opts.count || []).filter(Boolean).forEach(function (key) { - flags.counts[key] = true; - flags.keys.push(key); - }); - [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { - flags.normalize[key] = true; - flags.keys.push(key); + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs); + } + + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. + + fs.chown = chownFix(fs.chown); + fs.fchown = chownFix(fs.fchown); + fs.lchown = chownFix(fs.lchown); + + fs.chmod = chmodFix(fs.chmod); + fs.fchmod = chmodFix(fs.fchmod); + fs.lchmod = chmodFix(fs.lchmod); + + fs.chownSync = chownFixSync(fs.chownSync); + fs.fchownSync = chownFixSync(fs.fchownSync); + fs.lchownSync = chownFixSync(fs.lchownSync); + + fs.chmodSync = chmodFixSync(fs.chmodSync); + fs.fchmodSync = chmodFixSync(fs.fchmodSync); + fs.lchmodSync = chmodFixSync(fs.lchmodSync); + + fs.stat = statFix(fs.stat); + fs.fstat = statFix(fs.fstat); + fs.lstat = statFix(fs.lstat); + + fs.statSync = statFixSync(fs.statSync); + fs.fstatSync = statFixSync(fs.fstatSync); + fs.lstatSync = statFixSync(fs.lstatSync); + + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb); + }; + fs.lchmodSync = function () {}; + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb); + }; + fs.lchownSync = function () {}; + } + + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform$1 === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now(); + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er); + }); + }, backoff); + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er); }); - if (typeof opts.narg === 'object') { - Object.entries(opts.narg).forEach(([key, value]) => { - if (typeof value === 'number') { - flags.nargs[key] = value; - flags.keys.push(key); - } - }); + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename); + return rename + })(fs.rename); + } + + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback; + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0; + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++; + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments); + }; + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read); + return read + })(fs.read); + + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0; + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++; + continue } - if (typeof opts.coerce === 'object') { - Object.entries(opts.coerce).forEach(([key, value]) => { - if (typeof value === 'function') { - flags.coercions[key] = value; - flags.keys.push(key); - } - }); + throw er + } + } + }})(fs.readSync); + + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err); + return } - if (typeof opts.config !== 'undefined') { - if (Array.isArray(opts.config) || typeof opts.config === 'string') { - [].concat(opts.config).filter(Boolean).forEach(function (key) { - flags.configs[key] = true; - }); - } - else if (typeof opts.config === 'object') { - Object.entries(opts.config).forEach(([key, value]) => { - if (typeof value === 'boolean' || typeof value === 'function') { - flags.configs[key] = value; - } - }); - } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2); + }); + }); + }); + }; + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode); + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true; + var ret; + try { + ret = fs.fchmodSync(fd, mode); + threw = false; + } finally { + if (threw) { + try { + fs.closeSync(fd); + } catch (er) {} + } else { + fs.closeSync(fd); } - // create a lookup table that takes into account all - // combinations of aliases: {f: ['foo'], foo: ['f']} - extendAliases(opts.key, aliases, opts.default, flags.arrays); - // apply default values to all aliases. - Object.keys(defaults).forEach(function (key) { - (flags.aliases[key] || []).forEach(function (alias) { - defaults[alias] = defaults[key]; + } + return ret + }; + } + + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er); + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2); }); + }); }); - let error = null; - checkConfiguration(); - let notFlags = []; - const argv = Object.assign(Object.create(null), { _: [] }); - // TODO(bcoe): for the first pass at removing object prototype we didn't - // remove all prototypes from objects returned by this API, we might want - // to gradually move towards doing so. - const argvReturn = {}; - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - const truncatedArg = arg.replace(/^-{3,}/, '---'); - let broken; - let key; - let letters; - let m; - let next; - let value; - // any unknown option (except for end-of-options, "--") - if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { - pushPositional(arg); - // ---, ---=, ----, etc, - } - else if (truncatedArg.match(/^---+(=|$)/)) { - // options without key name are invalid. - pushPositional(arg); - continue; - // -- separated by = - } - else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - m = arg.match(/^--?([^=]+)=([\s\S]*)$/); - // arrays format = '--f=a b c' - if (m !== null && Array.isArray(m) && m.length >= 3) { - if (checkAllAliases(m[1], flags.arrays)) { - i = eatArray(i, m[1], args, m[2]); - } - else if (checkAllAliases(m[1], flags.nargs) !== false) { - // nargs format = '--f=monkey washing cat' - i = eatNargs(i, m[1], args, m[2]); - } - else { - setArg(m[1], m[2], true); - } - } - } - else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { - m = arg.match(negatedBoolean); - if (m !== null && Array.isArray(m) && m.length >= 2) { - key = m[1]; - setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); - } - // -- separated by space. - } - else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { - m = arg.match(/^--?(.+)/); - if (m !== null && Array.isArray(m) && m.length >= 2) { - key = m[1]; - if (checkAllAliases(key, flags.arrays)) { - // array format = '--foo a b c' - i = eatArray(i, key, args); - } - else if (checkAllAliases(key, flags.nargs) !== false) { - // nargs format = '--foo a b c' - // should be truthy even if: flags.nargs[key] === 0 - i = eatNargs(i, key, args); - } - else { - next = args[i + 1]; - if (next !== undefined && (!next.match(/^-/) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next); - i++; - } - else { - setArg(key, defaultValue(key)); - } - } - } - // dot-notation flag separated by '='. - } - else if (arg.match(/^-.\..+=/)) { - m = arg.match(/^-([^=]+)=([\s\S]*)$/); - if (m !== null && Array.isArray(m) && m.length >= 3) { - setArg(m[1], m[2]); - } - // dot-notation flag separated by space. - } - else if (arg.match(/^-.\..+/) && !arg.match(negative)) { - next = args[i + 1]; - m = arg.match(/^-(.\..+)/); - if (m !== null && Array.isArray(m) && m.length >= 2) { - key = m[1]; - if (next !== undefined && !next.match(/^-/) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next); - i++; - } - else { - setArg(key, defaultValue(key)); - } - } - } - else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { - letters = arg.slice(1, -1).split(''); - broken = false; - for (let j = 0; j < letters.length; j++) { - next = arg.slice(j + 2); - if (letters[j + 1] && letters[j + 1] === '=') { - value = arg.slice(j + 3); - key = letters[j]; - if (checkAllAliases(key, flags.arrays)) { - // array format = '-f=a b c' - i = eatArray(i, key, args, value); - } - else if (checkAllAliases(key, flags.nargs) !== false) { - // nargs format = '-f=monkey washing cat' - i = eatNargs(i, key, args, value); - } - else { - setArg(key, value); - } - broken = true; - break; - } - if (next === '-') { - setArg(letters[j], next); - continue; - } - // current letter is an alphabetic character and next value is a number - if (/[A-Za-z]/.test(letters[j]) && - /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && - checkAllAliases(next, flags.bools) === false) { - setArg(letters[j], next); - broken = true; - break; - } - if (letters[j + 1] && letters[j + 1].match(/\W/)) { - setArg(letters[j], next); - broken = true; - break; - } - else { - setArg(letters[j], defaultValue(letters[j])); - } - } - key = arg.slice(-1)[0]; - if (!broken && key !== '-') { - if (checkAllAliases(key, flags.arrays)) { - // array format = '-f a b c' - i = eatArray(i, key, args); - } - else if (checkAllAliases(key, flags.nargs) !== false) { - // nargs format = '-f a b c' - // should be truthy even if: flags.nargs[key] === 0 - i = eatNargs(i, key, args); - } - else { - next = args[i + 1]; - if (next !== undefined && (!/^(-|--)[^-]/.test(next) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next); - i++; - } - else { - setArg(key, defaultValue(key)); - } - } - } - } - else if (arg.match(/^-[0-9]$/) && - arg.match(negative) && - checkAllAliases(arg.slice(1), flags.bools)) { - // single-digit boolean alias, e.g: xargs -0 - key = arg.slice(1); - setArg(key, defaultValue(key)); - } - else if (arg === '--') { - notFlags = args.slice(i + 1); - break; - } - else if (configuration['halt-at-non-option']) { - notFlags = args.slice(i); - break; - } - else { - pushPositional(arg); - } - } - // order of precedence: - // 1. command line arg - // 2. value from env var - // 3. value from config file - // 4. value from config objects - // 5. configured default value - applyEnvVars(argv, true); // special case: check env vars that point to config file - applyEnvVars(argv, false); - setConfig(argv); - setConfigObjects(); - applyDefaultsAndAliases(argv, flags.aliases, defaults, true); - applyCoercions(argv); - if (configuration['set-placeholder-key']) - setPlaceholderKeys(argv); - // for any counts either not in args or without an explicit default, set to 0 - Object.keys(flags.counts).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) - setArg(key, 0); - }); - // '--' defaults to undefined. - if (notFlagsOption && notFlags.length) - argv[notFlagsArgv] = []; - notFlags.forEach(function (key) { - argv[notFlagsArgv].push(key); - }); - if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { - Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { - delete argv[key]; - }); + }; + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK); + var ret; + var threw = true; + try { + ret = fs.futimesSync(fd, at, mt); + threw = false; + } finally { + if (threw) { + try { + fs.closeSync(fd); + } catch (er) {} + } else { + fs.closeSync(fd); + } } - if (configuration['strip-aliased']) { - [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { - if (configuration['camel-case-expansion'] && alias.includes('-')) { - delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; - } - delete argv[alias]; - }); + return ret + }; + + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); }; + fs.lutimesSync = function () {}; + } + } + + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null; + if (cb) cb.apply(this, arguments); + }) + } + } + + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null; + if (cb) cb.apply(this, arguments); + }) + } + } + + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000; + if (stats.gid < 0) stats.gid += 0x100000000; } - // Push argument into positional array, applying numeric coercion: - function pushPositional(arg) { - const maybeCoercedNumber = maybeCoerceNumber('_', arg); - if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { - argv._.push(maybeCoercedNumber); - } + if (cb) cb.apply(this, arguments); + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target); + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000; + if (stats.gid < 0) stats.gid += 0x100000000; + } + return stats; + } + } + + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0; + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false + } +} + +var Stream$1 = require$$0$4.Stream; + +var legacyStreams = legacy$1; + +function legacy$1 (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream$1.call(this); + + var self = this; + + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); + } + + this.pos = this.start; + } + + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + + self.fd = fd; + self.emit('open', fd); + self._read(); + }); + } + + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream$1.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; + } + + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} + +var clone_1 = clone$1; + +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +}; + +function clone$1 (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) }; + else + var copy = Object.create(null); + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)); + }); + + return copy +} + +var fs$v = require$$0$5; +var polyfills = polyfills$1; +var legacy = legacyStreams; +var clone = clone_1; + +var util$t = require$$0$6; + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue; +var previousSymbol; + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue'); + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous'); +} else { + gracefulQueue = '___graceful-fs.queue'; + previousSymbol = '___graceful-fs.previous'; +} + +function noop$2 () {} + +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }); +} + +var debug = noop$2; +if (util$t.debuglog) + debug = util$t.debuglog('gfs4'); +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util$t.format.apply(util$t, arguments); + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: '); + console.error(m); + }; + +// Once time initialization +if (!fs$v[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = commonjsGlobal[gracefulQueue] || []; + publishQueue(fs$v, queue); + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs$v.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs$v, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue(); } - // how many arguments should we consume, based - // on the nargs option? - function eatNargs(i, key, args, argAfterEqualSign) { - let ii; - let toEat = checkAllAliases(key, flags.nargs); - // NaN has a special meaning for the array type, indicating that one or - // more values are expected. - toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; - if (toEat === 0) { - if (!isUndefined(argAfterEqualSign)) { - error = Error(__('Argument unexpected for: %s', key)); - } - setArg(key, defaultValue(key)); - return i; - } - let available = isUndefined(argAfterEqualSign) ? 0 : 1; - if (configuration['nargs-eats-options']) { - // classic behavior, yargs eats positional and dash arguments. - if (args.length - (i + 1) + available < toEat) { - error = Error(__('Not enough arguments following: %s', key)); - } - available = toEat; - } - else { - // nargs will not consume flag arguments, e.g., -abc, --foo, - // and terminates when one is observed. - for (ii = i + 1; ii < args.length; ii++) { - if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) - available++; - else - break; - } - if (available < toEat) - error = Error(__('Not enough arguments following: %s', key)); - } - let consumed = Math.min(available, toEat); - if (!isUndefined(argAfterEqualSign) && consumed > 0) { - setArg(key, argAfterEqualSign); - consumed--; - } - for (ii = i + 1; ii < (consumed + i + 1); ii++) { - setArg(key, args[ii]); - } - return (i + consumed); + + if (typeof cb === 'function') + cb.apply(this, arguments); + }) + } + + Object.defineProperty(close, previousSymbol, { + value: fs$close + }); + return close + })(fs$v.close); + + fs$v.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs$v, arguments); + resetQueue(); + } + + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }); + return closeSync + })(fs$v.closeSync); + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs$v[gracefulQueue]); + require$$5$1.equal(fs$v[gracefulQueue].length, 0); + }); + } +} + +if (!commonjsGlobal[gracefulQueue]) { + publishQueue(commonjsGlobal, fs$v[gracefulQueue]); +} + +var gracefulFs = patch(clone(fs$v)); +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$v.__patched) { + gracefulFs = patch(fs$v); + fs$v.__patched = true; +} + +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs); + fs.gracefulify = patch; + + fs.createReadStream = createReadStream; + fs.createWriteStream = createWriteStream; + var fs$readFile = fs.readFile; + fs.readFile = readFile; + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null; + + return go$readFile(path, options, cb) + + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb === 'function') + cb.apply(this, arguments); } - // if an option is an array, eat all non-hyphenated arguments - // following it... YUM! - // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] - function eatArray(i, key, args, argAfterEqualSign) { - let argsToSet = []; - let next = argAfterEqualSign || args[i + 1]; - // If both array and nargs are configured, enforce the nargs count: - const nargsCount = checkAllAliases(key, flags.nargs); - if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { - argsToSet.push(true); - } - else if (isUndefined(next) || - (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { - // for keys without value ==> argsToSet remains an empty [] - // set user default value, if available - if (defaults[key] !== undefined) { - const defVal = defaults[key]; - argsToSet = Array.isArray(defVal) ? defVal : [defVal]; - } - } - else { - // value in --option=value is eaten as is - if (!isUndefined(argAfterEqualSign)) { - argsToSet.push(processValue(key, argAfterEqualSign, true)); - } - for (let ii = i + 1; ii < args.length; ii++) { - if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || - (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) - break; - next = args[ii]; - if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) - break; - i = ii; - argsToSet.push(processValue(key, next, inputIsString)); - } - } - // If both array and nargs are configured, create an error if less than - // nargs positionals were found. NaN has special meaning, indicating - // that at least one value is required (more are okay). - if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || - (isNaN(nargsCount) && argsToSet.length === 0))) { - error = Error(__('Not enough arguments following: %s', key)); - } - setArg(key, argsToSet); - return i; - } - function setArg(key, val, shouldStripQuotes = inputIsString) { - if (/-/.test(key) && configuration['camel-case-expansion']) { - const alias = key.split('.').map(function (prop) { - return camelCase(prop); - }).join('.'); - addNewAlias(key, alias); - } - const value = processValue(key, val, shouldStripQuotes); - const splitKey = key.split('.'); - setKey(argv, splitKey, value); - // handle populating aliases of the full key - if (flags.aliases[key]) { - flags.aliases[key].forEach(function (x) { - const keyProperties = x.split('.'); - setKey(argv, keyProperties, value); - }); - } - // handle populating aliases of the first element of the dot-notation key - if (splitKey.length > 1 && configuration['dot-notation']) { - (flags.aliases[splitKey[0]] || []).forEach(function (x) { - let keyProperties = x.split('.'); - // expand alias with nested objects in key - const a = [].concat(splitKey); - a.shift(); // nuke the old key. - keyProperties = keyProperties.concat(a); - // populate alias only if is not already an alias of the full key - // (already populated above) - if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { - setKey(argv, keyProperties, value); - } - }); - } - // Set normalize getter and setter when key is in 'normalize' but isn't an array - if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { - const keys = [key].concat(flags.aliases[key] || []); - keys.forEach(function (key) { - Object.defineProperty(argvReturn, key, { - enumerable: true, - get() { - return val; - }, - set(value) { - val = typeof value === 'string' ? mixin.normalize(value) : value; - } - }); - }); - } - } - function addNewAlias(key, alias) { - if (!(flags.aliases[key] && flags.aliases[key].length)) { - flags.aliases[key] = [alias]; - newAliases[alias] = true; - } - if (!(flags.aliases[alias] && flags.aliases[alias].length)) { - addNewAlias(alias, key); - } - } - function processValue(key, val, shouldStripQuotes) { - // strings may be quoted, clean this up as we assign values. - if (shouldStripQuotes) { - val = stripQuotes(val); - } - // handle parsing boolean arguments --foo=true --bar false. - if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { - if (typeof val === 'string') - val = val === 'true'; - } - let value = Array.isArray(val) - ? val.map(function (v) { return maybeCoerceNumber(key, v); }) - : maybeCoerceNumber(key, val); - // increment a count given as arg (either no value or value parsed as boolean) - if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { - value = increment(); - } - // Set normalized value when key is in 'normalize' and in 'arrays' - if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { - if (Array.isArray(val)) - value = val.map((val) => { return mixin.normalize(val); }); - else - value = mixin.normalize(val); - } - return value; - } - function maybeCoerceNumber(key, value) { - if (!configuration['parse-positional-numbers'] && key === '_') - return value; - if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { - const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); - if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { - value = Number(value); - } - } - return value; - } - // set args from config.json file, this should be - // applied last so that defaults can be applied. - function setConfig(argv) { - const configLookup = Object.create(null); - // expand defaults/aliases, in-case any happen to reference - // the config.json file. - applyDefaultsAndAliases(configLookup, flags.aliases, defaults); - Object.keys(flags.configs).forEach(function (configKey) { - const configPath = argv[configKey] || configLookup[configKey]; - if (configPath) { - try { - let config = null; - const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); - const resolveConfig = flags.configs[configKey]; - if (typeof resolveConfig === 'function') { - try { - config = resolveConfig(resolvedConfigPath); - } - catch (e) { - config = e; - } - if (config instanceof Error) { - error = config; - return; - } - } - else { - config = mixin.require(resolvedConfigPath); - } - setConfigObject(config); - } - catch (ex) { - // Deno will receive a PermissionDenied error if an attempt is - // made to load config without the --allow-read flag: - if (ex.name === 'PermissionDenied') - error = ex; - else if (argv[configKey]) - error = Error(__('Invalid JSON config file: %s', configPath)); - } - } - }); - } - // set args from config object. - // it recursively checks nested objects. - function setConfigObject(config, prev) { - Object.keys(config).forEach(function (key) { - const value = config[key]; - const fullKey = prev ? prev + '.' + key : key; - // if the value is an inner object and we have dot-notation - // enabled, treat inner objects in config the same as - // heavily nested dot notations (foo.bar.apple). - if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { - // if the value is an object but not an array, check nested object - setConfigObject(value, fullKey); - } - else { - // setting arguments via CLI takes precedence over - // values within the config file. - if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { - setArg(fullKey, value); - } - } - }); - } - // set all config objects passed in opts - function setConfigObjects() { - if (typeof configObjects !== 'undefined') { - configObjects.forEach(function (configObject) { - setConfigObject(configObject); - }); - } - } - function applyEnvVars(argv, configOnly) { - if (typeof envPrefix === 'undefined') - return; - const prefix = typeof envPrefix === 'string' ? envPrefix : ''; - const env = mixin.env(); - Object.keys(env).forEach(function (envVar) { - if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { - // get array of nested keys and convert them to camel case - const keys = envVar.split('__').map(function (key, i) { - if (i === 0) { - key = key.substring(prefix.length); - } - return camelCase(key); - }); - if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { - setArg(keys.join('.'), env[envVar]); - } - } - }); + }) + } + } + + var fs$writeFile = fs.writeFile; + fs.writeFile = writeFile; + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null; + + return go$writeFile(path, data, options, cb) + + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb === 'function') + cb.apply(this, arguments); } - function applyCoercions(argv) { - let coerce; - const applied = new Set(); - Object.keys(argv).forEach(function (key) { - if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases - coerce = checkAllAliases(key, flags.coercions); - if (typeof coerce === 'function') { - try { - const value = maybeCoerceNumber(key, coerce(argv[key])); - ([].concat(flags.aliases[key] || [], key)).forEach(ali => { - applied.add(ali); - argv[ali] = value; - }); - } - catch (err) { - error = err; - } - } - } - }); + }) + } + } + + var fs$appendFile = fs.appendFile; + if (fs$appendFile) + fs.appendFile = appendFile; + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null; + + return go$appendFile(path, data, options, cb) + + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb === 'function') + cb.apply(this, arguments); } - function setPlaceholderKeys(argv) { - flags.keys.forEach((key) => { - // don't set placeholder keys for dot notation options 'foo.bar'. - if (~key.indexOf('.')) - return; - if (typeof argv[key] === 'undefined') - argv[key] = undefined; - }); - return argv; + }) + } + } + + var fs$copyFile = fs.copyFile; + if (fs$copyFile) + fs.copyFile = copyFile; + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags; + flags = 0; + } + return go$copyFile(src, dest, flags, cb) + + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb === 'function') + cb.apply(this, arguments); } - function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { - Object.keys(defaults).forEach(function (key) { - if (!hasKey(obj, key.split('.'))) { - setKey(obj, key.split('.'), defaults[key]); - if (canLog) - defaulted[key] = true; - (aliases[key] || []).forEach(function (x) { - if (hasKey(obj, x.split('.'))) - return; - setKey(obj, x.split('.'), defaults[key]); - }); - } - }); + }) + } + } + + var fs$readdir = fs.readdir; + fs.readdir = readdir; + var noReaddirOptionVersions = /^v[0-5]\./; + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null; + + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + }; + + return go$readdir(path, options, cb) + + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]); + else { + if (files && files.sort) + files.sort(); + + if (typeof cb === 'function') + cb.call(this, err, files); } - function hasKey(obj, keys) { - let o = obj; - if (!configuration['dot-notation']) - keys = [keys.join('.')]; - keys.slice(0, -1).forEach(function (key) { - o = (o[key] || {}); - }); - const key = keys[keys.length - 1]; - if (typeof o !== 'object') - return false; - else - return key in o; - } - function setKey(obj, keys, value) { - let o = obj; - if (!configuration['dot-notation']) - keys = [keys.join('.')]; - keys.slice(0, -1).forEach(function (key) { - // TODO(bcoe): in the next major version of yargs, switch to - // Object.create(null) for dot notation: - key = sanitizeKey(key); - if (typeof o === 'object' && o[key] === undefined) { - o[key] = {}; - } - if (typeof o[key] !== 'object' || Array.isArray(o[key])) { - // ensure that o[key] is an array, and that the last item is an empty object. - if (Array.isArray(o[key])) { - o[key].push({}); - } - else { - o[key] = [o[key], {}]; - } - // we want to update the empty object at the end of the o[key] array, so set o to that object - o = o[key][o[key].length - 1]; - } - else { - o = o[key]; - } - }); - // TODO(bcoe): in the next major version of yargs, switch to - // Object.create(null) for dot notation: - const key = sanitizeKey(keys[keys.length - 1]); - const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); - const isValueArray = Array.isArray(value); - let duplicate = configuration['duplicate-arguments-array']; - // nargs has higher priority than duplicate - if (!duplicate && checkAllAliases(key, flags.nargs)) { - duplicate = true; - if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { - o[key] = undefined; - } - } - if (value === increment()) { - o[key] = increment(o[key]); - } - else if (Array.isArray(o[key])) { - if (duplicate && isTypeArray && isValueArray) { - o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); - } - else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { - o[key] = value; - } - else { - o[key] = o[key].concat([value]); - } - } - else if (o[key] === undefined && isTypeArray) { - o[key] = isValueArray ? value : [value]; - } - else if (duplicate && !(o[key] === undefined || - checkAllAliases(key, flags.counts) || - checkAllAliases(key, flags.bools))) { - o[key] = [o[key], value]; - } - else { - o[key] = value; - } - } - // extend the aliases list with inferred aliases. - function extendAliases(...args) { - args.forEach(function (obj) { - Object.keys(obj || {}).forEach(function (key) { - // short-circuit if we've already added a key - // to the aliases array, for example it might - // exist in both 'opts.default' and 'opts.key'. - if (flags.aliases[key]) - return; - flags.aliases[key] = [].concat(aliases[key] || []); - // For "--option-name", also set argv.optionName - flags.aliases[key].concat(key).forEach(function (x) { - if (/-/.test(x) && configuration['camel-case-expansion']) { - const c = camelCase(x); - if (c !== key && flags.aliases[key].indexOf(c) === -1) { - flags.aliases[key].push(c); - newAliases[c] = true; - } - } - }); - // For "--optionName", also set argv['option-name'] - flags.aliases[key].concat(key).forEach(function (x) { - if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { - const c = decamelize(x, '-'); - if (c !== key && flags.aliases[key].indexOf(c) === -1) { - flags.aliases[key].push(c); - newAliases[c] = true; - } - } - }); - flags.aliases[key].forEach(function (x) { - flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { - return x !== y; - })); - }); - }); - }); - } - function checkAllAliases(key, flag) { - const toCheck = [].concat(flags.aliases[key] || [], key); - const keys = Object.keys(flag); - const setAlias = toCheck.find(key => keys.includes(key)); - return setAlias ? flag[setAlias] : false; - } - function hasAnyFlag(key) { - const flagsKeys = Object.keys(flags); - const toCheck = [].concat(flagsKeys.map(k => flags[k])); - return toCheck.some(function (flag) { - return Array.isArray(flag) ? flag.includes(key) : flag[key]; - }); - } - function hasFlagsMatching(arg, ...patterns) { - const toCheck = [].concat(...patterns); - return toCheck.some(function (pattern) { - const match = arg.match(pattern); - return match && hasAnyFlag(match[1]); - }); - } - // based on a simplified version of the short flag group parsing logic - function hasAllShortFlags(arg) { - // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group - if (arg.match(negative) || !arg.match(/^-[^-]+/)) { - return false; - } - let hasAllFlags = true; - let next; - const letters = arg.slice(1).split(''); - for (let j = 0; j < letters.length; j++) { - next = arg.slice(j + 2); - if (!hasAnyFlag(letters[j])) { - hasAllFlags = false; - break; - } - if ((letters[j + 1] && letters[j + 1] === '=') || - next === '-' || - (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || - (letters[j + 1] && letters[j + 1].match(/\W/))) { - break; - } - } - return hasAllFlags; - } - function isUnknownOptionAsArg(arg) { - return configuration['unknown-options-as-args'] && isUnknownOption(arg); - } - function isUnknownOption(arg) { - arg = arg.replace(/^-{3,}/, '--'); - // ignore negative numbers - if (arg.match(negative)) { - return false; - } - // if this is a short option group and all of them are configured, it isn't unknown - if (hasAllShortFlags(arg)) { - return false; - } - // e.g. '--count=2' - const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; - // e.g. '-a' or '--arg' - const normalFlag = /^-+([^=]+?)$/; - // e.g. '-a-' - const flagEndingInHyphen = /^-+([^=]+?)-$/; - // e.g. '-abc123' - const flagEndingInDigits = /^-+([^=]+?\d+)$/; - // e.g. '-a/usr/local' - const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; - // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method - return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); - } - // make a best effort to pick a default value - // for an option based on name and type. - function defaultValue(key) { - if (!checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts) && - `${key}` in defaults) { - return defaults[key]; - } - else { - return defaultForType(guessType(key)); - } - } - // return a default value, given the type of a flag., - function defaultForType(type) { - const def = { - [DefaultValuesForTypeKey.BOOLEAN]: true, - [DefaultValuesForTypeKey.STRING]: '', - [DefaultValuesForTypeKey.NUMBER]: undefined, - [DefaultValuesForTypeKey.ARRAY]: [] - }; - return def[type]; - } - // given a flag, enforce a default type. - function guessType(key) { - let type = DefaultValuesForTypeKey.BOOLEAN; - if (checkAllAliases(key, flags.strings)) - type = DefaultValuesForTypeKey.STRING; - else if (checkAllAliases(key, flags.numbers)) - type = DefaultValuesForTypeKey.NUMBER; - else if (checkAllAliases(key, flags.bools)) - type = DefaultValuesForTypeKey.BOOLEAN; - else if (checkAllAliases(key, flags.arrays)) - type = DefaultValuesForTypeKey.ARRAY; - return type; - } - function isUndefined(num) { - return num === undefined; - } - // check user configuration settings for inconsistencies - function checkConfiguration() { - // count keys should not be set as array/narg - Object.keys(flags.counts).find(key => { - if (checkAllAliases(key, flags.arrays)) { - error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); - return true; - } - else if (checkAllAliases(key, flags.nargs)) { - error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); - return true; - } - return false; - }); - } - return { - aliases: Object.assign({}, flags.aliases), - argv: Object.assign(argvReturn, argv), - configuration: configuration, - defaulted: Object.assign({}, defaulted), - error: error, - newAliases: Object.assign({}, newAliases) - }; - } -} -// if any aliases reference each other, we should -// merge them together. -function combineAliases(aliases) { - const aliasArrays = []; - const combined = Object.create(null); - let change = true; - // turn alias lookup hash {key: ['alias1', 'alias2']} into - // a simple array ['key', 'alias1', 'alias2'] - Object.keys(aliases).forEach(function (key) { - aliasArrays.push([].concat(aliases[key], key)); - }); - // combine arrays until zero changes are - // made in an iteration. - while (change) { - change = false; - for (let i = 0; i < aliasArrays.length; i++) { - for (let ii = i + 1; ii < aliasArrays.length; ii++) { - const intersect = aliasArrays[i].filter(function (v) { - return aliasArrays[ii].indexOf(v) !== -1; - }); - if (intersect.length) { - aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); - aliasArrays.splice(ii, 1); - change = true; - break; - } - } + } + } + } + + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs); + ReadStream = legStreams.ReadStream; + WriteStream = legStreams.WriteStream; + } + + var fs$ReadStream = fs.ReadStream; + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype); + ReadStream.prototype.open = ReadStream$open; + } + + var fs$WriteStream = fs.WriteStream; + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype); + WriteStream.prototype.open = WriteStream$open; + } + + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val; + }, + enumerable: true, + configurable: true + }); + + // legacy names + var FileReadStream = ReadStream; + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val; + }, + enumerable: true, + configurable: true + }); + var FileWriteStream = WriteStream; + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val; + }, + enumerable: true, + configurable: true + }); + + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } + + function ReadStream$open () { + var that = this; + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy(); + + that.emit('error', err); + } else { + that.fd = fd; + that.emit('open', fd); + that.read(); + } + }); + } + + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } + + function WriteStream$open () { + var that = this; + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy(); + that.emit('error', err); + } else { + that.fd = fd; + that.emit('open', fd); + } + }); + } + + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } + + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + + var fs$open = fs.open; + fs.open = open; + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null; + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb === 'function') + cb.apply(this, arguments); } + }) } - // map arrays back to the hash-lookup (de-dupe while - // we're at it). - aliasArrays.forEach(function (aliasArray) { - aliasArray = aliasArray.filter(function (v, i, self) { - return self.indexOf(v) === i; - }); - const lastAlias = aliasArray.pop(); - if (lastAlias !== undefined && typeof lastAlias === 'string') { - combined[lastAlias] = aliasArray; - } - }); - return combined; -} -// this function should only be called when a count is given as an arg -// it is NOT called to set a default value -// thus we can start the count at 1 instead of 0 -function increment(orig) { - return orig !== undefined ? orig + 1 : 1; -} -// TODO(bcoe): in the next major version of yargs, switch to -// Object.create(null) for dot notation: -function sanitizeKey(key) { - if (key === '__proto__') - return '___proto___'; - return key; + } + + return fs } -function stripQuotes(val) { - return (typeof val === 'string' && - (val[0] === "'" || val[0] === '"') && - val[val.length - 1] === val[0]) - ? val.substring(1, val.length - 1) - : val; + +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]); + fs$v[gracefulQueue].push(elem); + retry(); } -/** - * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js - * CJS and ESM environments. - * - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -var _a, _b, _c$1; -// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our -// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only. -const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) - ? Number(process.env.YARGS_MIN_NODE_VERSION) - : 12; -const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c$1 = process === null || process === void 0 ? void 0 : process.version) === null || _c$1 === void 0 ? void 0 : _c$1.slice(1); -if (nodeVersion) { - const major = Number(nodeVersion.match(/^([^.]+)/)[1]); - if (major < minNodeVersion) { - throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); +// keep track of the timeout between retry() calls +var retryTimer; + +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now(); + for (var i = 0; i < fs$v[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs$v[gracefulQueue][i].length > 2) { + fs$v[gracefulQueue][i][3] = now; // startTime + fs$v[gracefulQueue][i][4] = now; // lastTime } + } + // call retry to make sure we're actively processing the queue + retry(); } -// Creates a yargs-parser instance using Node.js standard libraries: -const env$a = process ? process.env : {}; -const parser = new YargsParser({ - cwd: process.cwd, - env: () => { - return env$a; - }, - format, - normalize, - resolve, - // TODO: figure out a way to combine ESM and CJS coverage, such that - // we can exercise all the lines below: - require: (path) => { - if (typeof require !== 'undefined') { - return require(path); - } - else if (path.match(/\.json$/)) { - // Addresses: https://github.com/yargs/yargs/issues/2040 - return JSON.parse(readFileSync$1(path, 'utf8')); - } - else { - throw Error('only .json config files are supported in ESM'); - } - } -}); -const yargsParser = function Parser(args, opts) { - const result = parser.parse(args.slice(), opts); - return result.argv; -}; -yargsParser.detailed = function (args, opts) { - return parser.parse(args.slice(), opts); -}; -yargsParser.camelCase = camelCase; -yargsParser.decamelize = decamelize; -yargsParser.looksLikeNumber = looksLikeNumber; -function getProcessArgvBinIndex() { - if (isBundledElectronApp()) - return 0; - return 1; -} -function isBundledElectronApp() { - return isElectronApp() && !process.defaultApp; -} -function isElectronApp() { - return !!process.versions.electron; -} -function hideBin(argv) { - return argv.slice(getProcessArgvBinIndex() + 1); -} -function getProcessArgvBin() { - return process.argv[getProcessArgvBinIndex()]; -} +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer); + retryTimer = undefined; -class YError extends Error { - constructor(msg) { - super(msg || 'yargs error'); - this.name = 'YError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, YError); - } + if (fs$v[gracefulQueue].length === 0) + return + + var elem = fs$v[gracefulQueue].shift(); + var fn = elem[0]; + var args = elem[1]; + // these items may be unset if they were added by an older graceful-fs + var err = elem[2]; + var startTime = elem[3]; + var lastTime = elem[4]; + + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args); + fn.apply(null, args); + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args); + var cb = args.pop(); + if (typeof cb === 'function') + cb.call(null, err); + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime; + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1); + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100); + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args); + fn.apply(null, args.concat([startTime])); + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs$v[gracefulQueue].push(elem); } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0); + } } -var shim$3 = { - fs: { - readFileSync: readFileSync$1, - writeFile: writeFile$1 - }, - format, - resolve, - exists: (file) => { - try { - return statSync(file).isFile(); - } - catch (err) { - return false; - } - } -}; +(function (exports) { + // This is adapted from https://github.com/normalize/mz + // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors + const u = universalify$1.fromCallback; + const fs = gracefulFs; -let shim$2; -class Y18N { - constructor(opts) { - // configurable options. - opts = opts || {}; - this.directory = opts.directory || './locales'; - this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true; - this.locale = opts.locale || 'en'; - this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true; - // internal stuff. - this.cache = Object.create(null); - this.writeQueue = []; - } - __(...args) { - if (typeof arguments[0] !== 'string') { - return this._taggedLiteral(arguments[0], ...arguments); - } - const str = args.shift(); - let cb = function () { }; // start with noop. - if (typeof args[args.length - 1] === 'function') - cb = args.pop(); - cb = cb || function () { }; // noop. - if (!this.cache[this.locale]) - this._readLocaleFile(); - // we've observed a new string, update the language file. - if (!this.cache[this.locale][str] && this.updateFiles) { - this.cache[this.locale][str] = str; - // include the current directory and locale, - // since these values could change before the - // write is performed. - this._enqueueWrite({ - directory: this.directory, - locale: this.locale, - cb - }); - } - else { - cb(); - } - return shim$2.format.apply(shim$2.format, [this.cache[this.locale][str] || str].concat(args)); - } - __n() { - const args = Array.prototype.slice.call(arguments); - const singular = args.shift(); - const plural = args.shift(); - const quantity = args.shift(); - let cb = function () { }; // start with noop. - if (typeof args[args.length - 1] === 'function') - cb = args.pop(); - if (!this.cache[this.locale]) - this._readLocaleFile(); - let str = quantity === 1 ? singular : plural; - if (this.cache[this.locale][singular]) { - const entry = this.cache[this.locale][singular]; - str = entry[quantity === 1 ? 'one' : 'other']; - } - // we've observed a new string, update the language file. - if (!this.cache[this.locale][singular] && this.updateFiles) { - this.cache[this.locale][singular] = { - one: singular, - other: plural - }; - // include the current directory and locale, - // since these values could change before the - // write is performed. - this._enqueueWrite({ - directory: this.directory, - locale: this.locale, - cb - }); - } - else { - cb(); - } - // if a %d placeholder is provided, add quantity - // to the arguments expanded by util.format. - const values = [str]; - if (~str.indexOf('%d')) - values.push(quantity); - return shim$2.format.apply(shim$2.format, values.concat(args)); - } - setLocale(locale) { - this.locale = locale; - } - getLocale() { - return this.locale; - } - updateLocale(obj) { - if (!this.cache[this.locale]) - this._readLocaleFile(); - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - this.cache[this.locale][key] = obj[key]; - } - } - } - _taggedLiteral(parts, ...args) { - let str = ''; - parts.forEach(function (part, i) { - const arg = args[i + 1]; - str += part; - if (typeof arg !== 'undefined') { - str += '%s'; - } - }); - return this.__.apply(this, [str].concat([].slice.call(args, 1))); - } - _enqueueWrite(work) { - this.writeQueue.push(work); - if (this.writeQueue.length === 1) - this._processWriteQueue(); - } - _processWriteQueue() { - const _this = this; - const work = this.writeQueue[0]; - // destructure the enqueued work. - const directory = work.directory; - const locale = work.locale; - const cb = work.cb; - const languageFile = this._resolveLocaleFile(directory, locale); - const serializedLocale = JSON.stringify(this.cache[locale], null, 2); - shim$2.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { - _this.writeQueue.shift(); - if (_this.writeQueue.length > 0) - _this._processWriteQueue(); - cb(err); - }); - } - _readLocaleFile() { - let localeLookup = {}; - const languageFile = this._resolveLocaleFile(this.directory, this.locale); - try { - // When using a bundler such as webpack, readFileSync may not be defined: - if (shim$2.fs.readFileSync) { - localeLookup = JSON.parse(shim$2.fs.readFileSync(languageFile, 'utf-8')); - } - } - catch (err) { - if (err instanceof SyntaxError) { - err.message = 'syntax error in ' + languageFile; - } - if (err.code === 'ENOENT') - localeLookup = {}; - else - throw err; - } - this.cache[this.locale] = localeLookup; - } - _resolveLocaleFile(directory, locale) { - let file = shim$2.resolve(directory, './', locale + '.json'); - if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { - // attempt fallback to language only - const languageFile = shim$2.resolve(directory, './', locale.split('_')[0] + '.json'); - if (this._fileExistsSync(languageFile)) - file = languageFile; - } - return file; - } - _fileExistsSync(file) { - return shim$2.exists(file); + const api = [ + 'access', + 'appendFile', + 'chmod', + 'chown', + 'close', + 'copyFile', + 'fchmod', + 'fchown', + 'fdatasync', + 'fstat', + 'fsync', + 'ftruncate', + 'futimes', + 'lchmod', + 'lchown', + 'link', + 'lstat', + 'mkdir', + 'mkdtemp', + 'open', + 'opendir', + 'readdir', + 'readFile', + 'readlink', + 'realpath', + 'rename', + 'rm', + 'rmdir', + 'stat', + 'symlink', + 'truncate', + 'unlink', + 'utimes', + 'writeFile' + ].filter(key => { + // Some commands are not available on some systems. Ex: + // fs.cp was added in Node.js v16.7.0 + // fs.lchown is not available on at least some Linux + return typeof fs[key] === 'function' + }); + + // Export cloned fs: + Object.assign(exports, fs); + + // Universalify async methods: + api.forEach(method => { + exports[method] = u(fs[method]); + }); + + // We differ from mz/fs in that we still ship the old, broken, fs.exists() + // since we are a drop-in replacement for the native module + exports.exists = function (filename, callback) { + if (typeof callback === 'function') { + return fs.exists(filename, callback) + } + return new Promise(resolve => { + return fs.exists(filename, resolve) + }) + }; + + // fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args + + exports.read = function (fd, buffer, offset, length, position, callback) { + if (typeof callback === 'function') { + return fs.read(fd, buffer, offset, length, position, callback) + } + return new Promise((resolve, reject) => { + fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { + if (err) return reject(err) + resolve({ bytesRead, buffer }); + }); + }) + }; + + // Function signature can be + // fs.write(fd, buffer[, offset[, length[, position]]], callback) + // OR + // fs.write(fd, string[, position[, encoding]], callback) + // We need to handle both cases, so we use ...args + exports.write = function (fd, buffer, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.write(fd, buffer, ...args) + } + + return new Promise((resolve, reject) => { + fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { + if (err) return reject(err) + resolve({ bytesWritten, buffer }); + }); + }) + }; + + // Function signature is + // s.readv(fd, buffers[, position], callback) + // We need to handle the optional arg, so we use ...args + exports.readv = function (fd, buffers, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.readv(fd, buffers, ...args) + } + + return new Promise((resolve, reject) => { + fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => { + if (err) return reject(err) + resolve({ bytesRead, buffers }); + }); + }) + }; + + // Function signature is + // s.writev(fd, buffers[, position], callback) + // We need to handle the optional arg, so we use ...args + exports.writev = function (fd, buffers, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.writev(fd, buffers, ...args) + } + + return new Promise((resolve, reject) => { + fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { + if (err) return reject(err) + resolve({ bytesWritten, buffers }); + }); + }) + }; + + // fs.realpath.native sometimes not available if fs is monkey-patched + if (typeof fs.realpath.native === 'function') { + exports.realpath.native = u(fs.realpath.native); + } else { + process.emitWarning( + 'fs.realpath.native is not a function. Is fs being monkey-patched?', + 'Warning', 'fs-extra-WARN0003' + ); + } +} (fs$w)); + +var makeDir$1 = {}; + +var utils$1 = {}; + +const path$j = require$$1$1; + +// https://github.com/nodejs/node/issues/8987 +// https://github.com/libuv/libuv/pull/1088 +utils$1.checkPath = function checkPath (pth) { + if (process.platform === 'win32') { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path$j.parse(pth).root, '')); + + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`); + error.code = 'EINVAL'; + throw error } -} -function y18n$1(opts, _shim) { - shim$2 = _shim; - const y18n = new Y18N(opts); - return { - __: y18n.__.bind(y18n), - __n: y18n.__n.bind(y18n), - setLocale: y18n.setLocale.bind(y18n), - getLocale: y18n.getLocale.bind(y18n), - updateLocale: y18n.updateLocale.bind(y18n), - locale: y18n.locale - }; -} + } +}; -const y18n = (opts) => { - return y18n$1(opts, shim$3) +const fs$u = fs$w; +const { checkPath } = utils$1; + +const getMode = options => { + const defaults = { mode: 0o777 }; + if (typeof options === 'number') return options + return ({ ...defaults, ...options }).mode }; -const REQUIRE_ERROR = 'require is not supported by ESM'; -const REQUIRE_DIRECTORY_ERROR = 'loading a directory of commands is not supported yet for ESM'; +makeDir$1.makeDir = async (dir, options) => { + checkPath(dir); -let __dirname; -try { - __dirname = fileURLToPath(import.meta.url); -} catch (e) { - __dirname = process.cwd(); -} -const mainFilename = __dirname.substring(0, __dirname.lastIndexOf('node_modules')); + return fs$u.mkdir(dir, { + mode: getMode(options), + recursive: true + }) +}; -var shim$1 = { - assert: { - notStrictEqual, - strictEqual - }, - cliui: ui, - findUp: escalade, - getEnv: (key) => { - return process.env[key] - }, - inspect, - getCallerFile: () => { - throw new YError(REQUIRE_DIRECTORY_ERROR) - }, - getProcessArgvBin, - mainFilename: mainFilename || process.cwd(), - Parser: yargsParser, - path: { - basename, - dirname, - extname, - relative, - resolve - }, - process: { - argv: () => process.argv, - cwd: process.cwd, - emitWarning: (warning, type) => process.emitWarning(warning, type), - execPath: () => process.execPath, - exit: process.exit, - nextTick: process.nextTick, - stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null - }, - readFileSync: readFileSync$1, - require: () => { - throw new YError(REQUIRE_ERROR) - }, - requireDirectory: () => { - throw new YError(REQUIRE_DIRECTORY_ERROR) - }, - stringWidth: (str) => { - return [...str].length - }, - y18n: y18n({ - directory: resolve(__dirname, '../../../locales'), - updateFiles: false +makeDir$1.makeDirSync = (dir, options) => { + checkPath(dir); + + return fs$u.mkdirSync(dir, { + mode: getMode(options), + recursive: true }) }; -function assertNotStrictEqual(actual, expected, shim, message) { - shim.assert.notStrictEqual(actual, expected, message); -} -function assertSingleKey(actual, shim) { - shim.assert.strictEqual(typeof actual, 'string'); -} -function objectKeys(object) { - return Object.keys(object); -} +const u$e = universalify$1.fromPromise; +const { makeDir: _makeDir, makeDirSync } = makeDir$1; +const makeDir = u$e(_makeDir); -function isPromise(maybePromise) { - return (!!maybePromise && - !!maybePromise.then && - typeof maybePromise.then === 'function'); -} +var mkdirs$2 = { + mkdirs: makeDir, + mkdirsSync: makeDirSync, + // alias + mkdirp: makeDir, + mkdirpSync: makeDirSync, + ensureDir: makeDir, + ensureDirSync: makeDirSync +}; -function parseCommand(cmd) { - const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' '); - const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/); - const bregex = /\.*[\][<>]/g; - const firstCommand = splitCommand.shift(); - if (!firstCommand) - throw new Error(`No command found in: ${cmd}`); - const parsedCommand = { - cmd: firstCommand.replace(bregex, ''), - demanded: [], - optional: [], - }; - splitCommand.forEach((cmd, i) => { - let variadic = false; - cmd = cmd.replace(/\s/g, ''); - if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) - variadic = true; - if (/^\[/.test(cmd)) { - parsedCommand.optional.push({ - cmd: cmd.replace(bregex, '').split('|'), - variadic, - }); - } - else { - parsedCommand.demanded.push({ - cmd: cmd.replace(bregex, '').split('|'), - variadic, - }); - } - }); - return parsedCommand; +const u$d = universalify$1.fromPromise; +const fs$t = fs$w; + +function pathExists$6 (path) { + return fs$t.access(path).then(() => true).catch(() => false) } -const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']; -function argsert(arg1, arg2, arg3) { - function parseArgs() { - return typeof arg1 === 'object' - ? [{ demanded: [], optional: [] }, arg1, arg2] - : [ - parseCommand(`cmd ${arg1}`), - arg2, - arg3, - ]; - } +var pathExists_1 = { + pathExists: u$d(pathExists$6), + pathExistsSync: fs$t.existsSync +}; + +const fs$s = fs$w; +const u$c = universalify$1.fromPromise; + +async function utimesMillis$1 (path, atime, mtime) { + // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) + const fd = await fs$s.open(path, 'r+'); + + let closeErr = null; + + try { + await fs$s.futimes(fd, atime, mtime); + } finally { try { - let position = 0; - const [parsed, callerArguments, _length] = parseArgs(); - const args = [].slice.call(callerArguments); - while (args.length && args[args.length - 1] === undefined) - args.pop(); - const length = _length || args.length; - if (length < parsed.demanded.length) { - throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`); - } - const totalCommands = parsed.demanded.length + parsed.optional.length; - if (length > totalCommands) { - throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`); - } - parsed.demanded.forEach(demanded => { - const arg = args.shift(); - const observedType = guessType(arg); - const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*'); - if (matchingTypes.length === 0) - argumentTypeError(observedType, demanded.cmd, position); - position += 1; - }); - parsed.optional.forEach(optional => { - if (args.length === 0) - return; - const arg = args.shift(); - const observedType = guessType(arg); - const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*'); - if (matchingTypes.length === 0) - argumentTypeError(observedType, optional.cmd, position); - position += 1; - }); - } - catch (err) { - console.warn(err.stack); - } -} -function guessType(arg) { - if (Array.isArray(arg)) { - return 'array'; - } - else if (arg === null) { - return 'null'; + await fs$s.close(fd); + } catch (e) { + closeErr = e; } - return typeof arg; + } + + if (closeErr) { + throw closeErr + } } -function argumentTypeError(observedType, allowedTypes, position) { - throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`); + +function utimesMillisSync$1 (path, atime, mtime) { + const fd = fs$s.openSync(path, 'r+'); + fs$s.futimesSync(fd, atime, mtime); + return fs$s.closeSync(fd) } -class GlobalMiddleware { - constructor(yargs) { - this.globalMiddleware = []; - this.frozens = []; - this.yargs = yargs; - } - addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) { - argsert(' [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length); - if (Array.isArray(callback)) { - for (let i = 0; i < callback.length; i++) { - if (typeof callback[i] !== 'function') { - throw Error('middleware must be a function'); - } - const m = callback[i]; - m.applyBeforeValidation = applyBeforeValidation; - m.global = global; - } - Array.prototype.push.apply(this.globalMiddleware, callback); - } - else if (typeof callback === 'function') { - const m = callback; - m.applyBeforeValidation = applyBeforeValidation; - m.global = global; - m.mutates = mutates; - this.globalMiddleware.push(callback); - } - return this.yargs; +var utimes = { + utimesMillis: u$c(utimesMillis$1), + utimesMillisSync: utimesMillisSync$1 +}; + +const fs$r = fs$w; +const path$i = require$$1$1; +const u$b = universalify$1.fromPromise; + +function getStats$1 (src, dest, opts) { + const statFunc = opts.dereference + ? (file) => fs$r.stat(file, { bigint: true }) + : (file) => fs$r.lstat(file, { bigint: true }); + return Promise.all([ + statFunc(src), + statFunc(dest).catch(err => { + if (err.code === 'ENOENT') return null + throw err + }) + ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) +} + +function getStatsSync (src, dest, opts) { + let destStat; + const statFunc = opts.dereference + ? (file) => fs$r.statSync(file, { bigint: true }) + : (file) => fs$r.lstatSync(file, { bigint: true }); + const srcStat = statFunc(src); + try { + destStat = statFunc(dest); + } catch (err) { + if (err.code === 'ENOENT') return { srcStat, destStat: null } + throw err + } + return { srcStat, destStat } +} + +async function checkPaths (src, dest, funcName, opts) { + const { srcStat, destStat } = await getStats$1(src, dest, opts); + if (destStat) { + if (areIdentical$2(srcStat, destStat)) { + const srcBaseName = path$i.basename(src); + const destBaseName = path$i.basename(dest); + if (funcName === 'move' && + srcBaseName !== destBaseName && + srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { + return { srcStat, destStat, isChangingCase: true } + } + throw new Error('Source and destination must not be the same.') } - addCoerceMiddleware(callback, option) { - const aliases = this.yargs.getAliases(); - this.globalMiddleware = this.globalMiddleware.filter(m => { - const toCheck = [...(aliases[option] || []), option]; - if (!m.option) - return true; - else - return !toCheck.includes(m.option); - }); - callback.option = option; - return this.addMiddleware(callback, true, true, true); + if (srcStat.isDirectory() && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } - getMiddleware() { - return this.globalMiddleware; + if (!srcStat.isDirectory() && destStat.isDirectory()) { + throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) } - freeze() { - this.frozens.push([...this.globalMiddleware]); + } + + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + throw new Error(errMsg(src, dest, funcName)) + } + + return { srcStat, destStat } +} + +function checkPathsSync (src, dest, funcName, opts) { + const { srcStat, destStat } = getStatsSync(src, dest, opts); + + if (destStat) { + if (areIdentical$2(srcStat, destStat)) { + const srcBaseName = path$i.basename(src); + const destBaseName = path$i.basename(dest); + if (funcName === 'move' && + srcBaseName !== destBaseName && + srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { + return { srcStat, destStat, isChangingCase: true } + } + throw new Error('Source and destination must not be the same.') } - unfreeze() { - const frozen = this.frozens.pop(); - if (frozen !== undefined) - this.globalMiddleware = frozen; + if (srcStat.isDirectory() && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } - reset() { - this.globalMiddleware = this.globalMiddleware.filter(m => m.global); + if (!srcStat.isDirectory() && destStat.isDirectory()) { + throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) } + } + + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + throw new Error(errMsg(src, dest, funcName)) + } + return { srcStat, destStat } } -function commandMiddlewareFactory(commandMiddleware) { - if (!commandMiddleware) - return []; - return commandMiddleware.map(middleware => { - middleware.applyBeforeValidation = false; - return middleware; - }); + +// 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, funcName) { + const srcParent = path$i.resolve(path$i.dirname(src)); + const destParent = path$i.resolve(path$i.dirname(dest)); + if (destParent === srcParent || destParent === path$i.parse(destParent).root) return + + let destStat; + try { + destStat = await fs$r.stat(destParent, { bigint: true }); + } catch (err) { + if (err.code === 'ENOENT') return + throw err + } + + if (areIdentical$2(srcStat, destStat)) { + throw new Error(errMsg(src, dest, funcName)) + } + + return checkParentPaths(src, srcStat, destParent, funcName) } -function applyMiddleware(argv, yargs, middlewares, beforeValidation) { - return middlewares.reduce((acc, middleware) => { - if (middleware.applyBeforeValidation !== beforeValidation) { - return acc; - } - if (middleware.mutates) { - if (middleware.applied) - return acc; - middleware.applied = true; - } - if (isPromise(acc)) { - return acc - .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)])) - .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj)); - } - else { - const result = middleware(acc, yargs); - return isPromise(result) - ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) - : Object.assign(acc, result); - } - }, argv); + +function checkParentPathsSync (src, srcStat, dest, funcName) { + const srcParent = path$i.resolve(path$i.dirname(src)); + const destParent = path$i.resolve(path$i.dirname(dest)); + if (destParent === srcParent || destParent === path$i.parse(destParent).root) return + let destStat; + try { + destStat = fs$r.statSync(destParent, { bigint: true }); + } catch (err) { + if (err.code === 'ENOENT') return + throw err + } + if (areIdentical$2(srcStat, destStat)) { + throw new Error(errMsg(src, dest, funcName)) + } + return checkParentPathsSync(src, srcStat, destParent, funcName) } -function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => { - throw err; -}) { - try { - const result = isFunction$1(getResult) ? getResult() : getResult; - return isPromise(result) - ? result.then((result) => resultHandler(result)) - : resultHandler(result); - } - catch (err) { - return errorHandler(err); - } +function areIdentical$2 (srcStat, destStat) { + return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev } -function isFunction$1(arg) { - return typeof arg === 'function'; + +// return true if dest is a subdir of src, otherwise false. +// It only checks the path strings. +function isSrcSubdir (src, dest) { + const srcArr = path$i.resolve(src).split(path$i.sep).filter(i => i); + const destArr = path$i.resolve(dest).split(path$i.sep).filter(i => i); + return srcArr.every((cur, i) => destArr[i] === cur) } -function whichModule(exported) { - if (typeof require === 'undefined') - return null; - for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) { - mod = require.cache[files[i]]; - if (mod.exports === exported) - return mod; - } - return null; +function errMsg (src, dest, funcName) { + return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` } -const DEFAULT_MARKER = /(^\*)|(^\$0)/; -class CommandInstance { - constructor(usage, validation, globalMiddleware, shim) { - this.requireCache = new Set(); - this.handlers = {}; - this.aliasMap = {}; - this.frozens = []; - this.shim = shim; - this.usage = usage; - this.globalMiddleware = globalMiddleware; - this.validation = validation; - } - addDirectory(dir, req, callerFile, opts) { - opts = opts || {}; - if (typeof opts.recurse !== 'boolean') - opts.recurse = false; - if (!Array.isArray(opts.extensions)) - opts.extensions = ['js']; - const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o; - opts.visit = (obj, joined, filename) => { - const visited = parentVisit(obj, joined, filename); - if (visited) { - if (this.requireCache.has(joined)) - return visited; - else - this.requireCache.add(joined); - this.addHandler(visited); - } - return visited; - }; - this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts); - } - addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) { - let aliases = []; - const middlewares = commandMiddlewareFactory(commandMiddleware); - handler = handler || (() => { }); - if (Array.isArray(cmd)) { - if (isCommandAndAliases(cmd)) { - [cmd, ...aliases] = cmd; - } - else { - for (const command of cmd) { - this.addHandler(command); - } - } - } - else if (isCommandHandlerDefinition(cmd)) { - let command = Array.isArray(cmd.command) || typeof cmd.command === 'string' - ? cmd.command - : this.moduleName(cmd); - if (cmd.aliases) - command = [].concat(command).concat(cmd.aliases); - this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated); - return; - } - else if (isCommandBuilderDefinition(builder)) { - this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated); - return; - } - if (typeof cmd === 'string') { - const parsedCommand = parseCommand(cmd); - aliases = aliases.map(alias => parseCommand(alias).cmd); - let isDefault = false; - const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => { - if (DEFAULT_MARKER.test(c)) { - isDefault = true; - return false; - } - return true; - }); - if (parsedAliases.length === 0 && isDefault) - parsedAliases.push('$0'); - if (isDefault) { - parsedCommand.cmd = parsedAliases[0]; - aliases = parsedAliases.slice(1); - cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd); - } - aliases.forEach(alias => { - this.aliasMap[alias] = parsedCommand.cmd; - }); - if (description !== false) { - this.usage.command(cmd, description, isDefault, aliases, deprecated); - } - this.handlers[parsedCommand.cmd] = { - original: cmd, - description, - handler, - builder: builder || {}, - middlewares, - deprecated, - demanded: parsedCommand.demanded, - optional: parsedCommand.optional, - }; - if (isDefault) - this.defaultCommand = this.handlers[parsedCommand.cmd]; - } - } - getCommandHandlers() { - return this.handlers; - } - getCommands() { - return Object.keys(this.handlers).concat(Object.keys(this.aliasMap)); - } - hasDefaultCommand() { - return !!this.defaultCommand; - } - runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) { - const commandHandler = this.handlers[command] || - this.handlers[this.aliasMap[command]] || - this.defaultCommand; - const currentContext = yargs.getInternalMethods().getContext(); - const parentCommands = currentContext.commands.slice(); - const isDefaultCommand = !command; - if (command) { - currentContext.commands.push(command); - currentContext.fullCommands.push(commandHandler.original); - } - const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet); - return isPromise(builderResult) - ? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) - : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs); - } - applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) { - const builder = commandHandler.builder; - let innerYargs = yargs; - if (isCommandBuilderCallback(builder)) { - yargs.getInternalMethods().getUsageInstance().freeze(); - const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet); - if (isPromise(builderOutput)) { - return builderOutput.then(output => { - innerYargs = isYargsInstance(output) ? output : yargs; - return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); - }); - } - } - else if (isCommandBuilderOptionDefinitions(builder)) { - yargs.getInternalMethods().getUsageInstance().freeze(); - innerYargs = yargs.getInternalMethods().reset(aliases); - Object.keys(commandHandler.builder).forEach(key => { - innerYargs.option(key, builder[key]); - }); - } - return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); - } - parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) { - if (isDefaultCommand) - innerYargs.getInternalMethods().getUsageInstance().unfreeze(true); - if (this.shouldUpdateUsage(innerYargs)) { - innerYargs - .getInternalMethods() - .getUsageInstance() - .usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); - } - const innerArgv = innerYargs - .getInternalMethods() - .runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly); - return isPromise(innerArgv) - ? innerArgv.then(argv => ({ - aliases: innerYargs.parsed.aliases, - innerArgv: argv, - })) - : { - aliases: innerYargs.parsed.aliases, - innerArgv: innerArgv, - }; - } - shouldUpdateUsage(yargs) { - return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && - yargs.getInternalMethods().getUsageInstance().getUsage().length === 0); - } - usageFromParentCommandsCommandHandler(parentCommands, commandHandler) { - const c = DEFAULT_MARKER.test(commandHandler.original) - ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() - : commandHandler.original; - const pc = parentCommands.filter(c => { - return !DEFAULT_MARKER.test(c); - }); - pc.push(c); - return `$0 ${pc.join(' ')}`; - } - handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) { - if (!yargs.getInternalMethods().getHasOutput()) { - const validation = yargs - .getInternalMethods() - .runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand); - innerArgv = maybeAsyncResult(innerArgv, result => { - validation(result); - return result; - }); - } - if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) { - yargs.getInternalMethods().setHasOutput(); - const populateDoubleDash = !!yargs.getOptions().configuration['populate--']; - yargs - .getInternalMethods() - .postProcess(innerArgv, populateDoubleDash, false, false); - innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false); - innerArgv = maybeAsyncResult(innerArgv, result => { - const handlerResult = commandHandler.handler(result); - return isPromise(handlerResult) - ? handlerResult.then(() => result) - : result; - }); - if (!isDefaultCommand) { - yargs.getInternalMethods().getUsageInstance().cacheHelpMessage(); - } - if (isPromise(innerArgv) && - !yargs.getInternalMethods().hasParseCallback()) { - innerArgv.catch(error => { - try { - yargs.getInternalMethods().getUsageInstance().fail(null, error); - } - catch (_err) { - } - }); - } - } - if (!isDefaultCommand) { - currentContext.commands.pop(); - currentContext.fullCommands.pop(); - } - return innerArgv; - } - applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) { - let positionalMap = {}; - if (helpOnly) - return innerArgv; - if (!yargs.getInternalMethods().getHasOutput()) { - positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs); - } - const middlewares = this.globalMiddleware - .getMiddleware() - .slice(0) - .concat(commandHandler.middlewares); - const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true); - return isPromise(maybePromiseArgv) - ? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) - : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap); - } - populatePositionals(commandHandler, argv, context, yargs) { - argv._ = argv._.slice(context.commands.length); - const demanded = commandHandler.demanded.slice(0); - const optional = commandHandler.optional.slice(0); - const positionalMap = {}; - this.validation.positionalCount(demanded.length, argv._.length); - while (demanded.length) { - const demand = demanded.shift(); - this.populatePositional(demand, argv, positionalMap); - } - while (optional.length) { - const maybe = optional.shift(); - this.populatePositional(maybe, argv, positionalMap); - } - argv._ = context.commands.concat(argv._.map(a => '' + a)); - this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs); - return positionalMap; - } - populatePositional(positional, argv, positionalMap) { - const cmd = positional.cmd[0]; - if (positional.variadic) { - positionalMap[cmd] = argv._.splice(0).map(String); - } - else { - if (argv._.length) - positionalMap[cmd] = [String(argv._.shift())]; - } - } - cmdToParseOptions(cmdString) { - const parseOptions = { - array: [], - default: {}, - alias: {}, - demand: {}, - }; - const parsed = parseCommand(cmdString); - parsed.demanded.forEach(d => { - const [cmd, ...aliases] = d.cmd; - if (d.variadic) { - parseOptions.array.push(cmd); - parseOptions.default[cmd] = []; - } - parseOptions.alias[cmd] = aliases; - parseOptions.demand[cmd] = true; - }); - parsed.optional.forEach(o => { - const [cmd, ...aliases] = o.cmd; - if (o.variadic) { - parseOptions.array.push(cmd); - parseOptions.default[cmd] = []; - } - parseOptions.alias[cmd] = aliases; - }); - return parseOptions; - } - postProcessPositionals(argv, positionalMap, parseOptions, yargs) { - const options = Object.assign({}, yargs.getOptions()); - options.default = Object.assign(parseOptions.default, options.default); - for (const key of Object.keys(parseOptions.alias)) { - options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]); - } - options.array = options.array.concat(parseOptions.array); - options.config = {}; - const unparsed = []; - Object.keys(positionalMap).forEach(key => { - positionalMap[key].map(value => { - if (options.configuration['unknown-options-as-args']) - options.key[key] = true; - unparsed.push(`--${key}`); - unparsed.push(value); - }); - }); - if (!unparsed.length) - return; - const config = Object.assign({}, options.configuration, { - 'populate--': false, - }); - const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, { - configuration: config, - })); - if (parsed.error) { - yargs - .getInternalMethods() - .getUsageInstance() - .fail(parsed.error.message, parsed.error); - } - else { - const positionalKeys = Object.keys(positionalMap); - Object.keys(positionalMap).forEach(key => { - positionalKeys.push(...parsed.aliases[key]); - }); - Object.keys(parsed.argv).forEach(key => { - if (positionalKeys.includes(key)) { - if (!positionalMap[key]) - positionalMap[key] = parsed.argv[key]; - if (!this.isInConfigs(yargs, key) && - !this.isDefaulted(yargs, key) && - Object.prototype.hasOwnProperty.call(argv, key) && - Object.prototype.hasOwnProperty.call(parsed.argv, key) && - (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) { - argv[key] = [].concat(argv[key], parsed.argv[key]); - } - else { - argv[key] = parsed.argv[key]; - } - } - }); - } - } - isDefaulted(yargs, key) { - const { default: defaults } = yargs.getOptions(); - return (Object.prototype.hasOwnProperty.call(defaults, key) || - Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key))); - } - isInConfigs(yargs, key) { - const { configObjects } = yargs.getOptions(); - return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) || - configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)))); - } - runDefaultBuilderOn(yargs) { - if (!this.defaultCommand) - return; - if (this.shouldUpdateUsage(yargs)) { - const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) - ? this.defaultCommand.original - : this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 '); - yargs - .getInternalMethods() - .getUsageInstance() - .usage(commandString, this.defaultCommand.description); - } - const builder = this.defaultCommand.builder; - if (isCommandBuilderCallback(builder)) { - return builder(yargs, true); - } - else if (!isCommandBuilderDefinition(builder)) { - Object.keys(builder).forEach(key => { - yargs.option(key, builder[key]); - }); - } - return undefined; - } - moduleName(obj) { - const mod = whichModule(obj); - if (!mod) - throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`); - return this.commandFromFilename(mod.filename); - } - commandFromFilename(filename) { - return this.shim.path.basename(filename, this.shim.path.extname(filename)); - } - extractDesc({ describe, description, desc }) { - for (const test of [describe, description, desc]) { - if (typeof test === 'string' || test === false) - return test; - assertNotStrictEqual(test, true, this.shim); - } - return false; - } - freeze() { - this.frozens.push({ - handlers: this.handlers, - aliasMap: this.aliasMap, - defaultCommand: this.defaultCommand, - }); - } - unfreeze() { - const frozen = this.frozens.pop(); - assertNotStrictEqual(frozen, undefined, this.shim); - ({ - handlers: this.handlers, - aliasMap: this.aliasMap, - defaultCommand: this.defaultCommand, - } = frozen); - } - reset() { - this.handlers = {}; - this.aliasMap = {}; - this.defaultCommand = undefined; - this.requireCache = new Set(); - return this; +var stat$4 = { + // checkPaths + checkPaths: u$b(checkPaths), + checkPathsSync, + // checkParent + checkParentPaths: u$b(checkParentPaths), + checkParentPathsSync, + // Misc + isSrcSubdir, + areIdentical: areIdentical$2 +}; + +const fs$q = fs$w; +const path$h = require$$1$1; +const { mkdirs: mkdirs$1 } = mkdirs$2; +const { pathExists: pathExists$5 } = pathExists_1; +const { utimesMillis } = utimes; +const stat$3 = stat$4; + +async function copy$2 (src, dest, opts = {}) { + if (typeof opts === 'function') { + opts = { filter: opts }; + } + + opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber + + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + process.emitWarning( + 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', + 'Warning', 'fs-extra-WARN0001' + ); + } + + const { srcStat, destStat } = await stat$3.checkPaths(src, dest, 'copy', opts); + + await stat$3.checkParentPaths(src, srcStat, dest, 'copy'); + + const include = await runFilter(src, dest, opts); + + if (!include) return + + // check if the parent of dest exists, and create it if it doesn't exist + const destParent = path$h.dirname(dest); + const dirExists = await pathExists$5(destParent); + if (!dirExists) { + await mkdirs$1(destParent); + } + + await getStatsAndPerformCopy(destStat, src, dest, opts); +} + +async function runFilter (src, dest, opts) { + if (!opts.filter) return true + return opts.filter(src, dest) +} + +async function getStatsAndPerformCopy (destStat, src, dest, opts) { + const statFn = opts.dereference ? fs$q.stat : fs$q.lstat; + const srcStat = await statFn(src); + + if (srcStat.isDirectory()) return onDir$1(srcStat, destStat, src, dest, opts) + + if ( + srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice() + ) return onFile$1(srcStat, destStat, src, dest, opts) + + if (srcStat.isSymbolicLink()) return onLink$1(destStat, src, dest, opts) + if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) + if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) + throw new Error(`Unknown file: ${src}`) +} + +async function onFile$1 (srcStat, destStat, src, dest, opts) { + if (!destStat) return copyFile$1(srcStat, src, dest, opts) + + if (opts.overwrite) { + await fs$q.unlink(dest); + return copyFile$1(srcStat, src, dest, opts) + } + if (opts.errorOnExist) { + throw new Error(`'${dest}' already exists`) + } +} + +async function copyFile$1 (srcStat, src, dest, opts) { + await fs$q.copyFile(src, dest); + if (opts.preserveTimestamps) { + // Make sure the file is writable before setting the timestamp + // otherwise open fails with EPERM when invoked with 'r+' + // (through utimes call) + if (fileIsNotWritable$1(srcStat.mode)) { + await makeFileWritable$1(dest, srcStat.mode); } + + // Set timestamps and mode correspondingly + + // Note that 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 fs$q.stat(src); + await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime); + } + + return fs$q.chmod(dest, srcStat.mode) } -function command$1(usage, validation, globalMiddleware, shim) { - return new CommandInstance(usage, validation, globalMiddleware, shim); + +function fileIsNotWritable$1 (srcMode) { + return (srcMode & 0o200) === 0 } -function isCommandBuilderDefinition(builder) { - return (typeof builder === 'object' && - !!builder.builder && - typeof builder.handler === 'function'); + +function makeFileWritable$1 (dest, srcMode) { + return fs$q.chmod(dest, srcMode | 0o200) } -function isCommandAndAliases(cmd) { - return cmd.every(c => typeof c === 'string'); + +async function onDir$1 (srcStat, destStat, src, dest, opts) { + // the dest directory might not exist, create it + if (!destStat) { + await fs$q.mkdir(dest); + } + + const items = await fs$q.readdir(src); + + // loop through the files in the current directory to copy everything + await Promise.all(items.map(async item => { + const srcItem = path$h.join(src, item); + const destItem = path$h.join(dest, item); + + // skip the item if it is matches by the filter function + const include = await runFilter(srcItem, destItem, opts); + if (!include) return + + const { destStat } = await stat$3.checkPaths(srcItem, destItem, 'copy', opts); + + // If the item is a copyable file, `getStatsAndPerformCopy` will copy it + // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively + return getStatsAndPerformCopy(destStat, srcItem, destItem, opts) + })); + + if (!destStat) { + await fs$q.chmod(dest, srcStat.mode); + } } -function isCommandBuilderCallback(builder) { - return typeof builder === 'function'; + +async function onLink$1 (destStat, src, dest, opts) { + let resolvedSrc = await fs$q.readlink(src); + if (opts.dereference) { + resolvedSrc = path$h.resolve(process.cwd(), resolvedSrc); + } + if (!destStat) { + return fs$q.symlink(resolvedSrc, dest) + } + + let resolvedDest = null; + try { + resolvedDest = await fs$q.readlink(dest); + } catch (e) { + // 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. + if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs$q.symlink(resolvedSrc, dest) + throw e + } + if (opts.dereference) { + resolvedDest = path$h.resolve(process.cwd(), resolvedDest); + } + if (stat$3.isSrcSubdir(resolvedSrc, resolvedDest)) { + throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) + } + + // 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. + if (stat$3.isSrcSubdir(resolvedDest, resolvedSrc)) { + throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) + } + + // copy the link + await fs$q.unlink(dest); + return fs$q.symlink(resolvedSrc, dest) } -function isCommandBuilderOptionDefinitions(builder) { - return typeof builder === 'object'; + +var copy_1 = copy$2; + +const fs$p = gracefulFs; +const path$g = require$$1$1; +const mkdirsSync$1 = mkdirs$2.mkdirsSync; +const utimesMillisSync = utimes.utimesMillisSync; +const stat$2 = stat$4; + +function copySync$1 (src, dest, opts) { + if (typeof opts === 'function') { + opts = { filter: opts }; + } + + opts = opts || {}; + opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber + + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + process.emitWarning( + 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', + 'Warning', 'fs-extra-WARN0002' + ); + } + + const { srcStat, destStat } = stat$2.checkPathsSync(src, dest, 'copy', opts); + stat$2.checkParentPathsSync(src, srcStat, dest, 'copy'); + if (opts.filter && !opts.filter(src, dest)) return + const destParent = path$g.dirname(dest); + if (!fs$p.existsSync(destParent)) mkdirsSync$1(destParent); + return getStats(destStat, src, dest, opts) } -function isCommandHandlerDefinition(cmd) { - return typeof cmd === 'object' && !Array.isArray(cmd); + +function getStats (destStat, src, dest, opts) { + const statSync = opts.dereference ? fs$p.statSync : fs$p.lstatSync; + const srcStat = statSync(src); + + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) + else if (srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) + else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) + else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) + else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) + throw new Error(`Unknown file: ${src}`) } -function objFilter(original = {}, filter = () => true) { - const obj = {}; - objectKeys(original).forEach(key => { - if (filter(key, original[key])) { - obj[key] = original[key]; - } - }); - return obj; +function onFile (srcStat, destStat, src, dest, opts) { + if (!destStat) return copyFile(srcStat, src, dest, opts) + return mayCopyFile(srcStat, src, dest, opts) } -function setBlocking(blocking) { - if (typeof process === 'undefined') - return; - [process.stdout, process.stderr].forEach(_stream => { - const stream = _stream; - if (stream._handle && - stream.isTTY && - typeof stream._handle.setBlocking === 'function') { - stream._handle.setBlocking(blocking); - } - }); +function mayCopyFile (srcStat, src, dest, opts) { + if (opts.overwrite) { + fs$p.unlinkSync(dest); + return copyFile(srcStat, src, dest, opts) + } else if (opts.errorOnExist) { + throw new Error(`'${dest}' already exists`) + } } -function isBoolean(fail) { - return typeof fail === 'boolean'; +function copyFile (srcStat, src, dest, opts) { + fs$p.copyFileSync(src, dest); + if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest); + return setDestMode(dest, srcStat.mode) } -function usage(yargs, shim) { - const __ = shim.y18n.__; - const self = {}; - const fails = []; - self.failFn = function failFn(f) { - fails.push(f); - }; - let failMessage = null; - let globalFailMessage = null; - let showHelpOnFail = true; - self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) { - const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2]; - if (yargs.getInternalMethods().isGlobalContext()) { - globalFailMessage = message; - } - failMessage = message; - showHelpOnFail = enabled; - return self; - }; - let failureOutput = false; - self.fail = function fail(msg, err) { - const logger = yargs.getInternalMethods().getLoggerInstance(); - if (fails.length) { - for (let i = fails.length - 1; i >= 0; --i) { - const fail = fails[i]; - if (isBoolean(fail)) { - if (err) - throw err; - else if (msg) - throw Error(msg); - } - else { - fail(msg, err, self); - } - } - } - else { - if (yargs.getExitProcess()) - setBlocking(true); - if (!failureOutput) { - failureOutput = true; - if (showHelpOnFail) { - yargs.showHelp('error'); - logger.error(); - } - if (msg || err) - logger.error(msg || err); - const globalOrCommandFailMessage = failMessage || globalFailMessage; - if (globalOrCommandFailMessage) { - if (msg || err) - logger.error(''); - logger.error(globalOrCommandFailMessage); - } - } - err = err || new YError(msg); - if (yargs.getExitProcess()) { - return yargs.exit(1); - } - else if (yargs.getInternalMethods().hasParseCallback()) { - return yargs.exit(1, err); - } - else { - throw err; - } - } - }; - let usages = []; - let usageDisabled = false; - self.usage = (msg, description) => { - if (msg === null) { - usageDisabled = true; - usages = []; - return self; - } - usageDisabled = false; - usages.push([msg, description || '']); - return self; - }; - self.getUsage = () => { - return usages; - }; - self.getUsageDisabled = () => { - return usageDisabled; - }; - self.getPositionalGroupName = () => { - return __('Positionals:'); - }; - let examples = []; - self.example = (cmd, description) => { - examples.push([cmd, description || '']); - }; - let commands = []; - self.command = function command(cmd, description, isDefault, aliases, deprecated = false) { - if (isDefault) { - commands = commands.map(cmdArray => { - cmdArray[2] = false; - return cmdArray; - }); - } - commands.push([cmd, description || '', isDefault, aliases, deprecated]); - }; - self.getCommands = () => commands; - let descriptions = {}; - self.describe = function describe(keyOrKeys, desc) { - if (Array.isArray(keyOrKeys)) { - keyOrKeys.forEach(k => { - self.describe(k, desc); - }); - } - else if (typeof keyOrKeys === 'object') { - Object.keys(keyOrKeys).forEach(k => { - self.describe(k, keyOrKeys[k]); - }); - } - else { - descriptions[keyOrKeys] = desc; - } - }; - self.getDescriptions = () => descriptions; - let epilogs = []; - self.epilog = msg => { - epilogs.push(msg); - }; - let wrapSet = false; - let wrap; - self.wrap = cols => { - wrapSet = true; - wrap = cols; - }; - self.getWrap = () => { - if (shim.getEnv('YARGS_DISABLE_WRAP')) { - return null; - } - if (!wrapSet) { - wrap = windowWidth(); - wrapSet = true; - } - return wrap; - }; - const deferY18nLookupPrefix = '__yargsString__:'; - self.deferY18nLookup = str => deferY18nLookupPrefix + str; - self.help = function help() { - if (cachedHelpMessage) - return cachedHelpMessage; - normalizeAliases(); - const base$0 = yargs.customScriptName - ? yargs.$0 - : shim.path.basename(yargs.$0); - const demandedOptions = yargs.getDemandedOptions(); - const demandedCommands = yargs.getDemandedCommands(); - const deprecatedOptions = yargs.getDeprecatedOptions(); - const groups = yargs.getGroups(); - const options = yargs.getOptions(); - let keys = []; - keys = keys.concat(Object.keys(descriptions)); - keys = keys.concat(Object.keys(demandedOptions)); - keys = keys.concat(Object.keys(demandedCommands)); - keys = keys.concat(Object.keys(options.default)); - keys = keys.filter(filterHiddenOptions); - keys = Object.keys(keys.reduce((acc, key) => { - if (key !== '_') - acc[key] = true; - return acc; - }, {})); - const theWrap = self.getWrap(); - const ui = shim.cliui({ - width: theWrap, - wrap: !!theWrap, - }); - if (!usageDisabled) { - if (usages.length) { - usages.forEach(usage => { - ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` }); - if (usage[1]) { - ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }); - } - }); - ui.div(); - } - else if (commands.length) { - let u = null; - if (demandedCommands._) { - u = `${base$0} <${__('command')}>\n`; - } - else { - u = `${base$0} [${__('command')}]\n`; - } - ui.div(`${u}`); - } - } - if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) { - ui.div(__('Commands:')); - const context = yargs.getInternalMethods().getContext(); - const parentCommands = context.commands.length - ? `${context.commands.join(' ')} ` - : ''; - if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] === - true) { - commands = commands.sort((a, b) => a[0].localeCompare(b[0])); - } - const prefix = base$0 ? `${base$0} ` : ''; - commands.forEach(command => { - const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; - ui.span({ - text: commandString, - padding: [0, 2, 0, 2], - width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4, - }, { text: command[1] }); - const hints = []; - if (command[2]) - hints.push(`[${__('default')}]`); - if (command[3] && command[3].length) { - hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`); - } - if (command[4]) { - if (typeof command[4] === 'string') { - hints.push(`[${__('deprecated: %s', command[4])}]`); - } - else { - hints.push(`[${__('deprecated')}]`); - } - } - if (hints.length) { - ui.div({ - text: hints.join(' '), - padding: [0, 0, 0, 2], - align: 'right', - }); - } - else { - ui.div(); - } - }); - ui.div(); - } - const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []); - keys = keys.filter(key => !yargs.parsed.newAliases[key] && - aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)); - const defaultGroup = __('Options:'); - if (!groups[defaultGroup]) - groups[defaultGroup] = []; - addUngroupedKeys(keys, options.alias, groups, defaultGroup); - const isLongSwitch = (sw) => /^--/.test(getText(sw)); - const displayedGroups = Object.keys(groups) - .filter(groupName => groups[groupName].length > 0) - .map(groupName => { - const normalizedKeys = groups[groupName] - .filter(filterHiddenOptions) - .map(key => { - if (aliasKeys.includes(key)) - return key; - for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { - if ((options.alias[aliasKey] || []).includes(key)) - return aliasKey; - } - return key; - }); - return { groupName, normalizedKeys }; - }) - .filter(({ normalizedKeys }) => normalizedKeys.length > 0) - .map(({ groupName, normalizedKeys }) => { - const switches = normalizedKeys.reduce((acc, key) => { - acc[key] = [key] - .concat(options.alias[key] || []) - .map(sw => { - if (groupName === self.getPositionalGroupName()) - return sw; - else { - return ((/^[0-9]$/.test(sw) - ? options.boolean.includes(key) - ? '-' - : '--' - : sw.length > 1 - ? '--' - : '-') + sw); - } - }) - .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) - ? 0 - : isLongSwitch(sw1) - ? 1 - : -1) - .join(', '); - return acc; - }, {}); - return { groupName, normalizedKeys, switches }; - }); - const shortSwitchesUsed = displayedGroups - .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) - .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key]))); - if (shortSwitchesUsed) { - displayedGroups - .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) - .forEach(({ normalizedKeys, switches }) => { - normalizedKeys.forEach(key => { - if (isLongSwitch(switches[key])) { - switches[key] = addIndentation(switches[key], '-x, '.length); - } - }); - }); - } - displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => { - ui.div(groupName); - normalizedKeys.forEach(key => { - const kswitch = switches[key]; - let desc = descriptions[key] || ''; - let type = null; - if (desc.includes(deferY18nLookupPrefix)) - desc = __(desc.substring(deferY18nLookupPrefix.length)); - if (options.boolean.includes(key)) - type = `[${__('boolean')}]`; - if (options.count.includes(key)) - type = `[${__('count')}]`; - if (options.string.includes(key)) - type = `[${__('string')}]`; - if (options.normalize.includes(key)) - type = `[${__('string')}]`; - if (options.array.includes(key)) - type = `[${__('array')}]`; - if (options.number.includes(key)) - type = `[${__('number')}]`; - const deprecatedExtra = (deprecated) => typeof deprecated === 'string' - ? `[${__('deprecated: %s', deprecated)}]` - : `[${__('deprecated')}]`; - const extra = [ - key in deprecatedOptions - ? deprecatedExtra(deprecatedOptions[key]) - : null, - type, - key in demandedOptions ? `[${__('required')}]` : null, - options.choices && options.choices[key] - ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` - : null, - defaultString(options.default[key], options.defaultDescription[key]), - ] - .filter(Boolean) - .join(' '); - ui.span({ - text: getText(kswitch), - padding: [0, 2, 0, 2 + getIndentation(kswitch)], - width: maxWidth(switches, theWrap) + 4, - }, desc); - const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] === - true; - if (extra && !shouldHideOptionExtras) - ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }); - else - ui.div(); - }); - ui.div(); - }); - if (examples.length) { - ui.div(__('Examples:')); - examples.forEach(example => { - example[0] = example[0].replace(/\$0/g, base$0); - }); - examples.forEach(example => { - if (example[1] === '') { - ui.div({ - text: example[0], - padding: [0, 2, 0, 2], - }); - } - else { - ui.div({ - text: example[0], - padding: [0, 2, 0, 2], - width: maxWidth(examples, theWrap) + 4, - }, { - text: example[1], - }); - } - }); - ui.div(); - } - if (epilogs.length > 0) { - const e = epilogs - .map(epilog => epilog.replace(/\$0/g, base$0)) - .join('\n'); - ui.div(`${e}\n`); - } - return ui.toString().replace(/\s*$/, ''); - }; - function maxWidth(table, theWrap, modifier) { - let width = 0; - if (!Array.isArray(table)) { - table = Object.values(table).map(v => [v]); - } - table.forEach(v => { - width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width); - }); - if (theWrap) - width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10)); - return width; - } - function normalizeAliases() { - const demandedOptions = yargs.getDemandedOptions(); - const options = yargs.getOptions(); - (Object.keys(options.alias) || []).forEach(key => { - options.alias[key].forEach(alias => { - if (descriptions[alias]) - self.describe(key, descriptions[alias]); - if (alias in demandedOptions) - yargs.demandOption(key, demandedOptions[alias]); - if (options.boolean.includes(alias)) - yargs.boolean(key); - if (options.count.includes(alias)) - yargs.count(key); - if (options.string.includes(alias)) - yargs.string(key); - if (options.normalize.includes(alias)) - yargs.normalize(key); - if (options.array.includes(alias)) - yargs.array(key); - if (options.number.includes(alias)) - yargs.number(key); - }); - }); - } - let cachedHelpMessage; - self.cacheHelpMessage = function () { - cachedHelpMessage = this.help(); - }; - self.clearCachedHelpMessage = function () { - cachedHelpMessage = undefined; - }; - self.hasCachedHelpMessage = function () { - return !!cachedHelpMessage; - }; - function addUngroupedKeys(keys, aliases, groups, defaultGroup) { - let groupedKeys = []; - let toCheck = null; - Object.keys(groups).forEach(group => { - groupedKeys = groupedKeys.concat(groups[group]); - }); - keys.forEach(key => { - toCheck = [key].concat(aliases[key]); - if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { - groups[defaultGroup].push(key); - } - }); - return groupedKeys; - } - function filterHiddenOptions(key) { - return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 || - yargs.parsed.argv[yargs.getOptions().showHiddenOpt]); - } - self.showHelp = (level) => { - const logger = yargs.getInternalMethods().getLoggerInstance(); - if (!level) - level = 'error'; - const emit = typeof level === 'function' ? level : logger[level]; - emit(self.help()); - }; - self.functionDescription = fn => { - const description = fn.name - ? shim.Parser.decamelize(fn.name, '-') - : __('generated-value'); - return ['(', description, ')'].join(''); - }; - self.stringifiedValues = function stringifiedValues(values, separator) { - let string = ''; - const sep = separator || ', '; - const array = [].concat(values); - if (!values || !array.length) - return string; - array.forEach(value => { - if (string.length) - string += sep; - string += JSON.stringify(value); - }); - return string; - }; - function defaultString(value, defaultDescription) { - let string = `[${__('default:')} `; - if (value === undefined && !defaultDescription) - return null; - if (defaultDescription) { - string += defaultDescription; - } - else { - switch (typeof value) { - case 'string': - string += `"${value}"`; - break; - case 'object': - string += JSON.stringify(value); - break; - default: - string += value; - } - } - return `${string}]`; - } - function windowWidth() { - const maxWidth = 80; - if (shim.process.stdColumns) { - return Math.min(maxWidth, shim.process.stdColumns); - } - else { - return maxWidth; - } - } - let version = null; - self.version = ver => { - version = ver; - }; - self.showVersion = level => { - const logger = yargs.getInternalMethods().getLoggerInstance(); - if (!level) - level = 'error'; - const emit = typeof level === 'function' ? level : logger[level]; - emit(version); - }; - self.reset = function reset(localLookup) { - failMessage = null; - failureOutput = false; - usages = []; - usageDisabled = false; - epilogs = []; - examples = []; - commands = []; - descriptions = objFilter(descriptions, k => !localLookup[k]); - return self; - }; - const frozens = []; - self.freeze = function freeze() { - frozens.push({ - failMessage, - failureOutput, - usages, - usageDisabled, - epilogs, - examples, - commands, - descriptions, - }); - }; - self.unfreeze = function unfreeze(defaultCommand = false) { - const frozen = frozens.pop(); - if (!frozen) - return; - if (defaultCommand) { - descriptions = { ...frozen.descriptions, ...descriptions }; - commands = [...frozen.commands, ...commands]; - usages = [...frozen.usages, ...usages]; - examples = [...frozen.examples, ...examples]; - epilogs = [...frozen.epilogs, ...epilogs]; - } - else { - ({ - failMessage, - failureOutput, - usages, - usageDisabled, - epilogs, - examples, - commands, - descriptions, - } = frozen); - } - }; - return self; -} -function isIndentedText(text) { - return typeof text === 'object'; + +function handleTimestamps (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)) makeFileWritable(dest, srcMode); + return setDestTimestamps(src, dest) } -function addIndentation(text, indent) { - return isIndentedText(text) - ? { text: text.text, indentation: text.indentation + indent } - : { text, indentation: indent }; + +function fileIsNotWritable (srcMode) { + return (srcMode & 0o200) === 0 } -function getIndentation(text) { - return isIndentedText(text) ? text.indentation : 0; + +function makeFileWritable (dest, srcMode) { + return setDestMode(dest, srcMode | 0o200) } -function getText(text) { - return isIndentedText(text) ? text.text : text; + +function setDestMode (dest, srcMode) { + return fs$p.chmodSync(dest, srcMode) } -const completionShTemplate = `###-begin-{{app_name}}-completions-### -# -# yargs command completion script -# -# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc -# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. -# -_{{app_name}}_yargs_completions() -{ - local cur_word args type_list +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 = fs$p.statSync(src); + return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) +} - cur_word="\${COMP_WORDS[COMP_CWORD]}" - args=("\${COMP_WORDS[@]}") +function onDir (srcStat, destStat, src, dest, opts) { + if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) + return copyDir(src, dest, opts) +} - # ask yargs to generate completions. - type_list=$({{app_path}} --get-yargs-completions "\${args[@]}") +function mkDirAndCopy (srcMode, src, dest, opts) { + fs$p.mkdirSync(dest); + copyDir(src, dest, opts); + return setDestMode(dest, srcMode) +} - COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) ) - - # if no match was found, fall back to filename completion - if [ \${#COMPREPLY[@]} -eq 0 ]; then - COMPREPLY=() - fi - - return 0 +function copyDir (src, dest, opts) { + fs$p.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)); } -complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}} -###-end-{{app_name}}-completions-### -`; -const completionZshTemplate = `#compdef {{app_name}} -###-begin-{{app_name}}-completions-### -# -# yargs command completion script -# -# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc -# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX. -# -_{{app_name}}_yargs_completions() -{ - local reply - local si=$IFS - IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) - IFS=$si - _describe 'values' reply + +function copyDirItem (item, src, dest, opts) { + const srcItem = path$g.join(src, item); + const destItem = path$g.join(dest, item); + if (opts.filter && !opts.filter(srcItem, destItem)) return + const { destStat } = stat$2.checkPathsSync(srcItem, destItem, 'copy', opts); + return getStats(destStat, srcItem, destItem, opts) } -compdef _{{app_name}}_yargs_completions {{app_name}} -###-end-{{app_name}}-completions-### -`; -class Completion { - constructor(yargs, usage, command, shim) { - var _a, _b, _c; - this.yargs = yargs; - this.usage = usage; - this.command = command; - this.shim = shim; - this.completionKey = 'get-yargs-completions'; - this.aliases = null; - this.customCompletionFunction = null; - this.indexAfterLastReset = 0; - this.zshShell = - (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) || - ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false; - } - defaultCompletion(args, argv, current, done) { - const handlers = this.command.getCommandHandlers(); - for (let i = 0, ii = args.length; i < ii; ++i) { - if (handlers[args[i]] && handlers[args[i]].builder) { - const builder = handlers[args[i]].builder; - if (isCommandBuilderCallback(builder)) { - this.indexAfterLastReset = i + 1; - const y = this.yargs.getInternalMethods().reset(); - builder(y, true); - return y.argv; - } - } - } - const completions = []; - this.commandCompletions(completions, args, current); - this.optionCompletions(completions, args, argv, current); - this.choicesFromOptionsCompletions(completions, args, argv, current); - this.choicesFromPositionalsCompletions(completions, args, argv, current); - done(null, completions); - } - commandCompletions(completions, args, current) { - const parentCommands = this.yargs - .getInternalMethods() - .getContext().commands; - if (!current.match(/^-/) && - parentCommands[parentCommands.length - 1] !== current && - !this.previousArgHasChoices(args)) { - this.usage.getCommands().forEach(usageCommand => { - const commandName = parseCommand(usageCommand[0]).cmd; - if (args.indexOf(commandName) === -1) { - if (!this.zshShell) { - completions.push(commandName); - } - else { - const desc = usageCommand[1] || ''; - completions.push(commandName.replace(/:/g, '\\:') + ':' + desc); - } - } - }); - } - } - optionCompletions(completions, args, argv, current) { - if ((current.match(/^-/) || (current === '' && completions.length === 0)) && - !this.previousArgHasChoices(args)) { - const options = this.yargs.getOptions(); - const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; - Object.keys(options.key).forEach(key => { - const negable = !!options.configuration['boolean-negation'] && - options.boolean.includes(key); - const isPositionalKey = positionalKeys.includes(key); - if (!isPositionalKey && - !options.hiddenOptions.includes(key) && - !this.argsContainKey(args, key, negable)) { - this.completeOptionKey(key, completions, current, negable && !!options.default[key]); - } - }); - } - } - choicesFromOptionsCompletions(completions, args, argv, current) { - if (this.previousArgHasChoices(args)) { - const choices = this.getPreviousArgChoices(args); - if (choices && choices.length > 0) { - completions.push(...choices.map(c => c.replace(/:/g, '\\:'))); - } - } - } - choicesFromPositionalsCompletions(completions, args, argv, current) { - if (current === '' && - completions.length > 0 && - this.previousArgHasChoices(args)) { - return; - } - const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; - const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + - 1); - const positionalKey = positionalKeys[argv._.length - offset - 1]; - if (!positionalKey) { - return; - } - const choices = this.yargs.getOptions().choices[positionalKey] || []; - for (const choice of choices) { - if (choice.startsWith(current)) { - completions.push(choice.replace(/:/g, '\\:')); - } - } - } - getPreviousArgChoices(args) { - if (args.length < 1) - return; - let previousArg = args[args.length - 1]; - let filter = ''; - if (!previousArg.startsWith('-') && args.length > 1) { - filter = previousArg; - previousArg = args[args.length - 2]; - } - if (!previousArg.startsWith('-')) - return; - const previousArgKey = previousArg.replace(/^-+/, ''); - const options = this.yargs.getOptions(); - const possibleAliases = [ - previousArgKey, - ...(this.yargs.getAliases()[previousArgKey] || []), - ]; - let choices; - for (const possibleAlias of possibleAliases) { - if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && - Array.isArray(options.choices[possibleAlias])) { - choices = options.choices[possibleAlias]; - break; - } - } - if (choices) { - return choices.filter(choice => !filter || choice.startsWith(filter)); - } - } - previousArgHasChoices(args) { - const choices = this.getPreviousArgChoices(args); - return choices !== undefined && choices.length > 0; - } - argsContainKey(args, key, negable) { - const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1; - if (argsContains(key)) - return true; - if (negable && argsContains(`no-${key}`)) - return true; - if (this.aliases) { - for (const alias of this.aliases[key]) { - if (argsContains(alias)) - return true; - } - } - return false; - } - completeOptionKey(key, completions, current, negable) { - var _a, _b, _c, _d; - let keyWithDesc = key; - if (this.zshShell) { - const descs = this.usage.getDescriptions(); - const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => { - const desc = descs[alias]; - return typeof desc === 'string' && desc.length > 0; - }); - const descFromAlias = aliasKey ? descs[aliasKey] : undefined; - const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : ''; - keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc - .replace('__yargsString__:', '') - .replace(/(\r\n|\n|\r)/gm, ' ')}`; - } - const startsByTwoDashes = (s) => /^--/.test(s); - const isShortOption = (s) => /^[^0-9]$/.test(s); - const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'; - completions.push(dashes + keyWithDesc); - if (negable) { - completions.push(dashes + 'no-' + keyWithDesc); - } - } - customCompletion(args, argv, current, done) { - assertNotStrictEqual(this.customCompletionFunction, null, this.shim); - if (isSyncCompletionFunction(this.customCompletionFunction)) { - const result = this.customCompletionFunction(current, argv); - if (isPromise(result)) { - return result - .then(list => { - this.shim.process.nextTick(() => { - done(null, list); - }); - }) - .catch(err => { - this.shim.process.nextTick(() => { - done(err, undefined); - }); - }); - } - return done(null, result); - } - else if (isFallbackCompletionFunction(this.customCompletionFunction)) { - return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => { - done(null, completions); - }); - } - else { - return this.customCompletionFunction(current, argv, completions => { - done(null, completions); - }); - } - } - getCompletion(args, done) { - const current = args.length ? args[args.length - 1] : ''; - const argv = this.yargs.parse(args, true); - const completionFunction = this.customCompletionFunction - ? (argv) => this.customCompletion(args, argv, current, done) - : (argv) => this.defaultCompletion(args, argv, current, done); - return isPromise(argv) - ? argv.then(completionFunction) - : completionFunction(argv); +function onLink (destStat, src, dest, opts) { + let resolvedSrc = fs$p.readlinkSync(src); + if (opts.dereference) { + resolvedSrc = path$g.resolve(process.cwd(), resolvedSrc); + } + + if (!destStat) { + return fs$p.symlinkSync(resolvedSrc, dest) + } else { + let resolvedDest; + try { + resolvedDest = fs$p.readlinkSync(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. + if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs$p.symlinkSync(resolvedSrc, dest) + throw err } - generateCompletionScript($0, cmd) { - let script = this.zshShell - ? completionZshTemplate - : completionShTemplate; - const name = this.shim.path.basename($0); - if ($0.match(/\.js$/)) - $0 = `./${$0}`; - script = script.replace(/{{app_name}}/g, name); - script = script.replace(/{{completion_command}}/g, cmd); - return script.replace(/{{app_path}}/g, $0); + if (opts.dereference) { + resolvedDest = path$g.resolve(process.cwd(), resolvedDest); } - registerFunction(fn) { - this.customCompletionFunction = fn; + if (stat$2.isSrcSubdir(resolvedSrc, resolvedDest)) { + throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) } - setParsed(parsed) { - this.aliases = parsed.aliases; + + // prevent 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. + if (stat$2.isSrcSubdir(resolvedDest, resolvedSrc)) { + throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) } + return copyLink(resolvedSrc, dest) + } } -function completion(yargs, usage, command, shim) { - return new Completion(yargs, usage, command, shim); + +function copyLink (resolvedSrc, dest) { + fs$p.unlinkSync(dest); + return fs$p.symlinkSync(resolvedSrc, dest) } -function isSyncCompletionFunction(completionFunction) { - return completionFunction.length < 3; + +var copySync_1 = copySync$1; + +const u$a = universalify$1.fromPromise; +var copy$1 = { + copy: u$a(copy_1), + copySync: copySync_1 +}; + +const fs$o = gracefulFs; +const u$9 = universalify$1.fromCallback; + +function remove$2 (path, callback) { + fs$o.rm(path, { recursive: true, force: true }, callback); } -function isFallbackCompletionFunction(completionFunction) { - return completionFunction.length > 3; + +function removeSync$1 (path) { + fs$o.rmSync(path, { recursive: true, force: true }); } -function levenshtein(a, b) { - if (a.length === 0) - return b.length; - if (b.length === 0) - return a.length; - const matrix = []; - let i; - for (i = 0; i <= b.length; i++) { - matrix[i] = [i]; - } - let j; - for (j = 0; j <= a.length; j++) { - matrix[0][j] = j; +var remove_1 = { + remove: u$9(remove$2), + removeSync: removeSync$1 +}; + +const u$8 = universalify$1.fromPromise; +const fs$n = fs$w; +const path$f = require$$1$1; +const mkdir$3 = mkdirs$2; +const remove$1 = remove_1; + +const emptyDir = u$8(async function emptyDir (dir) { + let items; + try { + items = await fs$n.readdir(dir); + } catch { + return mkdir$3.mkdirs(dir) + } + + return Promise.all(items.map(item => remove$1.remove(path$f.join(dir, item)))) +}); + +function emptyDirSync (dir) { + let items; + try { + items = fs$n.readdirSync(dir); + } catch { + return mkdir$3.mkdirsSync(dir) + } + + items.forEach(item => { + item = path$f.join(dir, item); + remove$1.removeSync(item); + }); +} + +var empty = { + emptyDirSync, + emptydirSync: emptyDirSync, + emptyDir, + emptydir: emptyDir +}; + +const u$7 = universalify$1.fromPromise; +const path$e = require$$1$1; +const fs$m = fs$w; +const mkdir$2 = mkdirs$2; + +async function createFile$1 (file) { + let stats; + try { + stats = await fs$m.stat(file); + } catch { } + if (stats && stats.isFile()) return + + const dir = path$e.dirname(file); + + let dirStats = null; + try { + dirStats = await fs$m.stat(dir); + } catch (err) { + // if the directory doesn't exist, make it + if (err.code === 'ENOENT') { + await mkdir$2.mkdirs(dir); + await fs$m.writeFile(file, ''); + return + } else { + throw err } - for (i = 1; i <= b.length; i++) { - for (j = 1; j <= a.length; j++) { - if (b.charAt(i - 1) === a.charAt(j - 1)) { - matrix[i][j] = matrix[i - 1][j - 1]; - } - else { - if (i > 1 && - j > 1 && - b.charAt(i - 2) === a.charAt(j - 1) && - b.charAt(i - 1) === a.charAt(j - 2)) { - matrix[i][j] = matrix[i - 2][j - 2] + 1; - } - else { - matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)); - } - } - } + } + + if (dirStats.isDirectory()) { + await fs$m.writeFile(file, ''); + } else { + // parent is not a directory + // This is just to cause an internal ENOTDIR error to be thrown + await fs$m.readdir(dir); + } +} + +function createFileSync$1 (file) { + let stats; + try { + stats = fs$m.statSync(file); + } catch { } + if (stats && stats.isFile()) return + + const dir = path$e.dirname(file); + try { + if (!fs$m.statSync(dir).isDirectory()) { + // parent is not a directory + // This is just to cause an internal ENOTDIR error to be thrown + fs$m.readdirSync(dir); } - return matrix[b.length][a.length]; + } catch (err) { + // If the stat call above failed because the directory doesn't exist, create it + if (err && err.code === 'ENOENT') mkdir$2.mkdirsSync(dir); + else throw err + } + + fs$m.writeFileSync(file, ''); } -const specialKeys = ['$0', '--', '_']; -function validation(yargs, usage, shim) { - const __ = shim.y18n.__; - const __n = shim.y18n.__n; - const self = {}; - self.nonOptionCount = function nonOptionCount(argv) { - const demandedCommands = yargs.getDemandedCommands(); - const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0); - const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length; - if (demandedCommands._ && - (_s < demandedCommands._.min || _s > demandedCommands._.max)) { - if (_s < demandedCommands._.min) { - if (demandedCommands._.minMsg !== undefined) { - usage.fail(demandedCommands._.minMsg - ? demandedCommands._.minMsg - .replace(/\$0/g, _s.toString()) - .replace(/\$1/, demandedCommands._.min.toString()) - : null); - } - else { - usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString())); - } - } - else if (_s > demandedCommands._.max) { - if (demandedCommands._.maxMsg !== undefined) { - usage.fail(demandedCommands._.maxMsg - ? demandedCommands._.maxMsg - .replace(/\$0/g, _s.toString()) - .replace(/\$1/, demandedCommands._.max.toString()) - : null); - } - else { - usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString())); - } - } - } - }; - self.positionalCount = function positionalCount(required, observed) { - if (observed < required) { - usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + '')); - } - }; - self.requiredArguments = function requiredArguments(argv, demandedOptions) { - let missing = null; - for (const key of Object.keys(demandedOptions)) { - if (!Object.prototype.hasOwnProperty.call(argv, key) || - typeof argv[key] === 'undefined') { - missing = missing || {}; - missing[key] = demandedOptions[key]; - } - } - if (missing) { - const customMsgs = []; - for (const key of Object.keys(missing)) { - const msg = missing[key]; - if (msg && customMsgs.indexOf(msg) < 0) { - customMsgs.push(msg); - } - } - const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''; - usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg)); - } - }; - self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) { - var _a; - const commandKeys = yargs - .getInternalMethods() - .getCommandInstance() - .getCommands(); - const unknown = []; - const currentContext = yargs.getInternalMethods().getContext(); - Object.keys(argv).forEach(key => { - if (!specialKeys.includes(key) && - !Object.prototype.hasOwnProperty.call(positionalMap, key) && - !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && - !self.isValidAndSomeAliasIsNotNew(key, aliases)) { - unknown.push(key); - } - }); - if (checkPositionals && - (currentContext.commands.length > 0 || - commandKeys.length > 0 || - isDefaultCommand)) { - argv._.slice(currentContext.commands.length).forEach(key => { - if (!commandKeys.includes('' + key)) { - unknown.push('' + key); - } - }); - } - if (checkPositionals) { - const demandedCommands = yargs.getDemandedCommands(); - const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0; - const expected = currentContext.commands.length + maxNonOptDemanded; - if (expected < argv._.length) { - argv._.slice(expected).forEach(key => { - key = String(key); - if (!currentContext.commands.includes(key) && - !unknown.includes(key)) { - unknown.push(key); - } - }); - } - } - if (unknown.length) { - usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', '))); - } - }; - self.unknownCommands = function unknownCommands(argv) { - const commandKeys = yargs - .getInternalMethods() - .getCommandInstance() - .getCommands(); - const unknown = []; - const currentContext = yargs.getInternalMethods().getContext(); - if (currentContext.commands.length > 0 || commandKeys.length > 0) { - argv._.slice(currentContext.commands.length).forEach(key => { - if (!commandKeys.includes('' + key)) { - unknown.push('' + key); - } - }); - } - if (unknown.length > 0) { - usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', '))); - return true; - } - else { - return false; - } - }; - self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) { - if (!Object.prototype.hasOwnProperty.call(aliases, key)) { - return false; - } - const newAliases = yargs.parsed.newAliases; - return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]); - }; - self.limitedChoices = function limitedChoices(argv) { - const options = yargs.getOptions(); - const invalid = {}; - if (!Object.keys(options.choices).length) - return; - Object.keys(argv).forEach(key => { - if (specialKeys.indexOf(key) === -1 && - Object.prototype.hasOwnProperty.call(options.choices, key)) { - [].concat(argv[key]).forEach(value => { - if (options.choices[key].indexOf(value) === -1 && - value !== undefined) { - invalid[key] = (invalid[key] || []).concat(value); - } - }); - } - }); - const invalidKeys = Object.keys(invalid); - if (!invalidKeys.length) - return; - let msg = __('Invalid values:'); - invalidKeys.forEach(key => { - msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`; - }); - usage.fail(msg); - }; - let implied = {}; - self.implies = function implies(key, value) { - argsert(' [array|number|string]', [key, value], arguments.length); - if (typeof key === 'object') { - Object.keys(key).forEach(k => { - self.implies(k, key[k]); - }); - } - else { - yargs.global(key); - if (!implied[key]) { - implied[key] = []; - } - if (Array.isArray(value)) { - value.forEach(i => self.implies(key, i)); - } - else { - assertNotStrictEqual(value, undefined, shim); - implied[key].push(value); - } - } - }; - self.getImplied = function getImplied() { - return implied; - }; - function keyExists(argv, val) { - const num = Number(val); - val = isNaN(num) ? val : num; - if (typeof val === 'number') { - val = argv._.length >= val; - } - else if (val.match(/^--no-.+/)) { - val = val.match(/^--no-(.+)/)[1]; - val = !Object.prototype.hasOwnProperty.call(argv, val); - } - else { - val = Object.prototype.hasOwnProperty.call(argv, val); - } - return val; - } - self.implications = function implications(argv) { - const implyFail = []; - Object.keys(implied).forEach(key => { - const origKey = key; - (implied[key] || []).forEach(value => { - let key = origKey; - const origValue = value; - key = keyExists(argv, key); - value = keyExists(argv, value); - if (key && !value) { - implyFail.push(` ${origKey} -> ${origValue}`); - } - }); - }); - if (implyFail.length) { - let msg = `${__('Implications failed:')}\n`; - implyFail.forEach(value => { - msg += value; - }); - usage.fail(msg); - } - }; - let conflicting = {}; - self.conflicts = function conflicts(key, value) { - argsert(' [array|string]', [key, value], arguments.length); - if (typeof key === 'object') { - Object.keys(key).forEach(k => { - self.conflicts(k, key[k]); - }); - } - else { - yargs.global(key); - if (!conflicting[key]) { - conflicting[key] = []; - } - if (Array.isArray(value)) { - value.forEach(i => self.conflicts(key, i)); - } - else { - conflicting[key].push(value); - } - } - }; - self.getConflicting = () => conflicting; - self.conflicting = function conflictingFn(argv) { - Object.keys(argv).forEach(key => { - if (conflicting[key]) { - conflicting[key].forEach(value => { - if (value && argv[key] !== undefined && argv[value] !== undefined) { - usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); - } - }); - } - }); - if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) { - Object.keys(conflicting).forEach(key => { - conflicting[key].forEach(value => { - if (value && - argv[shim.Parser.camelCase(key)] !== undefined && - argv[shim.Parser.camelCase(value)] !== undefined) { - usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); - } - }); - }); - } - }; - self.recommendCommands = function recommendCommands(cmd, potentialCommands) { - const threshold = 3; - potentialCommands = potentialCommands.sort((a, b) => b.length - a.length); - let recommended = null; - let bestDistance = Infinity; - for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { - const d = levenshtein(cmd, candidate); - if (d <= threshold && d < bestDistance) { - bestDistance = d; - recommended = candidate; - } - } - if (recommended) - usage.fail(__('Did you mean %s?', recommended)); - }; - self.reset = function reset(localLookup) { - implied = objFilter(implied, k => !localLookup[k]); - conflicting = objFilter(conflicting, k => !localLookup[k]); - return self; - }; - const frozens = []; - self.freeze = function freeze() { - frozens.push({ - implied, - conflicting, - }); - }; - self.unfreeze = function unfreeze() { - const frozen = frozens.pop(); - assertNotStrictEqual(frozen, undefined, shim); - ({ implied, conflicting } = frozen); - }; - return self; +var file$1 = { + createFile: u$7(createFile$1), + createFileSync: createFileSync$1 +}; + +const u$6 = universalify$1.fromPromise; +const path$d = require$$1$1; +const fs$l = fs$w; +const mkdir$1 = mkdirs$2; +const { pathExists: pathExists$4 } = pathExists_1; +const { areIdentical: areIdentical$1 } = stat$4; + +async function createLink$1 (srcpath, dstpath) { + let dstStat; + try { + dstStat = await fs$l.lstat(dstpath); + } catch { + // ignore error + } + + let srcStat; + try { + srcStat = await fs$l.lstat(srcpath); + } catch (err) { + err.message = err.message.replace('lstat', 'ensureLink'); + throw err + } + + if (dstStat && areIdentical$1(srcStat, dstStat)) return + + const dir = path$d.dirname(dstpath); + + const dirExists = await pathExists$4(dir); + + if (!dirExists) { + await mkdir$1.mkdirs(dir); + } + + await fs$l.link(srcpath, dstpath); } -let previouslyVisitedConfigs = []; -let shim; -function applyExtends(config, cwd, mergeExtends, _shim) { - shim = _shim; - let defaultConfig = {}; - if (Object.prototype.hasOwnProperty.call(config, 'extends')) { - if (typeof config.extends !== 'string') - return defaultConfig; - const isPath = /\.json|\..*rc$/.test(config.extends); - let pathToDefault = null; - if (!isPath) { - try { - pathToDefault = require.resolve(config.extends); - } - catch (_err) { - return config; - } - } - else { - pathToDefault = getPathToDefaultConfig(cwd, config.extends); - } - checkForCircularExtends(pathToDefault); - previouslyVisitedConfigs.push(pathToDefault); - defaultConfig = isPath - ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) - : require(config.extends); - delete config.extends; - defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim); - } - previouslyVisitedConfigs = []; - return mergeExtends - ? mergeDeep(defaultConfig, config) - : Object.assign({}, defaultConfig, config); +function createLinkSync$1 (srcpath, dstpath) { + let dstStat; + try { + dstStat = fs$l.lstatSync(dstpath); + } catch {} + + try { + const srcStat = fs$l.lstatSync(srcpath); + if (dstStat && areIdentical$1(srcStat, dstStat)) return + } catch (err) { + err.message = err.message.replace('lstat', 'ensureLink'); + throw err + } + + const dir = path$d.dirname(dstpath); + const dirExists = fs$l.existsSync(dir); + if (dirExists) return fs$l.linkSync(srcpath, dstpath) + mkdir$1.mkdirsSync(dir); + + return fs$l.linkSync(srcpath, dstpath) } -function checkForCircularExtends(cfgPath) { - if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { - throw new YError(`Circular extended configurations: '${cfgPath}'.`); + +var link = { + createLink: u$6(createLink$1), + createLinkSync: createLinkSync$1 +}; + +const path$c = require$$1$1; +const fs$k = fs$w; +const { pathExists: pathExists$3 } = pathExists_1; + +const u$5 = universalify$1.fromPromise; + +/** + * Function that returns two types of paths, one relative to symlink, and one + * relative to the current working directory. Checks if path is absolute or + * relative. If the path is relative, this function checks if the path is + * relative to symlink or relative to current working directory. This is an + * initiative to find a smarter `srcpath` to supply when building symlinks. + * This allows you to determine which path to use out of one of three possible + * types of source paths. The first is an absolute path. This is detected by + * `path.isAbsolute()`. When an absolute path is provided, it is checked to + * see if it exists. If it does it's used, if not an error is returned + * (callback)/ thrown (sync). The other two options for `srcpath` are a + * relative url. By default Node's `fs.symlink` works by creating a symlink + * using `dstpath` and expects the `srcpath` to be relative to the newly + * created symlink. If you provide a `srcpath` that does not exist on the file + * system it results in a broken symlink. To minimize this, the function + * checks to see if the 'relative to symlink' source file exists, and if it + * does it will use it. If it does not, it checks if there's a file that + * exists that is relative to the current working directory, if does its used. + * This preserves the expectations of the original fs.symlink spec and adds + * the ability to pass in `relative to current working direcotry` paths. + */ + +async function symlinkPaths$1 (srcpath, dstpath) { + if (path$c.isAbsolute(srcpath)) { + try { + await fs$k.lstat(srcpath); + } catch (err) { + err.message = err.message.replace('lstat', 'ensureSymlink'); + throw err } + + return { + toCwd: srcpath, + toDst: srcpath + } + } + + const dstdir = path$c.dirname(dstpath); + const relativeToDst = path$c.join(dstdir, srcpath); + + const exists = await pathExists$3(relativeToDst); + if (exists) { + return { + toCwd: relativeToDst, + toDst: srcpath + } + } + + try { + await fs$k.lstat(srcpath); + } catch (err) { + err.message = err.message.replace('lstat', 'ensureSymlink'); + throw err + } + + return { + toCwd: srcpath, + toDst: path$c.relative(dstdir, srcpath) + } } -function getPathToDefaultConfig(cwd, pathToExtend) { - return shim.path.resolve(cwd, pathToExtend); -} -function mergeDeep(config1, config2) { - const target = {}; - function isObject(obj) { - return obj && typeof obj === 'object' && !Array.isArray(obj); + +function symlinkPathsSync$1 (srcpath, dstpath) { + if (path$c.isAbsolute(srcpath)) { + const exists = fs$k.existsSync(srcpath); + if (!exists) throw new Error('absolute srcpath does not exist') + return { + toCwd: srcpath, + toDst: srcpath } - Object.assign(target, config1); - for (const key of Object.keys(config2)) { - if (isObject(config2[key]) && isObject(target[key])) { - target[key] = mergeDeep(config1[key], config2[key]); - } - else { - target[key] = config2[key]; - } + } + + const dstdir = path$c.dirname(dstpath); + const relativeToDst = path$c.join(dstdir, srcpath); + const exists = fs$k.existsSync(relativeToDst); + if (exists) { + return { + toCwd: relativeToDst, + toDst: srcpath } - return target; + } + + const srcExists = fs$k.existsSync(srcpath); + if (!srcExists) throw new Error('relative srcpath does not exist') + return { + toCwd: srcpath, + toDst: path$c.relative(dstdir, srcpath) + } } -var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +var symlinkPaths_1 = { + symlinkPaths: u$5(symlinkPaths$1), + symlinkPathsSync: symlinkPathsSync$1 }; -var _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation; -function YargsFactory(_shim) { - return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => { - const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim); - Object.defineProperty(yargs, 'argv', { - get: () => { - return yargs.parse(); - }, - enumerable: true, - }); - yargs.help(); - yargs.version(); - return yargs; - }; + +const fs$j = fs$w; +const u$4 = universalify$1.fromPromise; + +async function symlinkType$1 (srcpath, type) { + if (type) return type + + let stats; + try { + stats = await fs$j.lstat(srcpath); + } catch { + return 'file' + } + + return (stats && stats.isDirectory()) ? 'dir' : 'file' } -const kCopyDoubleDash = Symbol('copyDoubleDash'); -const kCreateLogger = Symbol('copyDoubleDash'); -const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject'); -const kEmitWarning = Symbol('emitWarning'); -const kFreeze = Symbol('freeze'); -const kGetDollarZero = Symbol('getDollarZero'); -const kGetParserConfiguration = Symbol('getParserConfiguration'); -const kGetUsageConfiguration = Symbol('getUsageConfiguration'); -const kGuessLocale = Symbol('guessLocale'); -const kGuessVersion = Symbol('guessVersion'); -const kParsePositionalNumbers = Symbol('parsePositionalNumbers'); -const kPkgUp = Symbol('pkgUp'); -const kPopulateParserHintArray = Symbol('populateParserHintArray'); -const kPopulateParserHintSingleValueDictionary = Symbol('populateParserHintSingleValueDictionary'); -const kPopulateParserHintArrayDictionary = Symbol('populateParserHintArrayDictionary'); -const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary'); -const kSanitizeKey = Symbol('sanitizeKey'); -const kSetKey = Symbol('setKey'); -const kUnfreeze = Symbol('unfreeze'); -const kValidateAsync = Symbol('validateAsync'); -const kGetCommandInstance = Symbol('getCommandInstance'); -const kGetContext = Symbol('getContext'); -const kGetHasOutput = Symbol('getHasOutput'); -const kGetLoggerInstance = Symbol('getLoggerInstance'); -const kGetParseContext = Symbol('getParseContext'); -const kGetUsageInstance = Symbol('getUsageInstance'); -const kGetValidationInstance = Symbol('getValidationInstance'); -const kHasParseCallback = Symbol('hasParseCallback'); -const kIsGlobalContext = Symbol('isGlobalContext'); -const kPostProcess = Symbol('postProcess'); -const kRebase = Symbol('rebase'); -const kReset = Symbol('reset'); -const kRunYargsParserAndExecuteCommands = Symbol('runYargsParserAndExecuteCommands'); -const kRunValidation = Symbol('runValidation'); -const kSetHasOutput = Symbol('setHasOutput'); -const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys'); -class YargsInstance { - constructor(processArgs = [], cwd, parentRequire, shim) { - this.customScriptName = false; - this.parsed = false; - _YargsInstance_command.set(this, void 0); - _YargsInstance_cwd.set(this, void 0); - _YargsInstance_context.set(this, { commands: [], fullCommands: [] }); - _YargsInstance_completion.set(this, null); - _YargsInstance_completionCommand.set(this, null); - _YargsInstance_defaultShowHiddenOpt.set(this, 'show-hidden'); - _YargsInstance_exitError.set(this, null); - _YargsInstance_detectLocale.set(this, true); - _YargsInstance_emittedWarnings.set(this, {}); - _YargsInstance_exitProcess.set(this, true); - _YargsInstance_frozens.set(this, []); - _YargsInstance_globalMiddleware.set(this, void 0); - _YargsInstance_groups.set(this, {}); - _YargsInstance_hasOutput.set(this, false); - _YargsInstance_helpOpt.set(this, null); - _YargsInstance_isGlobalContext.set(this, true); - _YargsInstance_logger.set(this, void 0); - _YargsInstance_output.set(this, ''); - _YargsInstance_options.set(this, void 0); - _YargsInstance_parentRequire.set(this, void 0); - _YargsInstance_parserConfig.set(this, {}); - _YargsInstance_parseFn.set(this, null); - _YargsInstance_parseContext.set(this, null); - _YargsInstance_pkgs.set(this, {}); - _YargsInstance_preservedGroups.set(this, {}); - _YargsInstance_processArgs.set(this, void 0); - _YargsInstance_recommendCommands.set(this, false); - _YargsInstance_shim.set(this, void 0); - _YargsInstance_strict.set(this, false); - _YargsInstance_strictCommands.set(this, false); - _YargsInstance_strictOptions.set(this, false); - _YargsInstance_usage.set(this, void 0); - _YargsInstance_usageConfig.set(this, {}); - _YargsInstance_versionOpt.set(this, null); - _YargsInstance_validation.set(this, void 0); - __classPrivateFieldSet(this, _YargsInstance_shim, shim, "f"); - __classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f"); - __classPrivateFieldSet(this, _YargsInstance_cwd, cwd, "f"); - __classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f"); - __classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f"); - this.$0 = this[kGetDollarZero](); - this[kReset](); - __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f"); - __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f"); - __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f"); - __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f"); - __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); - __classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f"); - } - addHelpOpt(opt, msg) { - const defaultHelpOpt = 'help'; - argsert('[string|boolean] [string]', [opt, msg], arguments.length); - if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { - this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); - __classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f"); - } - if (opt === false && msg === undefined) - return this; - __classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === 'string' ? opt : defaultHelpOpt, "f"); - this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); - this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show help')); - return this; - } - help(opt, msg) { - return this.addHelpOpt(opt, msg); - } - addShowHiddenOpt(opt, msg) { - argsert('[string|boolean] [string]', [opt, msg], arguments.length); - if (opt === false && msg === undefined) - return this; - const showHiddenOpt = typeof opt === 'string' ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); - this.boolean(showHiddenOpt); - this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show hidden options')); - __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt; - return this; - } - showHidden(opt, msg) { - return this.addShowHiddenOpt(opt, msg); - } - alias(key, value) { - argsert(' [string|array]', [key, value], arguments.length); - this[kPopulateParserHintArrayDictionary](this.alias.bind(this), 'alias', key, value); - return this; - } - array(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('array', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - boolean(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('boolean', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - check(f, global) { - argsert(' [boolean]', [f, global], arguments.length); - this.middleware((argv, _yargs) => { - return maybeAsyncResult(() => { - return f(argv, _yargs.getOptions()); - }, (result) => { - if (!result) { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__('Argument check failed: %s', f.toString())); - } - else if (typeof result === 'string' || result instanceof Error) { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(result.toString(), result); - } - return argv; - }, (err) => { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err); - return argv; - }); - }, false, global); - return this; + +function symlinkTypeSync$1 (srcpath, type) { + if (type) return type + + let stats; + try { + stats = fs$j.lstatSync(srcpath); + } catch { + return 'file' + } + return (stats && stats.isDirectory()) ? 'dir' : 'file' +} + +var symlinkType_1 = { + symlinkType: u$4(symlinkType$1), + symlinkTypeSync: symlinkTypeSync$1 +}; + +const u$3 = universalify$1.fromPromise; +const path$b = require$$1$1; +const fs$i = fs$w; + +const { mkdirs, mkdirsSync } = mkdirs$2; + +const { symlinkPaths, symlinkPathsSync } = symlinkPaths_1; +const { symlinkType, symlinkTypeSync } = symlinkType_1; + +const { pathExists: pathExists$2 } = pathExists_1; + +const { areIdentical } = stat$4; + +async function createSymlink$1 (srcpath, dstpath, type) { + let stats; + try { + stats = await fs$i.lstat(dstpath); + } catch { } + + if (stats && stats.isSymbolicLink()) { + const [srcStat, dstStat] = await Promise.all([ + fs$i.stat(srcpath), + fs$i.stat(dstpath) + ]); + + if (areIdentical(srcStat, dstStat)) return + } + + const relative = await symlinkPaths(srcpath, dstpath); + srcpath = relative.toDst; + const toType = await symlinkType(relative.toCwd, type); + const dir = path$b.dirname(dstpath); + + if (!(await pathExists$2(dir))) { + await mkdirs(dir); + } + + return fs$i.symlink(srcpath, dstpath, toType) +} + +function createSymlinkSync$1 (srcpath, dstpath, type) { + let stats; + try { + stats = fs$i.lstatSync(dstpath); + } catch { } + if (stats && stats.isSymbolicLink()) { + const srcStat = fs$i.statSync(srcpath); + const dstStat = fs$i.statSync(dstpath); + if (areIdentical(srcStat, dstStat)) return + } + + const relative = symlinkPathsSync(srcpath, dstpath); + srcpath = relative.toDst; + type = symlinkTypeSync(relative.toCwd, type); + const dir = path$b.dirname(dstpath); + const exists = fs$i.existsSync(dir); + if (exists) return fs$i.symlinkSync(srcpath, dstpath, type) + mkdirsSync(dir); + return fs$i.symlinkSync(srcpath, dstpath, type) +} + +var symlink = { + createSymlink: u$3(createSymlink$1), + createSymlinkSync: createSymlinkSync$1 +}; + +const { createFile, createFileSync } = file$1; +const { createLink, createLinkSync } = link; +const { createSymlink, createSymlinkSync } = symlink; + +var ensure = { + // file + createFile, + createFileSync, + ensureFile: createFile, + ensureFileSync: createFileSync, + // link + createLink, + createLinkSync, + ensureLink: createLink, + ensureLinkSync: createLinkSync, + // symlink + createSymlink, + createSymlinkSync, + ensureSymlink: createSymlink, + ensureSymlinkSync: createSymlinkSync +}; + +function stringify$3 (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) { + const EOF = finalEOL ? EOL : ''; + const str = JSON.stringify(obj, replacer, spaces); + + return str.replace(/\n/g, EOL) + EOF +} + +function stripBom$1 (content) { + // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified + if (Buffer.isBuffer(content)) content = content.toString('utf8'); + return content.replace(/^\uFEFF/, '') +} + +var utils = { stringify: stringify$3, stripBom: stripBom$1 }; + +let _fs; +try { + _fs = gracefulFs; +} catch (_) { + _fs = require$$0$5; +} +const universalify = universalify$1; +const { stringify: stringify$2, stripBom } = utils; + +async function _readFile (file, options = {}) { + if (typeof options === 'string') { + options = { encoding: options }; + } + + const fs = options.fs || _fs; + + const shouldThrow = 'throws' in options ? options.throws : true; + + let data = await universalify.fromCallback(fs.readFile)(file, options); + + data = stripBom(data); + + let obj; + try { + obj = JSON.parse(data, options ? options.reviver : null); + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}`; + throw err + } else { + return null } - choices(key, value) { - argsert(' [string|array]', [key, value], arguments.length); - this[kPopulateParserHintArrayDictionary](this.choices.bind(this), 'choices', key, value); - return this; + } + + return obj +} + +const readFile = universalify.fromPromise(_readFile); + +function readFileSync (file, options = {}) { + if (typeof options === 'string') { + options = { encoding: options }; + } + + const fs = options.fs || _fs; + + const shouldThrow = 'throws' in options ? options.throws : true; + + try { + let content = fs.readFileSync(file, options); + content = stripBom(content); + return JSON.parse(content, options.reviver) + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}`; + throw err + } else { + return null } - coerce(keys, value) { - argsert(' [function]', [keys, value], arguments.length); - if (Array.isArray(keys)) { - if (!value) { - throw new YError('coerce callback must be provided'); - } - for (const key of keys) { - this.coerce(key, value); - } - return this; - } - else if (typeof keys === 'object') { - for (const key of Object.keys(keys)) { - this.coerce(key, keys[key]); - } - return this; - } - if (!value) { - throw new YError('coerce callback must be provided'); - } - __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; - __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => { - let aliases; - const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); - if (!shouldCoerce) { - return argv; - } - return maybeAsyncResult(() => { - aliases = yargs.getAliases(); - return value(argv[keys]); - }, (result) => { - argv[keys] = result; - const stripAliased = yargs - .getInternalMethods() - .getParserConfiguration()['strip-aliased']; - if (aliases[keys] && stripAliased !== true) { - for (const alias of aliases[keys]) { - argv[alias] = result; - } - } - return argv; - }, (err) => { - throw new YError(err.message); - }); - }, keys); - return this; + } +} + +async function _writeFile (file, obj, options = {}) { + const fs = options.fs || _fs; + + const str = stringify$2(obj, options); + + await universalify.fromCallback(fs.writeFile)(file, str, options); +} + +const writeFile = universalify.fromPromise(_writeFile); + +function writeFileSync (file, obj, options = {}) { + const fs = options.fs || _fs; + + const str = stringify$2(obj, options); + // not sure if fs.writeFileSync returns anything, but just in case + return fs.writeFileSync(file, str, options) +} + +const jsonfile$1 = { + readFile, + readFileSync, + writeFile, + writeFileSync +}; + +var jsonfile_1 = jsonfile$1; + +const jsonFile$1 = jsonfile_1; + +var jsonfile = { + // jsonfile exports + readJson: jsonFile$1.readFile, + readJsonSync: jsonFile$1.readFileSync, + writeJson: jsonFile$1.writeFile, + writeJsonSync: jsonFile$1.writeFileSync +}; + +const u$2 = universalify$1.fromPromise; +const fs$h = fs$w; +const path$a = require$$1$1; +const mkdir = mkdirs$2; +const pathExists$1 = pathExists_1.pathExists; + +async function outputFile$1 (file, data, encoding = 'utf-8') { + const dir = path$a.dirname(file); + + if (!(await pathExists$1(dir))) { + await mkdir.mkdirs(dir); + } + + return fs$h.writeFile(file, data, encoding) +} + +function outputFileSync$1 (file, ...args) { + const dir = path$a.dirname(file); + if (!fs$h.existsSync(dir)) { + mkdir.mkdirsSync(dir); + } + + fs$h.writeFileSync(file, ...args); +} + +var outputFile_1 = { + outputFile: u$2(outputFile$1), + outputFileSync: outputFileSync$1 +}; + +const { stringify: stringify$1 } = utils; +const { outputFile } = outputFile_1; + +async function outputJson (file, data, options = {}) { + const str = stringify$1(data, options); + + await outputFile(file, str, options); +} + +var outputJson_1 = outputJson; + +const { stringify } = utils; +const { outputFileSync } = outputFile_1; + +function outputJsonSync (file, data, options) { + const str = stringify(data, options); + + outputFileSync(file, str, options); +} + +var outputJsonSync_1 = outputJsonSync; + +const u$1 = universalify$1.fromPromise; +const jsonFile = jsonfile; + +jsonFile.outputJson = u$1(outputJson_1); +jsonFile.outputJsonSync = outputJsonSync_1; +// aliases +jsonFile.outputJSON = jsonFile.outputJson; +jsonFile.outputJSONSync = jsonFile.outputJsonSync; +jsonFile.writeJSON = jsonFile.writeJson; +jsonFile.writeJSONSync = jsonFile.writeJsonSync; +jsonFile.readJSON = jsonFile.readJson; +jsonFile.readJSONSync = jsonFile.readJsonSync; + +var json = jsonFile; + +const fs$g = fs$w; +const path$9 = require$$1$1; +const { copy } = copy$1; +const { remove } = remove_1; +const { mkdirp } = mkdirs$2; +const { pathExists } = pathExists_1; +const stat$1 = stat$4; + +async function move$1 (src, dest, opts = {}) { + const overwrite = opts.overwrite || opts.clobber || false; + + const { srcStat, isChangingCase = false } = await stat$1.checkPaths(src, dest, 'move', opts); + + await stat$1.checkParentPaths(src, srcStat, dest, 'move'); + + // If the parent of dest is not root, make sure it exists before proceeding + const destParent = path$9.dirname(dest); + const parsedParentPath = path$9.parse(destParent); + if (parsedParentPath.root !== destParent) { + await mkdirp(destParent); + } + + return doRename$1(src, dest, overwrite, isChangingCase) +} + +async function doRename$1 (src, dest, overwrite, isChangingCase) { + if (!isChangingCase) { + if (overwrite) { + await remove(dest); + } else if (await pathExists(dest)) { + throw new Error('dest already exists.') } - conflicts(key1, key2) { - argsert(' [string|array]', [key1, key2], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicts(key1, key2); - return this; - } - config(key = 'config', msg, parseFn) { - argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length); - if (typeof key === 'object' && !Array.isArray(key)) { - key = applyExtends(key, __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(key); - return this; - } - if (typeof msg === 'function') { - parseFn = msg; - msg = undefined; - } - this.describe(key, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Path to JSON config file')); - (Array.isArray(key) ? key : [key]).forEach(k => { - __classPrivateFieldGet(this, _YargsInstance_options, "f").config[k] = parseFn || true; - }); - return this; - } - completion(cmd, desc, fn) { - argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length); - if (typeof desc === 'function') { - fn = desc; - desc = undefined; - } - __classPrivateFieldSet(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion', "f"); - if (!desc && desc !== false) { - desc = 'generate completion script'; - } - this.command(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), desc); - if (fn) - __classPrivateFieldGet(this, _YargsInstance_completion, "f").registerFunction(fn); - return this; - } - command(cmd, description, builder, handler, middlewares, deprecated) { - argsert(' [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated); - return this; - } - commands(cmd, description, builder, handler, middlewares, deprecated) { - return this.command(cmd, description, builder, handler, middlewares, deprecated); - } - commandDir(dir, opts) { - argsert(' [object]', [dir, opts], arguments.length); - const req = __classPrivateFieldGet(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").require; - __classPrivateFieldGet(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet(this, _YargsInstance_shim, "f").getCallerFile(), opts); - return this; - } - count(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('count', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - default(key, value, defaultDescription) { - argsert(' [*] [string]', [key, value, defaultDescription], arguments.length); - if (defaultDescription) { - assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription; - } - if (typeof value === 'function') { - assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key]) - __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = - __classPrivateFieldGet(this, _YargsInstance_usage, "f").functionDescription(value); - value = value.call(); - } - this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), 'default', key, value); - return this; - } - defaults(key, value, defaultDescription) { - return this.default(key, value, defaultDescription); - } - demandCommand(min = 1, max, minMsg, maxMsg) { - argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length); - if (typeof max !== 'number') { - minMsg = max; - max = Infinity; - } - this.global('_', false); - __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands._ = { - min, - max, - minMsg, - maxMsg, - }; - return this; - } - demand(keys, max, msg) { - if (Array.isArray(max)) { - max.forEach(key => { - assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - this.demandOption(key, msg); - }); - max = Infinity; - } - else if (typeof max !== 'number') { - msg = max; - max = Infinity; - } - if (typeof keys === 'number') { - assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - this.demandCommand(keys, max, msg, msg); - } - else if (Array.isArray(keys)) { - keys.forEach(key => { - assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - this.demandOption(key, msg); - }); - } - else { - if (typeof msg === 'string') { - this.demandOption(keys, msg); - } - else if (msg === true || typeof msg === 'undefined') { - this.demandOption(keys); - } - } - return this; - } - demandOption(keys, msg) { - argsert(' [string]', [keys, msg], arguments.length); - this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), 'demandedOptions', keys, msg); - return this; - } - deprecateOption(option, message) { - argsert(' [string|boolean]', [option, message], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions[option] = message; - return this; - } - describe(keys, description) { - argsert(' [string]', [keys, description], arguments.length); - this[kSetKey](keys, true); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").describe(keys, description); - return this; - } - detectLocale(detect) { - argsert('', [detect], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_detectLocale, detect, "f"); - return this; - } - env(prefix) { - argsert('[string|boolean]', [prefix], arguments.length); - if (prefix === false) - delete __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; - else - __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix = prefix || ''; - return this; - } - epilogue(msg) { - argsert('', [msg], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").epilog(msg); - return this; - } - epilog(msg) { - return this.epilogue(msg); - } - example(cmd, description) { - argsert(' [string]', [cmd, description], arguments.length); - if (Array.isArray(cmd)) { - cmd.forEach(exampleParams => this.example(...exampleParams)); - } - else { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").example(cmd, description); - } - return this; - } - exit(code, err) { - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - __classPrivateFieldSet(this, _YargsInstance_exitError, err, "f"); - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.exit(code); - } - exitProcess(enabled = true) { - argsert('[boolean]', [enabled], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_exitProcess, enabled, "f"); - return this; - } - fail(f) { - argsert('', [f], arguments.length); - if (typeof f === 'boolean' && f !== false) { - throw new YError("Invalid first argument. Expected function or boolean 'false'"); - } - __classPrivateFieldGet(this, _YargsInstance_usage, "f").failFn(f); - return this; - } - getAliases() { - return this.parsed ? this.parsed.aliases : {}; - } - async getCompletion(args, done) { - argsert(' [function]', [args, done], arguments.length); - if (!done) { - return new Promise((resolve, reject) => { - __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => { - if (err) - reject(err); - else - resolve(completions); - }); - }); - } - else { - return __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, done); - } - } - getDemandedOptions() { - argsert([], 0); - return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedOptions; - } - getDemandedCommands() { - argsert([], 0); - return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands; - } - getDeprecatedOptions() { - argsert([], 0); - return __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions; - } - getDetectLocale() { - return __classPrivateFieldGet(this, _YargsInstance_detectLocale, "f"); - } - getExitProcess() { - return __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"); - } - getGroups() { - return Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_groups, "f"), __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")); - } - getHelp() { - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { - if (!this.parsed) { - const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); - if (isPromise(parse)) { - return parse.then(() => { - return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); - }); - } - } - const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); - if (isPromise(builderResponse)) { - return builderResponse.then(() => { - return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); - }); - } - } - return Promise.resolve(__classPrivateFieldGet(this, _YargsInstance_usage, "f").help()); - } - getOptions() { - return __classPrivateFieldGet(this, _YargsInstance_options, "f"); - } - getStrict() { - return __classPrivateFieldGet(this, _YargsInstance_strict, "f"); - } - getStrictCommands() { - return __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"); - } - getStrictOptions() { - return __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"); - } - global(globals, global) { - argsert(' [boolean]', [globals, global], arguments.length); - globals = [].concat(globals); - if (global !== false) { - __classPrivateFieldGet(this, _YargsInstance_options, "f").local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local.filter(l => globals.indexOf(l) === -1); - } - else { - globals.forEach(g => { - if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").local.includes(g)) - __classPrivateFieldGet(this, _YargsInstance_options, "f").local.push(g); - }); - } - return this; - } - group(opts, groupName) { - argsert(' ', [opts, groupName], arguments.length); - const existing = __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName]; - if (__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]) { - delete __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]; - } - const seen = {}; - __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter(key => { - if (seen[key]) - return false; - return (seen[key] = true); - }); - return this; - } - hide(key) { - argsert('', [key], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_options, "f").hiddenOptions.push(key); - return this; - } - implies(key, value) { - argsert(' [number|string|array]', [key, value], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").implies(key, value); - return this; - } - locale(locale) { - argsert('[string]', [locale], arguments.length); - if (locale === undefined) { - this[kGuessLocale](); - return __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.getLocale(); - } - __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); - __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(locale); - return this; - } - middleware(callback, applyBeforeValidation, global) { - return __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global); - } - nargs(key, value) { - argsert(' [number]', [key, value], arguments.length); - this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), 'narg', key, value); - return this; - } - normalize(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('normalize', keys); - return this; - } - number(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('number', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - option(key, opt) { - argsert(' [object]', [key, opt], arguments.length); - if (typeof key === 'object') { - Object.keys(key).forEach(k => { - this.options(k, key[k]); - }); - } - else { - if (typeof opt !== 'object') { - opt = {}; - } - this[kTrackManuallySetKeys](key); - if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && (key === 'version' || (opt === null || opt === void 0 ? void 0 : opt.alias) === 'version')) { - this[kEmitWarning]([ - '"version" is a reserved word.', - 'Please do one of the following:', - '- Disable version with `yargs.version(false)` if using "version" as an option', - '- Use the built-in `yargs.version` method instead (if applicable)', - '- Use a different option key', - 'https://yargs.js.org/docs/#api-reference-version', - ].join('\n'), undefined, 'versionWarning'); - } - __classPrivateFieldGet(this, _YargsInstance_options, "f").key[key] = true; - if (opt.alias) - this.alias(key, opt.alias); - const deprecate = opt.deprecate || opt.deprecated; - if (deprecate) { - this.deprecateOption(key, deprecate); - } - const demand = opt.demand || opt.required || opt.require; - if (demand) { - this.demand(key, demand); - } - if (opt.demandOption) { - this.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined); - } - if (opt.conflicts) { - this.conflicts(key, opt.conflicts); - } - if ('default' in opt) { - this.default(key, opt.default); - } - if (opt.implies !== undefined) { - this.implies(key, opt.implies); - } - if (opt.nargs !== undefined) { - this.nargs(key, opt.nargs); - } - if (opt.config) { - this.config(key, opt.configParser); - } - if (opt.normalize) { - this.normalize(key); - } - if (opt.choices) { - this.choices(key, opt.choices); - } - if (opt.coerce) { - this.coerce(key, opt.coerce); - } - if (opt.group) { - this.group(key, opt.group); - } - if (opt.boolean || opt.type === 'boolean') { - this.boolean(key); - if (opt.alias) - this.boolean(opt.alias); - } - if (opt.array || opt.type === 'array') { - this.array(key); - if (opt.alias) - this.array(opt.alias); - } - if (opt.number || opt.type === 'number') { - this.number(key); - if (opt.alias) - this.number(opt.alias); - } - if (opt.string || opt.type === 'string') { - this.string(key); - if (opt.alias) - this.string(opt.alias); - } - if (opt.count || opt.type === 'count') { - this.count(key); - } - if (typeof opt.global === 'boolean') { - this.global(key, opt.global); - } - if (opt.defaultDescription) { - __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription; - } - if (opt.skipValidation) { - this.skipValidation(key); - } - const desc = opt.describe || opt.description || opt.desc; - const descriptions = __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions(); - if (!Object.prototype.hasOwnProperty.call(descriptions, key) || - typeof desc === 'string') { - this.describe(key, desc); - } - if (opt.hidden) { - this.hide(key); - } - if (opt.requiresArg) { - this.requiresArg(key); - } - } - return this; - } - options(key, opt) { - return this.option(key, opt); - } - parse(args, shortCircuit, _parseFn) { - argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length); - this[kFreeze](); - if (typeof args === 'undefined') { - args = __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); - } - if (typeof shortCircuit === 'object') { - __classPrivateFieldSet(this, _YargsInstance_parseContext, shortCircuit, "f"); - shortCircuit = _parseFn; - } - if (typeof shortCircuit === 'function') { - __classPrivateFieldSet(this, _YargsInstance_parseFn, shortCircuit, "f"); - shortCircuit = false; - } - if (!shortCircuit) - __classPrivateFieldSet(this, _YargsInstance_processArgs, args, "f"); - if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) - __classPrivateFieldSet(this, _YargsInstance_exitProcess, false, "f"); - const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit); - const tmpParsed = this.parsed; - __classPrivateFieldGet(this, _YargsInstance_completion, "f").setParsed(this.parsed); - if (isPromise(parsed)) { - return parsed - .then(argv => { - if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) - __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); - return argv; - }) - .catch(err => { - if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) { - __classPrivateFieldGet(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); - } - throw err; - }) - .finally(() => { - this[kUnfreeze](); - this.parsed = tmpParsed; - }); - } - else { - if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) - __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet(this, _YargsInstance_output, "f")); - this[kUnfreeze](); - this.parsed = tmpParsed; - } - return parsed; - } - parseAsync(args, shortCircuit, _parseFn) { - const maybePromise = this.parse(args, shortCircuit, _parseFn); - return !isPromise(maybePromise) - ? Promise.resolve(maybePromise) - : maybePromise; - } - parseSync(args, shortCircuit, _parseFn) { - const maybePromise = this.parse(args, shortCircuit, _parseFn); - if (isPromise(maybePromise)) { - throw new YError('.parseSync() must not be used with asynchronous builders, handlers, or middleware'); - } - return maybePromise; - } - parserConfiguration(config) { - argsert('', [config], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_parserConfig, config, "f"); - return this; - } - pkgConf(key, rootPath) { - argsert(' [string]', [key, rootPath], arguments.length); - let conf = null; - const obj = this[kPkgUp](rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f")); - if (obj[key] && typeof obj[key] === 'object') { - conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(conf); - } - return this; - } - positional(key, opts) { - argsert(' ', [key, opts], arguments.length); - const supportedOpts = [ - 'default', - 'defaultDescription', - 'implies', - 'normalize', - 'choices', - 'conflicts', - 'coerce', - 'type', - 'describe', - 'desc', - 'description', - 'alias', - ]; - opts = objFilter(opts, (k, v) => { - if (k === 'type' && !['string', 'number', 'boolean'].includes(v)) - return false; - return supportedOpts.includes(k); - }); - const fullCommand = __classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands.length - 1]; - const parseOptions = fullCommand - ? __classPrivateFieldGet(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) - : { - array: [], - alias: {}, - default: {}, - demand: {}, - }; - objectKeys(parseOptions).forEach(pk => { - const parseOption = parseOptions[pk]; - if (Array.isArray(parseOption)) { - if (parseOption.indexOf(key) !== -1) - opts[pk] = true; - } - else { - if (parseOption[key] && !(pk in opts)) - opts[pk] = parseOption[key]; - } - }); - this.group(key, __classPrivateFieldGet(this, _YargsInstance_usage, "f").getPositionalGroupName()); - return this.option(key, opts); - } - recommendCommands(recommend = true) { - argsert('[boolean]', [recommend], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_recommendCommands, recommend, "f"); - return this; - } - required(keys, max, msg) { - return this.demand(keys, max, msg); - } - require(keys, max, msg) { - return this.demand(keys, max, msg); - } - requiresArg(keys) { - argsert(' [number]', [keys], arguments.length); - if (typeof keys === 'string' && __classPrivateFieldGet(this, _YargsInstance_options, "f").narg[keys]) { - return this; - } - else { - this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), 'narg', keys, NaN); - } - return this; - } - showCompletionScript($0, cmd) { - argsert('[string] [string]', [$0, cmd], arguments.length); - $0 = $0 || this.$0; - __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion')); - return this; - } - showHelp(level) { - argsert('[string|function]', [level], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { - if (!this.parsed) { - const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); - if (isPromise(parse)) { - parse.then(() => { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); - }); - return this; - } - } - const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); - if (isPromise(builderResponse)) { - builderResponse.then(() => { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); - }); - return this; - } - } - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); - return this; - } - scriptName(scriptName) { - this.customScriptName = true; - this.$0 = scriptName; - return this; - } - showHelpOnFail(enabled, message) { - argsert('[boolean|string] [string]', [enabled, message], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message); - return this; - } - showVersion(level) { - argsert('[string|function]', [level], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion(level); - return this; - } - skipValidation(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('skipValidation', keys); - return this; - } - strict(enabled) { - argsert('[boolean]', [enabled], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_strict, enabled !== false, "f"); - return this; - } - strictCommands(enabled) { - argsert('[boolean]', [enabled], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_strictCommands, enabled !== false, "f"); - return this; - } - strictOptions(enabled) { - argsert('[boolean]', [enabled], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_strictOptions, enabled !== false, "f"); - return this; - } - string(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('string', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - terminalWidth() { - argsert([], 0); - return __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.stdColumns; - } - updateLocale(obj) { - return this.updateStrings(obj); - } - updateStrings(obj) { - argsert('', [obj], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); - __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.updateLocale(obj); - return this; - } - usage(msg, description, builder, handler) { - argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length); - if (description !== undefined) { - assertNotStrictEqual(msg, null, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - if ((msg || '').match(/^\$0( |$)/)) { - return this.command(msg, description, builder, handler); - } - else { - throw new YError('.usage() description must start with $0 if being used as alias for .command()'); - } - } - else { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").usage(msg); - return this; - } - } - usageConfiguration(config) { - argsert('', [config], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_usageConfig, config, "f"); - return this; - } - version(opt, msg, ver) { - const defaultVersionOpt = 'version'; - argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length); - if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")) { - this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(undefined); - __classPrivateFieldSet(this, _YargsInstance_versionOpt, null, "f"); - } - if (arguments.length === 0) { - ver = this[kGuessVersion](); - opt = defaultVersionOpt; - } - else if (arguments.length === 1) { - if (opt === false) { - return this; - } - ver = opt; - opt = defaultVersionOpt; - } - else if (arguments.length === 2) { - ver = msg; - msg = undefined; - } - __classPrivateFieldSet(this, _YargsInstance_versionOpt, typeof opt === 'string' ? opt : defaultVersionOpt, "f"); - msg = msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show version number'); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(ver || undefined); - this.boolean(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); - this.describe(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"), msg); - return this; - } - wrap(cols) { - argsert('', [cols], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").wrap(cols); - return this; - } - [(_YargsInstance_command = new WeakMap(), _YargsInstance_cwd = new WeakMap(), _YargsInstance_context = new WeakMap(), _YargsInstance_completion = new WeakMap(), _YargsInstance_completionCommand = new WeakMap(), _YargsInstance_defaultShowHiddenOpt = new WeakMap(), _YargsInstance_exitError = new WeakMap(), _YargsInstance_detectLocale = new WeakMap(), _YargsInstance_emittedWarnings = new WeakMap(), _YargsInstance_exitProcess = new WeakMap(), _YargsInstance_frozens = new WeakMap(), _YargsInstance_globalMiddleware = new WeakMap(), _YargsInstance_groups = new WeakMap(), _YargsInstance_hasOutput = new WeakMap(), _YargsInstance_helpOpt = new WeakMap(), _YargsInstance_isGlobalContext = new WeakMap(), _YargsInstance_logger = new WeakMap(), _YargsInstance_output = new WeakMap(), _YargsInstance_options = new WeakMap(), _YargsInstance_parentRequire = new WeakMap(), _YargsInstance_parserConfig = new WeakMap(), _YargsInstance_parseFn = new WeakMap(), _YargsInstance_parseContext = new WeakMap(), _YargsInstance_pkgs = new WeakMap(), _YargsInstance_preservedGroups = new WeakMap(), _YargsInstance_processArgs = new WeakMap(), _YargsInstance_recommendCommands = new WeakMap(), _YargsInstance_shim = new WeakMap(), _YargsInstance_strict = new WeakMap(), _YargsInstance_strictCommands = new WeakMap(), _YargsInstance_strictOptions = new WeakMap(), _YargsInstance_usage = new WeakMap(), _YargsInstance_usageConfig = new WeakMap(), _YargsInstance_versionOpt = new WeakMap(), _YargsInstance_validation = new WeakMap(), kCopyDoubleDash)](argv) { - if (!argv._ || !argv['--']) - return argv; - argv._.push.apply(argv._, argv['--']); - try { - delete argv['--']; - } - catch (_err) { } - return argv; - } - [kCreateLogger]() { - return { - log: (...args) => { - if (!this[kHasParseCallback]()) - console.log(...args); - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) - __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); - __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); - }, - error: (...args) => { - if (!this[kHasParseCallback]()) - console.error(...args); - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) - __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); - __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); - }, - }; - } - [kDeleteFromParserHintObject](optionKey) { - objectKeys(__classPrivateFieldGet(this, _YargsInstance_options, "f")).forEach((hintKey) => { - if (((key) => key === 'configObjects')(hintKey)) - return; - const hint = __classPrivateFieldGet(this, _YargsInstance_options, "f")[hintKey]; - if (Array.isArray(hint)) { - if (hint.includes(optionKey)) - hint.splice(hint.indexOf(optionKey), 1); - } - else if (typeof hint === 'object') { - delete hint[optionKey]; - } - }); - delete __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions()[optionKey]; - } - [kEmitWarning](warning, type, deduplicationId) { - if (!__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) { - __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.emitWarning(warning, type); - __classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true; - } - } - [kFreeze]() { - __classPrivateFieldGet(this, _YargsInstance_frozens, "f").push({ - options: __classPrivateFieldGet(this, _YargsInstance_options, "f"), - configObjects: __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects.slice(0), - exitProcess: __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"), - groups: __classPrivateFieldGet(this, _YargsInstance_groups, "f"), - strict: __classPrivateFieldGet(this, _YargsInstance_strict, "f"), - strictCommands: __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"), - strictOptions: __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"), - completionCommand: __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), - output: __classPrivateFieldGet(this, _YargsInstance_output, "f"), - exitError: __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), - hasOutput: __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"), - parsed: this.parsed, - parseFn: __classPrivateFieldGet(this, _YargsInstance_parseFn, "f"), - parseContext: __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"), - }); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").freeze(); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").freeze(); - __classPrivateFieldGet(this, _YargsInstance_command, "f").freeze(); - __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").freeze(); - } - [kGetDollarZero]() { - let $0 = ''; - let default$0; - if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv()[0])) { - default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(1, 2); - } - else { - default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(0, 1); - } - $0 = default$0 - .map(x => { - const b = this[kRebase](__classPrivateFieldGet(this, _YargsInstance_cwd, "f"), x); - return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; - }) - .join(' ') - .trim(); - if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_') && - __classPrivateFieldGet(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_')) { - $0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f") - .getEnv('_') - .replace(`${__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.execPath())}/`, ''); - } - return $0; - } - [kGetParserConfiguration]() { - return __classPrivateFieldGet(this, _YargsInstance_parserConfig, "f"); - } - [kGetUsageConfiguration]() { - return __classPrivateFieldGet(this, _YargsInstance_usageConfig, "f"); - } - [kGuessLocale]() { - if (!__classPrivateFieldGet(this, _YargsInstance_detectLocale, "f")) - return; - const locale = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_ALL') || - __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_MESSAGES') || - __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANG') || - __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANGUAGE') || - 'en_US'; - this.locale(locale.replace(/[.:].*/, '')); - } - [kGuessVersion]() { - const obj = this[kPkgUp](); - return obj.version || 'unknown'; - } - [kParsePositionalNumbers](argv) { - const args = argv['--'] ? argv['--'] : argv._; - for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { - if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && - Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) { - args[i] = Number(arg); - } - } - return argv; - } - [kPkgUp](rootPath) { - const npath = rootPath || '*'; - if (__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]) - return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; - let obj = {}; - try { - let startDir = rootPath || __classPrivateFieldGet(this, _YargsInstance_shim, "f").mainFilename; - if (!rootPath && __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.extname(startDir)) { - startDir = __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(startDir); - } - const pkgJsonPath = __classPrivateFieldGet(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => { - if (names.includes('package.json')) { - return 'package.json'; - } - else { - return undefined; - } - }); - assertNotStrictEqual(pkgJsonPath, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - obj = JSON.parse(__classPrivateFieldGet(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, 'utf8')); - } - catch (_noop) { } - __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath] = obj || {}; - return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; - } - [kPopulateParserHintArray](type, keys) { - keys = [].concat(keys); - keys.forEach(key => { - key = this[kSanitizeKey](key); - __classPrivateFieldGet(this, _YargsInstance_options, "f")[type].push(key); - }); - } - [kPopulateParserHintSingleValueDictionary](builder, type, key, value) { - this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { - __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = value; - }); - } - [kPopulateParserHintArrayDictionary](builder, type, key, value) { - this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { - __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] || []).concat(value); - }); - } - [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) { - if (Array.isArray(key)) { - key.forEach(k => { - builder(k, value); - }); - } - else if (((key) => typeof key === 'object')(key)) { - for (const k of objectKeys(key)) { - builder(k, key[k]); - } - } - else { - singleKeyHandler(type, this[kSanitizeKey](key), value); - } - } - [kSanitizeKey](key) { - if (key === '__proto__') - return '___proto___'; - return key; - } - [kSetKey](key, set) { - this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), 'key', key, set); - return this; - } - [kUnfreeze]() { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; - const frozen = __classPrivateFieldGet(this, _YargsInstance_frozens, "f").pop(); - assertNotStrictEqual(frozen, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - let configObjects; - (_a = this, _b = this, _c = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, { - options: ({ set value(_o) { __classPrivateFieldSet(_a, _YargsInstance_options, _o, "f"); } }).value, - configObjects, - exitProcess: ({ set value(_o) { __classPrivateFieldSet(_b, _YargsInstance_exitProcess, _o, "f"); } }).value, - groups: ({ set value(_o) { __classPrivateFieldSet(_c, _YargsInstance_groups, _o, "f"); } }).value, - output: ({ set value(_o) { __classPrivateFieldSet(_d, _YargsInstance_output, _o, "f"); } }).value, - exitError: ({ set value(_o) { __classPrivateFieldSet(_e, _YargsInstance_exitError, _o, "f"); } }).value, - hasOutput: ({ set value(_o) { __classPrivateFieldSet(_f, _YargsInstance_hasOutput, _o, "f"); } }).value, - parsed: this.parsed, - strict: ({ set value(_o) { __classPrivateFieldSet(_g, _YargsInstance_strict, _o, "f"); } }).value, - strictCommands: ({ set value(_o) { __classPrivateFieldSet(_h, _YargsInstance_strictCommands, _o, "f"); } }).value, - strictOptions: ({ set value(_o) { __classPrivateFieldSet(_j, _YargsInstance_strictOptions, _o, "f"); } }).value, - completionCommand: ({ set value(_o) { __classPrivateFieldSet(_k, _YargsInstance_completionCommand, _o, "f"); } }).value, - parseFn: ({ set value(_o) { __classPrivateFieldSet(_l, _YargsInstance_parseFn, _o, "f"); } }).value, - parseContext: ({ set value(_o) { __classPrivateFieldSet(_m, _YargsInstance_parseContext, _o, "f"); } }).value, - } = frozen); - __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = configObjects; - __classPrivateFieldGet(this, _YargsInstance_usage, "f").unfreeze(); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").unfreeze(); - __classPrivateFieldGet(this, _YargsInstance_command, "f").unfreeze(); - __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").unfreeze(); - } - [kValidateAsync](validation, argv) { - return maybeAsyncResult(argv, result => { - validation(result); - return result; - }); - } - getInternalMethods() { - return { - getCommandInstance: this[kGetCommandInstance].bind(this), - getContext: this[kGetContext].bind(this), - getHasOutput: this[kGetHasOutput].bind(this), - getLoggerInstance: this[kGetLoggerInstance].bind(this), - getParseContext: this[kGetParseContext].bind(this), - getParserConfiguration: this[kGetParserConfiguration].bind(this), - getUsageConfiguration: this[kGetUsageConfiguration].bind(this), - getUsageInstance: this[kGetUsageInstance].bind(this), - getValidationInstance: this[kGetValidationInstance].bind(this), - hasParseCallback: this[kHasParseCallback].bind(this), - isGlobalContext: this[kIsGlobalContext].bind(this), - postProcess: this[kPostProcess].bind(this), - reset: this[kReset].bind(this), - runValidation: this[kRunValidation].bind(this), - runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this), - setHasOutput: this[kSetHasOutput].bind(this), - }; - } - [kGetCommandInstance]() { - return __classPrivateFieldGet(this, _YargsInstance_command, "f"); - } - [kGetContext]() { - return __classPrivateFieldGet(this, _YargsInstance_context, "f"); - } - [kGetHasOutput]() { - return __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"); - } - [kGetLoggerInstance]() { - return __classPrivateFieldGet(this, _YargsInstance_logger, "f"); - } - [kGetParseContext]() { - return __classPrivateFieldGet(this, _YargsInstance_parseContext, "f") || {}; - } - [kGetUsageInstance]() { - return __classPrivateFieldGet(this, _YargsInstance_usage, "f"); - } - [kGetValidationInstance]() { - return __classPrivateFieldGet(this, _YargsInstance_validation, "f"); - } - [kHasParseCallback]() { - return !!__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"); - } - [kIsGlobalContext]() { - return __classPrivateFieldGet(this, _YargsInstance_isGlobalContext, "f"); - } - [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) { - if (calledFromCommand) - return argv; - if (isPromise(argv)) - return argv; - if (!populateDoubleDash) { - argv = this[kCopyDoubleDash](argv); - } - const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] || - this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined; - if (parsePositionalNumbers) { - argv = this[kParsePositionalNumbers](argv); - } - if (runGlobalMiddleware) { - argv = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); - } - return argv; - } - [kReset](aliases = {}) { - __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f") || {}, "f"); - const tmpOptions = {}; - tmpOptions.local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local || []; - tmpOptions.configObjects = __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []; - const localLookup = {}; - tmpOptions.local.forEach(l => { - localLookup[l] = true; - (aliases[l] || []).forEach(a => { - localLookup[a] = true; - }); - }); - Object.assign(__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => { - const keys = __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName].filter(key => !(key in localLookup)); - if (keys.length > 0) { - acc[groupName] = keys; - } - return acc; - }, {})); - __classPrivateFieldSet(this, _YargsInstance_groups, {}, "f"); - const arrayOptions = [ - 'array', - 'boolean', - 'string', - 'skipValidation', - 'count', - 'normalize', - 'number', - 'hiddenOptions', - ]; - const objectOptions = [ - 'narg', - 'key', - 'alias', - 'default', - 'defaultDescription', - 'config', - 'choices', - 'demandedOptions', - 'demandedCommands', - 'deprecatedOptions', - ]; - arrayOptions.forEach(k => { - tmpOptions[k] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[k] || []).filter((k) => !localLookup[k]); - }); - objectOptions.forEach((k) => { - tmpOptions[k] = objFilter(__classPrivateFieldGet(this, _YargsInstance_options, "f")[k], k => !localLookup[k]); - }); - tmpOptions.envPrefix = __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; - __classPrivateFieldSet(this, _YargsInstance_options, tmpOptions, "f"); - __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f") - ? __classPrivateFieldGet(this, _YargsInstance_usage, "f").reset(localLookup) - : usage(this, __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); - __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f") - ? __classPrivateFieldGet(this, _YargsInstance_validation, "f").reset(localLookup) - : validation(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); - __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f") - ? __classPrivateFieldGet(this, _YargsInstance_command, "f").reset() - : command$1(__classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_validation, "f"), __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); - if (!__classPrivateFieldGet(this, _YargsInstance_completion, "f")) - __classPrivateFieldSet(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_command, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); - __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").reset(); - __classPrivateFieldSet(this, _YargsInstance_completionCommand, null, "f"); - __classPrivateFieldSet(this, _YargsInstance_output, '', "f"); - __classPrivateFieldSet(this, _YargsInstance_exitError, null, "f"); - __classPrivateFieldSet(this, _YargsInstance_hasOutput, false, "f"); - this.parsed = false; - return this; - } - [kRebase](base, dir) { - return __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.relative(base, dir); - } - [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) { - let skipValidation = !!calledFromCommand || helpOnly; - args = args || __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); - __classPrivateFieldGet(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__; - __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration](); - const populateDoubleDash = !!__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration['populate--']; - const config = Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration, { - 'populate--': true, - }); - const parsed = __classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f"), { - configuration: { 'parse-positional-numbers': false, ...config }, - })); - const argv = Object.assign(parsed.argv, __classPrivateFieldGet(this, _YargsInstance_parseContext, "f")); - let argvPromise = undefined; - const aliases = parsed.aliases; - let helpOptSet = false; - let versionOptSet = false; - Object.keys(argv).forEach(key => { - if (key === __classPrivateFieldGet(this, _YargsInstance_helpOpt, "f") && argv[key]) { - helpOptSet = true; - } - else if (key === __classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && argv[key]) { - versionOptSet = true; - } - }); - argv.$0 = this.$0; - this.parsed = parsed; - if (commandIndex === 0) { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").clearCachedHelpMessage(); - } - try { - this[kGuessLocale](); - if (shortCircuit) { - return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false); - } - if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { - const helpCmds = [__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] - .concat(aliases[__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] || []) - .filter(k => k.length > 1); - if (helpCmds.includes('' + argv._[argv._.length - 1])) { - argv._.pop(); - helpOptSet = true; - } - } - __classPrivateFieldSet(this, _YargsInstance_isGlobalContext, false, "f"); - const handlerKeys = __classPrivateFieldGet(this, _YargsInstance_command, "f").getCommands(); - const requestCompletions = __classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey in argv; - const skipRecommendation = helpOptSet || requestCompletions || helpOnly; - if (argv._.length) { - if (handlerKeys.length) { - let firstUnknownCommand; - for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) { - cmd = String(argv._[i]); - if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { - const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly); - return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); - } - else if (!firstUnknownCommand && - cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { - firstUnknownCommand = cmd; - break; - } - } - if (!__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && - __classPrivateFieldGet(this, _YargsInstance_recommendCommands, "f") && - firstUnknownCommand && - !skipRecommendation) { - __classPrivateFieldGet(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys); - } - } - if (__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") && - argv._.includes(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) && - !requestCompletions) { - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - setBlocking(true); - this.showCompletionScript(); - this.exit(0); - } - } - if (__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) { - const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly); - return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); - } - if (requestCompletions) { - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - setBlocking(true); - args = [].concat(args); - const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey}`) + 1); - __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => { - if (err) - throw new YError(err.message); - (completions || []).forEach(completion => { - __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(completion); - }); - this.exit(0); - }); - return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false); - } - if (!__classPrivateFieldGet(this, _YargsInstance_hasOutput, "f")) { - if (helpOptSet) { - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - setBlocking(true); - skipValidation = true; - this.showHelp('log'); - this.exit(0); - } - else if (versionOptSet) { - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - setBlocking(true); - skipValidation = true; - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion('log'); - this.exit(0); - } - } - if (!skipValidation && __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.length > 0) { - skipValidation = Object.keys(argv).some(key => __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true); - } - if (!skipValidation) { - if (parsed.error) - throw new YError(parsed.error.message); - if (!requestCompletions) { - const validation = this[kRunValidation](aliases, {}, parsed.error); - if (!calledFromCommand) { - argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true); - } - argvPromise = this[kValidateAsync](validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv); - if (isPromise(argvPromise) && !calledFromCommand) { - argvPromise = argvPromise.then(() => { - return applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); - }); - } - } - } - } - catch (err) { - if (err instanceof YError) - __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message, err); - else - throw err; - } - return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true); - } - [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) { - const demandedOptions = { ...this.getDemandedOptions() }; - return (argv) => { - if (parseErrors) - throw new YError(parseErrors.message); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").nonOptionCount(argv); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions); - let failedStrictCommands = false; - if (__classPrivateFieldGet(this, _YargsInstance_strictCommands, "f")) { - failedStrictCommands = __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownCommands(argv); - } - if (__classPrivateFieldGet(this, _YargsInstance_strict, "f") && !failedStrictCommands) { - __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand); - } - else if (__classPrivateFieldGet(this, _YargsInstance_strictOptions, "f")) { - __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false); - } - __classPrivateFieldGet(this, _YargsInstance_validation, "f").limitedChoices(argv); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").implications(argv); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicting(argv); - }; - } - [kSetHasOutput]() { - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - } - [kTrackManuallySetKeys](keys) { - if (typeof keys === 'string') { - __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; - } - else { - for (const k of keys) { - __classPrivateFieldGet(this, _YargsInstance_options, "f").key[k] = true; - } - } - } -} -function isYargsInstance(y) { - return !!y && typeof y.getInternalMethods === 'function'; -} - -const Yargs = YargsFactory(shim$1); - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -var fs$w = {}; - -var universalify$1 = {}; - -universalify$1.fromCallback = function (fn) { - return Object.defineProperty(function (...args) { - if (typeof args[args.length - 1] === 'function') fn.apply(this, args); - else { - return new Promise((resolve, reject) => { - args.push((err, res) => (err != null) ? reject(err) : resolve(res)); - fn.apply(this, args); - }) - } - }, 'name', { value: fn.name }) -}; - -universalify$1.fromPromise = function (fn) { - return Object.defineProperty(function (...args) { - const cb = args[args.length - 1]; - if (typeof cb !== 'function') return fn.apply(this, args) - else { - args.pop(); - fn.apply(this, args).then(r => cb(null, r), cb); - } - }, 'name', { value: fn.name }) -}; - -var constants = require$$0$3; - -var origCwd = process.cwd; -var cwd = null; - -var platform$1 = process.env.GRACEFUL_FS_PLATFORM || process.platform; - -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process); - return cwd -}; -try { - process.cwd(); -} catch (er) {} - -// This check is needed until node.js 12 is required -if (typeof process.chdir === 'function') { - var chdir = process.chdir; - process.chdir = function (d) { - cwd = null; - chdir.call(process, d); - }; - if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir); -} - -var polyfills$1 = patch$1; - -function patch$1 (fs) { - // (re-)implement some things that are known busted or missing. - - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs); - } - - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs); - } - - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - - fs.chown = chownFix(fs.chown); - fs.fchown = chownFix(fs.fchown); - fs.lchown = chownFix(fs.lchown); - - fs.chmod = chmodFix(fs.chmod); - fs.fchmod = chmodFix(fs.fchmod); - fs.lchmod = chmodFix(fs.lchmod); - - fs.chownSync = chownFixSync(fs.chownSync); - fs.fchownSync = chownFixSync(fs.fchownSync); - fs.lchownSync = chownFixSync(fs.lchownSync); - - fs.chmodSync = chmodFixSync(fs.chmodSync); - fs.fchmodSync = chmodFixSync(fs.fchmodSync); - fs.lchmodSync = chmodFixSync(fs.lchmodSync); - - fs.stat = statFix(fs.stat); - fs.fstat = statFix(fs.fstat); - fs.lstat = statFix(fs.lstat); - - fs.statSync = statFixSync(fs.statSync); - fs.fstatSync = statFixSync(fs.fstatSync); - fs.lstatSync = statFixSync(fs.lstatSync); - - // if lchmod/lchown do not exist, then make them no-ops - if (fs.chmod && !fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb); - }; - fs.lchmodSync = function () {}; - } - if (fs.chown && !fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb); - }; - fs.lchownSync = function () {}; - } - - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. - - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform$1 === "win32") { - fs.rename = typeof fs.rename !== 'function' ? fs.rename - : (function (fs$rename) { - function rename (from, to, cb) { - var start = Date.now(); - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er); - }); - }, backoff); - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er); - }); - } - if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename); - return rename - })(fs.rename); - } - - // if read() returns EAGAIN, then just try it again. - fs.read = typeof fs.read !== 'function' ? fs.read - : (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback; - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0; - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++; - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments); - }; - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - - // This ensures `util.promisify` works as it does for native `fs.read`. - if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read); - return read - })(fs.read); - - fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync - : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0; - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++; - continue - } - throw er - } - } - }})(fs.readSync); - - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err); - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2); - }); - }); - }); - }; - - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode); - - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true; - var ret; - try { - ret = fs.fchmodSync(fd, mode); - threw = false; - } finally { - if (threw) { - try { - fs.closeSync(fd); - } catch (er) {} - } else { - fs.closeSync(fd); - } - } - return ret - }; - } - - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er); - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2); - }); - }); - }); - }; - - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK); - var ret; - var threw = true; - try { - ret = fs.futimesSync(fd, at, mt); - threw = false; - } finally { - if (threw) { - try { - fs.closeSync(fd); - } catch (er) {} - } else { - fs.closeSync(fd); - } - } - return ret - }; - - } else if (fs.futimes) { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); }; - fs.lutimesSync = function () {}; - } - } - - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null; - if (cb) cb.apply(this, arguments); - }) - } - } - - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } - - - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null; - if (cb) cb.apply(this, arguments); - }) - } - } - - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } - - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options; - options = null; - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000; - if (stats.gid < 0) stats.gid += 0x100000000; - } - if (cb) cb.apply(this, arguments); - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } - - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target); - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000; - if (stats.gid < 0) stats.gid += 0x100000000; - } - return stats; - } - } - - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true - - if (er.code === "ENOSYS") - return true - - var nonroot = !process.getuid || process.getuid() !== 0; - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } - - return false - } -} - -var Stream$1 = require$$0$4.Stream; - -var legacyStreams = legacy$1; - -function legacy$1 (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } - - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); - - Stream$1.call(this); - - var self = this; - - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; - - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.encoding) this.setEncoding(this.encoding); - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } - - if (this.start > this.end) { - throw new Error('start must be <= end'); - } - - this.pos = this.start; - } - - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } - - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } - - self.fd = fd; - self.emit('open', fd); - self._read(); - }); - } - - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - - Stream$1.call(this); - - this.path = path; - this.fd = null; - this.writable = true; - - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } - - this.pos = this.start; - } - - this.busy = false; - this._queue = []; - - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } -} - -var clone_1 = clone$1; - -var getPrototypeOf = Object.getPrototypeOf || function (obj) { - return obj.__proto__ -}; - -function clone$1 (obj) { - if (obj === null || typeof obj !== 'object') - return obj - - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) }; - else - var copy = Object.create(null); - - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)); - }); - - return copy -} - -var fs$v = require$$0$5; -var polyfills = polyfills$1; -var legacy = legacyStreams; -var clone = clone_1; - -var util$t = require$$0$6; - -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue; -var previousSymbol; - -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue'); - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous'); -} else { - gracefulQueue = '___graceful-fs.queue'; - previousSymbol = '___graceful-fs.previous'; -} - -function noop$2 () {} - -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }); -} - -var debug = noop$2; -if (util$t.debuglog) - debug = util$t.debuglog('gfs4'); -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util$t.format.apply(util$t, arguments); - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: '); - console.error(m); - }; - -// Once time initialization -if (!fs$v[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = commonjsGlobal[gracefulQueue] || []; - publishQueue(fs$v, queue); - - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs$v.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs$v, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - resetQueue(); - } - - if (typeof cb === 'function') - cb.apply(this, arguments); - }) - } - - Object.defineProperty(close, previousSymbol, { - value: fs$close - }); - return close - })(fs$v.close); - - fs$v.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs$v, arguments); - resetQueue(); - } - - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }); - return closeSync - })(fs$v.closeSync); - - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs$v[gracefulQueue]); - require$$5$1.equal(fs$v[gracefulQueue].length, 0); - }); - } -} - -if (!commonjsGlobal[gracefulQueue]) { - publishQueue(commonjsGlobal, fs$v[gracefulQueue]); -} - -var gracefulFs = patch(clone(fs$v)); -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$v.__patched) { - gracefulFs = patch(fs$v); - fs$v.__patched = true; -} - -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs); - fs.gracefulify = patch; - - fs.createReadStream = createReadStream; - fs.createWriteStream = createWriteStream; - var fs$readFile = fs.readFile; - fs.readFile = readFile; - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null; - - return go$readFile(path, options, cb) - - function go$readFile (path, options, cb, startTime) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb === 'function') - cb.apply(this, arguments); - } - }) - } - } - - var fs$writeFile = fs.writeFile; - fs.writeFile = writeFile; - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null; - - return go$writeFile(path, data, options, cb) - - function go$writeFile (path, data, options, cb, startTime) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb === 'function') - cb.apply(this, arguments); - } - }) - } - } - - var fs$appendFile = fs.appendFile; - if (fs$appendFile) - fs.appendFile = appendFile; - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null; - - return go$appendFile(path, data, options, cb) - - function go$appendFile (path, data, options, cb, startTime) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb === 'function') - cb.apply(this, arguments); - } - }) - } - } - - var fs$copyFile = fs.copyFile; - if (fs$copyFile) - fs.copyFile = copyFile; - function copyFile (src, dest, flags, cb) { - if (typeof flags === 'function') { - cb = flags; - flags = 0; - } - return go$copyFile(src, dest, flags, cb) - - function go$copyFile (src, dest, flags, cb, startTime) { - return fs$copyFile(src, dest, flags, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb === 'function') - cb.apply(this, arguments); - } - }) - } - } - - var fs$readdir = fs.readdir; - fs.readdir = readdir; - var noReaddirOptionVersions = /^v[0-5]\./; - function readdir (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null; - - var go$readdir = noReaddirOptionVersions.test(process.version) - ? function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, fs$readdirCallback( - path, options, cb, startTime - )) - } - : function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, options, fs$readdirCallback( - path, options, cb, startTime - )) - }; - - return go$readdir(path, options, cb) - - function fs$readdirCallback (path, options, cb, startTime) { - return function (err, files) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([ - go$readdir, - [path, options, cb], - err, - startTime || Date.now(), - Date.now() - ]); - else { - if (files && files.sort) - files.sort(); - - if (typeof cb === 'function') - cb.call(this, err, files); - } - } - } - } - - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs); - ReadStream = legStreams.ReadStream; - WriteStream = legStreams.WriteStream; - } - - var fs$ReadStream = fs.ReadStream; - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype); - ReadStream.prototype.open = ReadStream$open; - } - - var fs$WriteStream = fs.WriteStream; - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype); - WriteStream.prototype.open = WriteStream$open; - } - - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val; - }, - enumerable: true, - configurable: true - }); - - // legacy names - var FileReadStream = ReadStream; - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val; - }, - enumerable: true, - configurable: true - }); - var FileWriteStream = WriteStream; - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val; - }, - enumerable: true, - configurable: true - }); - - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } - - function ReadStream$open () { - var that = this; - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy(); - - that.emit('error', err); - } else { - that.fd = fd; - that.emit('open', fd); - that.read(); - } - }); - } - - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } - - function WriteStream$open () { - var that = this; - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy(); - that.emit('error', err); - } else { - that.fd = fd; - that.emit('open', fd); - } - }); - } - - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } - - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } - - var fs$open = fs.open; - fs.open = open; - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null; - - return go$open(path, flags, mode, cb) - - function go$open (path, flags, mode, cb, startTime) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]); - else { - if (typeof cb === 'function') - cb.apply(this, arguments); - } - }) - } - } - - return fs -} - -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]); - fs$v[gracefulQueue].push(elem); - retry(); -} - -// keep track of the timeout between retry() calls -var retryTimer; - -// reset the startTime and lastTime to now -// this resets the start of the 60 second overall timeout as well as the -// delay between attempts so that we'll retry these jobs sooner -function resetQueue () { - var now = Date.now(); - for (var i = 0; i < fs$v[gracefulQueue].length; ++i) { - // entries that are only a length of 2 are from an older version, don't - // bother modifying those since they'll be retried anyway. - if (fs$v[gracefulQueue][i].length > 2) { - fs$v[gracefulQueue][i][3] = now; // startTime - fs$v[gracefulQueue][i][4] = now; // lastTime - } - } - // call retry to make sure we're actively processing the queue - retry(); -} - -function retry () { - // clear the timer and remove it to help prevent unintended concurrency - clearTimeout(retryTimer); - retryTimer = undefined; - - if (fs$v[gracefulQueue].length === 0) - return - - var elem = fs$v[gracefulQueue].shift(); - var fn = elem[0]; - var args = elem[1]; - // these items may be unset if they were added by an older graceful-fs - var err = elem[2]; - var startTime = elem[3]; - var lastTime = elem[4]; - - // if we don't have a startTime we have no way of knowing if we've waited - // long enough, so go ahead and retry this item now - if (startTime === undefined) { - debug('RETRY', fn.name, args); - fn.apply(null, args); - } else if (Date.now() - startTime >= 60000) { - // it's been more than 60 seconds total, bail now - debug('TIMEOUT', fn.name, args); - var cb = args.pop(); - if (typeof cb === 'function') - cb.call(null, err); - } else { - // the amount of time between the last attempt and right now - var sinceAttempt = Date.now() - lastTime; - // the amount of time between when we first tried, and when we last tried - // rounded up to at least 1 - var sinceStart = Math.max(lastTime - startTime, 1); - // backoff. wait longer than the total time we've been retrying, but only - // up to a maximum of 100ms - var desiredDelay = Math.min(sinceStart * 1.2, 100); - // it's been long enough since the last retry, do it again - if (sinceAttempt >= desiredDelay) { - debug('RETRY', fn.name, args); - fn.apply(null, args.concat([startTime])); - } else { - // if we can't do this job yet, push it to the end of the queue - // and let the next iteration check again - fs$v[gracefulQueue].push(elem); - } - } - - // schedule our next run if one isn't already scheduled - if (retryTimer === undefined) { - retryTimer = setTimeout(retry, 0); - } -} - -(function (exports) { - // This is adapted from https://github.com/normalize/mz - // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors - const u = universalify$1.fromCallback; - const fs = gracefulFs; - - const api = [ - 'access', - 'appendFile', - 'chmod', - 'chown', - 'close', - 'copyFile', - 'fchmod', - 'fchown', - 'fdatasync', - 'fstat', - 'fsync', - 'ftruncate', - 'futimes', - 'lchmod', - 'lchown', - 'link', - 'lstat', - 'mkdir', - 'mkdtemp', - 'open', - 'opendir', - 'readdir', - 'readFile', - 'readlink', - 'realpath', - 'rename', - 'rm', - 'rmdir', - 'stat', - 'symlink', - 'truncate', - 'unlink', - 'utimes', - 'writeFile' - ].filter(key => { - // Some commands are not available on some systems. Ex: - // fs.cp was added in Node.js v16.7.0 - // fs.lchown is not available on at least some Linux - return typeof fs[key] === 'function' - }); - - // Export cloned fs: - Object.assign(exports, fs); - - // Universalify async methods: - api.forEach(method => { - exports[method] = u(fs[method]); - }); - - // We differ from mz/fs in that we still ship the old, broken, fs.exists() - // since we are a drop-in replacement for the native module - exports.exists = function (filename, callback) { - if (typeof callback === 'function') { - return fs.exists(filename, callback) - } - return new Promise(resolve => { - return fs.exists(filename, resolve) - }) - }; - - // fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args - - exports.read = function (fd, buffer, offset, length, position, callback) { - if (typeof callback === 'function') { - return fs.read(fd, buffer, offset, length, position, callback) - } - return new Promise((resolve, reject) => { - fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { - if (err) return reject(err) - resolve({ bytesRead, buffer }); - }); - }) - }; - - // Function signature can be - // fs.write(fd, buffer[, offset[, length[, position]]], callback) - // OR - // fs.write(fd, string[, position[, encoding]], callback) - // We need to handle both cases, so we use ...args - exports.write = function (fd, buffer, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.write(fd, buffer, ...args) - } - - return new Promise((resolve, reject) => { - fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { - if (err) return reject(err) - resolve({ bytesWritten, buffer }); - }); - }) - }; - - // Function signature is - // s.readv(fd, buffers[, position], callback) - // We need to handle the optional arg, so we use ...args - exports.readv = function (fd, buffers, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.readv(fd, buffers, ...args) - } - - return new Promise((resolve, reject) => { - fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => { - if (err) return reject(err) - resolve({ bytesRead, buffers }); - }); - }) - }; - - // Function signature is - // s.writev(fd, buffers[, position], callback) - // We need to handle the optional arg, so we use ...args - exports.writev = function (fd, buffers, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.writev(fd, buffers, ...args) - } - - return new Promise((resolve, reject) => { - fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { - if (err) return reject(err) - resolve({ bytesWritten, buffers }); - }); - }) - }; - - // fs.realpath.native sometimes not available if fs is monkey-patched - if (typeof fs.realpath.native === 'function') { - exports.realpath.native = u(fs.realpath.native); - } else { - process.emitWarning( - 'fs.realpath.native is not a function. Is fs being monkey-patched?', - 'Warning', 'fs-extra-WARN0003' - ); - } -} (fs$w)); - -var makeDir$1 = {}; - -var utils$1 = {}; - -const path$j = require$$1$1; - -// https://github.com/nodejs/node/issues/8987 -// https://github.com/libuv/libuv/pull/1088 -utils$1.checkPath = function checkPath (pth) { - if (process.platform === 'win32') { - const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path$j.parse(pth).root, '')); - - if (pathHasInvalidWinCharacters) { - const error = new Error(`Path contains invalid characters: ${pth}`); - error.code = 'EINVAL'; - throw error - } - } -}; - -const fs$u = fs$w; -const { checkPath } = utils$1; - -const getMode = options => { - const defaults = { mode: 0o777 }; - if (typeof options === 'number') return options - return ({ ...defaults, ...options }).mode -}; - -makeDir$1.makeDir = async (dir, options) => { - checkPath(dir); - - return fs$u.mkdir(dir, { - mode: getMode(options), - recursive: true - }) -}; - -makeDir$1.makeDirSync = (dir, options) => { - checkPath(dir); - - return fs$u.mkdirSync(dir, { - mode: getMode(options), - recursive: true - }) -}; - -const u$e = universalify$1.fromPromise; -const { makeDir: _makeDir, makeDirSync } = makeDir$1; -const makeDir = u$e(_makeDir); - -var mkdirs$2 = { - mkdirs: makeDir, - mkdirsSync: makeDirSync, - // alias - mkdirp: makeDir, - mkdirpSync: makeDirSync, - ensureDir: makeDir, - ensureDirSync: makeDirSync -}; - -const u$d = universalify$1.fromPromise; -const fs$t = fs$w; - -function pathExists$6 (path) { - return fs$t.access(path).then(() => true).catch(() => false) -} - -var pathExists_1 = { - pathExists: u$d(pathExists$6), - pathExistsSync: fs$t.existsSync -}; - -const fs$s = fs$w; -const u$c = universalify$1.fromPromise; - -async function utimesMillis$1 (path, atime, mtime) { - // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) - const fd = await fs$s.open(path, 'r+'); - - let closeErr = null; - - try { - await fs$s.futimes(fd, atime, mtime); - } finally { - try { - await fs$s.close(fd); - } catch (e) { - closeErr = e; - } - } - - if (closeErr) { - throw closeErr - } -} - -function utimesMillisSync$1 (path, atime, mtime) { - const fd = fs$s.openSync(path, 'r+'); - fs$s.futimesSync(fd, atime, mtime); - return fs$s.closeSync(fd) -} - -var utimes = { - utimesMillis: u$c(utimesMillis$1), - utimesMillisSync: utimesMillisSync$1 -}; - -const fs$r = fs$w; -const path$i = require$$1$1; -const u$b = universalify$1.fromPromise; - -function getStats$1 (src, dest, opts) { - const statFunc = opts.dereference - ? (file) => fs$r.stat(file, { bigint: true }) - : (file) => fs$r.lstat(file, { bigint: true }); - return Promise.all([ - statFunc(src), - statFunc(dest).catch(err => { - if (err.code === 'ENOENT') return null - throw err - }) - ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) -} - -function getStatsSync (src, dest, opts) { - let destStat; - const statFunc = opts.dereference - ? (file) => fs$r.statSync(file, { bigint: true }) - : (file) => fs$r.lstatSync(file, { bigint: true }); - const srcStat = statFunc(src); - try { - destStat = statFunc(dest); - } catch (err) { - if (err.code === 'ENOENT') return { srcStat, destStat: null } - throw err - } - return { srcStat, destStat } -} - -async function checkPaths (src, dest, funcName, opts) { - const { srcStat, destStat } = await getStats$1(src, dest, opts); - if (destStat) { - if (areIdentical$2(srcStat, destStat)) { - const srcBaseName = path$i.basename(src); - const destBaseName = path$i.basename(dest); - if (funcName === 'move' && - srcBaseName !== destBaseName && - srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { - return { srcStat, destStat, isChangingCase: true } - } - throw new Error('Source and destination must not be the same.') - } - if (srcStat.isDirectory() && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) - } - if (!srcStat.isDirectory() && destStat.isDirectory()) { - throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) - } - } - - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)) - } - - return { srcStat, destStat } -} - -function checkPathsSync (src, dest, funcName, opts) { - const { srcStat, destStat } = getStatsSync(src, dest, opts); - - if (destStat) { - if (areIdentical$2(srcStat, destStat)) { - const srcBaseName = path$i.basename(src); - const destBaseName = path$i.basename(dest); - if (funcName === 'move' && - srcBaseName !== destBaseName && - srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { - return { srcStat, destStat, isChangingCase: true } - } - throw new Error('Source and destination must not be the same.') - } - if (srcStat.isDirectory() && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) - } - if (!srcStat.isDirectory() && destStat.isDirectory()) { - throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) - } - } - - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)) - } - return { srcStat, destStat } -} - -// 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, funcName) { - const srcParent = path$i.resolve(path$i.dirname(src)); - const destParent = path$i.resolve(path$i.dirname(dest)); - if (destParent === srcParent || destParent === path$i.parse(destParent).root) return - - let destStat; - try { - destStat = await fs$r.stat(destParent, { bigint: true }); - } catch (err) { - if (err.code === 'ENOENT') return - throw err - } - - if (areIdentical$2(srcStat, destStat)) { - throw new Error(errMsg(src, dest, funcName)) - } - - return checkParentPaths(src, srcStat, destParent, funcName) -} - -function checkParentPathsSync (src, srcStat, dest, funcName) { - const srcParent = path$i.resolve(path$i.dirname(src)); - const destParent = path$i.resolve(path$i.dirname(dest)); - if (destParent === srcParent || destParent === path$i.parse(destParent).root) return - let destStat; - try { - destStat = fs$r.statSync(destParent, { bigint: true }); - } catch (err) { - if (err.code === 'ENOENT') return - throw err - } - if (areIdentical$2(srcStat, destStat)) { - throw new Error(errMsg(src, dest, funcName)) - } - return checkParentPathsSync(src, srcStat, destParent, funcName) -} - -function areIdentical$2 (srcStat, destStat) { - return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev -} - -// return true if dest is a subdir of src, otherwise false. -// It only checks the path strings. -function isSrcSubdir (src, dest) { - const srcArr = path$i.resolve(src).split(path$i.sep).filter(i => i); - const destArr = path$i.resolve(dest).split(path$i.sep).filter(i => i); - return srcArr.every((cur, i) => destArr[i] === cur) -} - -function errMsg (src, dest, funcName) { - return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` -} - -var stat$4 = { - // checkPaths - checkPaths: u$b(checkPaths), - checkPathsSync, - // checkParent - checkParentPaths: u$b(checkParentPaths), - checkParentPathsSync, - // Misc - isSrcSubdir, - areIdentical: areIdentical$2 -}; - -const fs$q = fs$w; -const path$h = require$$1$1; -const { mkdirs: mkdirs$1 } = mkdirs$2; -const { pathExists: pathExists$5 } = pathExists_1; -const { utimesMillis } = utimes; -const stat$3 = stat$4; - -async function copy$2 (src, dest, opts = {}) { - if (typeof opts === 'function') { - opts = { filter: opts }; - } - - opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber - - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - process.emitWarning( - 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + - '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', - 'Warning', 'fs-extra-WARN0001' - ); - } - - const { srcStat, destStat } = await stat$3.checkPaths(src, dest, 'copy', opts); - - await stat$3.checkParentPaths(src, srcStat, dest, 'copy'); - - const include = await runFilter(src, dest, opts); - - if (!include) return - - // check if the parent of dest exists, and create it if it doesn't exist - const destParent = path$h.dirname(dest); - const dirExists = await pathExists$5(destParent); - if (!dirExists) { - await mkdirs$1(destParent); - } - - await getStatsAndPerformCopy(destStat, src, dest, opts); -} - -async function runFilter (src, dest, opts) { - if (!opts.filter) return true - return opts.filter(src, dest) -} - -async function getStatsAndPerformCopy (destStat, src, dest, opts) { - const statFn = opts.dereference ? fs$q.stat : fs$q.lstat; - const srcStat = await statFn(src); - - if (srcStat.isDirectory()) return onDir$1(srcStat, destStat, src, dest, opts) - - if ( - srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice() - ) return onFile$1(srcStat, destStat, src, dest, opts) - - if (srcStat.isSymbolicLink()) return onLink$1(destStat, src, dest, opts) - if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) - if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) - throw new Error(`Unknown file: ${src}`) -} - -async function onFile$1 (srcStat, destStat, src, dest, opts) { - if (!destStat) return copyFile$1(srcStat, src, dest, opts) - - if (opts.overwrite) { - await fs$q.unlink(dest); - return copyFile$1(srcStat, src, dest, opts) - } - if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`) - } -} - -async function copyFile$1 (srcStat, src, dest, opts) { - await fs$q.copyFile(src, dest); - if (opts.preserveTimestamps) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable$1(srcStat.mode)) { - await makeFileWritable$1(dest, srcStat.mode); - } - - // Set timestamps and mode correspondingly - - // Note that 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 fs$q.stat(src); - await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime); - } - - return fs$q.chmod(dest, srcStat.mode) -} - -function fileIsNotWritable$1 (srcMode) { - return (srcMode & 0o200) === 0 -} - -function makeFileWritable$1 (dest, srcMode) { - return fs$q.chmod(dest, srcMode | 0o200) -} - -async function onDir$1 (srcStat, destStat, src, dest, opts) { - // the dest directory might not exist, create it - if (!destStat) { - await fs$q.mkdir(dest); - } - - const items = await fs$q.readdir(src); - - // loop through the files in the current directory to copy everything - await Promise.all(items.map(async item => { - const srcItem = path$h.join(src, item); - const destItem = path$h.join(dest, item); - - // skip the item if it is matches by the filter function - const include = await runFilter(srcItem, destItem, opts); - if (!include) return - - const { destStat } = await stat$3.checkPaths(srcItem, destItem, 'copy', opts); - - // If the item is a copyable file, `getStatsAndPerformCopy` will copy it - // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively - return getStatsAndPerformCopy(destStat, srcItem, destItem, opts) - })); - - if (!destStat) { - await fs$q.chmod(dest, srcStat.mode); - } -} - -async function onLink$1 (destStat, src, dest, opts) { - let resolvedSrc = await fs$q.readlink(src); - if (opts.dereference) { - resolvedSrc = path$h.resolve(process.cwd(), resolvedSrc); - } - if (!destStat) { - return fs$q.symlink(resolvedSrc, dest) - } - - let resolvedDest = null; - try { - resolvedDest = await fs$q.readlink(dest); - } catch (e) { - // 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. - if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs$q.symlink(resolvedSrc, dest) - throw e - } - if (opts.dereference) { - resolvedDest = path$h.resolve(process.cwd(), resolvedDest); - } - if (stat$3.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) - } - - // 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. - if (stat$3.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) - } - - // copy the link - await fs$q.unlink(dest); - return fs$q.symlink(resolvedSrc, dest) -} - -var copy_1 = copy$2; - -const fs$p = gracefulFs; -const path$g = require$$1$1; -const mkdirsSync$1 = mkdirs$2.mkdirsSync; -const utimesMillisSync = utimes.utimesMillisSync; -const stat$2 = stat$4; - -function copySync$1 (src, dest, opts) { - if (typeof opts === 'function') { - opts = { filter: opts }; - } - - opts = opts || {}; - opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber - - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - process.emitWarning( - 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + - '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', - 'Warning', 'fs-extra-WARN0002' - ); - } - - const { srcStat, destStat } = stat$2.checkPathsSync(src, dest, 'copy', opts); - stat$2.checkParentPathsSync(src, srcStat, dest, 'copy'); - if (opts.filter && !opts.filter(src, dest)) return - const destParent = path$g.dirname(dest); - if (!fs$p.existsSync(destParent)) mkdirsSync$1(destParent); - return getStats(destStat, src, dest, opts) -} - -function getStats (destStat, src, dest, opts) { - const statSync = opts.dereference ? fs$p.statSync : fs$p.lstatSync; - const srcStat = statSync(src); - - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) - else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) - else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) - throw new Error(`Unknown file: ${src}`) -} - -function onFile (srcStat, destStat, src, dest, opts) { - if (!destStat) return copyFile(srcStat, src, dest, opts) - return mayCopyFile(srcStat, src, dest, opts) -} - -function mayCopyFile (srcStat, src, dest, opts) { - if (opts.overwrite) { - fs$p.unlinkSync(dest); - return copyFile(srcStat, src, dest, opts) - } else if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`) - } -} - -function copyFile (srcStat, src, dest, opts) { - fs$p.copyFileSync(src, dest); - if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest); - return setDestMode(dest, srcStat.mode) -} - -function handleTimestamps (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)) makeFileWritable(dest, srcMode); - return setDestTimestamps(src, dest) -} - -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} - -function makeFileWritable (dest, srcMode) { - return setDestMode(dest, srcMode | 0o200) -} - -function setDestMode (dest, srcMode) { - return fs$p.chmodSync(dest, srcMode) -} - -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 = fs$p.statSync(src); - return utimesMillisSync(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) -} - -function mkDirAndCopy (srcMode, src, dest, opts) { - fs$p.mkdirSync(dest); - copyDir(src, dest, opts); - return setDestMode(dest, srcMode) -} - -function copyDir (src, dest, opts) { - fs$p.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)); -} - -function copyDirItem (item, src, dest, opts) { - const srcItem = path$g.join(src, item); - const destItem = path$g.join(dest, item); - if (opts.filter && !opts.filter(srcItem, destItem)) return - const { destStat } = stat$2.checkPathsSync(srcItem, destItem, 'copy', opts); - return getStats(destStat, srcItem, destItem, opts) -} - -function onLink (destStat, src, dest, opts) { - let resolvedSrc = fs$p.readlinkSync(src); - if (opts.dereference) { - resolvedSrc = path$g.resolve(process.cwd(), resolvedSrc); - } - - if (!destStat) { - return fs$p.symlinkSync(resolvedSrc, dest) - } else { - let resolvedDest; - try { - resolvedDest = fs$p.readlinkSync(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. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs$p.symlinkSync(resolvedSrc, dest) - throw err - } - if (opts.dereference) { - resolvedDest = path$g.resolve(process.cwd(), resolvedDest); - } - if (stat$2.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) - } - - // prevent 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. - if (stat$2.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) - } - return copyLink(resolvedSrc, dest) - } -} - -function copyLink (resolvedSrc, dest) { - fs$p.unlinkSync(dest); - return fs$p.symlinkSync(resolvedSrc, dest) -} - -var copySync_1 = copySync$1; - -const u$a = universalify$1.fromPromise; -var copy$1 = { - copy: u$a(copy_1), - copySync: copySync_1 -}; - -const fs$o = gracefulFs; -const u$9 = universalify$1.fromCallback; - -function remove$2 (path, callback) { - fs$o.rm(path, { recursive: true, force: true }, callback); -} - -function removeSync$1 (path) { - fs$o.rmSync(path, { recursive: true, force: true }); -} - -var remove_1 = { - remove: u$9(remove$2), - removeSync: removeSync$1 -}; - -const u$8 = universalify$1.fromPromise; -const fs$n = fs$w; -const path$f = require$$1$1; -const mkdir$3 = mkdirs$2; -const remove$1 = remove_1; - -const emptyDir = u$8(async function emptyDir (dir) { - let items; - try { - items = await fs$n.readdir(dir); - } catch { - return mkdir$3.mkdirs(dir) - } - - return Promise.all(items.map(item => remove$1.remove(path$f.join(dir, item)))) -}); - -function emptyDirSync (dir) { - let items; - try { - items = fs$n.readdirSync(dir); - } catch { - return mkdir$3.mkdirsSync(dir) - } - - items.forEach(item => { - item = path$f.join(dir, item); - remove$1.removeSync(item); - }); -} - -var empty = { - emptyDirSync, - emptydirSync: emptyDirSync, - emptyDir, - emptydir: emptyDir -}; - -const u$7 = universalify$1.fromPromise; -const path$e = require$$1$1; -const fs$m = fs$w; -const mkdir$2 = mkdirs$2; - -async function createFile$1 (file) { - let stats; - try { - stats = await fs$m.stat(file); - } catch { } - if (stats && stats.isFile()) return - - const dir = path$e.dirname(file); - - let dirStats = null; - try { - dirStats = await fs$m.stat(dir); - } catch (err) { - // if the directory doesn't exist, make it - if (err.code === 'ENOENT') { - await mkdir$2.mkdirs(dir); - await fs$m.writeFile(file, ''); - return - } else { - throw err - } - } - - if (dirStats.isDirectory()) { - await fs$m.writeFile(file, ''); - } else { - // parent is not a directory - // This is just to cause an internal ENOTDIR error to be thrown - await fs$m.readdir(dir); - } -} - -function createFileSync$1 (file) { - let stats; - try { - stats = fs$m.statSync(file); - } catch { } - if (stats && stats.isFile()) return - - const dir = path$e.dirname(file); - try { - if (!fs$m.statSync(dir).isDirectory()) { - // parent is not a directory - // This is just to cause an internal ENOTDIR error to be thrown - fs$m.readdirSync(dir); - } - } catch (err) { - // If the stat call above failed because the directory doesn't exist, create it - if (err && err.code === 'ENOENT') mkdir$2.mkdirsSync(dir); - else throw err - } - - fs$m.writeFileSync(file, ''); -} - -var file$1 = { - createFile: u$7(createFile$1), - createFileSync: createFileSync$1 -}; - -const u$6 = universalify$1.fromPromise; -const path$d = require$$1$1; -const fs$l = fs$w; -const mkdir$1 = mkdirs$2; -const { pathExists: pathExists$4 } = pathExists_1; -const { areIdentical: areIdentical$1 } = stat$4; - -async function createLink$1 (srcpath, dstpath) { - let dstStat; - try { - dstStat = await fs$l.lstat(dstpath); - } catch { - // ignore error - } - - let srcStat; - try { - srcStat = await fs$l.lstat(srcpath); - } catch (err) { - err.message = err.message.replace('lstat', 'ensureLink'); - throw err - } - - if (dstStat && areIdentical$1(srcStat, dstStat)) return - - const dir = path$d.dirname(dstpath); - - const dirExists = await pathExists$4(dir); - - if (!dirExists) { - await mkdir$1.mkdirs(dir); - } - - await fs$l.link(srcpath, dstpath); -} - -function createLinkSync$1 (srcpath, dstpath) { - let dstStat; - try { - dstStat = fs$l.lstatSync(dstpath); - } catch {} - - try { - const srcStat = fs$l.lstatSync(srcpath); - if (dstStat && areIdentical$1(srcStat, dstStat)) return - } catch (err) { - err.message = err.message.replace('lstat', 'ensureLink'); - throw err - } - - const dir = path$d.dirname(dstpath); - const dirExists = fs$l.existsSync(dir); - if (dirExists) return fs$l.linkSync(srcpath, dstpath) - mkdir$1.mkdirsSync(dir); - - return fs$l.linkSync(srcpath, dstpath) -} - -var link = { - createLink: u$6(createLink$1), - createLinkSync: createLinkSync$1 -}; - -const path$c = require$$1$1; -const fs$k = fs$w; -const { pathExists: pathExists$3 } = pathExists_1; - -const u$5 = universalify$1.fromPromise; - -/** - * Function that returns two types of paths, one relative to symlink, and one - * relative to the current working directory. Checks if path is absolute or - * relative. If the path is relative, this function checks if the path is - * relative to symlink or relative to current working directory. This is an - * initiative to find a smarter `srcpath` to supply when building symlinks. - * This allows you to determine which path to use out of one of three possible - * types of source paths. The first is an absolute path. This is detected by - * `path.isAbsolute()`. When an absolute path is provided, it is checked to - * see if it exists. If it does it's used, if not an error is returned - * (callback)/ thrown (sync). The other two options for `srcpath` are a - * relative url. By default Node's `fs.symlink` works by creating a symlink - * using `dstpath` and expects the `srcpath` to be relative to the newly - * created symlink. If you provide a `srcpath` that does not exist on the file - * system it results in a broken symlink. To minimize this, the function - * checks to see if the 'relative to symlink' source file exists, and if it - * does it will use it. If it does not, it checks if there's a file that - * exists that is relative to the current working directory, if does its used. - * This preserves the expectations of the original fs.symlink spec and adds - * the ability to pass in `relative to current working direcotry` paths. - */ - -async function symlinkPaths$1 (srcpath, dstpath) { - if (path$c.isAbsolute(srcpath)) { - try { - await fs$k.lstat(srcpath); - } catch (err) { - err.message = err.message.replace('lstat', 'ensureSymlink'); - throw err - } - - return { - toCwd: srcpath, - toDst: srcpath - } - } - - const dstdir = path$c.dirname(dstpath); - const relativeToDst = path$c.join(dstdir, srcpath); - - const exists = await pathExists$3(relativeToDst); - if (exists) { - return { - toCwd: relativeToDst, - toDst: srcpath - } - } - - try { - await fs$k.lstat(srcpath); - } catch (err) { - err.message = err.message.replace('lstat', 'ensureSymlink'); - throw err - } - - return { - toCwd: srcpath, - toDst: path$c.relative(dstdir, srcpath) - } -} - -function symlinkPathsSync$1 (srcpath, dstpath) { - if (path$c.isAbsolute(srcpath)) { - const exists = fs$k.existsSync(srcpath); - if (!exists) throw new Error('absolute srcpath does not exist') - return { - toCwd: srcpath, - toDst: srcpath - } - } - - const dstdir = path$c.dirname(dstpath); - const relativeToDst = path$c.join(dstdir, srcpath); - const exists = fs$k.existsSync(relativeToDst); - if (exists) { - return { - toCwd: relativeToDst, - toDst: srcpath - } - } - - const srcExists = fs$k.existsSync(srcpath); - if (!srcExists) throw new Error('relative srcpath does not exist') - return { - toCwd: srcpath, - toDst: path$c.relative(dstdir, srcpath) - } -} - -var symlinkPaths_1 = { - symlinkPaths: u$5(symlinkPaths$1), - symlinkPathsSync: symlinkPathsSync$1 -}; - -const fs$j = fs$w; -const u$4 = universalify$1.fromPromise; - -async function symlinkType$1 (srcpath, type) { - if (type) return type - - let stats; - try { - stats = await fs$j.lstat(srcpath); - } catch { - return 'file' - } - - return (stats && stats.isDirectory()) ? 'dir' : 'file' -} - -function symlinkTypeSync$1 (srcpath, type) { - if (type) return type - - let stats; - try { - stats = fs$j.lstatSync(srcpath); - } catch { - return 'file' - } - return (stats && stats.isDirectory()) ? 'dir' : 'file' -} - -var symlinkType_1 = { - symlinkType: u$4(symlinkType$1), - symlinkTypeSync: symlinkTypeSync$1 -}; - -const u$3 = universalify$1.fromPromise; -const path$b = require$$1$1; -const fs$i = fs$w; - -const { mkdirs, mkdirsSync } = mkdirs$2; - -const { symlinkPaths, symlinkPathsSync } = symlinkPaths_1; -const { symlinkType, symlinkTypeSync } = symlinkType_1; - -const { pathExists: pathExists$2 } = pathExists_1; - -const { areIdentical } = stat$4; - -async function createSymlink$1 (srcpath, dstpath, type) { - let stats; - try { - stats = await fs$i.lstat(dstpath); - } catch { } - - if (stats && stats.isSymbolicLink()) { - const [srcStat, dstStat] = await Promise.all([ - fs$i.stat(srcpath), - fs$i.stat(dstpath) - ]); - - if (areIdentical(srcStat, dstStat)) return - } - - const relative = await symlinkPaths(srcpath, dstpath); - srcpath = relative.toDst; - const toType = await symlinkType(relative.toCwd, type); - const dir = path$b.dirname(dstpath); - - if (!(await pathExists$2(dir))) { - await mkdirs(dir); - } - - return fs$i.symlink(srcpath, dstpath, toType) -} - -function createSymlinkSync$1 (srcpath, dstpath, type) { - let stats; - try { - stats = fs$i.lstatSync(dstpath); - } catch { } - if (stats && stats.isSymbolicLink()) { - const srcStat = fs$i.statSync(srcpath); - const dstStat = fs$i.statSync(dstpath); - if (areIdentical(srcStat, dstStat)) return - } - - const relative = symlinkPathsSync(srcpath, dstpath); - srcpath = relative.toDst; - type = symlinkTypeSync(relative.toCwd, type); - const dir = path$b.dirname(dstpath); - const exists = fs$i.existsSync(dir); - if (exists) return fs$i.symlinkSync(srcpath, dstpath, type) - mkdirsSync(dir); - return fs$i.symlinkSync(srcpath, dstpath, type) -} - -var symlink = { - createSymlink: u$3(createSymlink$1), - createSymlinkSync: createSymlinkSync$1 -}; - -const { createFile, createFileSync } = file$1; -const { createLink, createLinkSync } = link; -const { createSymlink, createSymlinkSync } = symlink; - -var ensure = { - // file - createFile, - createFileSync, - ensureFile: createFile, - ensureFileSync: createFileSync, - // link - createLink, - createLinkSync, - ensureLink: createLink, - ensureLinkSync: createLinkSync, - // symlink - createSymlink, - createSymlinkSync, - ensureSymlink: createSymlink, - ensureSymlinkSync: createSymlinkSync -}; - -function stringify$3 (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) { - const EOF = finalEOL ? EOL : ''; - const str = JSON.stringify(obj, replacer, spaces); - - return str.replace(/\n/g, EOL) + EOF -} - -function stripBom$1 (content) { - // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified - if (Buffer.isBuffer(content)) content = content.toString('utf8'); - return content.replace(/^\uFEFF/, '') -} - -var utils = { stringify: stringify$3, stripBom: stripBom$1 }; - -let _fs; -try { - _fs = gracefulFs; -} catch (_) { - _fs = require$$0$5; -} -const universalify = universalify$1; -const { stringify: stringify$2, stripBom } = utils; - -async function _readFile (file, options = {}) { - if (typeof options === 'string') { - options = { encoding: options }; - } - - const fs = options.fs || _fs; - - const shouldThrow = 'throws' in options ? options.throws : true; - - let data = await universalify.fromCallback(fs.readFile)(file, options); - - data = stripBom(data); - - let obj; - try { - obj = JSON.parse(data, options ? options.reviver : null); - } catch (err) { - if (shouldThrow) { - err.message = `${file}: ${err.message}`; - throw err - } else { - return null - } - } - - return obj -} - -const readFile = universalify.fromPromise(_readFile); - -function readFileSync (file, options = {}) { - if (typeof options === 'string') { - options = { encoding: options }; - } - - const fs = options.fs || _fs; - - const shouldThrow = 'throws' in options ? options.throws : true; - - try { - let content = fs.readFileSync(file, options); - content = stripBom(content); - return JSON.parse(content, options.reviver) - } catch (err) { - if (shouldThrow) { - err.message = `${file}: ${err.message}`; - throw err - } else { - return null - } - } -} - -async function _writeFile (file, obj, options = {}) { - const fs = options.fs || _fs; - - const str = stringify$2(obj, options); - - await universalify.fromCallback(fs.writeFile)(file, str, options); -} - -const writeFile = universalify.fromPromise(_writeFile); - -function writeFileSync (file, obj, options = {}) { - const fs = options.fs || _fs; - - const str = stringify$2(obj, options); - // not sure if fs.writeFileSync returns anything, but just in case - return fs.writeFileSync(file, str, options) -} - -const jsonfile$1 = { - readFile, - readFileSync, - writeFile, - writeFileSync -}; - -var jsonfile_1 = jsonfile$1; - -const jsonFile$1 = jsonfile_1; - -var jsonfile = { - // jsonfile exports - readJson: jsonFile$1.readFile, - readJsonSync: jsonFile$1.readFileSync, - writeJson: jsonFile$1.writeFile, - writeJsonSync: jsonFile$1.writeFileSync -}; - -const u$2 = universalify$1.fromPromise; -const fs$h = fs$w; -const path$a = require$$1$1; -const mkdir = mkdirs$2; -const pathExists$1 = pathExists_1.pathExists; - -async function outputFile$1 (file, data, encoding = 'utf-8') { - const dir = path$a.dirname(file); - - if (!(await pathExists$1(dir))) { - await mkdir.mkdirs(dir); - } - - return fs$h.writeFile(file, data, encoding) -} - -function outputFileSync$1 (file, ...args) { - const dir = path$a.dirname(file); - if (!fs$h.existsSync(dir)) { - mkdir.mkdirsSync(dir); - } - - fs$h.writeFileSync(file, ...args); -} - -var outputFile_1 = { - outputFile: u$2(outputFile$1), - outputFileSync: outputFileSync$1 -}; - -const { stringify: stringify$1 } = utils; -const { outputFile } = outputFile_1; - -async function outputJson (file, data, options = {}) { - const str = stringify$1(data, options); - - await outputFile(file, str, options); -} - -var outputJson_1 = outputJson; - -const { stringify } = utils; -const { outputFileSync } = outputFile_1; - -function outputJsonSync (file, data, options) { - const str = stringify(data, options); - - outputFileSync(file, str, options); -} - -var outputJsonSync_1 = outputJsonSync; - -const u$1 = universalify$1.fromPromise; -const jsonFile = jsonfile; - -jsonFile.outputJson = u$1(outputJson_1); -jsonFile.outputJsonSync = outputJsonSync_1; -// aliases -jsonFile.outputJSON = jsonFile.outputJson; -jsonFile.outputJSONSync = jsonFile.outputJsonSync; -jsonFile.writeJSON = jsonFile.writeJson; -jsonFile.writeJSONSync = jsonFile.writeJsonSync; -jsonFile.readJSON = jsonFile.readJson; -jsonFile.readJSONSync = jsonFile.readJsonSync; - -var json = jsonFile; - -const fs$g = fs$w; -const path$9 = require$$1$1; -const { copy } = copy$1; -const { remove } = remove_1; -const { mkdirp } = mkdirs$2; -const { pathExists } = pathExists_1; -const stat$1 = stat$4; - -async function move$1 (src, dest, opts = {}) { - const overwrite = opts.overwrite || opts.clobber || false; - - const { srcStat, isChangingCase = false } = await stat$1.checkPaths(src, dest, 'move', opts); - - await stat$1.checkParentPaths(src, srcStat, dest, 'move'); - - // If the parent of dest is not root, make sure it exists before proceeding - const destParent = path$9.dirname(dest); - const parsedParentPath = path$9.parse(destParent); - if (parsedParentPath.root !== destParent) { - await mkdirp(destParent); - } - - return doRename$1(src, dest, overwrite, isChangingCase) -} - -async function doRename$1 (src, dest, overwrite, isChangingCase) { - if (!isChangingCase) { - if (overwrite) { - await remove(dest); - } else if (await pathExists(dest)) { - throw new Error('dest already exists.') - } - } - - try { - // Try w/ rename first, and try copy + remove if EXDEV - await fs$g.rename(src, dest); - } catch (err) { - if (err.code !== 'EXDEV') { - throw err + } + + try { + // Try w/ rename first, and try copy + remove if EXDEV + await fs$g.rename(src, dest); + } catch (err) { + if (err.code !== 'EXDEV') { + throw err } await moveAcrossDevice$1(src, dest, overwrite); } @@ -25210,7 +19907,7 @@ function hasFlag$i(flag, argv = globalThis.Deno ? globalThis.Deno.args : process return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); } -const {env: env$9} = process$2; +const {env: env$a} = process$2; let flagForceColor; if ( @@ -25230,16 +19927,16 @@ if ( } function envForceColor() { - if ('FORCE_COLOR' in env$9) { - if (env$9.FORCE_COLOR === 'true') { + if ('FORCE_COLOR' in env$a) { + if (env$a.FORCE_COLOR === 'true') { return 1; } - if (env$9.FORCE_COLOR === 'false') { + if (env$a.FORCE_COLOR === 'false') { return 0; } - return env$9.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env$9.FORCE_COLOR, 10), 3); + return env$a.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env$a.FORCE_COLOR, 10), 3); } } @@ -25282,7 +19979,7 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { // Check for Azure DevOps pipelines. // Has to be above the `!streamIsTTY` check. - if ('TF_BUILD' in env$9 && 'AGENT_NAME' in env$9) { + if ('TF_BUILD' in env$a && 'AGENT_NAME' in env$a) { return 1; } @@ -25292,7 +19989,7 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { const min = forceColor || 0; - if (env$9.TERM === 'dumb') { + if (env$a.TERM === 'dumb') { return min; } @@ -25310,34 +20007,34 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { return 1; } - if ('CI' in env$9) { - if ('GITHUB_ACTIONS' in env$9 || 'GITEA_ACTIONS' in env$9) { + if ('CI' in env$a) { + if ('GITHUB_ACTIONS' in env$a || 'GITEA_ACTIONS' in env$a) { return 3; } - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env$9) || env$9.CI_NAME === 'codeship') { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env$a) || env$a.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env$9) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$9.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$a) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$a.TEAMCITY_VERSION) ? 1 : 0; } - if (env$9.COLORTERM === 'truecolor') { + if (env$a.COLORTERM === 'truecolor') { return 3; } - if (env$9.TERM === 'xterm-kitty') { + if (env$a.TERM === 'xterm-kitty') { return 3; } - if ('TERM_PROGRAM' in env$9) { - const version = Number.parseInt((env$9.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$a) { + const version = Number.parseInt((env$a.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env$9.TERM_PROGRAM) { + switch (env$a.TERM_PROGRAM) { case 'iTerm.app': { return version >= 3 ? 3 : 2; } @@ -25349,15 +20046,15 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { } } - if (/-256(color)?$/i.test(env$9.TERM)) { + if (/-256(color)?$/i.test(env$a.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$9.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$a.TERM)) { return 1; } - if ('COLORTERM' in env$9) { + if ('COLORTERM' in env$a) { return 1; } @@ -31572,7 +26269,7 @@ const os$i = require$$0$7; const tty$8 = require$$1$3; const hasFlag$g = hasFlag$h; -const {env: env$8} = process; +const {env: env$9} = process; let forceColor$8; if (hasFlag$g('no-color') || @@ -31587,13 +26284,13 @@ if (hasFlag$g('no-color') || forceColor$8 = 1; } -if ('FORCE_COLOR' in env$8) { - if (env$8.FORCE_COLOR === 'true') { +if ('FORCE_COLOR' in env$9) { + if (env$9.FORCE_COLOR === 'true') { forceColor$8 = 1; - } else if (env$8.FORCE_COLOR === 'false') { + } else if (env$9.FORCE_COLOR === 'false') { forceColor$8 = 0; } else { - forceColor$8 = env$8.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$8.FORCE_COLOR, 10), 3); + forceColor$8 = env$9.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$9.FORCE_COLOR, 10), 3); } } @@ -31631,7 +26328,7 @@ function supportsColor$8(haveStream, streamIsTTY) { const min = forceColor$8 || 0; - if (env$8.TERM === 'dumb') { + if (env$9.TERM === 'dumb') { return min; } @@ -31649,26 +26346,26 @@ function supportsColor$8(haveStream, streamIsTTY) { return 1; } - if ('CI' in env$8) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$8) || env$8.CI_NAME === 'codeship') { + if ('CI' in env$9) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$9) || env$9.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env$8) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$8.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$9) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$9.TEAMCITY_VERSION) ? 1 : 0; } - if (env$8.COLORTERM === 'truecolor') { + if (env$9.COLORTERM === 'truecolor') { return 3; } - if ('TERM_PROGRAM' in env$8) { - const version = parseInt((env$8.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$9) { + const version = parseInt((env$9.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env$8.TERM_PROGRAM) { + switch (env$9.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': @@ -31677,15 +26374,15 @@ function supportsColor$8(haveStream, streamIsTTY) { } } - if (/-256(color)?$/i.test(env$8.TERM)) { + if (/-256(color)?$/i.test(env$9.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$8.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$9.TERM)) { return 1; } - if ('COLORTERM' in env$8) { + if ('COLORTERM' in env$9) { return 1; } @@ -34075,9 +28772,9 @@ var ansiRegex$1 = ({onlyFirst = false} = {}) => { const ansiRegex = ansiRegex$1; -var stripAnsi$2 = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; +var stripAnsi$3 = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; -var stripAnsi$3 = /*@__PURE__*/getDefaultExportFromCjs(stripAnsi$2); +var stripAnsi$4 = /*@__PURE__*/getDefaultExportFromCjs(stripAnsi$3); var isFullwidthCodePoint$2 = {exports: {}}; @@ -34138,7 +28835,7 @@ var emojiRegex$1 = function () { return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; -const stripAnsi$1 = stripAnsi$2; +const stripAnsi$2 = stripAnsi$3; const isFullwidthCodePoint = isFullwidthCodePointExports; const emojiRegex = emojiRegex$1; @@ -34147,7 +28844,7 @@ const stringWidth$1 = string => { return 0; } - string = stripAnsi$1(string); + string = stripAnsi$2(string); if (string.length === 0) { return 0; @@ -34188,7 +28885,7 @@ stringWidth$2.exports.default = stringWidth$1; var stringWidthExports = stringWidth$2.exports; const stringWidth = stringWidthExports; -const stripAnsi = stripAnsi$2; +const stripAnsi$1 = stripAnsi$3; const ansiStyles$8 = ansiStylesExports; const ESCAPES = new Set([ @@ -34210,7 +28907,7 @@ const wrapWord = (rows, word, columns) => { const characters = [...word]; let isInsideEscape = false; - let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + let visible = stringWidth(stripAnsi$1(rows[rows.length - 1])); for (const [index, character] of characters.entries()) { const characterLength = stringWidth(character); @@ -34849,7 +29546,7 @@ class ScreenManager { * Write message to screen and setPrompt to control backspace */ const promptLine = lastLine(content); - const rawPromptLine = stripAnsi$3(promptLine); + const rawPromptLine = stripAnsi$4(promptLine); // Remove the rl.line from our prompt. We can't rely on the content of // rl.line (mainly because of the password prompt), so just rely on it's // length. @@ -35217,7 +29914,7 @@ const os$h = require$$0$7; const tty$7 = require$$1$3; const hasFlag$e = hasFlag$f; -const {env: env$7} = process; +const {env: env$8} = process; let forceColor$7; if (hasFlag$e('no-color') || @@ -35232,13 +29929,13 @@ if (hasFlag$e('no-color') || forceColor$7 = 1; } -if ('FORCE_COLOR' in env$7) { - if (env$7.FORCE_COLOR === 'true') { +if ('FORCE_COLOR' in env$8) { + if (env$8.FORCE_COLOR === 'true') { forceColor$7 = 1; - } else if (env$7.FORCE_COLOR === 'false') { + } else if (env$8.FORCE_COLOR === 'false') { forceColor$7 = 0; } else { - forceColor$7 = env$7.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$7.FORCE_COLOR, 10), 3); + forceColor$7 = env$8.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$8.FORCE_COLOR, 10), 3); } } @@ -35276,7 +29973,7 @@ function supportsColor$7(haveStream, streamIsTTY) { const min = forceColor$7 || 0; - if (env$7.TERM === 'dumb') { + if (env$8.TERM === 'dumb') { return min; } @@ -35294,26 +29991,26 @@ function supportsColor$7(haveStream, streamIsTTY) { return 1; } - if ('CI' in env$7) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$7) || env$7.CI_NAME === 'codeship') { + if ('CI' in env$8) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$8) || env$8.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env$7) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$7.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$8) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$8.TEAMCITY_VERSION) ? 1 : 0; } - if (env$7.COLORTERM === 'truecolor') { + if (env$8.COLORTERM === 'truecolor') { return 3; } - if ('TERM_PROGRAM' in env$7) { - const version = parseInt((env$7.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$8) { + const version = parseInt((env$8.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env$7.TERM_PROGRAM) { + switch (env$8.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': @@ -35322,15 +30019,15 @@ function supportsColor$7(haveStream, streamIsTTY) { } } - if (/-256(color)?$/i.test(env$7.TERM)) { + if (/-256(color)?$/i.test(env$8.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$7.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$8.TERM)) { return 1; } - if ('COLORTERM' in env$7) { + if ('COLORTERM' in env$8) { return 1; } @@ -35766,7 +30463,7 @@ const os$g = require$$0$7; const tty$6 = require$$1$3; const hasFlag$c = hasFlag$d; -const {env: env$6} = process; +const {env: env$7} = process; let forceColor$6; if (hasFlag$c('no-color') || @@ -35781,13 +30478,13 @@ if (hasFlag$c('no-color') || forceColor$6 = 1; } -if ('FORCE_COLOR' in env$6) { - if (env$6.FORCE_COLOR === 'true') { +if ('FORCE_COLOR' in env$7) { + if (env$7.FORCE_COLOR === 'true') { forceColor$6 = 1; - } else if (env$6.FORCE_COLOR === 'false') { + } else if (env$7.FORCE_COLOR === 'false') { forceColor$6 = 0; } else { - forceColor$6 = env$6.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$6.FORCE_COLOR, 10), 3); + forceColor$6 = env$7.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$7.FORCE_COLOR, 10), 3); } } @@ -35825,7 +30522,7 @@ function supportsColor$6(haveStream, streamIsTTY) { const min = forceColor$6 || 0; - if (env$6.TERM === 'dumb') { + if (env$7.TERM === 'dumb') { return min; } @@ -35843,26 +30540,26 @@ function supportsColor$6(haveStream, streamIsTTY) { return 1; } - if ('CI' in env$6) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$6) || env$6.CI_NAME === 'codeship') { + if ('CI' in env$7) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$7) || env$7.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env$6) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$6.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$7) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$7.TEAMCITY_VERSION) ? 1 : 0; } - if (env$6.COLORTERM === 'truecolor') { + if (env$7.COLORTERM === 'truecolor') { return 3; } - if ('TERM_PROGRAM' in env$6) { - const version = parseInt((env$6.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$7) { + const version = parseInt((env$7.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env$6.TERM_PROGRAM) { + switch (env$7.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': @@ -35871,15 +30568,15 @@ function supportsColor$6(haveStream, streamIsTTY) { } } - if (/-256(color)?$/i.test(env$6.TERM)) { + if (/-256(color)?$/i.test(env$7.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$6.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$7.TERM)) { return 1; } - if ('COLORTERM' in env$6) { + if ('COLORTERM' in env$7) { return 1; } @@ -36315,7 +31012,7 @@ const os$f = require$$0$7; const tty$5 = require$$1$3; const hasFlag$a = hasFlag$b; -const {env: env$5} = process; +const {env: env$6} = process; let forceColor$5; if (hasFlag$a('no-color') || @@ -36330,13 +31027,13 @@ if (hasFlag$a('no-color') || forceColor$5 = 1; } -if ('FORCE_COLOR' in env$5) { - if (env$5.FORCE_COLOR === 'true') { +if ('FORCE_COLOR' in env$6) { + if (env$6.FORCE_COLOR === 'true') { forceColor$5 = 1; - } else if (env$5.FORCE_COLOR === 'false') { + } else if (env$6.FORCE_COLOR === 'false') { forceColor$5 = 0; } else { - forceColor$5 = env$5.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$5.FORCE_COLOR, 10), 3); + forceColor$5 = env$6.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$6.FORCE_COLOR, 10), 3); } } @@ -36374,7 +31071,7 @@ function supportsColor$5(haveStream, streamIsTTY) { const min = forceColor$5 || 0; - if (env$5.TERM === 'dumb') { + if (env$6.TERM === 'dumb') { return min; } @@ -36392,26 +31089,26 @@ function supportsColor$5(haveStream, streamIsTTY) { return 1; } - if ('CI' in env$5) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$5) || env$5.CI_NAME === 'codeship') { + if ('CI' in env$6) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$6) || env$6.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env$5) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$5.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$6) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$6.TEAMCITY_VERSION) ? 1 : 0; } - if (env$5.COLORTERM === 'truecolor') { + if (env$6.COLORTERM === 'truecolor') { return 3; } - if ('TERM_PROGRAM' in env$5) { - const version = parseInt((env$5.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$6) { + const version = parseInt((env$6.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env$5.TERM_PROGRAM) { + switch (env$6.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': @@ -36420,15 +31117,15 @@ function supportsColor$5(haveStream, streamIsTTY) { } } - if (/-256(color)?$/i.test(env$5.TERM)) { + if (/-256(color)?$/i.test(env$6.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$5.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$6.TERM)) { return 1; } - if ('COLORTERM' in env$5) { + if ('COLORTERM' in env$6) { return 1; } @@ -52633,7 +47330,7 @@ const fs$b = require$$0$5; const path$3 = require$$1$1; const crypto = require$$2$1; const osTmpDir = osTmpdir; -const _c = process.binding('constants'); +const _c$1 = process.binding('constants'); /* * The working inner variables. @@ -52652,10 +47349,10 @@ const DEFAULT_TRIES = 3, - CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), + CREATE_FLAGS = (_c$1.O_CREAT || _c$1.fs.O_CREAT) | (_c$1.O_EXCL || _c$1.fs.O_EXCL) | (_c$1.O_RDWR || _c$1.fs.O_RDWR), - EBADF = _c.EBADF || _c.os.errno.EBADF, - ENOENT = _c.ENOENT || _c.os.errno.ENOENT, + EBADF = _c$1.EBADF || _c$1.os.errno.EBADF, + ENOENT = _c$1.ENOENT || _c$1.os.errno.ENOENT, DIR_MODE = 448 /* 0o700 */, FILE_MODE = 384 /* 0o600 */, @@ -53598,7 +48295,7 @@ const os$e = require$$0$7; const tty$4 = require$$1$3; const hasFlag$8 = hasFlag$9; -const {env: env$4} = process; +const {env: env$5} = process; let forceColor$4; if (hasFlag$8('no-color') || @@ -53613,13 +48310,13 @@ if (hasFlag$8('no-color') || forceColor$4 = 1; } -if ('FORCE_COLOR' in env$4) { - if (env$4.FORCE_COLOR === 'true') { +if ('FORCE_COLOR' in env$5) { + if (env$5.FORCE_COLOR === 'true') { forceColor$4 = 1; - } else if (env$4.FORCE_COLOR === 'false') { + } else if (env$5.FORCE_COLOR === 'false') { forceColor$4 = 0; } else { - forceColor$4 = env$4.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$4.FORCE_COLOR, 10), 3); + forceColor$4 = env$5.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$5.FORCE_COLOR, 10), 3); } } @@ -53657,7 +48354,7 @@ function supportsColor$4(haveStream, streamIsTTY) { const min = forceColor$4 || 0; - if (env$4.TERM === 'dumb') { + if (env$5.TERM === 'dumb') { return min; } @@ -53675,26 +48372,26 @@ function supportsColor$4(haveStream, streamIsTTY) { return 1; } - if ('CI' in env$4) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$4) || env$4.CI_NAME === 'codeship') { + if ('CI' in env$5) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$5) || env$5.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env$4) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$4.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$5) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$5.TEAMCITY_VERSION) ? 1 : 0; } - if (env$4.COLORTERM === 'truecolor') { + if (env$5.COLORTERM === 'truecolor') { return 3; } - if ('TERM_PROGRAM' in env$4) { - const version = parseInt((env$4.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$5) { + const version = parseInt((env$5.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env$4.TERM_PROGRAM) { + switch (env$5.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': @@ -53703,15 +48400,15 @@ function supportsColor$4(haveStream, streamIsTTY) { } } - if (/-256(color)?$/i.test(env$4.TERM)) { + if (/-256(color)?$/i.test(env$5.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$4.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$5.TERM)) { return 1; } - if ('COLORTERM' in env$4) { + if ('COLORTERM' in env$5) { return 1; } @@ -54147,7 +48844,7 @@ const os$d = require$$0$7; const tty$3 = require$$1$3; const hasFlag$6 = hasFlag$7; -const {env: env$3} = process; +const {env: env$4} = process; let forceColor$3; if (hasFlag$6('no-color') || @@ -54162,13 +48859,13 @@ if (hasFlag$6('no-color') || forceColor$3 = 1; } -if ('FORCE_COLOR' in env$3) { - if (env$3.FORCE_COLOR === 'true') { +if ('FORCE_COLOR' in env$4) { + if (env$4.FORCE_COLOR === 'true') { forceColor$3 = 1; - } else if (env$3.FORCE_COLOR === 'false') { + } else if (env$4.FORCE_COLOR === 'false') { forceColor$3 = 0; } else { - forceColor$3 = env$3.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$3.FORCE_COLOR, 10), 3); + forceColor$3 = env$4.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$4.FORCE_COLOR, 10), 3); } } @@ -54206,7 +48903,7 @@ function supportsColor$3(haveStream, streamIsTTY) { const min = forceColor$3 || 0; - if (env$3.TERM === 'dumb') { + if (env$4.TERM === 'dumb') { return min; } @@ -54224,26 +48921,26 @@ function supportsColor$3(haveStream, streamIsTTY) { return 1; } - if ('CI' in env$3) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$3) || env$3.CI_NAME === 'codeship') { + if ('CI' in env$4) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$4) || env$4.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env$3) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$3.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$4) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$4.TEAMCITY_VERSION) ? 1 : 0; } - if (env$3.COLORTERM === 'truecolor') { + if (env$4.COLORTERM === 'truecolor') { return 3; } - if ('TERM_PROGRAM' in env$3) { - const version = parseInt((env$3.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$4) { + const version = parseInt((env$4.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env$3.TERM_PROGRAM) { + switch (env$4.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': @@ -54252,15 +48949,15 @@ function supportsColor$3(haveStream, streamIsTTY) { } } - if (/-256(color)?$/i.test(env$3.TERM)) { + if (/-256(color)?$/i.test(env$4.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$3.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$4.TERM)) { return 1; } - if ('COLORTERM' in env$3) { + if ('COLORTERM' in env$4) { return 1; } @@ -54696,7 +49393,7 @@ const os$c = require$$0$7; const tty$2 = require$$1$3; const hasFlag$4 = hasFlag$5; -const {env: env$2} = process; +const {env: env$3} = process; let forceColor$2; if (hasFlag$4('no-color') || @@ -54711,13 +49408,13 @@ if (hasFlag$4('no-color') || forceColor$2 = 1; } -if ('FORCE_COLOR' in env$2) { - if (env$2.FORCE_COLOR === 'true') { +if ('FORCE_COLOR' in env$3) { + if (env$3.FORCE_COLOR === 'true') { forceColor$2 = 1; - } else if (env$2.FORCE_COLOR === 'false') { + } else if (env$3.FORCE_COLOR === 'false') { forceColor$2 = 0; } else { - forceColor$2 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3); + forceColor$2 = env$3.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$3.FORCE_COLOR, 10), 3); } } @@ -54755,7 +49452,7 @@ function supportsColor$2(haveStream, streamIsTTY) { const min = forceColor$2 || 0; - if (env$2.TERM === 'dumb') { + if (env$3.TERM === 'dumb') { return min; } @@ -54773,26 +49470,26 @@ function supportsColor$2(haveStream, streamIsTTY) { return 1; } - if ('CI' in env$2) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { + if ('CI' in env$3) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$3) || env$3.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env$2) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$3) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$3.TEAMCITY_VERSION) ? 1 : 0; } - if (env$2.COLORTERM === 'truecolor') { + if (env$3.COLORTERM === 'truecolor') { return 3; } - if ('TERM_PROGRAM' in env$2) { - const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$3) { + const version = parseInt((env$3.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env$2.TERM_PROGRAM) { + switch (env$3.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': @@ -54801,15 +49498,15 @@ function supportsColor$2(haveStream, streamIsTTY) { } } - if (/-256(color)?$/i.test(env$2.TERM)) { + if (/-256(color)?$/i.test(env$3.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$3.TERM)) { return 1; } - if ('COLORTERM' in env$2) { + if ('COLORTERM' in env$3) { return 1; } @@ -55245,7 +49942,7 @@ const os$b = require$$0$7; const tty$1 = require$$1$3; const hasFlag$2 = hasFlag$3; -const {env: env$1} = process; +const {env: env$2} = process; let forceColor$1; if (hasFlag$2('no-color') || @@ -55260,13 +49957,13 @@ if (hasFlag$2('no-color') || forceColor$1 = 1; } -if ('FORCE_COLOR' in env$1) { - if (env$1.FORCE_COLOR === 'true') { +if ('FORCE_COLOR' in env$2) { + if (env$2.FORCE_COLOR === 'true') { forceColor$1 = 1; - } else if (env$1.FORCE_COLOR === 'false') { + } else if (env$2.FORCE_COLOR === 'false') { forceColor$1 = 0; } else { - forceColor$1 = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3); + forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3); } } @@ -55304,7 +50001,7 @@ function supportsColor$1(haveStream, streamIsTTY) { const min = forceColor$1 || 0; - if (env$1.TERM === 'dumb') { + if (env$2.TERM === 'dumb') { return min; } @@ -55322,26 +50019,26 @@ function supportsColor$1(haveStream, streamIsTTY) { return 1; } - if ('CI' in env$1) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { + if ('CI' in env$2) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env$1) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$2) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; } - if (env$1.COLORTERM === 'truecolor') { + if (env$2.COLORTERM === 'truecolor') { return 3; } - if ('TERM_PROGRAM' in env$1) { - const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$2) { + const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env$1.TERM_PROGRAM) { + switch (env$2.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': @@ -55350,15 +50047,15 @@ function supportsColor$1(haveStream, streamIsTTY) { } } - if (/-256(color)?$/i.test(env$1.TERM)) { + if (/-256(color)?$/i.test(env$2.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { return 1; } - if ('COLORTERM' in env$1) { + if ('COLORTERM' in env$2) { return 1; } @@ -55794,7 +50491,7 @@ const os$a = require$$0$7; const tty = require$$1$3; const hasFlag = hasFlag$1; -const {env} = process; +const {env: env$1} = process; let forceColor; if (hasFlag('no-color') || @@ -55809,13 +50506,13 @@ if (hasFlag('no-color') || forceColor = 1; } -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { +if ('FORCE_COLOR' in env$1) { + if (env$1.FORCE_COLOR === 'true') { forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { + } else if (env$1.FORCE_COLOR === 'false') { forceColor = 0; } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + forceColor = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3); } } @@ -55853,7 +50550,7 @@ function supportsColor(haveStream, streamIsTTY) { const min = forceColor || 0; - if (env.TERM === 'dumb') { + if (env$1.TERM === 'dumb') { return min; } @@ -55871,26 +50568,26 @@ function supportsColor(haveStream, streamIsTTY) { return 1; } - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + if ('CI' in env$1) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { return 1; } return min; } - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + if ('TEAMCITY_VERSION' in env$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; } - if (env.COLORTERM === 'truecolor') { + if (env$1.COLORTERM === 'truecolor') { return 3; } - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if ('TERM_PROGRAM' in env$1) { + const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env.TERM_PROGRAM) { + switch (env$1.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': @@ -55899,15 +50596,15 @@ function supportsColor(haveStream, streamIsTTY) { } } - if (/-256(color)?$/i.test(env.TERM)) { + if (/-256(color)?$/i.test(env$1.TERM)) { return 2; } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { return 1; } - if ('COLORTERM' in env) { + if ('COLORTERM' in env$1) { return 1; } @@ -56612,7 +51309,7 @@ const stringTrim = new String().trim; const stringStartWith = new String().startsWith; const mathMin = Math.min; -function isFunction(functionToCheck) { +function isFunction$1(functionToCheck) { let getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } @@ -57839,7 +52536,7 @@ util$j.toInt = toInt; util$j.execOptsWin = execOptsWin; util$j.getCodepage = getCodepage; util$j.execWin = execWin; -util$j.isFunction = isFunction; +util$j.isFunction = isFunction$1; util$j.unique = unique; util$j.sortByKey = sortByKey; util$j.cores = cores; @@ -60508,252 +55205,1065 @@ function getCpu() { if (countProcessors) { result.processors = parseInt(countProcessors) || 1; } - if (countCores && countThreads) { - result.cores = parseInt(countThreads) || util$f.cores(); - result.physicalCores = parseInt(countCores) || util$f.cores(); + if (countCores && countThreads) { + result.cores = parseInt(countThreads) || util$f.cores(); + result.physicalCores = parseInt(countCores) || util$f.cores(); + } + cpuCache().then((res) => { + result.cache = res; + resolve(result); + }); + }); + } + if (_linux$d) { + let modelline = ''; + let lines = []; + if (os$5.cpus()[0] && os$5.cpus()[0].model) { modelline = os$5.cpus()[0].model; } + exec$d('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', function (error, stdout) { + if (!error) { + lines = stdout.toString().split('\n'); + } + modelline = util$f.getValue(lines, 'model name') || modelline; + const modellineParts = modelline.split('@'); + result.brand = modellineParts[0].trim(); + result.speed = modellineParts[1] ? parseFloat(modellineParts[1].trim()) : 0; + if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) { + result.speed = getAMDSpeed(result.brand); + } + if (result.speed === 0) { + const current = getCpuCurrentSpeedSync(); + if (current.avg !== 0) { result.speed = current.avg; } + } + _cpu_speed = result.speed; + result.speedMin = Math.round(parseFloat(util$f.getValue(lines, 'cpu min mhz').replace(/,/g, '.')) / 10.0) / 100; + result.speedMax = Math.round(parseFloat(util$f.getValue(lines, 'cpu max mhz').replace(/,/g, '.')) / 10.0) / 100; + + result = cpuBrandManufacturer(result); + result.vendor = cpuManufacturer(util$f.getValue(lines, 'vendor id')); + + result.family = util$f.getValue(lines, 'cpu family'); + result.model = util$f.getValue(lines, 'model:'); + result.stepping = util$f.getValue(lines, 'stepping'); + result.revision = util$f.getValue(lines, 'cpu revision'); + result.cache.l1d = util$f.getValue(lines, 'l1d cache'); + if (result.cache.l1d) { result.cache.l1d = parseInt(result.cache.l1d) * (result.cache.l1d.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1d.indexOf('K') !== -1 ? 1024 : 1)); } + result.cache.l1i = util$f.getValue(lines, 'l1i cache'); + if (result.cache.l1i) { result.cache.l1i = parseInt(result.cache.l1i) * (result.cache.l1i.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1i.indexOf('K') !== -1 ? 1024 : 1)); } + result.cache.l2 = util$f.getValue(lines, 'l2 cache'); + if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * (result.cache.l2.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l2.indexOf('K') !== -1 ? 1024 : 1)); } + result.cache.l3 = util$f.getValue(lines, 'l3 cache'); + if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * (result.cache.l3.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l3.indexOf('K') !== -1 ? 1024 : 1)); } + + const threadsPerCore = util$f.getValue(lines, 'thread(s) per core') || '1'; + const processors = util$f.getValue(lines, 'socket(s)') || '1'; + let threadsPerCoreInt = parseInt(threadsPerCore, 10); // threads per code (normally only for performance cores) + let processorsInt = parseInt(processors, 10) || 1; // number of sockets / processor units in machine (normally 1) + const coresPerSocket = parseInt(util$f.getValue(lines, 'core(s) per socket'), 10); // number of cores (e.g. 16 on i12900) + result.physicalCores = coresPerSocket ? coresPerSocket * processorsInt : result.cores / threadsPerCoreInt; + result.performanceCores = threadsPerCoreInt > 1 ? result.cores - result.physicalCores : result.cores; + result.efficiencyCores = threadsPerCoreInt > 1 ? result.cores - (threadsPerCoreInt * result.performanceCores) : 0; + result.processors = processorsInt; + result.governor = util$f.getValue(lines, 'governor') || ''; + + // Test Raspberry + if (result.vendor === 'ARM') { + const linesRpi = fs$7.readFileSync('/proc/cpuinfo').toString().split('\n'); + const rPIRevision = util$f.decodePiCpuinfo(linesRpi); + if (rPIRevision.model.toLowerCase().indexOf('raspberry') >= 0) { + result.family = result.manufacturer; + result.manufacturer = rPIRevision.manufacturer; + result.brand = rPIRevision.processor; + result.revision = rPIRevision.revisionCode; + result.socket = 'SOC'; + } + } + + // socket type + let lines2 = []; + exec$d('export LC_ALL=C; dmidecode –t 4 2>/dev/null | grep "Upgrade: Socket"; unset LC_ALL', function (error2, stdout2) { + lines2 = stdout2.toString().split('\n'); + if (lines2 && lines2.length) { + result.socket = util$f.getValue(lines2, 'Upgrade').replace('Socket', '').trim() || result.socket; + } + resolve(result); + }); + }); + } + if (_freebsd$c || _openbsd$c || _netbsd$c) { + let modelline = ''; + let lines = []; + if (os$5.cpus()[0] && os$5.cpus()[0].model) { modelline = os$5.cpus()[0].model; } + exec$d('export LC_ALL=C; dmidecode -t 4; dmidecode -t 7 unset LC_ALL', function (error, stdout) { + let cache = []; + if (!error) { + const data = stdout.toString().split('# dmidecode'); + const processor = data.length > 1 ? data[1] : ''; + cache = data.length > 2 ? data[2].split('Cache Information') : []; + + lines = processor.split('\n'); + } + result.brand = modelline.split('@')[0].trim(); + result.speed = modelline.split('@')[1] ? parseFloat(modelline.split('@')[1].trim()) : 0; + if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) { + result.speed = getAMDSpeed(result.brand); + } + if (result.speed === 0) { + const current = getCpuCurrentSpeedSync(); + if (current.avg !== 0) { result.speed = current.avg; } + } + _cpu_speed = result.speed; + result.speedMin = result.speed; + result.speedMax = Math.round(parseFloat(util$f.getValue(lines, 'max speed').replace(/Mhz/g, '')) / 10.0) / 100; + + result = cpuBrandManufacturer(result); + result.vendor = cpuManufacturer(util$f.getValue(lines, 'manufacturer')); + let sig = util$f.getValue(lines, 'signature'); + sig = sig.split(','); + for (let i = 0; i < sig.length; i++) { + sig[i] = sig[i].trim(); + } + result.family = util$f.getValue(sig, 'Family', ' ', true); + result.model = util$f.getValue(sig, 'Model', ' ', true); + result.stepping = util$f.getValue(sig, 'Stepping', ' ', true); + result.revision = ''; + const voltage = parseFloat(util$f.getValue(lines, 'voltage')); + result.voltage = isNaN(voltage) ? '' : voltage.toFixed(2); + for (let i = 0; i < cache.length; i++) { + lines = cache[i].split('\n'); + let cacheType = util$f.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-'); + cacheType = cacheType.length ? cacheType[0] : ''; + const sizeParts = util$f.getValue(lines, 'Installed Size').split(' '); + let size = parseInt(sizeParts[0], 10); + const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb'; + size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1))); + if (cacheType) { + if (cacheType === 'l1') { + result.cache[cacheType + 'd'] = size / 2; + result.cache[cacheType + 'i'] = size / 2; + } else { + result.cache[cacheType] = size; + } + } + } + // socket type + result.socket = util$f.getValue(lines, 'Upgrade').replace('Socket', '').trim(); + // # threads / # cores + const threadCount = util$f.getValue(lines, 'thread count').trim(); + const coreCount = util$f.getValue(lines, 'core count').trim(); + if (coreCount && threadCount) { + result.cores = parseInt(threadCount, 10); + result.physicalCores = parseInt(coreCount, 10); + } + resolve(result); + }); + } + if (_sunos$c) { + resolve(result); + } + if (_windows$e) { + try { + const workload = []; + workload.push(util$f.powerShell('Get-CimInstance Win32_processor | select Name, Revision, L2CacheSize, L3CacheSize, Manufacturer, MaxClockSpeed, Description, UpgradeMethod, Caption, NumberOfLogicalProcessors, NumberOfCores | fl')); + workload.push(util$f.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl')); + workload.push(util$f.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent')); + + Promise.all( + workload + ).then((data) => { + let lines = data[0].split('\r\n'); + let name = util$f.getValue(lines, 'name', ':') || ''; + if (name.indexOf('@') >= 0) { + result.brand = name.split('@')[0].trim(); + result.speed = name.split('@')[1] ? parseFloat(name.split('@')[1].trim()) : 0; + _cpu_speed = result.speed; + } else { + result.brand = name.trim(); + result.speed = 0; + } + result = cpuBrandManufacturer(result); + result.revision = util$f.getValue(lines, 'revision', ':'); + result.vendor = util$f.getValue(lines, 'manufacturer', ':'); + result.speedMax = Math.round(parseFloat(util$f.getValue(lines, 'maxclockspeed', ':').replace(/,/g, '.')) / 10.0) / 100; + if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) { + result.speed = getAMDSpeed(result.brand); + } + if (result.speed === 0) { + result.speed = result.speedMax; + } + result.speedMin = result.speed; + + let description = util$f.getValue(lines, 'description', ':').split(' '); + for (let i = 0; i < description.length; i++) { + if (description[i].toLowerCase().startsWith('family') && (i + 1) < description.length && description[i + 1]) { + result.family = description[i + 1]; + } + if (description[i].toLowerCase().startsWith('model') && (i + 1) < description.length && description[i + 1]) { + result.model = description[i + 1]; + } + if (description[i].toLowerCase().startsWith('stepping') && (i + 1) < description.length && description[i + 1]) { + result.stepping = description[i + 1]; + } + } + // socket type + const socketId = util$f.getValue(lines, 'UpgradeMethod', ':'); + if (socketTypes[socketId]) { + result.socket = socketTypes[socketId]; + } + const socketByName = getSocketTypesByName(name); + if (socketByName) { + result.socket = socketByName; + } + // # threads / # cores + const countProcessors = util$f.countLines(lines, 'Caption'); + const countThreads = util$f.getValue(lines, 'NumberOfLogicalProcessors', ':'); + const countCores = util$f.getValue(lines, 'NumberOfCores', ':'); + if (countProcessors) { + result.processors = parseInt(countProcessors) || 1; + } + if (countCores && countThreads) { + result.cores = parseInt(countThreads) || util$f.cores(); + result.physicalCores = parseInt(countCores) || util$f.cores(); + } + if (countProcessors > 1) { + result.cores = result.cores * countProcessors; + result.physicalCores = result.physicalCores * countProcessors; + } + result.cache = parseWinCache(data[0], data[1]); + const hyperv = data[2] ? data[2].toString().toLowerCase() : ''; + result.virtualization = hyperv.indexOf('true') !== -1; + + resolve(result); + }); + } catch (e) { + resolve(result); + } + } + }); + }); + }); +} + +// -------------------------- +// CPU - Processor Data + +function cpu(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + getCpu().then(result => { + if (callback) { callback(result); } + resolve(result); + }); + }); + }); +} + +cpu$1.cpu = cpu; + +// -------------------------- +// CPU - current speed - in GHz + +function getCpuCurrentSpeedSync() { + + let cpus = os$5.cpus(); + let minFreq = 999999999; + let maxFreq = 0; + let avgFreq = 0; + let cores = []; + + if (cpus && cpus.length) { + for (let i in cpus) { + if ({}.hasOwnProperty.call(cpus, i)) { + let freq = cpus[i].speed > 100 ? (cpus[i].speed + 1) / 1000 : cpus[i].speed / 10; + avgFreq = avgFreq + freq; + if (freq > maxFreq) { maxFreq = freq; } + if (freq < minFreq) { minFreq = freq; } + cores.push(parseFloat(freq.toFixed(2))); + } + } + avgFreq = avgFreq / cpus.length; + return { + min: parseFloat(minFreq.toFixed(2)), + max: parseFloat(maxFreq.toFixed(2)), + avg: parseFloat((avgFreq).toFixed(2)), + cores: cores + }; + } else { + return { + min: 0, + max: 0, + avg: 0, + cores: cores + }; + } +} + +function cpuCurrentSpeed(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + let result = getCpuCurrentSpeedSync(); + if (result.avg === 0 && _cpu_speed !== 0) { + const currCpuSpeed = parseFloat(_cpu_speed); + result = { + min: currCpuSpeed, + max: currCpuSpeed, + avg: currCpuSpeed, + cores: [] + }; + } + if (callback) { callback(result); } + resolve(result); + }); + }); +} + +cpu$1.cpuCurrentSpeed = cpuCurrentSpeed; + +// -------------------------- +// CPU - temperature +// if sensors are installed + +function cpuTemperature(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + let result = { + main: null, + cores: [], + max: null, + socket: [], + chipset: null + }; + if (_linux$d) { + // CPU Chipset, Socket + try { + const cmd = 'cat /sys/class/thermal/thermal_zone*/type 2>/dev/null; echo "-----"; cat /sys/class/thermal/thermal_zone*/temp 2>/dev/null;'; + const parts = execSync$8(cmd).toString().split('-----\n'); + if (parts.length === 2) { + const lines = parts[0].split('\n'); + const lines2 = parts[1].split('\n'); + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line.startsWith('acpi') && lines2[i]) { + result.socket.push(Math.round(parseInt(lines2[i], 10) / 100) / 10); + } + if (line.startsWith('pch') && lines2[i]) { + result.chipset = Math.round(parseInt(lines2[i], 10) / 100) / 10; + } + } + } + } catch (e) { + util$f.noop(); + } + + const cmd = 'for mon in /sys/class/hwmon/hwmon*; do for label in "$mon"/temp*_label; do if [ -f $label ]; then value=${label%_*}_input; echo $(cat "$label")___$(cat "$value"); fi; done; done;'; + try { + exec$d(cmd, function (error, stdout) { + stdout = stdout.toString(); + const tdiePos = stdout.toLowerCase().indexOf('tdie'); + if (tdiePos !== -1) { + stdout = stdout.substring(tdiePos); + } + let lines = stdout.split('\n'); + let tctl = 0; + lines.forEach(line => { + const parts = line.split('___'); + const label = parts[0]; + const value = parts.length > 1 && parts[1] ? parts[1] : '0'; + if (value && label && label.toLowerCase() === 'tctl') { + tctl = result.main = Math.round(parseInt(value, 10) / 100) / 10; + } + if (value && (label === undefined || (label && label.toLowerCase().startsWith('core')))) { + result.cores.push(Math.round(parseInt(value, 10) / 100) / 10); + } else if (value && label && result.main === null && (label.toLowerCase().indexOf('package') >= 0 || label.toLowerCase().indexOf('physical') >= 0 || label.toLowerCase() === 'tccd1')) { + result.main = Math.round(parseInt(value, 10) / 100) / 10; + } + }); + if (tctl && result.main === null) { + result.main = tctl; + } + + if (result.cores.length > 0) { + if (result.main === null) { + result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length); + } + let maxtmp = Math.max.apply(Math, result.cores); + result.max = (maxtmp > result.main) ? maxtmp : result.main; + } + if (result.main !== null) { + if (result.max === null) { + result.max = result.main; + } + if (callback) { callback(result); } + resolve(result); + return; + } + exec$d('sensors', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + let tdieTemp = null; + let newSectionStarts = true; + let section = ''; + lines.forEach(function (line) { + // determine section + if (line.trim() === '') { + newSectionStarts = true; + } else if (newSectionStarts) { + if (line.trim().toLowerCase().startsWith('acpi')) { section = 'acpi'; } + if (line.trim().toLowerCase().startsWith('pch')) { section = 'pch'; } + if (line.trim().toLowerCase().startsWith('core')) { section = 'core'; } + newSectionStarts = false; + } + let regex = /[+-]([^°]*)/g; + let temps = line.match(regex); + let firstPart = line.split(':')[0].toUpperCase(); + if (section === 'acpi') { + // socket temp + if (firstPart.indexOf('TEMP') !== -1) { + result.socket.push(parseFloat(temps)); + } + } else if (section === 'pch') { + // chipset temp + if (firstPart.indexOf('TEMP') !== -1 && !result.chipset) { + result.chipset = parseFloat(temps); + } + } + // cpu temp + if (firstPart.indexOf('PHYSICAL') !== -1 || firstPart.indexOf('PACKAGE') !== -1) { + result.main = parseFloat(temps); + } + if (firstPart.indexOf('CORE ') !== -1) { + result.cores.push(parseFloat(temps)); + } + if (firstPart.indexOf('TDIE') !== -1 && tdieTemp === null) { + tdieTemp = parseFloat(temps); + } + }); + if (result.cores.length > 0) { + result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length); + let maxtmp = Math.max.apply(Math, result.cores); + result.max = (maxtmp > result.main) ? maxtmp : result.main; + } else { + if (result.main === null && tdieTemp !== null) { + result.main = tdieTemp; + result.max = tdieTemp; + } + } + if (result.main !== null || result.max !== null) { + if (callback) { callback(result); } + resolve(result); + return; + } + } + fs$7.stat('/sys/class/thermal/thermal_zone0/temp', function (err) { + if (err === null) { + fs$7.readFile('/sys/class/thermal/thermal_zone0/temp', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + if (lines.length > 0) { + result.main = parseFloat(lines[0]) / 1000.0; + result.max = result.main; + } + } + if (callback) { callback(result); } + resolve(result); + }); + } else { + exec$d('/opt/vc/bin/vcgencmd measure_temp', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + if (lines.length > 0 && lines[0].indexOf('=')) { + result.main = parseFloat(lines[0].split('=')[1]); + result.max = result.main; + } + } + if (callback) { callback(result); } + resolve(result); + }); + } + }); + }); + }); + } catch (er) { + if (callback) { callback(result); } + resolve(result); + } + } + if (_freebsd$c || _openbsd$c || _netbsd$c) { + exec$d('sysctl dev.cpu | grep temp', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + let sum = 0; + lines.forEach(function (line) { + const parts = line.split(':'); + if (parts.length > 1) { + const temp = parseFloat(parts[1].replace(',', '.')); + if (temp > result.max) { result.max = temp; } + sum = sum + temp; + result.cores.push(temp); + } + }); + if (result.cores.length) { + result.main = Math.round(sum / result.cores.length * 100) / 100; + } + } + if (callback) { callback(result); } + resolve(result); + }); + } + if (_darwin$d) { + let osxTemp = null; + try { + osxTemp = require('osx-temperature-sensor'); + } catch (er) { + osxTemp = null; + } + if (osxTemp) { + result = osxTemp.cpuTemperature(); + // round to 2 digits + if (result.main) { + result.main = Math.round(result.main * 100) / 100; + } + if (result.max) { + result.max = Math.round(result.max * 100) / 100; + } + if (result.cores && result.cores.length) { + for (let i = 0; i < result.cores.length; i++) { + result.cores[i] = Math.round(result.cores[i] * 100) / 100; } - cpuCache().then((res) => { - result.cache = res; - resolve(result); - }); - }); + } } - if (_linux$d) { - let modelline = ''; - let lines = []; - if (os$5.cpus()[0] && os$5.cpus()[0].model) { modelline = os$5.cpus()[0].model; } - exec$d('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', function (error, stdout) { + + if (callback) { callback(result); } + resolve(result); + } + if (_sunos$c) { + if (callback) { callback(result); } + resolve(result); + } + if (_windows$e) { + try { + util$f.powerShell('Get-CimInstance MSAcpi_ThermalZoneTemperature -Namespace "root/wmi" | Select CurrentTemperature').then((stdout, error) => { if (!error) { - lines = stdout.toString().split('\n'); - } - modelline = util$f.getValue(lines, 'model name') || modelline; - const modellineParts = modelline.split('@'); - result.brand = modellineParts[0].trim(); - result.speed = modellineParts[1] ? parseFloat(modellineParts[1].trim()) : 0; - if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) { - result.speed = getAMDSpeed(result.brand); - } - if (result.speed === 0) { - const current = getCpuCurrentSpeedSync(); - if (current.avg !== 0) { result.speed = current.avg; } + let sum = 0; + let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); + lines.forEach(function (line) { + let value = (parseInt(line, 10) - 2732) / 10; + if (!isNaN(value)) { + sum = sum + value; + if (value > result.max) { result.max = value; } + result.cores.push(value); + } + }); + if (result.cores.length) { + result.main = sum / result.cores.length; + } } - _cpu_speed = result.speed; - result.speedMin = Math.round(parseFloat(util$f.getValue(lines, 'cpu min mhz').replace(/,/g, '.')) / 10.0) / 100; - result.speedMax = Math.round(parseFloat(util$f.getValue(lines, 'cpu max mhz').replace(/,/g, '.')) / 10.0) / 100; + if (callback) { callback(result); } + resolve(result); + }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } + } + }); + }); +} - result = cpuBrandManufacturer(result); - result.vendor = cpuManufacturer(util$f.getValue(lines, 'vendor id')); +cpu$1.cpuTemperature = cpuTemperature; - result.family = util$f.getValue(lines, 'cpu family'); - result.model = util$f.getValue(lines, 'model:'); - result.stepping = util$f.getValue(lines, 'stepping'); - result.revision = util$f.getValue(lines, 'cpu revision'); - result.cache.l1d = util$f.getValue(lines, 'l1d cache'); - if (result.cache.l1d) { result.cache.l1d = parseInt(result.cache.l1d) * (result.cache.l1d.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1d.indexOf('K') !== -1 ? 1024 : 1)); } - result.cache.l1i = util$f.getValue(lines, 'l1i cache'); - if (result.cache.l1i) { result.cache.l1i = parseInt(result.cache.l1i) * (result.cache.l1i.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1i.indexOf('K') !== -1 ? 1024 : 1)); } - result.cache.l2 = util$f.getValue(lines, 'l2 cache'); - if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * (result.cache.l2.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l2.indexOf('K') !== -1 ? 1024 : 1)); } - result.cache.l3 = util$f.getValue(lines, 'l3 cache'); - if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * (result.cache.l3.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l3.indexOf('K') !== -1 ? 1024 : 1)); } +// -------------------------- +// CPU Flags - const threadsPerCore = util$f.getValue(lines, 'thread(s) per core') || '1'; - const processors = util$f.getValue(lines, 'socket(s)') || '1'; - let threadsPerCoreInt = parseInt(threadsPerCore, 10); // threads per code (normally only for performance cores) - let processorsInt = parseInt(processors, 10) || 1; // number of sockets / processor units in machine (normally 1) - const coresPerSocket = parseInt(util$f.getValue(lines, 'core(s) per socket'), 10); // number of cores (e.g. 16 on i12900) - result.physicalCores = coresPerSocket ? coresPerSocket * processorsInt : result.cores / threadsPerCoreInt; - result.performanceCores = threadsPerCoreInt > 1 ? result.cores - result.physicalCores : result.cores; - result.efficiencyCores = threadsPerCoreInt > 1 ? result.cores - (threadsPerCoreInt * result.performanceCores) : 0; - result.processors = processorsInt; - result.governor = util$f.getValue(lines, 'governor') || ''; +function cpuFlags(callback) { - // Test Raspberry - if (result.vendor === 'ARM') { - const linesRpi = fs$7.readFileSync('/proc/cpuinfo').toString().split('\n'); - const rPIRevision = util$f.decodePiCpuinfo(linesRpi); - if (rPIRevision.model.toLowerCase().indexOf('raspberry') >= 0) { - result.family = result.manufacturer; - result.manufacturer = rPIRevision.manufacturer; - result.brand = rPIRevision.processor; - result.revision = rPIRevision.revisionCode; - result.socket = 'SOC'; + return new Promise((resolve) => { + process.nextTick(() => { + let result = ''; + if (_windows$e) { + try { + exec$d('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', util$f.execOptsWin, function (error, stdout) { + if (!error) { + let flag_hex = stdout.split('0x').pop().trim(); + let flag_bin_unpadded = parseInt(flag_hex, 16).toString(2); + let flag_bin = '0'.repeat(32 - flag_bin_unpadded.length) + flag_bin_unpadded; + // empty flags are the reserved fields in the CPUID feature bit list + // as found on wikipedia: + // https://en.wikipedia.org/wiki/CPUID + let all_flags = [ + 'fpu', 'vme', 'de', 'pse', 'tsc', 'msr', 'pae', 'mce', 'cx8', 'apic', + '', 'sep', 'mtrr', 'pge', 'mca', 'cmov', 'pat', 'pse-36', 'psn', 'clfsh', + '', 'ds', 'acpi', 'mmx', 'fxsr', 'sse', 'sse2', 'ss', 'htt', 'tm', 'ia64', 'pbe' + ]; + for (let f = 0; f < all_flags.length; f++) { + if (flag_bin[f] === '1' && all_flags[f] !== '') { + result += ' ' + all_flags[f]; + } } + result = result.trim().toLowerCase(); } - - // socket type - let lines2 = []; - exec$d('export LC_ALL=C; dmidecode –t 4 2>/dev/null | grep "Upgrade: Socket"; unset LC_ALL', function (error2, stdout2) { - lines2 = stdout2.toString().split('\n'); - if (lines2 && lines2.length) { - result.socket = util$f.getValue(lines2, 'Upgrade').replace('Socket', '').trim() || result.socket; - } - resolve(result); - }); + if (callback) { callback(result); } + resolve(result); }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); } - if (_freebsd$c || _openbsd$c || _netbsd$c) { - let modelline = ''; - let lines = []; - if (os$5.cpus()[0] && os$5.cpus()[0].model) { modelline = os$5.cpus()[0].model; } - exec$d('export LC_ALL=C; dmidecode -t 4; dmidecode -t 7 unset LC_ALL', function (error, stdout) { - let cache = []; - if (!error) { - const data = stdout.toString().split('# dmidecode'); - const processor = data.length > 1 ? data[1] : ''; - cache = data.length > 2 ? data[2].split('Cache Information') : []; + } + if (_linux$d) { + try { - lines = processor.split('\n'); + exec$d('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + lines.forEach(function (line) { + if (line.split(':')[0].toUpperCase().indexOf('FLAGS') !== -1) { + result = line.split(':')[1].trim().toLowerCase(); + } + }); } - result.brand = modelline.split('@')[0].trim(); - result.speed = modelline.split('@')[1] ? parseFloat(modelline.split('@')[1].trim()) : 0; - if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) { - result.speed = getAMDSpeed(result.brand); + if (!result) { + fs$7.readFile('/proc/cpuinfo', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + result = util$f.getValue(lines, 'features', ':', true).toLowerCase(); + } + if (callback) { callback(result); } + resolve(result); + }); + } else { + if (callback) { callback(result); } + resolve(result); } - if (result.speed === 0) { - const current = getCpuCurrentSpeedSync(); - if (current.avg !== 0) { result.speed = current.avg; } + }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } + } + if (_freebsd$c || _openbsd$c || _netbsd$c) { + exec$d('export LC_ALL=C; dmidecode -t 4 2>/dev/null; unset LC_ALL', function (error, stdout) { + let flags = []; + if (!error) { + let parts = stdout.toString().split('\tFlags:'); + const lines = parts.length > 1 ? parts[1].split('\tVersion:')[0].split('\n') : []; + lines.forEach(function (line) { + let flag = (line.indexOf('(') ? line.split('(')[0].toLowerCase() : '').trim().replace(/\t/g, ''); + if (flag) { + flags.push(flag); + } + }); + } + result = flags.join(' ').trim().toLowerCase(); + if (callback) { callback(result); } + resolve(result); + }); + } + if (_darwin$d) { + exec$d('sysctl machdep.cpu.features', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + if (lines.length > 0 && lines[0].indexOf('machdep.cpu.features:') !== -1) { + result = lines[0].split(':')[1].trim().toLowerCase(); } - _cpu_speed = result.speed; - result.speedMin = result.speed; - result.speedMax = Math.round(parseFloat(util$f.getValue(lines, 'max speed').replace(/Mhz/g, '')) / 10.0) / 100; + } + if (callback) { callback(result); } + resolve(result); + }); + } + if (_sunos$c) { + if (callback) { callback(result); } + resolve(result); + } + }); + }); +} - result = cpuBrandManufacturer(result); - result.vendor = cpuManufacturer(util$f.getValue(lines, 'manufacturer')); - let sig = util$f.getValue(lines, 'signature'); - sig = sig.split(','); - for (let i = 0; i < sig.length; i++) { - sig[i] = sig[i].trim(); - } - result.family = util$f.getValue(sig, 'Family', ' ', true); - result.model = util$f.getValue(sig, 'Model', ' ', true); - result.stepping = util$f.getValue(sig, 'Stepping', ' ', true); - result.revision = ''; - const voltage = parseFloat(util$f.getValue(lines, 'voltage')); - result.voltage = isNaN(voltage) ? '' : voltage.toFixed(2); - for (let i = 0; i < cache.length; i++) { - lines = cache[i].split('\n'); - let cacheType = util$f.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-'); - cacheType = cacheType.length ? cacheType[0] : ''; - const sizeParts = util$f.getValue(lines, 'Installed Size').split(' '); - let size = parseInt(sizeParts[0], 10); - const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb'; - size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1))); - if (cacheType) { - if (cacheType === 'l1') { - result.cache[cacheType + 'd'] = size / 2; - result.cache[cacheType + 'i'] = size / 2; - } else { - result.cache[cacheType] = size; +cpu$1.cpuFlags = cpuFlags; + +// -------------------------- +// CPU Cache + +function cpuCache(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + + let result = { + l1d: null, + l1i: null, + l2: null, + l3: null, + }; + if (_linux$d) { + try { + exec$d('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + lines.forEach(function (line) { + let parts = line.split(':'); + if (parts[0].toUpperCase().indexOf('L1D CACHE') !== -1) { + result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1)); } - } - } - // socket type - result.socket = util$f.getValue(lines, 'Upgrade').replace('Socket', '').trim(); - // # threads / # cores - const threadCount = util$f.getValue(lines, 'thread count').trim(); - const coreCount = util$f.getValue(lines, 'core count').trim(); - if (coreCount && threadCount) { - result.cores = parseInt(threadCount, 10); - result.physicalCores = parseInt(coreCount, 10); + if (parts[0].toUpperCase().indexOf('L1I CACHE') !== -1) { + result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1)); + } + if (parts[0].toUpperCase().indexOf('L2 CACHE') !== -1) { + result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1)); + } + if (parts[0].toUpperCase().indexOf('L3 CACHE') !== -1) { + result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1)); + } + }); } + if (callback) { callback(result); } resolve(result); }); - } - if (_sunos$c) { + } catch (e) { + if (callback) { callback(result); } resolve(result); } - if (_windows$e) { - try { - const workload = []; - workload.push(util$f.powerShell('Get-CimInstance Win32_processor | select Name, Revision, L2CacheSize, L3CacheSize, Manufacturer, MaxClockSpeed, Description, UpgradeMethod, Caption, NumberOfLogicalProcessors, NumberOfCores | fl')); - workload.push(util$f.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl')); - workload.push(util$f.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent')); - - Promise.all( - workload - ).then((data) => { - let lines = data[0].split('\r\n'); - let name = util$f.getValue(lines, 'name', ':') || ''; - if (name.indexOf('@') >= 0) { - result.brand = name.split('@')[0].trim(); - result.speed = name.split('@')[1] ? parseFloat(name.split('@')[1].trim()) : 0; - _cpu_speed = result.speed; + } + if (_freebsd$c || _openbsd$c || _netbsd$c) { + exec$d('export LC_ALL=C; dmidecode -t 7 2>/dev/null; unset LC_ALL', function (error, stdout) { + let cache = []; + if (!error) { + const data = stdout.toString(); + cache = data.split('Cache Information'); + cache.shift(); + } + for (let i = 0; i < cache.length; i++) { + const lines = cache[i].split('\n'); + let cacheType = util$f.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-'); + cacheType = cacheType.length ? cacheType[0] : ''; + const sizeParts = util$f.getValue(lines, 'Installed Size').split(' '); + let size = parseInt(sizeParts[0], 10); + const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb'; + size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1))); + if (cacheType) { + if (cacheType === 'l1') { + result.cache[cacheType + 'd'] = size / 2; + result.cache[cacheType + 'i'] = size / 2; } else { - result.brand = name.trim(); - result.speed = 0; + result.cache[cacheType] = size; } - result = cpuBrandManufacturer(result); - result.revision = util$f.getValue(lines, 'revision', ':'); - result.vendor = util$f.getValue(lines, 'manufacturer', ':'); - result.speedMax = Math.round(parseFloat(util$f.getValue(lines, 'maxclockspeed', ':').replace(/,/g, '.')) / 10.0) / 100; - if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) { - result.speed = getAMDSpeed(result.brand); + } + } + if (callback) { callback(result); } + resolve(result); + }); + } + if (_darwin$d) { + exec$d('sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + lines.forEach(function (line) { + let parts = line.split(':'); + if (parts[0].toLowerCase().indexOf('hw.l1icachesize') !== -1) { + result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1); } - if (result.speed === 0) { - result.speed = result.speedMax; + if (parts[0].toLowerCase().indexOf('hw.l1dcachesize') !== -1) { + result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1); } - result.speedMin = result.speed; + if (parts[0].toLowerCase().indexOf('hw.l2cachesize') !== -1) { + result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1); + } + if (parts[0].toLowerCase().indexOf('hw.l3cachesize') !== -1) { + result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1); + } + }); + } + if (callback) { callback(result); } + resolve(result); + }); + } + if (_sunos$c) { + if (callback) { callback(result); } + resolve(result); + } + if (_windows$e) { + try { + const workload = []; + workload.push(util$f.powerShell('Get-CimInstance Win32_processor | select L2CacheSize, L3CacheSize | fl')); + workload.push(util$f.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl')); + + Promise.all( + workload + ).then((data) => { + result = parseWinCache(data[0], data[1]); + + if (callback) { callback(result); } + resolve(result); + }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } + } + }); + }); +} + +function parseWinCache(linesProc, linesCache) { + let result = { + l1d: null, + l1i: null, + l2: null, + l3: null, + }; + + // Win32_processor + let lines = linesProc.split('\r\n'); + result.l1d = 0; + result.l1i = 0; + result.l2 = util$f.getValue(lines, 'l2cachesize', ':'); + result.l3 = util$f.getValue(lines, 'l3cachesize', ':'); + if (result.l2) { result.l2 = parseInt(result.l2, 10) * 1024; } else { result.l2 = 0; } + if (result.l3) { result.l3 = parseInt(result.l3, 10) * 1024; } else { result.l3 = 0; } + + // Win32_CacheMemory + const parts = linesCache.split(/\n\s*\n/); + let l1i = 0; + let l1d = 0; + let l2 = 0; + parts.forEach(function (part) { + const lines = part.split('\r\n'); + const cacheType = util$f.getValue(lines, 'CacheType'); + const level = util$f.getValue(lines, 'Level'); + const installedSize = util$f.getValue(lines, 'InstalledSize'); + // L1 Instructions + if (level === '3' && cacheType === '3') { + result.l1i = result.l1i + parseInt(installedSize, 10) * 1024; + } + // L1 Data + if (level === '3' && cacheType === '4') { + result.l1d = result.l1d + parseInt(installedSize, 10) * 1024; + } + // L1 all + if (level === '3' && cacheType === '5') { + l1i = parseInt(installedSize, 10) / 2; + l1d = parseInt(installedSize, 10) / 2; + } + // L2 + if (level === '4' && cacheType === '5') { + l2 = l2 + parseInt(installedSize, 10) * 1024; + } + }); + if (!result.l1i && !result.l1d) { + result.l1i = l1i; + result.l1d = l1d; + } + if (l2) { + result.l2 = l2; + } + return result; +} + +cpu$1.cpuCache = cpuCache; + +// -------------------------- +// CPU - current load - in % + +function getLoad() { + + return new Promise((resolve) => { + process.nextTick(() => { + let loads = os$5.loadavg().map(function (x) { return x / util$f.cores(); }); + let avgLoad = parseFloat((Math.max.apply(Math, loads)).toFixed(2)); + let result = {}; + + let now = Date.now() - _current_cpu.ms; + if (now >= 200) { + _current_cpu.ms = Date.now(); + const cpus = os$5.cpus().map(function (cpu) { + cpu.times.steal = 0; + cpu.times.guest = 0; + return cpu; + }); + let totalUser = 0; + let totalSystem = 0; + let totalNice = 0; + let totalIrq = 0; + let totalIdle = 0; + let totalSteal = 0; + let totalGuest = 0; + let cores = []; + _corecount = (cpus && cpus.length) ? cpus.length : 0; - let description = util$f.getValue(lines, 'description', ':').split(' '); - for (let i = 0; i < description.length; i++) { - if (description[i].toLowerCase().startsWith('family') && (i + 1) < description.length && description[i + 1]) { - result.family = description[i + 1]; - } - if (description[i].toLowerCase().startsWith('model') && (i + 1) < description.length && description[i + 1]) { - result.model = description[i + 1]; - } - if (description[i].toLowerCase().startsWith('stepping') && (i + 1) < description.length && description[i + 1]) { - result.stepping = description[i + 1]; + // linux: try to get other cpu stats + if (_linux$d) { + try { + const lines = execSync$8('cat /proc/stat 2>/dev/null | grep cpu', { encoding: 'utf8' }).toString().split('\n'); + if (lines.length > 1) { + lines.shift(); + if (lines.length === cpus.length) { + for (let i = 0; i < lines.length; i++) { + let parts = lines[i].split(' '); + if (parts.length >= 10) { + const steal = parseFloat(parts[8]) || 0; + const guest = parseFloat(parts[9]) || 0; + cpus[i].times.steal = steal; + cpus[i].times.guest = guest; + } } } - // socket type - const socketId = util$f.getValue(lines, 'UpgradeMethod', ':'); - if (socketTypes[socketId]) { - result.socket = socketTypes[socketId]; - } - const socketByName = getSocketTypesByName(name); - if (socketByName) { - result.socket = socketByName; - } - // # threads / # cores - const countProcessors = util$f.countLines(lines, 'Caption'); - const countThreads = util$f.getValue(lines, 'NumberOfLogicalProcessors', ':'); - const countCores = util$f.getValue(lines, 'NumberOfCores', ':'); - if (countProcessors) { - result.processors = parseInt(countProcessors) || 1; - } - if (countCores && countThreads) { - result.cores = parseInt(countThreads) || util$f.cores(); - result.physicalCores = parseInt(countCores) || util$f.cores(); - } - if (countProcessors > 1) { - result.cores = result.cores * countProcessors; - result.physicalCores = result.physicalCores * countProcessors; - } - result.cache = parseWinCache(data[0], data[1]); - const hyperv = data[2] ? data[2].toString().toLowerCase() : ''; - result.virtualization = hyperv.indexOf('true') !== -1; - - resolve(result); - }); + } } catch (e) { - resolve(result); + util$f.noop(); } } - }); + + for (let i = 0; i < _corecount; i++) { + const cpu = cpus[i].times; + totalUser += cpu.user; + totalSystem += cpu.sys; + totalNice += cpu.nice; + totalIdle += cpu.idle; + totalIrq += cpu.irq; + totalSteal += cpu.steal || 0; + totalGuest += cpu.guest || 0; + let tmpTick = (_cpus && _cpus[i] && _cpus[i].totalTick ? _cpus[i].totalTick : 0); + let tmpLoad = (_cpus && _cpus[i] && _cpus[i].totalLoad ? _cpus[i].totalLoad : 0); + let tmpUser = (_cpus && _cpus[i] && _cpus[i].user ? _cpus[i].user : 0); + let tmpSystem = (_cpus && _cpus[i] && _cpus[i].sys ? _cpus[i].sys : 0); + let tmpNice = (_cpus && _cpus[i] && _cpus[i].nice ? _cpus[i].nice : 0); + let tmpIdle = (_cpus && _cpus[i] && _cpus[i].idle ? _cpus[i].idle : 0); + let tmpIrq = (_cpus && _cpus[i] && _cpus[i].irq ? _cpus[i].irq : 0); + let tmpSteal = (_cpus && _cpus[i] && _cpus[i].steal ? _cpus[i].steal : 0); + let tmpGuest = (_cpus && _cpus[i] && _cpus[i].guest ? _cpus[i].guest : 0); + _cpus[i] = cpu; + _cpus[i].totalTick = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest + _cpus[i].idle; + _cpus[i].totalLoad = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest; + _cpus[i].currentTick = _cpus[i].totalTick - tmpTick; + _cpus[i].load = (_cpus[i].totalLoad - tmpLoad); + _cpus[i].loadUser = (_cpus[i].user - tmpUser); + _cpus[i].loadSystem = (_cpus[i].sys - tmpSystem); + _cpus[i].loadNice = (_cpus[i].nice - tmpNice); + _cpus[i].loadIdle = (_cpus[i].idle - tmpIdle); + _cpus[i].loadIrq = (_cpus[i].irq - tmpIrq); + _cpus[i].loadSteal = (_cpus[i].steal - tmpSteal); + _cpus[i].loadGuest = (_cpus[i].guest - tmpGuest); + cores[i] = {}; + cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100; + cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100; + cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100; + cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100; + cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100; + cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100; + cores[i].loadSteal = _cpus[i].loadSteal / _cpus[i].currentTick * 100; + cores[i].loadGuest = _cpus[i].loadGuest / _cpus[i].currentTick * 100; + cores[i].rawLoad = _cpus[i].load; + cores[i].rawLoadUser = _cpus[i].loadUser; + cores[i].rawLoadSystem = _cpus[i].loadSystem; + cores[i].rawLoadNice = _cpus[i].loadNice; + cores[i].rawLoadIdle = _cpus[i].loadIdle; + cores[i].rawLoadIrq = _cpus[i].loadIrq; + cores[i].rawLoadSteal = _cpus[i].loadSteal; + cores[i].rawLoadGuest = _cpus[i].loadGuest; + } + let totalTick = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest + totalIdle; + let totalLoad = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest; + let currentTick = totalTick - _current_cpu.tick; + result = { + avgLoad: avgLoad, + currentLoad: (totalLoad - _current_cpu.load) / currentTick * 100, + currentLoadUser: (totalUser - _current_cpu.user) / currentTick * 100, + currentLoadSystem: (totalSystem - _current_cpu.system) / currentTick * 100, + currentLoadNice: (totalNice - _current_cpu.nice) / currentTick * 100, + currentLoadIdle: (totalIdle - _current_cpu.idle) / currentTick * 100, + currentLoadIrq: (totalIrq - _current_cpu.irq) / currentTick * 100, + currentLoadSteal: (totalSteal - _current_cpu.steal) / currentTick * 100, + currentLoadGuest: (totalGuest - _current_cpu.guest) / currentTick * 100, + rawCurrentLoad: (totalLoad - _current_cpu.load), + rawCurrentLoadUser: (totalUser - _current_cpu.user), + rawCurrentLoadSystem: (totalSystem - _current_cpu.system), + rawCurrentLoadNice: (totalNice - _current_cpu.nice), + rawCurrentLoadIdle: (totalIdle - _current_cpu.idle), + rawCurrentLoadIrq: (totalIrq - _current_cpu.irq), + rawCurrentLoadSteal: (totalSteal - _current_cpu.steal), + rawCurrentLoadGuest: (totalGuest - _current_cpu.guest), + cpus: cores + }; + _current_cpu = { + user: totalUser, + nice: totalNice, + system: totalSystem, + idle: totalIdle, + irq: totalIrq, + steal: totalSteal, + guest: totalGuest, + tick: totalTick, + load: totalLoad, + ms: _current_cpu.ms, + currentLoad: result.currentLoad, + currentLoadUser: result.currentLoadUser, + currentLoadSystem: result.currentLoadSystem, + currentLoadNice: result.currentLoadNice, + currentLoadIdle: result.currentLoadIdle, + currentLoadIrq: result.currentLoadIrq, + currentLoadSteal: result.currentLoadSteal, + currentLoadGuest: result.currentLoadGuest, + rawCurrentLoad: result.rawCurrentLoad, + rawCurrentLoadUser: result.rawCurrentLoadUser, + rawCurrentLoadSystem: result.rawCurrentLoadSystem, + rawCurrentLoadNice: result.rawCurrentLoadNice, + rawCurrentLoadIdle: result.rawCurrentLoadIdle, + rawCurrentLoadIrq: result.rawCurrentLoadIrq, + rawCurrentLoadSteal: result.rawCurrentLoadSteal, + rawCurrentLoadGuest: result.rawCurrentLoadGuest, + }; + } else { + let cores = []; + for (let i = 0; i < _corecount; i++) { + cores[i] = {}; + cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100; + cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100; + cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100; + cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100; + cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100; + cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100; + cores[i].rawLoad = _cpus[i].load; + cores[i].rawLoadUser = _cpus[i].loadUser; + cores[i].rawLoadSystem = _cpus[i].loadSystem; + cores[i].rawLoadNice = _cpus[i].loadNice; + cores[i].rawLoadIdle = _cpus[i].loadIdle; + cores[i].rawLoadIrq = _cpus[i].loadIrq; + cores[i].rawLoadSteal = _cpus[i].loadSteal; + cores[i].rawLoadGuest = _cpus[i].loadGuest; + } + result = { + avgLoad: avgLoad, + currentLoad: _current_cpu.currentLoad, + currentLoadUser: _current_cpu.currentLoadUser, + currentLoadSystem: _current_cpu.currentLoadSystem, + currentLoadNice: _current_cpu.currentLoadNice, + currentLoadIdle: _current_cpu.currentLoadIdle, + currentLoadIrq: _current_cpu.currentLoadIrq, + currentLoadSteal: _current_cpu.currentLoadSteal, + currentLoadGuest: _current_cpu.currentLoadGuest, + rawCurrentLoad: _current_cpu.rawCurrentLoad, + rawCurrentLoadUser: _current_cpu.rawCurrentLoadUser, + rawCurrentLoadSystem: _current_cpu.rawCurrentLoadSystem, + rawCurrentLoadNice: _current_cpu.rawCurrentLoadNice, + rawCurrentLoadIdle: _current_cpu.rawCurrentLoadIdle, + rawCurrentLoadIrq: _current_cpu.rawCurrentLoadIrq, + rawCurrentLoadSteal: _current_cpu.rawCurrentLoadSteal, + rawCurrentLoadGuest: _current_cpu.rawCurrentLoadGuest, + cpus: cores + }; + } + resolve(result); }); }); } -// -------------------------- -// CPU - Processor Data - -function cpu(callback) { +function currentLoad(callback) { return new Promise((resolve) => { process.nextTick(() => { - getCpu().then(result => { + getLoad().then(result => { if (callback) { callback(result); } resolve(result); }); @@ -60761,308 +56271,360 @@ function cpu(callback) { }); } -cpu$1.cpu = cpu; +cpu$1.currentLoad = currentLoad; // -------------------------- -// CPU - current speed - in GHz +// PS - full load +// since bootup -function getCpuCurrentSpeedSync() { +function getFullLoad() { - let cpus = os$5.cpus(); - let minFreq = 999999999; - let maxFreq = 0; - let avgFreq = 0; - let cores = []; + return new Promise((resolve) => { + process.nextTick(() => { + + const cpus = os$5.cpus(); + let totalUser = 0; + let totalSystem = 0; + let totalNice = 0; + let totalIrq = 0; + let totalIdle = 0; + + let result = 0; + + if (cpus && cpus.length) { + for (let i = 0, len = cpus.length; i < len; i++) { + const cpu = cpus[i].times; + totalUser += cpu.user; + totalSystem += cpu.sys; + totalNice += cpu.nice; + totalIrq += cpu.irq; + totalIdle += cpu.idle; + } + let totalTicks = totalIdle + totalIrq + totalNice + totalSystem + totalUser; + result = (totalTicks - totalIdle) / totalTicks * 100.0; - if (cpus && cpus.length) { - for (let i in cpus) { - if ({}.hasOwnProperty.call(cpus, i)) { - let freq = cpus[i].speed > 100 ? (cpus[i].speed + 1) / 1000 : cpus[i].speed / 10; - avgFreq = avgFreq + freq; - if (freq > maxFreq) { maxFreq = freq; } - if (freq < minFreq) { minFreq = freq; } - cores.push(parseFloat(freq.toFixed(2))); } - } - avgFreq = avgFreq / cpus.length; - return { - min: parseFloat(minFreq.toFixed(2)), - max: parseFloat(maxFreq.toFixed(2)), - avg: parseFloat((avgFreq).toFixed(2)), - cores: cores - }; - } else { - return { - min: 0, - max: 0, - avg: 0, - cores: cores - }; - } + resolve(result); + }); + }); } -function cpuCurrentSpeed(callback) { +function fullLoad(callback) { return new Promise((resolve) => { process.nextTick(() => { - let result = getCpuCurrentSpeedSync(); - if (result.avg === 0 && _cpu_speed !== 0) { - const currCpuSpeed = parseFloat(_cpu_speed); - result = { - min: currCpuSpeed, - max: currCpuSpeed, - avg: currCpuSpeed, - cores: [] - }; - } - if (callback) { callback(result); } - resolve(result); + getFullLoad().then(result => { + if (callback) { callback(result); } + resolve(result); + }); }); }); } -cpu$1.cpuCurrentSpeed = cpuCurrentSpeed; +cpu$1.fullLoad = fullLoad; + +var memory = {}; + +// @ts-check +// ================================================================================== +// memory.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 5. Memory +// ---------------------------------------------------------------------------------- + +const os$4 = require$$0$7; +const exec$c = require$$1$2.exec; +const execSync$7 = require$$1$2.execSync; +const util$e = util$j; +const fs$6 = require$$0$5; + +let _platform$d = process.platform; + +const _linux$c = (_platform$d === 'linux' || _platform$d === 'android'); +const _darwin$c = (_platform$d === 'darwin'); +const _windows$d = (_platform$d === 'win32'); +const _freebsd$b = (_platform$d === 'freebsd'); +const _openbsd$b = (_platform$d === 'openbsd'); +const _netbsd$b = (_platform$d === 'netbsd'); +const _sunos$b = (_platform$d === 'sunos'); + +const OSX_RAM_manufacturers = { + '0x014F': 'Transcend Information', + '0x2C00': 'Micron Technology Inc.', + '0x802C': 'Micron Technology Inc.', + '0x80AD': 'Hynix Semiconductor Inc.', + '0x80CE': 'Samsung Electronics Inc.', + '0xAD00': 'Hynix Semiconductor Inc.', + '0xCE00': 'Samsung Electronics Inc.', + '0x02FE': 'Elpida', + '0x5105': 'Qimonda AG i. In.', + '0x8551': 'Qimonda AG i. In.', + '0x859B': 'Crucial', + '0x04CD': 'G-Skill' +}; + +const LINUX_RAM_manufacturers = { + '017A': 'Apacer', + '0198': 'HyperX', + '029E': 'Corsair', + '04CB': 'A-DATA', + '04CD': 'G-Skill', + '059B': 'Crucial', + '00CE': 'Samsung', + '1315': 'Crutial', + '014F': 'Transcend Information', + '2C00': 'Micron Technology Inc.', + '802C': 'Micron Technology Inc.', + '80AD': 'Hynix Semiconductor Inc.', + '80CE': 'Samsung Electronics Inc.', + 'AD00': 'Hynix Semiconductor Inc.', + 'CE00': 'Samsung Electronics Inc.', + '02FE': 'Elpida', + '5105': 'Qimonda AG i. In.', + '8551': 'Qimonda AG i. In.', + '859B': 'Crucial' +}; + +// _______________________________________________________________________________________ +// | R A M | H D | +// |______________________|_________________________| | | +// | active buffers/cache | | | +// |________________________________________________|___________|_________|______________| +// | used free | used free | +// |____________________________________________________________|________________________| +// | total | swap | +// |____________________________________________________________|________________________| + +// free (older versions) +// ---------------------------------- +// # free +// total used free shared buffers cached +// Mem: 16038 (1) 15653 (2) 384 (3) 0 (4) 236 (5) 14788 (6) +// -/+ buffers/cache: 628 (7) 15409 (8) +// Swap: 16371 83 16288 +// +// |------------------------------------------------------------| +// | R A M | +// |______________________|_____________________________________| +// | active (2-(5+6) = 7) | available (3+5+6 = 8) | +// |______________________|_________________________|___________| +// | active | buffers/cache (5+6) | | +// |________________________________________________|___________| +// | used (2) | free (3) | +// |____________________________________________________________| +// | total (1) | +// |____________________________________________________________| + +// +// free (since free von procps-ng 3.3.10) +// ---------------------------------- +// # free +// total used free shared buffers/cache available +// Mem: 16038 (1) 628 (2) 386 (3) 0 (4) 15024 (5) 14788 (6) +// Swap: 16371 83 16288 +// +// |------------------------------------------------------------| +// | R A M | +// |______________________|_____________________________________| +// | | available (6) estimated | +// |______________________|_________________________|___________| +// | active (2) | buffers/cache (5) | free (3) | +// |________________________________________________|___________| +// | total (1) | +// |____________________________________________________________| +// +// Reference: http://www.software-architect.net/blog/article/date/2015/06/12/-826c6e5052.html + +// /procs/meminfo - sample (all in kB) +// +// MemTotal: 32806380 kB +// MemFree: 17977744 kB +// MemAvailable: 19768972 kB +// Buffers: 517028 kB +// Cached: 2161876 kB +// SwapCached: 456 kB +// Active: 12081176 kB +// Inactive: 2164616 kB +// Active(anon): 10832884 kB +// Inactive(anon): 1477272 kB +// Active(file): 1248292 kB +// Inactive(file): 687344 kB +// Unevictable: 0 kB +// Mlocked: 0 kB +// SwapTotal: 16768892 kB +// SwapFree: 16768304 kB +// Dirty: 268 kB +// Writeback: 0 kB +// AnonPages: 11568832 kB +// Mapped: 719992 kB +// Shmem: 743272 kB +// Slab: 335716 kB +// SReclaimable: 256364 kB +// SUnreclaim: 79352 kB + +function mem(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + + let result = { + total: os$4.totalmem(), + free: os$4.freemem(), + used: os$4.totalmem() - os$4.freemem(), + + active: os$4.totalmem() - os$4.freemem(), // temporarily (fallback) + available: os$4.freemem(), // temporarily (fallback) + buffers: 0, + cached: 0, + slab: 0, + buffcache: 0, + + swaptotal: 0, + swapused: 0, + swapfree: 0, + writeback: null, + dirty: null + }; + + if (_linux$c) { + try { + fs$6.readFile('/proc/meminfo', function (error, stdout) { + if (!error) { + const lines = stdout.toString().split('\n'); + result.total = parseInt(util$e.getValue(lines, 'memtotal'), 10); + result.total = result.total ? result.total * 1024 : os$4.totalmem(); + result.free = parseInt(util$e.getValue(lines, 'memfree'), 10); + result.free = result.free ? result.free * 1024 : os$4.freemem(); + result.used = result.total - result.free; + + result.buffers = parseInt(util$e.getValue(lines, 'buffers'), 10); + result.buffers = result.buffers ? result.buffers * 1024 : 0; + result.cached = parseInt(util$e.getValue(lines, 'cached'), 10); + result.cached = result.cached ? result.cached * 1024 : 0; + result.slab = parseInt(util$e.getValue(lines, 'slab'), 10); + result.slab = result.slab ? result.slab * 1024 : 0; + result.buffcache = result.buffers + result.cached + result.slab; + + let available = parseInt(util$e.getValue(lines, 'memavailable'), 10); + result.available = available ? available * 1024 : result.free + result.buffcache; + result.active = result.total - result.available; + + result.swaptotal = parseInt(util$e.getValue(lines, 'swaptotal'), 10); + result.swaptotal = result.swaptotal ? result.swaptotal * 1024 : 0; + result.swapfree = parseInt(util$e.getValue(lines, 'swapfree'), 10); + result.swapfree = result.swapfree ? result.swapfree * 1024 : 0; + result.swapused = result.swaptotal - result.swapfree; + result.writeback = parseInt(util$e.getValue(lines, 'writeback'), 10); + result.writeback = result.writeback ? result.writeback * 1024 : 0; + result.dirty = parseInt(util$e.getValue(lines, 'dirty'), 10); + result.dirty = result.dirty ? result.dirty * 1024 : 0; + } + if (callback) { callback(result); } + resolve(result); + }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } + } + if (_freebsd$b || _openbsd$b || _netbsd$b) { + try { + exec$c('/sbin/sysctl hw.realmem hw.physmem vm.stats.vm.v_page_count vm.stats.vm.v_wire_count vm.stats.vm.v_active_count vm.stats.vm.v_inactive_count vm.stats.vm.v_cache_count vm.stats.vm.v_free_count vm.stats.vm.v_page_size', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + const pagesize = parseInt(util$e.getValue(lines, 'vm.stats.vm.v_page_size'), 10); + const inactive = parseInt(util$e.getValue(lines, 'vm.stats.vm.v_inactive_count'), 10) * pagesize; + const cache = parseInt(util$e.getValue(lines, 'vm.stats.vm.v_cache_count'), 10) * pagesize; -// -------------------------- -// CPU - temperature -// if sensors are installed + result.total = parseInt(util$e.getValue(lines, 'hw.realmem'), 10); + if (isNaN(result.total)) { result.total = parseInt(util$e.getValue(lines, 'hw.physmem'), 10); } + result.free = parseInt(util$e.getValue(lines, 'vm.stats.vm.v_free_count'), 10) * pagesize; + result.buffcache = inactive + cache; + result.available = result.buffcache + result.free; + result.active = result.total - result.free - result.buffcache; -function cpuTemperature(callback) { + result.swaptotal = 0; + result.swapfree = 0; + result.swapused = 0; - return new Promise((resolve) => { - process.nextTick(() => { - let result = { - main: null, - cores: [], - max: null, - socket: [], - chipset: null - }; - if (_linux$d) { - // CPU Chipset, Socket - try { - const cmd = 'cat /sys/class/thermal/thermal_zone*/type 2>/dev/null; echo "-----"; cat /sys/class/thermal/thermal_zone*/temp 2>/dev/null;'; - const parts = execSync$8(cmd).toString().split('-----\n'); - if (parts.length === 2) { - const lines = parts[0].split('\n'); - const lines2 = parts[1].split('\n'); - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - if (line.startsWith('acpi') && lines2[i]) { - result.socket.push(Math.round(parseInt(lines2[i], 10) / 100) / 10); - } - if (line.startsWith('pch') && lines2[i]) { - result.chipset = Math.round(parseInt(lines2[i], 10) / 100) / 10; - } } - } + if (callback) { callback(result); } + resolve(result); + }); } catch (e) { - util$f.noop(); + if (callback) { callback(result); } + resolve(result); } - - const cmd = 'for mon in /sys/class/hwmon/hwmon*; do for label in "$mon"/temp*_label; do if [ -f $label ]; then value=${label%_*}_input; echo $(cat "$label")___$(cat "$value"); fi; done; done;'; + } + if (_sunos$b) { + if (callback) { callback(result); } + resolve(result); + } + if (_darwin$c) { + let pageSize = 4096; try { - exec$d(cmd, function (error, stdout) { - stdout = stdout.toString(); - const tdiePos = stdout.toLowerCase().indexOf('tdie'); - if (tdiePos !== -1) { - stdout = stdout.substring(tdiePos); - } - let lines = stdout.split('\n'); - let tctl = 0; - lines.forEach(line => { - const parts = line.split('___'); - const label = parts[0]; - const value = parts.length > 1 && parts[1] ? parts[1] : '0'; - if (value && label && label.toLowerCase() === 'tctl') { - tctl = result.main = Math.round(parseInt(value, 10) / 100) / 10; - } - if (value && (label === undefined || (label && label.toLowerCase().startsWith('core')))) { - result.cores.push(Math.round(parseInt(value, 10) / 100) / 10); - } else if (value && label && result.main === null && (label.toLowerCase().indexOf('package') >= 0 || label.toLowerCase().indexOf('physical') >= 0 || label.toLowerCase() === 'tccd1')) { - result.main = Math.round(parseInt(value, 10) / 100) / 10; - } - }); - if (tctl && result.main === null) { - result.main = tctl; - } + let sysPpageSize = util$e.toInt(execSync$7('sysctl -n vm.pagesize').toString()); + pageSize = sysPpageSize || pageSize; + } catch (e) { + util$e.noop(); + } + try { + exec$c('vm_stat 2>/dev/null | grep "Pages active"', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); - if (result.cores.length > 0) { - if (result.main === null) { - result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length); - } - let maxtmp = Math.max.apply(Math, result.cores); - result.max = (maxtmp > result.main) ? maxtmp : result.main; - } - if (result.main !== null) { - if (result.max === null) { - result.max = result.main; - } - if (callback) { callback(result); } - resolve(result); - return; + result.active = parseInt(lines[0].split(':')[1], 10) * pageSize; + result.buffcache = result.used - result.active; + result.available = result.free + result.buffcache; } - exec$d('sensors', function (error, stdout) { + exec$c('sysctl -n vm.swapusage 2>/dev/null', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); - let tdieTemp = null; - let newSectionStarts = true; - let section = ''; - lines.forEach(function (line) { - // determine section - if (line.trim() === '') { - newSectionStarts = true; - } else if (newSectionStarts) { - if (line.trim().toLowerCase().startsWith('acpi')) { section = 'acpi'; } - if (line.trim().toLowerCase().startsWith('pch')) { section = 'pch'; } - if (line.trim().toLowerCase().startsWith('core')) { section = 'core'; } - newSectionStarts = false; - } - let regex = /[+-]([^°]*)/g; - let temps = line.match(regex); - let firstPart = line.split(':')[0].toUpperCase(); - if (section === 'acpi') { - // socket temp - if (firstPart.indexOf('TEMP') !== -1) { - result.socket.push(parseFloat(temps)); - } - } else if (section === 'pch') { - // chipset temp - if (firstPart.indexOf('TEMP') !== -1 && !result.chipset) { - result.chipset = parseFloat(temps); - } - } - // cpu temp - if (firstPart.indexOf('PHYSICAL') !== -1 || firstPart.indexOf('PACKAGE') !== -1) { - result.main = parseFloat(temps); - } - if (firstPart.indexOf('CORE ') !== -1) { - result.cores.push(parseFloat(temps)); - } - if (firstPart.indexOf('TDIE') !== -1 && tdieTemp === null) { - tdieTemp = parseFloat(temps); - } - }); - if (result.cores.length > 0) { - result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length); - let maxtmp = Math.max.apply(Math, result.cores); - result.max = (maxtmp > result.main) ? maxtmp : result.main; - } else { - if (result.main === null && tdieTemp !== null) { - result.main = tdieTemp; - result.max = tdieTemp; - } - } - if (result.main !== null || result.max !== null) { - if (callback) { callback(result); } - resolve(result); - return; - } - } - fs$7.stat('/sys/class/thermal/thermal_zone0/temp', function (err) { - if (err === null) { - fs$7.readFile('/sys/class/thermal/thermal_zone0/temp', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - if (lines.length > 0) { - result.main = parseFloat(lines[0]) / 1000.0; - result.max = result.main; - } - } - if (callback) { callback(result); } - resolve(result); - }); - } else { - exec$d('/opt/vc/bin/vcgencmd measure_temp', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - if (lines.length > 0 && lines[0].indexOf('=')) { - result.main = parseFloat(lines[0].split('=')[1]); - result.max = result.main; - } - } - if (callback) { callback(result); } - resolve(result); + if (lines.length > 0) { + let firstline = lines[0].replace(/,/g, '.').replace(/M/g, ''); + let lineArray = firstline.trim().split(' '); + lineArray.forEach(line => { + if (line.toLowerCase().indexOf('total') !== -1) { result.swaptotal = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; } + if (line.toLowerCase().indexOf('used') !== -1) { result.swapused = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; } + if (line.toLowerCase().indexOf('free') !== -1) { result.swapfree = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; } }); } - }); - }); - }); - } catch (er) { - if (callback) { callback(result); } - resolve(result); - } - } - if (_freebsd$c || _openbsd$c || _netbsd$c) { - exec$d('sysctl dev.cpu | grep temp', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - let sum = 0; - lines.forEach(function (line) { - const parts = line.split(':'); - if (parts.length > 1) { - const temp = parseFloat(parts[1].replace(',', '.')); - if (temp > result.max) { result.max = temp; } - sum = sum + temp; - result.cores.push(temp); } + if (callback) { callback(result); } + resolve(result); }); - if (result.cores.length) { - result.main = Math.round(sum / result.cores.length * 100) / 100; - } - } + }); + } catch (e) { if (callback) { callback(result); } resolve(result); - }); - } - if (_darwin$d) { - let osxTemp = null; - try { - osxTemp = require('osx-temperature-sensor'); - } catch (er) { - osxTemp = null; - } - if (osxTemp) { - result = osxTemp.cpuTemperature(); - // round to 2 digits - if (result.main) { - result.main = Math.round(result.main * 100) / 100; - } - if (result.max) { - result.max = Math.round(result.max * 100) / 100; - } - if (result.cores && result.cores.length) { - for (let i = 0; i < result.cores.length; i++) { - result.cores[i] = Math.round(result.cores[i] * 100) / 100; - } - } } - - if (callback) { callback(result); } - resolve(result); - } - if (_sunos$c) { - if (callback) { callback(result); } - resolve(result); } - if (_windows$e) { + if (_windows$d) { + let swaptotal = 0; + let swapused = 0; try { - util$f.powerShell('Get-CimInstance MSAcpi_ThermalZoneTemperature -Namespace "root/wmi" | Select CurrentTemperature').then((stdout, error) => { + util$e.powerShell('Get-CimInstance Win32_PageFileUsage | Select AllocatedBaseSize, CurrentUsage').then((stdout, error) => { if (!error) { - let sum = 0; let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); lines.forEach(function (line) { - let value = (parseInt(line, 10) - 2732) / 10; - if (!isNaN(value)) { - sum = sum + value; - if (value > result.max) { result.max = value; } - result.cores.push(value); + if (line !== '') { + line = line.trim().split(/\s\s+/); + swaptotal = swaptotal + (parseInt(line[0], 10) || 0); + swapused = swapused + (parseInt(line[1], 10) || 0); } }); - if (result.cores.length) { - result.main = sum / result.cores.length; - } } + result.swaptotal = swaptotal * 1024 * 1024; + result.swapused = swapused * 1024 * 1024; + result.swapfree = result.swaptotal - result.swapused; + if (callback) { callback(result); } resolve(result); }); @@ -61075,228 +56637,565 @@ function cpuTemperature(callback) { }); } -cpu$1.cpuTemperature = cpuTemperature; +memory.mem = mem; -// -------------------------- -// CPU Flags +function memLayout(callback) { -function cpuFlags(callback) { + function getManufacturerDarwin(manId) { + if ({}.hasOwnProperty.call(OSX_RAM_manufacturers, manId)) { + return (OSX_RAM_manufacturers[manId]); + } + return manId; + } + + function getManufacturerLinux(manId) { + const manIdSearch = manId.replace('0x', '').toUpperCase(); + if (manIdSearch.length === 4 && {}.hasOwnProperty.call(LINUX_RAM_manufacturers, manIdSearch)) { + return (LINUX_RAM_manufacturers[manIdSearch]); + } + return manId; + } return new Promise((resolve) => { process.nextTick(() => { - let result = ''; - if (_windows$e) { - try { - exec$d('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', util$f.execOptsWin, function (error, stdout) { - if (!error) { - let flag_hex = stdout.split('0x').pop().trim(); - let flag_bin_unpadded = parseInt(flag_hex, 16).toString(2); - let flag_bin = '0'.repeat(32 - flag_bin_unpadded.length) + flag_bin_unpadded; - // empty flags are the reserved fields in the CPUID feature bit list - // as found on wikipedia: - // https://en.wikipedia.org/wiki/CPUID - let all_flags = [ - 'fpu', 'vme', 'de', 'pse', 'tsc', 'msr', 'pae', 'mce', 'cx8', 'apic', - '', 'sep', 'mtrr', 'pge', 'mca', 'cmov', 'pat', 'pse-36', 'psn', 'clfsh', - '', 'ds', 'acpi', 'mmx', 'fxsr', 'sse', 'sse2', 'ss', 'htt', 'tm', 'ia64', 'pbe' - ]; - for (let f = 0; f < all_flags.length; f++) { - if (flag_bin[f] === '1' && all_flags[f] !== '') { - result += ' ' + all_flags[f]; + + let result = []; + + if (_linux$c || _freebsd$b || _openbsd$b || _netbsd$b) { + exec$c('export LC_ALL=C; dmidecode -t memory 2>/dev/null | grep -iE "Size:|Type|Speed|Manufacturer|Form Factor|Locator|Memory Device|Serial Number|Voltage|Part Number"; unset LC_ALL', function (error, stdout) { + if (!error) { + let devices = stdout.toString().split('Memory Device'); + devices.shift(); + devices.forEach(function (device) { + let lines = device.split('\n'); + const sizeString = util$e.getValue(lines, 'Size'); + const size = sizeString.indexOf('GB') >= 0 ? parseInt(sizeString, 10) * 1024 * 1024 * 1024 : parseInt(sizeString, 10) * 1024 * 1024; + let bank = util$e.getValue(lines, 'Bank Locator'); + if (bank.toLowerCase().indexOf('bad') >= 0) { + bank = ''; + } + if (parseInt(util$e.getValue(lines, 'Size'), 10) > 0) { + const totalWidth = util$e.toInt(util$e.getValue(lines, 'Total Width')); + const dataWidth = util$e.toInt(util$e.getValue(lines, 'Data Width')); + result.push({ + size, + bank, + type: util$e.getValue(lines, 'Type:'), + ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false, + clockSpeed: (util$e.getValue(lines, 'Configured Clock Speed:') ? parseInt(util$e.getValue(lines, 'Configured Clock Speed:'), 10) : (util$e.getValue(lines, 'Speed:') ? parseInt(util$e.getValue(lines, 'Speed:'), 10) : null)), + formFactor: util$e.getValue(lines, 'Form Factor:'), + manufacturer: getManufacturerLinux(util$e.getValue(lines, 'Manufacturer:')), + partNum: util$e.getValue(lines, 'Part Number:'), + serialNum: util$e.getValue(lines, 'Serial Number:'), + voltageConfigured: parseFloat(util$e.getValue(lines, 'Configured Voltage:')) || null, + voltageMin: parseFloat(util$e.getValue(lines, 'Minimum Voltage:')) || null, + voltageMax: parseFloat(util$e.getValue(lines, 'Maximum Voltage:')) || null, + }); + } else { + result.push({ + size: 0, + bank, + type: 'Empty', + ecc: null, + clockSpeed: 0, + formFactor: util$e.getValue(lines, 'Form Factor:'), + partNum: '', + serialNum: '', + voltageConfigured: null, + voltageMin: null, + voltageMax: null, + }); + } + }); + } + if (!result.length) { + result.push({ + size: os$4.totalmem(), + bank: '', + type: '', + ecc: null, + clockSpeed: 0, + formFactor: '', + partNum: '', + serialNum: '', + voltageConfigured: null, + voltageMin: null, + voltageMax: null, + }); + + // Try Raspberry PI + try { + let stdout = execSync$7('cat /proc/cpuinfo 2>/dev/null'); + let lines = stdout.toString().split('\n'); + let model = util$e.getValue(lines, 'hardware', ':', true).toUpperCase(); + let version = util$e.getValue(lines, 'revision', ':', true).toLowerCase(); + + if (model === 'BCM2835' || model === 'BCM2708' || model === 'BCM2709' || model === 'BCM2835' || model === 'BCM2837') { + + const clockSpeed = { + '0': 400, + '1': 450, + '2': 450, + '3': 3200 + }; + result[0].type = 'LPDDR2'; + result[0].type = version && version[2] && version[2] === '3' ? 'LPDDR4' : result[0].type; + result[0].ecc = false; + result[0].clockSpeed = version && version[2] && clockSpeed[version[2]] || 400; + result[0].clockSpeed = version && version[4] && version[4] === 'd' ? 500 : result[0].clockSpeed; + result[0].formFactor = 'SoC'; + + stdout = execSync$7('vcgencmd get_config sdram_freq 2>/dev/null'); + lines = stdout.toString().split('\n'); + let freq = parseInt(util$e.getValue(lines, 'sdram_freq', '=', true), 10) || 0; + if (freq) { + result[0].clockSpeed = freq; + } + + stdout = execSync$7('vcgencmd measure_volts sdram_p 2>/dev/null'); + lines = stdout.toString().split('\n'); + let voltage = parseFloat(util$e.getValue(lines, 'volt', '=', true)) || 0; + if (voltage) { + result[0].voltageConfigured = voltage; + result[0].voltageMin = voltage; + result[0].voltageMax = voltage; } } - result = result.trim().toLowerCase(); + } catch (e) { + util$e.noop(); } - if (callback) { callback(result); } - resolve(result); - }); - } catch (e) { + + } if (callback) { callback(result); } resolve(result); - } + }); } - if (_linux$d) { - try { - exec$d('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - lines.forEach(function (line) { - if (line.split(':')[0].toUpperCase().indexOf('FLAGS') !== -1) { - result = line.split(':')[1].trim().toLowerCase(); - } - }); + if (_darwin$c) { + exec$c('system_profiler SPMemoryDataType', function (error, stdout) { + if (!error) { + const allLines = stdout.toString().split('\n'); + const eccStatus = util$e.getValue(allLines, 'ecc', ':', true).toLowerCase(); + let devices = stdout.toString().split(' BANK '); + let hasBank = true; + if (devices.length === 1) { + devices = stdout.toString().split(' DIMM'); + hasBank = false; } - if (!result) { - fs$7.readFile('/proc/cpuinfo', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - result = util$f.getValue(lines, 'features', ':', true).toLowerCase(); - } - if (callback) { callback(result); } - resolve(result); + devices.shift(); + devices.forEach(function (device) { + let lines = device.split('\n'); + const bank = (hasBank ? 'BANK ' : 'DIMM') + lines[0].trim().split('/')[0]; + const size = parseInt(util$e.getValue(lines, ' Size')); + if (size) { + result.push({ + size: size * 1024 * 1024 * 1024, + bank: bank, + type: util$e.getValue(lines, ' Type:'), + ecc: eccStatus ? eccStatus === 'enabled' : null, + clockSpeed: parseInt(util$e.getValue(lines, ' Speed:'), 10), + formFactor: '', + manufacturer: getManufacturerDarwin(util$e.getValue(lines, ' Manufacturer:')), + partNum: util$e.getValue(lines, ' Part Number:'), + serialNum: util$e.getValue(lines, ' Serial Number:'), + voltageConfigured: null, + voltageMin: null, + voltageMax: null, + }); + } else { + result.push({ + size: 0, + bank: bank, + type: 'Empty', + ecc: null, + clockSpeed: 0, + formFactor: '', + manufacturer: '', + partNum: '', + serialNum: '', + voltageConfigured: null, + voltageMin: null, + voltageMax: null, + }); + } + }); + } + if (!result.length) { + const lines = stdout.toString().split('\n'); + const size = parseInt(util$e.getValue(lines, ' Memory:')); + const type = util$e.getValue(lines, ' Type:'); + if (size && type) { + result.push({ + size: size * 1024 * 1024 * 1024, + bank: '0', + type, + ecc: false, + clockSpeed: 0, + formFactor: '', + manufacturer: 'Apple', + partNum: '', + serialNum: '', + voltageConfigured: null, + voltageMin: null, + voltageMax: null, }); - } else { - if (callback) { callback(result); } - resolve(result); + } - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } - } - if (_freebsd$c || _openbsd$c || _netbsd$c) { - exec$d('export LC_ALL=C; dmidecode -t 4 2>/dev/null; unset LC_ALL', function (error, stdout) { - let flags = []; - if (!error) { - let parts = stdout.toString().split('\tFlags:'); - const lines = parts.length > 1 ? parts[1].split('\tVersion:')[0].split('\n') : []; - lines.forEach(function (line) { - let flag = (line.indexOf('(') ? line.split('(')[0].toLowerCase() : '').trim().replace(/\t/g, ''); - if (flag) { - flags.push(flag); - } - }); } - result = flags.join(' ').trim().toLowerCase(); if (callback) { callback(result); } resolve(result); }); } - if (_darwin$d) { - exec$d('sysctl machdep.cpu.features', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - if (lines.length > 0 && lines[0].indexOf('machdep.cpu.features:') !== -1) { - result = lines[0].split(':')[1].trim().toLowerCase(); + if (_sunos$b) { + if (callback) { callback(result); } + resolve(result); + } + if (_windows$d) { + // https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0a.pdf + const memoryTypes = 'Unknown|Other|DRAM|Synchronous DRAM|Cache DRAM|EDO|EDRAM|VRAM|SRAM|RAM|ROM|FLASH|EEPROM|FEPROM|EPROM|CDRAM|3DRAM|SDRAM|SGRAM|RDRAM|DDR|DDR2|DDR2 FB-DIMM|Reserved|DDR3|FBD2|DDR4|LPDDR|LPDDR2|LPDDR3|LPDDR4|Logical non-volatile device|HBM|HBM2|DDR5|LPDDR5'.split('|'); + const FormFactors = 'Unknown|Other|SIP|DIP|ZIP|SOJ|Proprietary|SIMM|DIMM|TSOP|PGA|RIMM|SODIMM|SRIMM|SMD|SSMP|QFP|TQFP|SOIC|LCC|PLCC|BGA|FPBGA|LGA'.split('|'); + + try { + util$e.powerShell('Get-CimInstance Win32_PhysicalMemory | select DataWidth,TotalWidth,Capacity,BankLabel,MemoryType,SMBIOSMemoryType,ConfiguredClockSpeed,FormFactor,Manufacturer,PartNumber,SerialNumber,ConfiguredVoltage,MinVoltage,MaxVoltage | fl').then((stdout, error) => { + if (!error) { + let devices = stdout.toString().split(/\n\s*\n/); + devices.shift(); + devices.forEach(function (device) { + let lines = device.split('\r\n'); + const dataWidth = util$e.toInt(util$e.getValue(lines, 'DataWidth', ':')); + const totalWidth = util$e.toInt(util$e.getValue(lines, 'TotalWidth', ':')); + const size = parseInt(util$e.getValue(lines, 'Capacity', ':'), 10) || 0; + if (size) { + result.push({ + size, + bank: util$e.getValue(lines, 'BankLabel', ':'), // BankLabel + type: memoryTypes[parseInt(util$e.getValue(lines, 'MemoryType', ':'), 10) || parseInt(util$e.getValue(lines, 'SMBIOSMemoryType', ':'), 10)], + ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false, + clockSpeed: parseInt(util$e.getValue(lines, 'ConfiguredClockSpeed', ':'), 10) || parseInt(util$e.getValue(lines, 'Speed', ':'), 10) || 0, + formFactor: FormFactors[parseInt(util$e.getValue(lines, 'FormFactor', ':'), 10) || 0], + manufacturer: util$e.getValue(lines, 'Manufacturer', ':'), + partNum: util$e.getValue(lines, 'PartNumber', ':'), + serialNum: util$e.getValue(lines, 'SerialNumber', ':'), + voltageConfigured: (parseInt(util$e.getValue(lines, 'ConfiguredVoltage', ':'), 10) || 0) / 1000.0, + voltageMin: (parseInt(util$e.getValue(lines, 'MinVoltage', ':'), 10) || 0) / 1000.0, + voltageMax: (parseInt(util$e.getValue(lines, 'MaxVoltage', ':'), 10) || 0) / 1000.0, + }); + } + }); } - } + if (callback) { callback(result); } + resolve(result); + }); + } catch (e) { if (callback) { callback(result); } resolve(result); - }); - } - if (_sunos$c) { - if (callback) { callback(result); } - resolve(result); + } } }); }); } -cpu$1.cpuFlags = cpuFlags; +memory.memLayout = memLayout; -// -------------------------- -// CPU Cache +// @ts-check; +// ================================================================================== +// battery.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 6. Battery +// ---------------------------------------------------------------------------------- -function cpuCache(callback) { +const exec$b = require$$1$2.exec; +const fs$5 = require$$0$5; +const util$d = util$j; + +let _platform$c = process.platform; + +const _linux$b = (_platform$c === 'linux' || _platform$c === 'android'); +const _darwin$b = (_platform$c === 'darwin'); +const _windows$c = (_platform$c === 'win32'); +const _freebsd$a = (_platform$c === 'freebsd'); +const _openbsd$a = (_platform$c === 'openbsd'); +const _netbsd$a = (_platform$c === 'netbsd'); +const _sunos$a = (_platform$c === 'sunos'); + +function parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity) { + const result = {}; + let status = util$d.getValue(lines, 'BatteryStatus', ':').trim(); + // 1 = "Discharging" + // 2 = "On A/C" + // 3 = "Fully Charged" + // 4 = "Low" + // 5 = "Critical" + // 6 = "Charging" + // 7 = "Charging High" + // 8 = "Charging Low" + // 9 = "Charging Critical" + // 10 = "Undefined" + // 11 = "Partially Charged" + if (status >= 0) { + const statusValue = status ? parseInt(status) : 0; + result.status = statusValue; + result.hasBattery = true; + result.maxCapacity = fullChargeCapacity || parseInt(util$d.getValue(lines, 'DesignCapacity', ':') || 0); + result.designedCapacity = parseInt(util$d.getValue(lines, 'DesignCapacity', ':') || designedCapacity); + result.voltage = parseInt(util$d.getValue(lines, 'DesignVoltage', ':') || 0) / 1000.0; + result.capacityUnit = 'mWh'; + result.percent = parseInt(util$d.getValue(lines, 'EstimatedChargeRemaining', ':') || 0); + result.currentCapacity = parseInt(result.maxCapacity * result.percent / 100); + result.isCharging = (statusValue >= 6 && statusValue <= 9) || statusValue === 11 || ((statusValue !== 3) && (statusValue !== 1) && result.percent < 100); + result.acConnected = result.isCharging || statusValue === 2; + result.model = util$d.getValue(lines, 'DeviceID', ':'); + } else { + result.status = -1; + } + + return result; +} + +var battery = function (callback) { return new Promise((resolve) => { process.nextTick(() => { - let result = { - l1d: null, - l1i: null, - l2: null, - l3: null, + hasBattery: false, + cycleCount: 0, + isCharging: false, + designedCapacity: 0, + maxCapacity: 0, + currentCapacity: 0, + voltage: 0, + capacityUnit: '', + percent: 0, + timeRemaining: null, + acConnected: true, + type: '', + model: '', + manufacturer: '', + serial: '' }; - if (_linux$d) { - try { - exec$d('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) { + + if (_linux$b) { + let battery_path = ''; + if (fs$5.existsSync('/sys/class/power_supply/BAT1/uevent')) { + battery_path = '/sys/class/power_supply/BAT1/'; + } else if (fs$5.existsSync('/sys/class/power_supply/BAT0/uevent')) { + battery_path = '/sys/class/power_supply/BAT0/'; + } + + let acConnected = false; + let acPath = ''; + if (fs$5.existsSync('/sys/class/power_supply/AC/online')) { + acPath = '/sys/class/power_supply/AC/online'; + } else if (fs$5.existsSync('/sys/class/power_supply/AC0/online')) { + acPath = '/sys/class/power_supply/AC0/online'; + } + + if (acPath) { + const file = fs$5.readFileSync(acPath); + acConnected = file.toString().trim() === '1'; + } + + if (battery_path) { + fs$5.readFile(battery_path + 'uevent', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); - lines.forEach(function (line) { - let parts = line.split(':'); - if (parts[0].toUpperCase().indexOf('L1D CACHE') !== -1) { - result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1)); - } - if (parts[0].toUpperCase().indexOf('L1I CACHE') !== -1) { - result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1)); - } - if (parts[0].toUpperCase().indexOf('L2 CACHE') !== -1) { - result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1)); - } - if (parts[0].toUpperCase().indexOf('L3 CACHE') !== -1) { - result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1)); + + result.isCharging = (util$d.getValue(lines, 'POWER_SUPPLY_STATUS', '=').toLowerCase() === 'charging'); + result.acConnected = acConnected || result.isCharging; + result.voltage = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_VOLTAGE_NOW', '='), 10) / 1000000.0; + result.capacityUnit = result.voltage ? 'mWh' : 'mAh'; + result.cycleCount = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CYCLE_COUNT', '='), 10); + result.maxCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL', '=', true, true), 10) / 1000.0 * (result.voltage || 1)); + const desingedMinVoltage = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_VOLTAGE_MIN_DESIGN', '='), 10) / 1000000.0; + result.designedCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL_DESIGN', '=', true, true), 10) / 1000.0 * (desingedMinVoltage || result.voltage || 1)); + result.currentCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10) / 1000.0 * (result.voltage || 1)); + if (!result.maxCapacity) { + result.maxCapacity = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL', '=', true, true), 10) / 1000.0; + result.designedCapacity = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL_DESIGN', '=', true, true), 10) / 1000.0 | result.maxCapacity; + result.currentCapacity = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10) / 1000.0; + } + const percent = util$d.getValue(lines, 'POWER_SUPPLY_CAPACITY', '='); + const energy = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10); + const power = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_POWER_NOW', '='), 10); + const current = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CURRENT_NOW', '='), 10); + const charge = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10); + + result.percent = parseInt('0' + percent, 10); + if (result.maxCapacity && result.currentCapacity) { + result.hasBattery = true; + if (!percent) { + result.percent = 100.0 * result.currentCapacity / result.maxCapacity; } - }); + } + if (result.isCharging) { + result.hasBattery = true; + } + if (energy && power) { + result.timeRemaining = Math.floor(energy / power * 60); + } else if (current && charge) { + result.timeRemaining = Math.floor(charge / current * 60); + } else if (current && result.currentCapacity) { + result.timeRemaining = Math.floor(result.currentCapacity / current * 60); + } + result.type = util$d.getValue(lines, 'POWER_SUPPLY_TECHNOLOGY', '='); + result.model = util$d.getValue(lines, 'POWER_SUPPLY_MODEL_NAME', '='); + result.manufacturer = util$d.getValue(lines, 'POWER_SUPPLY_MANUFACTURER', '='); + result.serial = util$d.getValue(lines, 'POWER_SUPPLY_SERIAL_NUMBER', '='); + if (callback) { callback(result); } + resolve(result); + } else { + if (callback) { callback(result); } + resolve(result); } - if (callback) { callback(result); } - resolve(result); }); - } catch (e) { + } else { if (callback) { callback(result); } resolve(result); } } - if (_freebsd$c || _openbsd$c || _netbsd$c) { - exec$d('export LC_ALL=C; dmidecode -t 7 2>/dev/null; unset LC_ALL', function (error, stdout) { - let cache = []; - if (!error) { - const data = stdout.toString(); - cache = data.split('Cache Information'); - cache.shift(); - } - for (let i = 0; i < cache.length; i++) { - const lines = cache[i].split('\n'); - let cacheType = util$f.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-'); - cacheType = cacheType.length ? cacheType[0] : ''; - const sizeParts = util$f.getValue(lines, 'Installed Size').split(' '); - let size = parseInt(sizeParts[0], 10); - const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb'; - size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1))); - if (cacheType) { - if (cacheType === 'l1') { - result.cache[cacheType + 'd'] = size / 2; - result.cache[cacheType + 'i'] = size / 2; - } else { - result.cache[cacheType] = size; - } - } - } + if (_freebsd$a || _openbsd$a || _netbsd$a) { + exec$b('sysctl -i hw.acpi.battery hw.acpi.acline', function (error, stdout) { + let lines = stdout.toString().split('\n'); + const batteries = parseInt('0' + util$d.getValue(lines, 'hw.acpi.battery.units'), 10); + const percent = parseInt('0' + util$d.getValue(lines, 'hw.acpi.battery.life'), 10); + result.hasBattery = (batteries > 0); + result.cycleCount = null; + result.isCharging = util$d.getValue(lines, 'hw.acpi.acline') !== '1'; + result.acConnected = result.isCharging; + result.maxCapacity = null; + result.currentCapacity = null; + result.capacityUnit = 'unknown'; + result.percent = batteries ? percent : null; if (callback) { callback(result); } resolve(result); }); } - if (_darwin$d) { - exec$d('sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - lines.forEach(function (line) { - let parts = line.split(':'); - if (parts[0].toLowerCase().indexOf('hw.l1icachesize') !== -1) { - result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1); - } - if (parts[0].toLowerCase().indexOf('hw.l1dcachesize') !== -1) { - result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1); - } - if (parts[0].toLowerCase().indexOf('hw.l2cachesize') !== -1) { - result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1); + + if (_darwin$b) { + exec$b('ioreg -n AppleSmartBattery -r | egrep "CycleCount|IsCharging|DesignCapacity|MaxCapacity|CurrentCapacity|BatterySerialNumber|TimeRemaining|Voltage"; pmset -g batt | grep %', function (error, stdout) { + if (stdout) { + let lines = stdout.toString().replace(/ +/g, '').replace(/"+/g, '').replace(/-/g, '').split('\n'); + result.cycleCount = parseInt('0' + util$d.getValue(lines, 'cyclecount', '='), 10); + result.voltage = parseInt('0' + util$d.getValue(lines, 'voltage', '='), 10) / 1000.0; + result.capacityUnit = result.voltage ? 'mWh' : 'mAh'; + result.maxCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'applerawmaxcapacity', '='), 10) * (result.voltage || 1)); + result.currentCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'applerawcurrentcapacity', '='), 10) * (result.voltage || 1)); + result.designedCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'DesignCapacity', '='), 10) * (result.voltage || 1)); + result.manufacturer = 'Apple'; + result.serial = util$d.getValue(lines, 'BatterySerialNumber', '='); + let percent = null; + const line = util$d.getValue(lines, 'internal', 'Battery'); + let parts = line.split(';'); + if (parts && parts[0]) { + let parts2 = parts[0].split('\t'); + if (parts2 && parts2[1]) { + percent = parseFloat(parts2[1].trim().replace(/%/g, '')); } - if (parts[0].toLowerCase().indexOf('hw.l3cachesize') !== -1) { - result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1); + } + if (parts && parts[1]) { + result.isCharging = (parts[1].trim() === 'charging'); + result.acConnected = (parts[1].trim() !== 'discharging'); + } else { + result.isCharging = util$d.getValue(lines, 'ischarging', '=').toLowerCase() === 'yes'; + result.acConnected = result.isCharging; + } + if (result.maxCapacity && result.currentCapacity) { + result.hasBattery = true; + result.type = 'Li-ion'; + result.percent = percent !== null ? percent : Math.round(100.0 * result.currentCapacity / result.maxCapacity); + if (!result.isCharging) { + result.timeRemaining = parseInt('0' + util$d.getValue(lines, 'TimeRemaining', '='), 10); } - }); + } } if (callback) { callback(result); } resolve(result); }); } - if (_sunos$c) { + if (_sunos$a) { if (callback) { callback(result); } resolve(result); } - if (_windows$e) { + if (_windows$c) { try { const workload = []; - workload.push(util$f.powerShell('Get-CimInstance Win32_processor | select L2CacheSize, L3CacheSize | fl')); - workload.push(util$f.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl')); - - Promise.all( + workload.push(util$d.powerShell('Get-CimInstance Win32_Battery | select BatteryStatus, DesignCapacity, DesignVoltage, EstimatedChargeRemaining, DeviceID | fl')); + workload.push(util$d.powerShell('(Get-CimInstance -Class BatteryStaticData -Namespace ROOT/WMI).DesignedCapacity')); + workload.push(util$d.powerShell('(Get-CimInstance -Class BatteryFullChargedCapacity -Namespace ROOT/WMI).FullChargedCapacity')); + util$d.promiseAll( workload ).then((data) => { - result = parseWinCache(data[0], data[1]); - + if (data) { + let parts = data.results[0].split(/\n\s*\n/); + let batteries = []; + const hasValue = value => /\S/.test(value); + for (let i = 0; i < parts.length; i++) { + if (hasValue(parts[i]) && (!batteries.length || !hasValue(parts[i - 1]))) { + batteries.push([]); + } + if (hasValue(parts[i])) { + batteries[batteries.length - 1].push(parts[i]); + } + } + let designCapacities = data.results[1].split('\r\n').filter(e => e); + let fullChargeCapacities = data.results[2].split('\r\n').filter(e => e); + if (batteries.length) { + let first = false; + let additionalBatteries = []; + for (let i = 0; i < batteries.length; i++) { + let lines = batteries[i][0].split('\r\n'); + const designedCapacity = designCapacities && designCapacities.length >= (i + 1) && designCapacities[i] ? util$d.toInt(designCapacities[i]) : 0; + const fullChargeCapacity = fullChargeCapacities && fullChargeCapacities.length >= (i + 1) && fullChargeCapacities[i] ? util$d.toInt(fullChargeCapacities[i]) : 0; + const parsed = parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity); + if (!first && parsed.status > 0 && parsed.status !== 10) { + result.hasBattery = parsed.hasBattery; + result.maxCapacity = parsed.maxCapacity; + result.designedCapacity = parsed.designedCapacity; + result.voltage = parsed.voltage; + result.capacityUnit = parsed.capacityUnit; + result.percent = parsed.percent; + result.currentCapacity = parsed.currentCapacity; + result.isCharging = parsed.isCharging; + result.acConnected = parsed.acConnected; + result.model = parsed.model; + first = true; + } else if (parsed.status !== -1) { + additionalBatteries.push( + { + hasBattery: parsed.hasBattery, + maxCapacity: parsed.maxCapacity, + designedCapacity: parsed.designedCapacity, + voltage: parsed.voltage, + capacityUnit: parsed.capacityUnit, + percent: parsed.percent, + currentCapacity: parsed.currentCapacity, + isCharging: parsed.isCharging, + timeRemaining: null, + acConnected: parsed.acConnected, + model: parsed.model, + type: '', + manufacturer: '', + serial: '' + } + ); + } + } + if (!first && additionalBatteries.length) { + result = additionalBatteries[0]; + additionalBatteries.shift(); + } + if (additionalBatteries.length) { + result.additionalBatteries = additionalBatteries; + } + } + } if (callback) { callback(result); } resolve(result); }); @@ -61307,888 +57206,947 @@ function cpuCache(callback) { } }); }); +}; + +var graphics$1 = {}; + +// @ts-check +// ================================================================================== +// graphics.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 7. Graphics (controller, display) +// ---------------------------------------------------------------------------------- + +const fs$4 = require$$0$5; +const exec$a = require$$1$2.exec; +const execSync$6 = require$$1$2.execSync; +const util$c = util$j; + +let _platform$b = process.platform; +let _nvidiaSmiPath = ''; + +const _linux$a = (_platform$b === 'linux' || _platform$b === 'android'); +const _darwin$a = (_platform$b === 'darwin'); +const _windows$b = (_platform$b === 'win32'); +const _freebsd$9 = (_platform$b === 'freebsd'); +const _openbsd$9 = (_platform$b === 'openbsd'); +const _netbsd$9 = (_platform$b === 'netbsd'); +const _sunos$9 = (_platform$b === 'sunos'); + +let _resolutionX = 0; +let _resolutionY = 0; +let _pixelDepth = 0; +let _refreshRate = 0; + +const videoTypes = { + '-2': 'UNINITIALIZED', + '-1': 'OTHER', + '0': 'HD15', + '1': 'SVIDEO', + '2': 'Composite video', + '3': 'Component video', + '4': 'DVI', + '5': 'HDMI', + '6': 'LVDS', + '8': 'D_JPN', + '9': 'SDI', + '10': 'DP', + '11': 'DP embedded', + '12': 'UDI', + '13': 'UDI embedded', + '14': 'SDTVDONGLE', + '15': 'MIRACAST', + '2147483648': 'INTERNAL' +}; + +function getVendorFromModel(model) { + const manufacturers = [ + { pattern: '^LG.+', manufacturer: 'LG' }, + { pattern: '^BENQ.+', manufacturer: 'BenQ' }, + { pattern: '^ASUS.+', manufacturer: 'Asus' }, + { pattern: '^DELL.+', manufacturer: 'Dell' }, + { pattern: '^SAMSUNG.+', manufacturer: 'Samsung' }, + { pattern: '^VIEWSON.+', manufacturer: 'ViewSonic' }, + { pattern: '^SONY.+', manufacturer: 'Sony' }, + { pattern: '^ACER.+', manufacturer: 'Acer' }, + { pattern: '^AOC.+', manufacturer: 'AOC Monitors' }, + { pattern: '^HP.+', manufacturer: 'HP' }, + { pattern: '^EIZO.?', manufacturer: 'Eizo' }, + { pattern: '^PHILIPS.?', manufacturer: 'Philips' }, + { pattern: '^IIYAMA.?', manufacturer: 'Iiyama' }, + { pattern: '^SHARP.?', manufacturer: 'Sharp' }, + { pattern: '^NEC.?', manufacturer: 'NEC' }, + { pattern: '^LENOVO.?', manufacturer: 'Lenovo' }, + { pattern: 'COMPAQ.?', manufacturer: 'Compaq' }, + { pattern: 'APPLE.?', manufacturer: 'Apple' }, + { pattern: 'INTEL.?', manufacturer: 'Intel' }, + { pattern: 'AMD.?', manufacturer: 'AMD' }, + { pattern: 'NVIDIA.?', manufacturer: 'NVDIA' }, + ]; + + let result = ''; + if (model) { + model = model.toUpperCase(); + manufacturers.forEach((manufacturer) => { + const re = RegExp(manufacturer.pattern); + if (re.test(model)) { result = manufacturer.manufacturer; } + }); + } + return result; } -function parseWinCache(linesProc, linesCache) { - let result = { - l1d: null, - l1i: null, - l2: null, - l3: null, +function getVendorFromId(id) { + const vendors = { + '610': 'Apple', + '1e6d': 'LG', + '10ac': 'DELL', + '4dd9': 'Sony', + '38a3': 'NEC', }; + return vendors[id] || ''; +} - // Win32_processor - let lines = linesProc.split('\r\n'); - result.l1d = 0; - result.l1i = 0; - result.l2 = util$f.getValue(lines, 'l2cachesize', ':'); - result.l3 = util$f.getValue(lines, 'l3cachesize', ':'); - if (result.l2) { result.l2 = parseInt(result.l2, 10) * 1024; } else { result.l2 = 0; } - if (result.l3) { result.l3 = parseInt(result.l3, 10) * 1024; } else { result.l3 = 0; } +function vendorToId(str) { + let result = ''; + str = (str || '').toLowerCase(); + if (str.indexOf('apple') >= 0) { result = '0x05ac'; } + else if (str.indexOf('nvidia') >= 0) { result = '0x10de'; } + else if (str.indexOf('intel') >= 0) { result = '0x8086'; } + else if (str.indexOf('ati') >= 0 || str.indexOf('amd') >= 0) { result = '0x1002'; } - // Win32_CacheMemory - const parts = linesCache.split(/\n\s*\n/); - let l1i = 0; - let l1d = 0; - let l2 = 0; - parts.forEach(function (part) { - const lines = part.split('\r\n'); - const cacheType = util$f.getValue(lines, 'CacheType'); - const level = util$f.getValue(lines, 'Level'); - const installedSize = util$f.getValue(lines, 'InstalledSize'); - // L1 Instructions - if (level === '3' && cacheType === '3') { - result.l1i = result.l1i + parseInt(installedSize, 10) * 1024; - } - // L1 Data - if (level === '3' && cacheType === '4') { - result.l1d = result.l1d + parseInt(installedSize, 10) * 1024; - } - // L1 all - if (level === '3' && cacheType === '5') { - l1i = parseInt(installedSize, 10) / 2; - l1d = parseInt(installedSize, 10) / 2; - } - // L2 - if (level === '4' && cacheType === '5') { - l2 = l2 + parseInt(installedSize, 10) * 1024; - } - }); - if (!result.l1i && !result.l1d) { - result.l1i = l1i; - result.l1d = l1d; - } - if (l2) { - result.l2 = l2; - } return result; } -cpu$1.cpuCache = cpuCache; +function getMetalVersion(id) { + const families = { + 'spdisplays_mtlgpufamilymac1': 'mac1', + 'spdisplays_mtlgpufamilymac2': 'mac2', + 'spdisplays_mtlgpufamilyapple1': 'apple1', + 'spdisplays_mtlgpufamilyapple2': 'apple2', + 'spdisplays_mtlgpufamilyapple3': 'apple3', + 'spdisplays_mtlgpufamilyapple4': 'apple4', + 'spdisplays_mtlgpufamilyapple5': 'apple5', + 'spdisplays_mtlgpufamilyapple6': 'apple6', + 'spdisplays_mtlgpufamilyapple7': 'apple7', + 'spdisplays_metalfeaturesetfamily11': 'family1_v1', + 'spdisplays_metalfeaturesetfamily12': 'family1_v2', + 'spdisplays_metalfeaturesetfamily13': 'family1_v3', + 'spdisplays_metalfeaturesetfamily14': 'family1_v4', + 'spdisplays_metalfeaturesetfamily21': 'family2_v1' + }; + return families[id] || ''; +} -// -------------------------- -// CPU - current load - in % +function graphics(callback) { -function getLoad() { + function parseLinesDarwin(graphicsArr) { + const res = { + controllers: [], + displays: [] + }; + try { + graphicsArr.forEach(function (item) { + // controllers + const bus = ((item.sppci_bus || '').indexOf('builtin') > -1 ? 'Built-In' : ((item.sppci_bus || '').indexOf('pcie') > -1 ? 'PCIe' : '')); + const vram = (parseInt((item.spdisplays_vram || ''), 10) || 0) * (((item.spdisplays_vram || '').indexOf('GB') > -1) ? 1024 : 1); + const vramDyn = (parseInt((item.spdisplays_vram_shared || ''), 10) || 0) * (((item.spdisplays_vram_shared || '').indexOf('GB') > -1) ? 1024 : 1); + let metalVersion = getMetalVersion(item.spdisplays_metal || item.spdisplays_metalfamily || ''); + res.controllers.push({ + vendor: getVendorFromModel(item.spdisplays_vendor || '') || item.spdisplays_vendor || '', + model: item.sppci_model || '', + bus, + vramDynamic: bus === 'Built-In', + vram: vram || vramDyn || null, + deviceId: item['spdisplays_device-id'] || '', + vendorId: item['spdisplays_vendor-id'] || vendorToId((item['spdisplays_vendor'] || '') + (item.sppci_model || '')), + external: (item.sppci_device_type === 'spdisplays_egpu'), + cores: item['sppci_cores'] || null, + metalVersion + }); - return new Promise((resolve) => { - process.nextTick(() => { - let loads = os$5.loadavg().map(function (x) { return x / util$f.cores(); }); - let avgLoad = parseFloat((Math.max.apply(Math, loads)).toFixed(2)); - let result = {}; + // displays + if (item.spdisplays_ndrvs && item.spdisplays_ndrvs.length) { + item.spdisplays_ndrvs.forEach(function (displayItem) { + const connectionType = displayItem['spdisplays_connection_type'] || ''; + const currentResolutionParts = (displayItem['_spdisplays_resolution'] || '').split('@'); + const currentResolution = currentResolutionParts[0].split('x'); + const pixelParts = (displayItem['_spdisplays_pixels'] || '').split('x'); + const pixelDepthString = displayItem['spdisplays_depth'] || ''; + const serial = displayItem['_spdisplays_display-serial-number'] || displayItem['_spdisplays_display-serial-number2'] || null; + res.displays.push({ + vendor: getVendorFromId(displayItem['_spdisplays_display-vendor-id'] || '') || getVendorFromModel(displayItem['_name'] || ''), + vendorId: displayItem['_spdisplays_display-vendor-id'] || '', + model: displayItem['_name'] || '', + productionYear: displayItem['_spdisplays_display-year'] || null, + serial: serial !== '0' ? serial : null, + displayId: displayItem['_spdisplays_displayID'] || null, + main: displayItem['spdisplays_main'] ? displayItem['spdisplays_main'] === 'spdisplays_yes' : false, + builtin: (displayItem['spdisplays_display_type'] || '').indexOf('built-in') > -1, + connection: ((connectionType.indexOf('_internal') > -1) ? 'Internal' : ((connectionType.indexOf('_displayport') > -1) ? 'Display Port' : ((connectionType.indexOf('_hdmi') > -1) ? 'HDMI' : null))), + sizeX: null, + sizeY: null, + pixelDepth: (pixelDepthString === 'CGSThirtyBitColor' ? 30 : (pixelDepthString === 'CGSThirtytwoBitColor' ? 32 : (pixelDepthString === 'CGSTwentyfourBitColor' ? 24 : null))), + resolutionX: pixelParts.length > 1 ? parseInt(pixelParts[0], 10) : null, + resolutionY: pixelParts.length > 1 ? parseInt(pixelParts[1], 10) : null, + currentResX: currentResolution.length > 1 ? parseInt(currentResolution[0], 10) : null, + currentResY: currentResolution.length > 1 ? parseInt(currentResolution[1], 10) : null, + positionX: 0, + positionY: 0, + currentRefreshRate: currentResolutionParts.length > 1 ? parseInt(currentResolutionParts[1], 10) : null, - let now = Date.now() - _current_cpu.ms; - if (now >= 200) { - _current_cpu.ms = Date.now(); - const cpus = os$5.cpus().map(function (cpu) { - cpu.times.steal = 0; - cpu.times.guest = 0; - return cpu; - }); - let totalUser = 0; - let totalSystem = 0; - let totalNice = 0; - let totalIrq = 0; - let totalIdle = 0; - let totalSteal = 0; - let totalGuest = 0; - let cores = []; - _corecount = (cpus && cpus.length) ? cpus.length : 0; + }); + }); + } + }); + return res; + } catch (e) { + return res; + } + } - // linux: try to get other cpu stats - if (_linux$d) { - try { - const lines = execSync$8('cat /proc/stat 2>/dev/null | grep cpu', { encoding: 'utf8' }).toString().split('\n'); - if (lines.length > 1) { - lines.shift(); - if (lines.length === cpus.length) { - for (let i = 0; i < lines.length; i++) { - let parts = lines[i].split(' '); - if (parts.length >= 10) { - const steal = parseFloat(parts[8]) || 0; - const guest = parseFloat(parts[9]) || 0; - cpus[i].times.steal = steal; - cpus[i].times.guest = guest; - } + function parseLinesLinuxControllers(lines) { + let controllers = []; + let currentController = { + vendor: '', + subVendor: '', + model: '', + bus: '', + busAddress: '', + vram: null, + vramDynamic: false, + pciID: '' + }; + let isGraphicsController = false; + // PCI bus IDs + let pciIDs = []; + try { + pciIDs = execSync$6('export LC_ALL=C; dmidecode -t 9 2>/dev/null; unset LC_ALL | grep "Bus Address: "').toString().split('\n'); + for (let i = 0; i < pciIDs.length; i++) { + pciIDs[i] = pciIDs[i].replace('Bus Address:', '').replace('0000:', '').trim(); + } + pciIDs = pciIDs.filter(function (el) { + return el != null && el; + }); + } catch (e) { + util$c.noop(); + } + let i = 1; + lines.forEach((line) => { + let subsystem = ''; + if (i < lines.length && lines[i]) { // get next line; + subsystem = lines[i]; + if (subsystem.indexOf(':') > 0) { + subsystem = subsystem.split(':')[1]; + } + } + if ('' !== line.trim()) { + if (' ' !== line[0] && '\t' !== line[0]) { // first line of new entry + let isExternal = (pciIDs.indexOf(line.split(' ')[0]) >= 0); + let vgapos = line.toLowerCase().indexOf(' vga '); + let _3dcontrollerpos = line.toLowerCase().indexOf('3d controller'); + if (vgapos !== -1 || _3dcontrollerpos !== -1) { // VGA + if (_3dcontrollerpos !== -1 && vgapos === -1) { + vgapos = _3dcontrollerpos; + } + if (currentController.vendor || currentController.model || currentController.bus || currentController.vram !== null || currentController.vramDynamic) { // already a controller found + controllers.push(currentController); + currentController = { + vendor: '', + model: '', + bus: '', + busAddress: '', + vram: null, + vramDynamic: false, + }; + } + + const pciIDCandidate = line.split(' ')[0]; + if (/[\da-fA-F]{2}:[\da-fA-F]{2}\.[\da-fA-F]/.test(pciIDCandidate)) { + currentController.busAddress = pciIDCandidate; + } + isGraphicsController = true; + let endpos = line.search(/\[[0-9a-f]{4}:[0-9a-f]{4}]|$/); + let parts = line.substr(vgapos, endpos - vgapos).split(':'); + currentController.busAddress = line.substr(0, vgapos).trim(); + if (parts.length > 1) { + parts[1] = parts[1].trim(); + if (parts[1].toLowerCase().indexOf('corporation') >= 0) { + currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf('corporation') + 11).trim(); + currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf('corporation') + 11, 200).split('(')[0].trim(); + currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard'; + currentController.vram = null; + currentController.vramDynamic = false; + } else if (parts[1].toLowerCase().indexOf(' inc.') >= 0) { + if ((parts[1].match(/]/g) || []).length > 1) { + currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim(); + currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim(); + } else { + currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' inc.') + 5).trim(); + currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' inc.') + 5, 200).trim().split('(')[0].trim(); + } + currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard'; + currentController.vram = null; + currentController.vramDynamic = false; + } else if (parts[1].toLowerCase().indexOf(' ltd.') >= 0) { + if ((parts[1].match(/]/g) || []).length > 1) { + currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim(); + currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim(); + } else { + currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' ltd.') + 5).trim(); + currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' ltd.') + 5, 200).trim().split('(')[0].trim(); + } + } + if (currentController.model && subsystem.indexOf(currentController.model) !== -1) { + const subVendor = subsystem.split(currentController.model)[0].trim(); + if (subVendor) { + currentController.subVendor = subVendor; } } } - } catch (e) { - util$f.noop(); - } - } - for (let i = 0; i < _corecount; i++) { - const cpu = cpus[i].times; - totalUser += cpu.user; - totalSystem += cpu.sys; - totalNice += cpu.nice; - totalIdle += cpu.idle; - totalIrq += cpu.irq; - totalSteal += cpu.steal || 0; - totalGuest += cpu.guest || 0; - let tmpTick = (_cpus && _cpus[i] && _cpus[i].totalTick ? _cpus[i].totalTick : 0); - let tmpLoad = (_cpus && _cpus[i] && _cpus[i].totalLoad ? _cpus[i].totalLoad : 0); - let tmpUser = (_cpus && _cpus[i] && _cpus[i].user ? _cpus[i].user : 0); - let tmpSystem = (_cpus && _cpus[i] && _cpus[i].sys ? _cpus[i].sys : 0); - let tmpNice = (_cpus && _cpus[i] && _cpus[i].nice ? _cpus[i].nice : 0); - let tmpIdle = (_cpus && _cpus[i] && _cpus[i].idle ? _cpus[i].idle : 0); - let tmpIrq = (_cpus && _cpus[i] && _cpus[i].irq ? _cpus[i].irq : 0); - let tmpSteal = (_cpus && _cpus[i] && _cpus[i].steal ? _cpus[i].steal : 0); - let tmpGuest = (_cpus && _cpus[i] && _cpus[i].guest ? _cpus[i].guest : 0); - _cpus[i] = cpu; - _cpus[i].totalTick = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest + _cpus[i].idle; - _cpus[i].totalLoad = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest; - _cpus[i].currentTick = _cpus[i].totalTick - tmpTick; - _cpus[i].load = (_cpus[i].totalLoad - tmpLoad); - _cpus[i].loadUser = (_cpus[i].user - tmpUser); - _cpus[i].loadSystem = (_cpus[i].sys - tmpSystem); - _cpus[i].loadNice = (_cpus[i].nice - tmpNice); - _cpus[i].loadIdle = (_cpus[i].idle - tmpIdle); - _cpus[i].loadIrq = (_cpus[i].irq - tmpIrq); - _cpus[i].loadSteal = (_cpus[i].steal - tmpSteal); - _cpus[i].loadGuest = (_cpus[i].guest - tmpGuest); - cores[i] = {}; - cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100; - cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100; - cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100; - cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100; - cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100; - cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100; - cores[i].loadSteal = _cpus[i].loadSteal / _cpus[i].currentTick * 100; - cores[i].loadGuest = _cpus[i].loadGuest / _cpus[i].currentTick * 100; - cores[i].rawLoad = _cpus[i].load; - cores[i].rawLoadUser = _cpus[i].loadUser; - cores[i].rawLoadSystem = _cpus[i].loadSystem; - cores[i].rawLoadNice = _cpus[i].loadNice; - cores[i].rawLoadIdle = _cpus[i].loadIdle; - cores[i].rawLoadIrq = _cpus[i].loadIrq; - cores[i].rawLoadSteal = _cpus[i].loadSteal; - cores[i].rawLoadGuest = _cpus[i].loadGuest; + } else { + isGraphicsController = false; + } } - let totalTick = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest + totalIdle; - let totalLoad = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest; - let currentTick = totalTick - _current_cpu.tick; - result = { - avgLoad: avgLoad, - currentLoad: (totalLoad - _current_cpu.load) / currentTick * 100, - currentLoadUser: (totalUser - _current_cpu.user) / currentTick * 100, - currentLoadSystem: (totalSystem - _current_cpu.system) / currentTick * 100, - currentLoadNice: (totalNice - _current_cpu.nice) / currentTick * 100, - currentLoadIdle: (totalIdle - _current_cpu.idle) / currentTick * 100, - currentLoadIrq: (totalIrq - _current_cpu.irq) / currentTick * 100, - currentLoadSteal: (totalSteal - _current_cpu.steal) / currentTick * 100, - currentLoadGuest: (totalGuest - _current_cpu.guest) / currentTick * 100, - rawCurrentLoad: (totalLoad - _current_cpu.load), - rawCurrentLoadUser: (totalUser - _current_cpu.user), - rawCurrentLoadSystem: (totalSystem - _current_cpu.system), - rawCurrentLoadNice: (totalNice - _current_cpu.nice), - rawCurrentLoadIdle: (totalIdle - _current_cpu.idle), - rawCurrentLoadIrq: (totalIrq - _current_cpu.irq), - rawCurrentLoadSteal: (totalSteal - _current_cpu.steal), - rawCurrentLoadGuest: (totalGuest - _current_cpu.guest), - cpus: cores - }; - _current_cpu = { - user: totalUser, - nice: totalNice, - system: totalSystem, - idle: totalIdle, - irq: totalIrq, - steal: totalSteal, - guest: totalGuest, - tick: totalTick, - load: totalLoad, - ms: _current_cpu.ms, - currentLoad: result.currentLoad, - currentLoadUser: result.currentLoadUser, - currentLoadSystem: result.currentLoadSystem, - currentLoadNice: result.currentLoadNice, - currentLoadIdle: result.currentLoadIdle, - currentLoadIrq: result.currentLoadIrq, - currentLoadSteal: result.currentLoadSteal, - currentLoadGuest: result.currentLoadGuest, - rawCurrentLoad: result.rawCurrentLoad, - rawCurrentLoadUser: result.rawCurrentLoadUser, - rawCurrentLoadSystem: result.rawCurrentLoadSystem, - rawCurrentLoadNice: result.rawCurrentLoadNice, - rawCurrentLoadIdle: result.rawCurrentLoadIdle, - rawCurrentLoadIrq: result.rawCurrentLoadIrq, - rawCurrentLoadSteal: result.rawCurrentLoadSteal, - rawCurrentLoadGuest: result.rawCurrentLoadGuest, - }; - } else { - let cores = []; - for (let i = 0; i < _corecount; i++) { - cores[i] = {}; - cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100; - cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100; - cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100; - cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100; - cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100; - cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100; - cores[i].rawLoad = _cpus[i].load; - cores[i].rawLoadUser = _cpus[i].loadUser; - cores[i].rawLoadSystem = _cpus[i].loadSystem; - cores[i].rawLoadNice = _cpus[i].loadNice; - cores[i].rawLoadIdle = _cpus[i].loadIdle; - cores[i].rawLoadIrq = _cpus[i].loadIrq; - cores[i].rawLoadSteal = _cpus[i].loadSteal; - cores[i].rawLoadGuest = _cpus[i].loadGuest; + if (isGraphicsController) { // within VGA details + let parts = line.split(':'); + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('devicename') !== -1 && parts[1].toLowerCase().indexOf('onboard') !== -1) { currentController.bus = 'Onboard'; } + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('region') !== -1 && parts[1].toLowerCase().indexOf('memory') !== -1) { + let memparts = parts[1].split('='); + if (memparts.length > 1) { + currentController.vram = parseInt(memparts[1]); + } + } } - result = { - avgLoad: avgLoad, - currentLoad: _current_cpu.currentLoad, - currentLoadUser: _current_cpu.currentLoadUser, - currentLoadSystem: _current_cpu.currentLoadSystem, - currentLoadNice: _current_cpu.currentLoadNice, - currentLoadIdle: _current_cpu.currentLoadIdle, - currentLoadIrq: _current_cpu.currentLoadIrq, - currentLoadSteal: _current_cpu.currentLoadSteal, - currentLoadGuest: _current_cpu.currentLoadGuest, - rawCurrentLoad: _current_cpu.rawCurrentLoad, - rawCurrentLoadUser: _current_cpu.rawCurrentLoadUser, - rawCurrentLoadSystem: _current_cpu.rawCurrentLoadSystem, - rawCurrentLoadNice: _current_cpu.rawCurrentLoadNice, - rawCurrentLoadIdle: _current_cpu.rawCurrentLoadIdle, - rawCurrentLoadIrq: _current_cpu.rawCurrentLoadIrq, - rawCurrentLoadSteal: _current_cpu.rawCurrentLoadSteal, - rawCurrentLoadGuest: _current_cpu.rawCurrentLoadGuest, - cpus: cores - }; } - resolve(result); + i++; }); - }); -} -function currentLoad(callback) { + if (currentController.vendor || currentController.model || currentController.bus || currentController.busAddress || currentController.vram !== null || currentController.vramDynamic) { // already a controller found + controllers.push(currentController); + } + return (controllers); + } - return new Promise((resolve) => { - process.nextTick(() => { - getLoad().then(result => { - if (callback) { callback(result); } - resolve(result); - }); - }); - }); -} + function parseLinesLinuxClinfo(controllers, lines) { + const fieldPattern = /\[([^\]]+)\]\s+(\w+)\s+(.*)/; + const devices = lines.reduce((devices, line) => { + const field = fieldPattern.exec(line.trim()); + if (field) { + if (!devices[field[1]]) { + devices[field[1]] = {}; + } + devices[field[1]][field[2]] = field[3]; + } + return devices; + }, {}); + for (let deviceId in devices) { + const device = devices[deviceId]; + if (device['CL_DEVICE_TYPE'] === 'CL_DEVICE_TYPE_GPU') { + let busAddress; + if (device['CL_DEVICE_TOPOLOGY_AMD']) { + const bdf = device['CL_DEVICE_TOPOLOGY_AMD'].match(/[a-zA-Z0-9]+:\d+\.\d+/); + if (bdf) { + busAddress = bdf[0]; + } + } else if (device['CL_DEVICE_PCI_BUS_ID_NV'] && device['CL_DEVICE_PCI_SLOT_ID_NV']) { + const bus = parseInt(device['CL_DEVICE_PCI_BUS_ID_NV']); + const slot = parseInt(device['CL_DEVICE_PCI_SLOT_ID_NV']); + if (!isNaN(bus) && !isNaN(slot)) { + const b = bus & 0xff; + const d = (slot >> 3) & 0xff; + const f = slot & 0x07; + busAddress = `${b.toString().padStart(2, '0')}:${d.toString().padStart(2, '0')}.${f}`; + } + } + if (busAddress) { + let controller = controllers.find(controller => controller.busAddress === busAddress); + if (!controller) { + controller = { + vendor: '', + model: '', + bus: '', + busAddress, + vram: null, + vramDynamic: false + }; + controllers.push(controller); + } + controller.vendor = device['CL_DEVICE_VENDOR']; + if (device['CL_DEVICE_BOARD_NAME_AMD']) { + controller.model = device['CL_DEVICE_BOARD_NAME_AMD']; + } else { + controller.model = device['CL_DEVICE_NAME']; + } + const memory = parseInt(device['CL_DEVICE_GLOBAL_MEM_SIZE']); + if (!isNaN(memory)) { + controller.vram = Math.round(memory / 1024 / 1024); + } + } + } + } + return controllers; + } -cpu$1.currentLoad = currentLoad; + function getNvidiaSmi() { + if (_nvidiaSmiPath) { + return _nvidiaSmiPath; + } -// -------------------------- -// PS - full load -// since bootup + if (_windows$b) { + try { + const basePath = util$c.WINDIR + '\\System32\\DriverStore\\FileRepository'; + // find all directories that have an nvidia-smi.exe file + const candidateDirs = fs$4.readdirSync(basePath).filter(dir => { + return fs$4.readdirSync([basePath, dir].join('/')).includes('nvidia-smi.exe'); + }); + // use the directory with the most recently created nvidia-smi.exe file + const targetDir = candidateDirs.reduce((prevDir, currentDir) => { + const previousNvidiaSmi = fs$4.statSync([basePath, prevDir, 'nvidia-smi.exe'].join('/')); + const currentNvidiaSmi = fs$4.statSync([basePath, currentDir, 'nvidia-smi.exe'].join('/')); + return (previousNvidiaSmi.ctimeMs > currentNvidiaSmi.ctimeMs) ? prevDir : currentDir; + }); -function getFullLoad() { + if (targetDir) { + _nvidiaSmiPath = [basePath, targetDir, 'nvidia-smi.exe'].join('/'); + } + } catch (e) { + util$c.noop(); + } + } else if (_linux$a) { + _nvidiaSmiPath = 'nvidia-smi'; + } + return _nvidiaSmiPath; + } - return new Promise((resolve) => { - process.nextTick(() => { + function nvidiaSmi(options) { + const nvidiaSmiExe = getNvidiaSmi(); + options = options || util$c.execOptsWin; + if (nvidiaSmiExe) { + const nvidiaSmiOpts = '--query-gpu=driver_version,pci.sub_device_id,name,pci.bus_id,fan.speed,memory.total,memory.used,memory.free,utilization.gpu,utilization.memory,temperature.gpu,temperature.memory,power.draw,power.limit,clocks.gr,clocks.mem --format=csv,noheader,nounits'; + const cmd = nvidiaSmiExe + ' ' + nvidiaSmiOpts + (_linux$a ? ' 2>/dev/null' : ''); + try { + const res = execSync$6(cmd, options).toString(); + return res; + } catch (e) { + util$c.noop(); + } + } + return ''; + } - const cpus = os$5.cpus(); - let totalUser = 0; - let totalSystem = 0; - let totalNice = 0; - let totalIrq = 0; - let totalIdle = 0; + function nvidiaDevices() { - let result = 0; + function safeParseNumber(value) { + if ([null, undefined].includes(value)) { + return value; + } + return parseFloat(value); + } - if (cpus && cpus.length) { - for (let i = 0, len = cpus.length; i < len; i++) { - const cpu = cpus[i].times; - totalUser += cpu.user; - totalSystem += cpu.sys; - totalNice += cpu.nice; - totalIrq += cpu.irq; - totalIdle += cpu.idle; - } - let totalTicks = totalIdle + totalIrq + totalNice + totalSystem + totalUser; - result = (totalTicks - totalIdle) / totalTicks * 100.0; + const stdout = nvidiaSmi(); + if (!stdout) { + return []; + } + const gpus = stdout.split('\n').filter(Boolean); + let results = gpus.map(gpu => { + const splittedData = gpu.split(', ').map(value => value.includes('N/A') ? undefined : value); + if (splittedData.length === 16) { + return { + driverVersion: splittedData[0], + subDeviceId: splittedData[1], + name: splittedData[2], + pciBus: splittedData[3], + fanSpeed: safeParseNumber(splittedData[4]), + memoryTotal: safeParseNumber(splittedData[5]), + memoryUsed: safeParseNumber(splittedData[6]), + memoryFree: safeParseNumber(splittedData[7]), + utilizationGpu: safeParseNumber(splittedData[8]), + utilizationMemory: safeParseNumber(splittedData[9]), + temperatureGpu: safeParseNumber(splittedData[10]), + temperatureMemory: safeParseNumber(splittedData[11]), + powerDraw: safeParseNumber(splittedData[12]), + powerLimit: safeParseNumber(splittedData[13]), + clockCore: safeParseNumber(splittedData[14]), + clockMemory: safeParseNumber(splittedData[15]), + }; + } else { + return {}; } - resolve(result); }); - }); -} - -function fullLoad(callback) { - - return new Promise((resolve) => { - process.nextTick(() => { - getFullLoad().then(result => { - if (callback) { callback(result); } - resolve(result); - }); + results = results.filter((item) => { + return ('pciBus' in item); }); - }); -} - -cpu$1.fullLoad = fullLoad; - -var memory = {}; - -// @ts-check -// ================================================================================== -// memory.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 5. Memory -// ---------------------------------------------------------------------------------- - -const os$4 = require$$0$7; -const exec$c = require$$1$2.exec; -const execSync$7 = require$$1$2.execSync; -const util$e = util$j; -const fs$6 = require$$0$5; - -let _platform$d = process.platform; - -const _linux$c = (_platform$d === 'linux' || _platform$d === 'android'); -const _darwin$c = (_platform$d === 'darwin'); -const _windows$d = (_platform$d === 'win32'); -const _freebsd$b = (_platform$d === 'freebsd'); -const _openbsd$b = (_platform$d === 'openbsd'); -const _netbsd$b = (_platform$d === 'netbsd'); -const _sunos$b = (_platform$d === 'sunos'); - -const OSX_RAM_manufacturers = { - '0x014F': 'Transcend Information', - '0x2C00': 'Micron Technology Inc.', - '0x802C': 'Micron Technology Inc.', - '0x80AD': 'Hynix Semiconductor Inc.', - '0x80CE': 'Samsung Electronics Inc.', - '0xAD00': 'Hynix Semiconductor Inc.', - '0xCE00': 'Samsung Electronics Inc.', - '0x02FE': 'Elpida', - '0x5105': 'Qimonda AG i. In.', - '0x8551': 'Qimonda AG i. In.', - '0x859B': 'Crucial', - '0x04CD': 'G-Skill' -}; - -const LINUX_RAM_manufacturers = { - '017A': 'Apacer', - '0198': 'HyperX', - '029E': 'Corsair', - '04CB': 'A-DATA', - '04CD': 'G-Skill', - '059B': 'Crucial', - '00CE': 'Samsung', - '1315': 'Crutial', - '014F': 'Transcend Information', - '2C00': 'Micron Technology Inc.', - '802C': 'Micron Technology Inc.', - '80AD': 'Hynix Semiconductor Inc.', - '80CE': 'Samsung Electronics Inc.', - 'AD00': 'Hynix Semiconductor Inc.', - 'CE00': 'Samsung Electronics Inc.', - '02FE': 'Elpida', - '5105': 'Qimonda AG i. In.', - '8551': 'Qimonda AG i. In.', - '859B': 'Crucial' -}; + return results; + } -// _______________________________________________________________________________________ -// | R A M | H D | -// |______________________|_________________________| | | -// | active buffers/cache | | | -// |________________________________________________|___________|_________|______________| -// | used free | used free | -// |____________________________________________________________|________________________| -// | total | swap | -// |____________________________________________________________|________________________| + function mergeControllerNvidia(controller, nvidia) { + if (nvidia.driverVersion) { controller.driverVersion = nvidia.driverVersion; } + if (nvidia.subDeviceId) { controller.subDeviceId = nvidia.subDeviceId; } + if (nvidia.name) { controller.name = nvidia.name; } + if (nvidia.pciBus) { controller.pciBus = nvidia.pciBus; } + if (nvidia.fanSpeed) { controller.fanSpeed = nvidia.fanSpeed; } + if (nvidia.memoryTotal) { + controller.memoryTotal = nvidia.memoryTotal; + controller.vram = nvidia.memoryTotal; + controller.vramDynamic = false; + } + if (nvidia.memoryUsed) { controller.memoryUsed = nvidia.memoryUsed; } + if (nvidia.memoryFree) { controller.memoryFree = nvidia.memoryFree; } + if (nvidia.utilizationGpu) { controller.utilizationGpu = nvidia.utilizationGpu; } + if (nvidia.utilizationMemory) { controller.utilizationMemory = nvidia.utilizationMemory; } + if (nvidia.temperatureGpu) { controller.temperatureGpu = nvidia.temperatureGpu; } + if (nvidia.temperatureMemory) { controller.temperatureMemory = nvidia.temperatureMemory; } + if (nvidia.powerDraw) { controller.powerDraw = nvidia.powerDraw; } + if (nvidia.powerLimit) { controller.powerLimit = nvidia.powerLimit; } + if (nvidia.clockCore) { controller.clockCore = nvidia.clockCore; } + if (nvidia.clockMemory) { controller.clockMemory = nvidia.clockMemory; } + return controller; + } -// free (older versions) -// ---------------------------------- -// # free -// total used free shared buffers cached -// Mem: 16038 (1) 15653 (2) 384 (3) 0 (4) 236 (5) 14788 (6) -// -/+ buffers/cache: 628 (7) 15409 (8) -// Swap: 16371 83 16288 -// -// |------------------------------------------------------------| -// | R A M | -// |______________________|_____________________________________| -// | active (2-(5+6) = 7) | available (3+5+6 = 8) | -// |______________________|_________________________|___________| -// | active | buffers/cache (5+6) | | -// |________________________________________________|___________| -// | used (2) | free (3) | -// |____________________________________________________________| -// | total (1) | -// |____________________________________________________________| + function parseLinesLinuxEdid(edid) { + // parsen EDID + // --> model + // --> resolutionx + // --> resolutiony + // --> builtin = false + // --> pixeldepth (?) + // --> sizex + // --> sizey + let result = { + vendor: '', + model: '', + deviceName: '', + main: false, + builtin: false, + connection: '', + sizeX: null, + sizeY: null, + pixelDepth: null, + resolutionX: null, + resolutionY: null, + currentResX: null, + currentResY: null, + positionX: 0, + positionY: 0, + currentRefreshRate: null + }; + // find first "Detailed Timing Description" + let start = 108; + if (edid.substr(start, 6) === '000000') { + start += 36; + } + if (edid.substr(start, 6) === '000000') { + start += 36; + } + if (edid.substr(start, 6) === '000000') { + start += 36; + } + if (edid.substr(start, 6) === '000000') { + start += 36; + } + result.resolutionX = parseInt('0x0' + edid.substr(start + 8, 1) + edid.substr(start + 4, 2)); + result.resolutionY = parseInt('0x0' + edid.substr(start + 14, 1) + edid.substr(start + 10, 2)); + result.sizeX = parseInt('0x0' + edid.substr(start + 28, 1) + edid.substr(start + 24, 2)); + result.sizeY = parseInt('0x0' + edid.substr(start + 29, 1) + edid.substr(start + 26, 2)); + // monitor name + start = edid.indexOf('000000fc00'); // find first "Monitor Description Data" + if (start >= 0) { + let model_raw = edid.substr(start + 10, 26); + if (model_raw.indexOf('0a') !== -1) { + model_raw = model_raw.substr(0, model_raw.indexOf('0a')); + } + try { + if (model_raw.length > 2) { + result.model = model_raw.match(/.{1,2}/g).map(function (v) { + return String.fromCharCode(parseInt(v, 16)); + }).join(''); + } + } catch (e) { + util$c.noop(); + } + } else { + result.model = ''; + } + return result; + } -// -// free (since free von procps-ng 3.3.10) -// ---------------------------------- -// # free -// total used free shared buffers/cache available -// Mem: 16038 (1) 628 (2) 386 (3) 0 (4) 15024 (5) 14788 (6) -// Swap: 16371 83 16288 -// -// |------------------------------------------------------------| -// | R A M | -// |______________________|_____________________________________| -// | | available (6) estimated | -// |______________________|_________________________|___________| -// | active (2) | buffers/cache (5) | free (3) | -// |________________________________________________|___________| -// | total (1) | -// |____________________________________________________________| -// -// Reference: http://www.software-architect.net/blog/article/date/2015/06/12/-826c6e5052.html + function parseLinesLinuxDisplays(lines, depth) { + let displays = []; + let currentDisplay = { + vendor: '', + model: '', + deviceName: '', + main: false, + builtin: false, + connection: '', + sizeX: null, + sizeY: null, + pixelDepth: null, + resolutionX: null, + resolutionY: null, + currentResX: null, + currentResY: null, + positionX: 0, + positionY: 0, + currentRefreshRate: null + }; + let is_edid = false; + let is_current = false; + let edid_raw = ''; + let start = 0; + for (let i = 1; i < lines.length; i++) { // start with second line + if ('' !== lines[i].trim()) { + if (' ' !== lines[i][0] && '\t' !== lines[i][0] && lines[i].toLowerCase().indexOf(' connected ') !== -1) { // first line of new entry + if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // push last display to array + displays.push(currentDisplay); + currentDisplay = { + vendor: '', + model: '', + main: false, + builtin: false, + connection: '', + sizeX: null, + sizeY: null, + pixelDepth: null, + resolutionX: null, + resolutionY: null, + currentResX: null, + currentResY: null, + positionX: 0, + positionY: 0, + currentRefreshRate: null + }; + } + let parts = lines[i].split(' '); + currentDisplay.connection = parts[0]; + currentDisplay.main = lines[i].toLowerCase().indexOf(' primary ') >= 0; + currentDisplay.builtin = (parts[0].toLowerCase().indexOf('edp') >= 0); + } -// /procs/meminfo - sample (all in kB) -// -// MemTotal: 32806380 kB -// MemFree: 17977744 kB -// MemAvailable: 19768972 kB -// Buffers: 517028 kB -// Cached: 2161876 kB -// SwapCached: 456 kB -// Active: 12081176 kB -// Inactive: 2164616 kB -// Active(anon): 10832884 kB -// Inactive(anon): 1477272 kB -// Active(file): 1248292 kB -// Inactive(file): 687344 kB -// Unevictable: 0 kB -// Mlocked: 0 kB -// SwapTotal: 16768892 kB -// SwapFree: 16768304 kB -// Dirty: 268 kB -// Writeback: 0 kB -// AnonPages: 11568832 kB -// Mapped: 719992 kB -// Shmem: 743272 kB -// Slab: 335716 kB -// SReclaimable: 256364 kB -// SUnreclaim: 79352 kB + // try to read EDID information + if (is_edid) { + if (lines[i].search(/\S|$/) > start) { + edid_raw += lines[i].toLowerCase().trim(); + } else { + // parsen EDID + let edid_decoded = parseLinesLinuxEdid(edid_raw); + currentDisplay.vendor = edid_decoded.vendor; + currentDisplay.model = edid_decoded.model; + currentDisplay.resolutionX = edid_decoded.resolutionX; + currentDisplay.resolutionY = edid_decoded.resolutionY; + currentDisplay.sizeX = edid_decoded.sizeX; + currentDisplay.sizeY = edid_decoded.sizeY; + currentDisplay.pixelDepth = depth; + is_edid = false; + } + } + if (lines[i].toLowerCase().indexOf('edid:') >= 0) { + is_edid = true; + start = lines[i].search(/\S|$/); + } + if (lines[i].toLowerCase().indexOf('*current') >= 0) { + const parts1 = lines[i].split('('); + if (parts1 && parts1.length > 1 && parts1[0].indexOf('x') >= 0) { + const resParts = parts1[0].trim().split('x'); + currentDisplay.currentResX = util$c.toInt(resParts[0]); + currentDisplay.currentResY = util$c.toInt(resParts[1]); + } + is_current = true; + } + if (is_current && lines[i].toLowerCase().indexOf('clock') >= 0 && lines[i].toLowerCase().indexOf('hz') >= 0 && lines[i].toLowerCase().indexOf('v: height') >= 0) { + const parts1 = lines[i].split('clock'); + if (parts1 && parts1.length > 1 && parts1[1].toLowerCase().indexOf('hz') >= 0) { + currentDisplay.currentRefreshRate = util$c.toInt(parts1[1]); + } + is_current = false; + } + } + } -function mem(callback) { + // pushen displays + if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // still information there + displays.push(currentDisplay); + } + return displays; + } + // function starts here return new Promise((resolve) => { process.nextTick(() => { - let result = { - total: os$4.totalmem(), - free: os$4.freemem(), - used: os$4.totalmem() - os$4.freemem(), - - active: os$4.totalmem() - os$4.freemem(), // temporarily (fallback) - available: os$4.freemem(), // temporarily (fallback) - buffers: 0, - cached: 0, - slab: 0, - buffcache: 0, - - swaptotal: 0, - swapused: 0, - swapfree: 0, - writeback: null, - dirty: null + controllers: [], + displays: [] }; - - if (_linux$c) { - try { - fs$6.readFile('/proc/meminfo', function (error, stdout) { - if (!error) { - const lines = stdout.toString().split('\n'); - result.total = parseInt(util$e.getValue(lines, 'memtotal'), 10); - result.total = result.total ? result.total * 1024 : os$4.totalmem(); - result.free = parseInt(util$e.getValue(lines, 'memfree'), 10); - result.free = result.free ? result.free * 1024 : os$4.freemem(); - result.used = result.total - result.free; - - result.buffers = parseInt(util$e.getValue(lines, 'buffers'), 10); - result.buffers = result.buffers ? result.buffers * 1024 : 0; - result.cached = parseInt(util$e.getValue(lines, 'cached'), 10); - result.cached = result.cached ? result.cached * 1024 : 0; - result.slab = parseInt(util$e.getValue(lines, 'slab'), 10); - result.slab = result.slab ? result.slab * 1024 : 0; - result.buffcache = result.buffers + result.cached + result.slab; - - let available = parseInt(util$e.getValue(lines, 'memavailable'), 10); - result.available = available ? available * 1024 : result.free + result.buffcache; - result.active = result.total - result.available; - - result.swaptotal = parseInt(util$e.getValue(lines, 'swaptotal'), 10); - result.swaptotal = result.swaptotal ? result.swaptotal * 1024 : 0; - result.swapfree = parseInt(util$e.getValue(lines, 'swapfree'), 10); - result.swapfree = result.swapfree ? result.swapfree * 1024 : 0; - result.swapused = result.swaptotal - result.swapfree; - result.writeback = parseInt(util$e.getValue(lines, 'writeback'), 10); - result.writeback = result.writeback ? result.writeback * 1024 : 0; - result.dirty = parseInt(util$e.getValue(lines, 'dirty'), 10); - result.dirty = result.dirty ? result.dirty * 1024 : 0; + if (_darwin$a) { + let cmd = 'system_profiler -xml -detailLevel full SPDisplaysDataType'; + exec$a(cmd, function (error, stdout) { + if (!error) { + try { + const output = stdout.toString(); + result = parseLinesDarwin(util$c.plistParser(output)[0]._items); + } catch (e) { + util$c.noop(); } - if (callback) { callback(result); } - resolve(result); - }); - } catch (e) { - if (callback) { callback(result); } + try { + stdout = execSync$6('defaults read /Library/Preferences/com.apple.windowserver.plist 2>/dev/null;defaults read /Library/Preferences/com.apple.windowserver.displays.plist 2>/dev/null; echo ""', { maxBuffer: 1024 * 20000 }); + const output = (stdout || '').toString(); + const obj = util$c.plistReader(output); + if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets']['Configs'] && obj['DisplayAnyUserSets']['Configs'][0] && obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig']) { + const current = obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig']; + let i = 0; + current.forEach((o) => { + if (o['CurrentInfo'] && o['CurrentInfo']['OriginX'] !== undefined && result.displays && result.displays[i]) { + result.displays[i].positionX = o['CurrentInfo']['OriginX']; + } + if (o['CurrentInfo'] && o['CurrentInfo']['OriginY'] !== undefined && result.displays && result.displays[i]) { + result.displays[i].positionY = o['CurrentInfo']['OriginY']; + } + i++; + }); + } + if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets'].length > 0 && obj['DisplayAnyUserSets'][0].length > 0 && obj['DisplayAnyUserSets'][0][0]['DisplayID']) { + const current = obj['DisplayAnyUserSets'][0]; + let i = 0; + current.forEach((o) => { + if ('OriginX' in o && result.displays && result.displays[i]) { + result.displays[i].positionX = o['OriginX']; + } + if ('OriginY' in o && result.displays && result.displays[i]) { + result.displays[i].positionY = o['OriginY']; + } + if (o['Mode'] && o['Mode']['BitsPerPixel'] !== undefined && result.displays && result.displays[i]) { + result.displays[i].pixelDepth = o['Mode']['BitsPerPixel']; + } + i++; + }); + } + } catch (e) { + util$c.noop(); + } + } + if (callback) { + callback(result); + } resolve(result); - } + }); } - if (_freebsd$b || _openbsd$b || _netbsd$b) { - try { - exec$c('/sbin/sysctl hw.realmem hw.physmem vm.stats.vm.v_page_count vm.stats.vm.v_wire_count vm.stats.vm.v_active_count vm.stats.vm.v_inactive_count vm.stats.vm.v_cache_count vm.stats.vm.v_free_count vm.stats.vm.v_page_size', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - const pagesize = parseInt(util$e.getValue(lines, 'vm.stats.vm.v_page_size'), 10); - const inactive = parseInt(util$e.getValue(lines, 'vm.stats.vm.v_inactive_count'), 10) * pagesize; - const cache = parseInt(util$e.getValue(lines, 'vm.stats.vm.v_cache_count'), 10) * pagesize; - - result.total = parseInt(util$e.getValue(lines, 'hw.realmem'), 10); - if (isNaN(result.total)) { result.total = parseInt(util$e.getValue(lines, 'hw.physmem'), 10); } - result.free = parseInt(util$e.getValue(lines, 'vm.stats.vm.v_free_count'), 10) * pagesize; - result.buffcache = inactive + cache; - result.available = result.buffcache + result.free; - result.active = result.total - result.free - result.buffcache; - - result.swaptotal = 0; - result.swapfree = 0; - result.swapused = 0; - + if (_linux$a) { + // Raspberry: https://elinux.org/RPI_vcgencmd_usage + if (util$c.isRaspberry() && util$c.isRaspbian()) { + let cmd = 'fbset -s | grep \'mode "\'; vcgencmd get_mem gpu; tvservice -s; tvservice -n;'; + exec$a(cmd, function (error, stdout) { + let lines = stdout.toString().split('\n'); + if (lines.length > 3 && lines[0].indexOf('mode "') >= -1 && lines[2].indexOf('0x12000a') > -1) { + const parts = lines[0].replace('mode', '').replace(/"/g, '').trim().split('x'); + if (parts.length === 2) { + result.displays.push({ + vendor: '', + model: util$c.getValue(lines, 'device_name', '='), + main: true, + builtin: false, + connection: 'HDMI', + sizeX: null, + sizeY: null, + pixelDepth: null, + resolutionX: parseInt(parts[0], 10), + resolutionY: parseInt(parts[1], 10), + currentResX: null, + currentResY: null, + positionX: 0, + positionY: 0, + currentRefreshRate: null + }); + } + } + if (lines.length > 1 && stdout.toString().indexOf('gpu=') >= -1) { + result.controllers.push({ + vendor: 'Broadcom', + model: util$c.getRpiGpu(), + bus: '', + vram: util$c.getValue(lines, 'gpu', '=').replace('M', ''), + vramDynamic: true + }); + } + if (callback) { + callback(result); } - if (callback) { callback(result); } resolve(result); }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } - } - if (_sunos$b) { - if (callback) { callback(result); } - resolve(result); - } - if (_darwin$c) { - let pageSize = 4096; - try { - let sysPpageSize = util$e.toInt(execSync$7('sysctl -n vm.pagesize').toString()); - pageSize = sysPpageSize || pageSize; - } catch (e) { - util$e.noop(); - } - try { - exec$c('vm_stat 2>/dev/null | grep "Pages active"', function (error, stdout) { + } else { + let cmd = 'lspci -vvv 2>/dev/null'; + exec$a(cmd, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); - - result.active = parseInt(lines[0].split(':')[1], 10) * pageSize; - result.buffcache = result.used - result.active; - result.available = result.free + result.buffcache; + result.controllers = parseLinesLinuxControllers(lines); + const nvidiaData = nvidiaDevices(); + // needs to be rewritten ... using no spread operators + result.controllers = result.controllers.map((controller) => { // match by busAddress + return mergeControllerNvidia(controller, nvidiaData.find((contr) => contr.pciBus.toLowerCase().endsWith(controller.busAddress.toLowerCase())) || {}); + }); } - exec$c('sysctl -n vm.swapusage 2>/dev/null', function (error, stdout) { + let cmd = 'clinfo --raw'; + exec$a(cmd, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); - if (lines.length > 0) { - let firstline = lines[0].replace(/,/g, '.').replace(/M/g, ''); - let lineArray = firstline.trim().split(' '); - lineArray.forEach(line => { - if (line.toLowerCase().indexOf('total') !== -1) { result.swaptotal = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; } - if (line.toLowerCase().indexOf('used') !== -1) { result.swapused = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; } - if (line.toLowerCase().indexOf('free') !== -1) { result.swapfree = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; } - }); - } + result.controllers = parseLinesLinuxClinfo(result.controllers, lines); } - if (callback) { callback(result); } - resolve(result); - }); - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } - } - if (_windows$d) { - let swaptotal = 0; - let swapused = 0; - try { - util$e.powerShell('Get-CimInstance Win32_PageFileUsage | Select AllocatedBaseSize, CurrentUsage').then((stdout, error) => { - if (!error) { - let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); - lines.forEach(function (line) { - if (line !== '') { - line = line.trim().split(/\s\s+/); - swaptotal = swaptotal + (parseInt(line[0], 10) || 0); - swapused = swapused + (parseInt(line[1], 10) || 0); + let cmd = 'xdpyinfo 2>/dev/null | grep \'depth of root window\' | awk \'{ print $5 }\''; + exec$a(cmd, function (error, stdout) { + let depth = 0; + if (!error) { + let lines = stdout.toString().split('\n'); + depth = parseInt(lines[0]) || 0; } + let cmd = 'xrandr --verbose 2>/dev/null'; + exec$a(cmd, function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + result.displays = parseLinesLinuxDisplays(lines, depth); + } + if (callback) { + callback(result); + } + resolve(result); + }); }); - } - result.swaptotal = swaptotal * 1024 * 1024; - result.swapused = swapused * 1024 * 1024; - result.swapfree = result.swaptotal - result.swapused; - - if (callback) { callback(result); } - resolve(result); + }); }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); } } - }); - }); -} - -memory.mem = mem; - -function memLayout(callback) { - - function getManufacturerDarwin(manId) { - if ({}.hasOwnProperty.call(OSX_RAM_manufacturers, manId)) { - return (OSX_RAM_manufacturers[manId]); - } - return manId; - } - - function getManufacturerLinux(manId) { - const manIdSearch = manId.replace('0x', '').toUpperCase(); - if (manIdSearch.length === 4 && {}.hasOwnProperty.call(LINUX_RAM_manufacturers, manIdSearch)) { - return (LINUX_RAM_manufacturers[manIdSearch]); - } - return manId; - } + if (_freebsd$9 || _openbsd$9 || _netbsd$9) { + if (callback) { callback(null); } + resolve(null); + } + if (_sunos$9) { + if (callback) { callback(null); } + resolve(null); + } + if (_windows$b) { - return new Promise((resolve) => { - process.nextTick(() => { + // https://blogs.technet.microsoft.com/heyscriptingguy/2013/10/03/use-powershell-to-discover-multi-monitor-information/ + // https://devblogs.microsoft.com/scripting/use-powershell-to-discover-multi-monitor-information/ + try { + const workload = []; + workload.push(util$c.powerShell('Get-CimInstance win32_VideoController | fl *')); + workload.push(util$c.powerShell('gp "HKLM:\\SYSTEM\\ControlSet001\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}\\*" -ErrorAction SilentlyContinue | where MatchingDeviceId $null -NE | select MatchingDeviceId,HardwareInformation.qwMemorySize | fl')); + workload.push(util$c.powerShell('Get-CimInstance win32_desktopmonitor | fl *')); + workload.push(util$c.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorBasicDisplayParams | fl')); + workload.push(util$c.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Screen]::AllScreens')); + workload.push(util$c.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorConnectionParams | fl')); + workload.push(util$c.powerShell('gwmi WmiMonitorID -Namespace root\\wmi | ForEach-Object {(($_.ManufacturerName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.ProductCodeID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.UserFriendlyName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.SerialNumberID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + $_.InstanceName}')); - let result = []; + const nvidiaData = nvidiaDevices(); - if (_linux$c || _freebsd$b || _openbsd$b || _netbsd$b) { - exec$c('export LC_ALL=C; dmidecode -t memory 2>/dev/null | grep -iE "Size:|Type|Speed|Manufacturer|Form Factor|Locator|Memory Device|Serial Number|Voltage|Part Number"; unset LC_ALL', function (error, stdout) { - if (!error) { - let devices = stdout.toString().split('Memory Device'); - devices.shift(); - devices.forEach(function (device) { - let lines = device.split('\n'); - const sizeString = util$e.getValue(lines, 'Size'); - const size = sizeString.indexOf('GB') >= 0 ? parseInt(sizeString, 10) * 1024 * 1024 * 1024 : parseInt(sizeString, 10) * 1024 * 1024; - let bank = util$e.getValue(lines, 'Bank Locator'); - if (bank.toLowerCase().indexOf('bad') >= 0) { - bank = ''; - } - if (parseInt(util$e.getValue(lines, 'Size'), 10) > 0) { - const totalWidth = util$e.toInt(util$e.getValue(lines, 'Total Width')); - const dataWidth = util$e.toInt(util$e.getValue(lines, 'Data Width')); - result.push({ - size, - bank, - type: util$e.getValue(lines, 'Type:'), - ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false, - clockSpeed: (util$e.getValue(lines, 'Configured Clock Speed:') ? parseInt(util$e.getValue(lines, 'Configured Clock Speed:'), 10) : (util$e.getValue(lines, 'Speed:') ? parseInt(util$e.getValue(lines, 'Speed:'), 10) : null)), - formFactor: util$e.getValue(lines, 'Form Factor:'), - manufacturer: getManufacturerLinux(util$e.getValue(lines, 'Manufacturer:')), - partNum: util$e.getValue(lines, 'Part Number:'), - serialNum: util$e.getValue(lines, 'Serial Number:'), - voltageConfigured: parseFloat(util$e.getValue(lines, 'Configured Voltage:')) || null, - voltageMin: parseFloat(util$e.getValue(lines, 'Minimum Voltage:')) || null, - voltageMax: parseFloat(util$e.getValue(lines, 'Maximum Voltage:')) || null, - }); + Promise.all( + workload + ).then((data) => { + // controller + vram + let csections = data[0].replace(/\r/g, '').split(/\n\s*\n/); + let vsections = data[1].replace(/\r/g, '').split(/\n\s*\n/); + result.controllers = parseLinesWindowsControllers(csections, vsections); + result.controllers = result.controllers.map((controller) => { // match by subDeviceId + if (controller.vendor.toLowerCase() === 'nvidia') { + return mergeControllerNvidia(controller, nvidiaData.find(device => { + let windowsSubDeviceId = (controller.subDeviceId || '').toLowerCase(); + const nvidiaSubDeviceIdParts = device.subDeviceId.split('x'); + let nvidiaSubDeviceId = nvidiaSubDeviceIdParts.length > 1 ? nvidiaSubDeviceIdParts[1].toLowerCase() : nvidiaSubDeviceIdParts[0].toLowerCase(); + const lengthDifference = Math.abs(windowsSubDeviceId.length - nvidiaSubDeviceId.length); + if (windowsSubDeviceId.length > nvidiaSubDeviceId.length) { + for (let i = 0; i < lengthDifference; i++) { + nvidiaSubDeviceId = '0' + nvidiaSubDeviceId; + } + } else if (windowsSubDeviceId.length < nvidiaSubDeviceId.length) { + for (let i = 0; i < lengthDifference; i++) { + windowsSubDeviceId = '0' + windowsSubDeviceId; + } + } + return windowsSubDeviceId === nvidiaSubDeviceId; + }) || {}); } else { - result.push({ - size: 0, - bank, - type: 'Empty', - ecc: null, - clockSpeed: 0, - formFactor: util$e.getValue(lines, 'Form Factor:'), - partNum: '', - serialNum: '', - voltageConfigured: null, - voltageMin: null, - voltageMax: null, - }); + return controller; } }); - } - if (!result.length) { - result.push({ - size: os$4.totalmem(), - bank: '', - type: '', - ecc: null, - clockSpeed: 0, - formFactor: '', - partNum: '', - serialNum: '', - voltageConfigured: null, - voltageMin: null, - voltageMax: null, - }); - // Try Raspberry PI - try { - let stdout = execSync$7('cat /proc/cpuinfo 2>/dev/null'); - let lines = stdout.toString().split('\n'); - let model = util$e.getValue(lines, 'hardware', ':', true).toUpperCase(); - let version = util$e.getValue(lines, 'revision', ':', true).toLowerCase(); - - if (model === 'BCM2835' || model === 'BCM2708' || model === 'BCM2709' || model === 'BCM2835' || model === 'BCM2837') { - - const clockSpeed = { - '0': 400, - '1': 450, - '2': 450, - '3': 3200 - }; - result[0].type = 'LPDDR2'; - result[0].type = version && version[2] && version[2] === '3' ? 'LPDDR4' : result[0].type; - result[0].ecc = false; - result[0].clockSpeed = version && version[2] && clockSpeed[version[2]] || 400; - result[0].clockSpeed = version && version[4] && version[4] === 'd' ? 500 : result[0].clockSpeed; - result[0].formFactor = 'SoC'; + // displays + let dsections = data[2].replace(/\r/g, '').split(/\n\s*\n/); + // result.displays = parseLinesWindowsDisplays(dsections); + if (dsections[0].trim() === '') { dsections.shift(); } + if (dsections.length && dsections[dsections.length - 1].trim() === '') { dsections.pop(); } - stdout = execSync$7('vcgencmd get_config sdram_freq 2>/dev/null'); - lines = stdout.toString().split('\n'); - let freq = parseInt(util$e.getValue(lines, 'sdram_freq', '=', true), 10) || 0; - if (freq) { - result[0].clockSpeed = freq; - } + // monitor (powershell) + let msections = data[3].replace(/\r/g, '').split('Active '); + msections.shift(); - stdout = execSync$7('vcgencmd measure_volts sdram_p 2>/dev/null'); - lines = stdout.toString().split('\n'); - let voltage = parseFloat(util$e.getValue(lines, 'volt', '=', true)) || 0; - if (voltage) { - result[0].voltageConfigured = voltage; - result[0].voltageMin = voltage; - result[0].voltageMax = voltage; - } - } - } catch (e) { - util$e.noop(); - } + // forms.screens (powershell) + let ssections = data[4].replace(/\r/g, '').split('BitsPerPixel '); + ssections.shift(); - } - if (callback) { callback(result); } - resolve(result); - }); - } + // connection params (powershell) - video type + let tsections = data[5].replace(/\r/g, '').split(/\n\s*\n/); + tsections.shift(); - if (_darwin$c) { - exec$c('system_profiler SPMemoryDataType', function (error, stdout) { - if (!error) { - const allLines = stdout.toString().split('\n'); - const eccStatus = util$e.getValue(allLines, 'ecc', ':', true).toLowerCase(); - let devices = stdout.toString().split(' BANK '); - let hasBank = true; - if (devices.length === 1) { - devices = stdout.toString().split(' DIMM'); - hasBank = false; - } - devices.shift(); - devices.forEach(function (device) { - let lines = device.split('\n'); - const bank = (hasBank ? 'BANK ' : 'DIMM') + lines[0].trim().split('/')[0]; - const size = parseInt(util$e.getValue(lines, ' Size')); - if (size) { - result.push({ - size: size * 1024 * 1024 * 1024, - bank: bank, - type: util$e.getValue(lines, ' Type:'), - ecc: eccStatus ? eccStatus === 'enabled' : null, - clockSpeed: parseInt(util$e.getValue(lines, ' Speed:'), 10), - formFactor: '', - manufacturer: getManufacturerDarwin(util$e.getValue(lines, ' Manufacturer:')), - partNum: util$e.getValue(lines, ' Part Number:'), - serialNum: util$e.getValue(lines, ' Serial Number:'), - voltageConfigured: null, - voltageMin: null, - voltageMax: null, - }); - } else { - result.push({ - size: 0, - bank: bank, - type: 'Empty', - ecc: null, - clockSpeed: 0, - formFactor: '', - manufacturer: '', - partNum: '', - serialNum: '', - voltageConfigured: null, - voltageMin: null, - voltageMax: null, + // monitor ID (powershell) - model / vendor + const res = data[6].replace(/\r/g, '').split(/\n/); + let isections = []; + res.forEach(element => { + const parts = element.split('|'); + if (parts.length === 5) { + isections.push({ + vendor: parts[0], + code: parts[1], + model: parts[2], + serial: parts[3], + instanceId: parts[4] }); } }); - } - if (!result.length) { - const lines = stdout.toString().split('\n'); - const size = parseInt(util$e.getValue(lines, ' Memory:')); - const type = util$e.getValue(lines, ' Type:'); - if (size && type) { - result.push({ - size: size * 1024 * 1024 * 1024, - bank: '0', - type, - ecc: false, - clockSpeed: 0, - formFactor: '', - manufacturer: 'Apple', - partNum: '', - serialNum: '', - voltageConfigured: null, - voltageMin: null, - voltageMax: null, - }); - } - } - if (callback) { callback(result); } - resolve(result); - }); - } - if (_sunos$b) { - if (callback) { callback(result); } - resolve(result); - } - if (_windows$d) { - // https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0a.pdf - const memoryTypes = 'Unknown|Other|DRAM|Synchronous DRAM|Cache DRAM|EDO|EDRAM|VRAM|SRAM|RAM|ROM|FLASH|EEPROM|FEPROM|EPROM|CDRAM|3DRAM|SDRAM|SGRAM|RDRAM|DDR|DDR2|DDR2 FB-DIMM|Reserved|DDR3|FBD2|DDR4|LPDDR|LPDDR2|LPDDR3|LPDDR4|Logical non-volatile device|HBM|HBM2|DDR5|LPDDR5'.split('|'); - const FormFactors = 'Unknown|Other|SIP|DIP|ZIP|SOJ|Proprietary|SIMM|DIMM|TSOP|PGA|RIMM|SODIMM|SRIMM|SMD|SSMP|QFP|TQFP|SOIC|LCC|PLCC|BGA|FPBGA|LGA'.split('|'); + result.displays = parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections); - try { - util$e.powerShell('Get-CimInstance Win32_PhysicalMemory | select DataWidth,TotalWidth,Capacity,BankLabel,MemoryType,SMBIOSMemoryType,ConfiguredClockSpeed,FormFactor,Manufacturer,PartNumber,SerialNumber,ConfiguredVoltage,MinVoltage,MaxVoltage | fl').then((stdout, error) => { - if (!error) { - let devices = stdout.toString().split(/\n\s*\n/); - devices.shift(); - devices.forEach(function (device) { - let lines = device.split('\r\n'); - const dataWidth = util$e.toInt(util$e.getValue(lines, 'DataWidth', ':')); - const totalWidth = util$e.toInt(util$e.getValue(lines, 'TotalWidth', ':')); - const size = parseInt(util$e.getValue(lines, 'Capacity', ':'), 10) || 0; - if (size) { - result.push({ - size, - bank: util$e.getValue(lines, 'BankLabel', ':'), // BankLabel - type: memoryTypes[parseInt(util$e.getValue(lines, 'MemoryType', ':'), 10) || parseInt(util$e.getValue(lines, 'SMBIOSMemoryType', ':'), 10)], - ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false, - clockSpeed: parseInt(util$e.getValue(lines, 'ConfiguredClockSpeed', ':'), 10) || parseInt(util$e.getValue(lines, 'Speed', ':'), 10) || 0, - formFactor: FormFactors[parseInt(util$e.getValue(lines, 'FormFactor', ':'), 10) || 0], - manufacturer: util$e.getValue(lines, 'Manufacturer', ':'), - partNum: util$e.getValue(lines, 'PartNumber', ':'), - serialNum: util$e.getValue(lines, 'SerialNumber', ':'), - voltageConfigured: (parseInt(util$e.getValue(lines, 'ConfiguredVoltage', ':'), 10) || 0) / 1000.0, - voltageMin: (parseInt(util$e.getValue(lines, 'MinVoltage', ':'), 10) || 0) / 1000.0, - voltageMax: (parseInt(util$e.getValue(lines, 'MaxVoltage', ':'), 10) || 0) / 1000.0, - }); + if (result.displays.length === 1) { + if (_resolutionX) { + result.displays[0].resolutionX = _resolutionX; + if (!result.displays[0].currentResX) { + result.displays[0].currentResX = _resolutionX; } - }); + } + if (_resolutionY) { + result.displays[0].resolutionY = _resolutionY; + if (result.displays[0].currentResY === 0) { + result.displays[0].currentResY = _resolutionY; + } + } + if (_pixelDepth) { + result.displays[0].pixelDepth = _pixelDepth; + } + } + result.displays = result.displays.map(element => { + if (_refreshRate && !element.currentRefreshRate) { + element.currentRefreshRate = _refreshRate; + } + return element; + }); + + if (callback) { + callback(result); } - if (callback) { callback(result); } resolve(result); - }); + }) + .catch(() => { + if (callback) { + callback(result); + } + resolve(result); + }); } catch (e) { if (callback) { callback(result); } resolve(result); @@ -62196,13 +58154,189 @@ function memLayout(callback) { } }); }); + + function parseLinesWindowsControllers(sections, vections) { + const memorySizes = {}; + for (const i in vections) { + if ({}.hasOwnProperty.call(vections, i)) { + if (vections[i].trim() !== '') { + const lines = vections[i].trim().split('\n'); + const matchingDeviceId = util$c.getValue(lines, 'MatchingDeviceId').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i); + if (matchingDeviceId) { + const quadWordmemorySize = parseInt(util$c.getValue(lines, 'HardwareInformation.qwMemorySize')); + if (!isNaN(quadWordmemorySize)) { + let deviceId = matchingDeviceId[1].toUpperCase() + '&' + matchingDeviceId[2].toUpperCase(); + if (matchingDeviceId[3]) { + deviceId += '&' + matchingDeviceId[3].toUpperCase(); + } + if (matchingDeviceId[4]) { + deviceId += '&' + matchingDeviceId[4].toUpperCase(); + } + memorySizes[deviceId] = quadWordmemorySize; + } + } + } + } + } + + let controllers = []; + for (let i in sections) { + if ({}.hasOwnProperty.call(sections, i)) { + if (sections[i].trim() !== '') { + let lines = sections[i].trim().split('\n'); + let pnpDeviceId = util$c.getValue(lines, 'PNPDeviceID', ':').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i); + let subDeviceId = null; + let memorySize = null; + if (pnpDeviceId) { + subDeviceId = pnpDeviceId[3] || ''; + if (subDeviceId) { + subDeviceId = subDeviceId.split('_')[1]; + } + + // Match PCI device identifier (there's an order of increasing generality): + // https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices + + // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)&REV_r(2) + if (memorySize == null && pnpDeviceId[3] && pnpDeviceId[4]) { + const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase(); + if ({}.hasOwnProperty.call(memorySizes, deviceId)) { + memorySize = memorySizes[deviceId]; + } + } + + // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4) + if (memorySize == null && pnpDeviceId[3]) { + const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase(); + if ({}.hasOwnProperty.call(memorySizes, deviceId)) { + memorySize = memorySizes[deviceId]; + } + } + + // PCI\VEN_v(4)&DEV_d(4)&REV_r(2) + if (memorySize == null && pnpDeviceId[4]) { + const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase(); + if ({}.hasOwnProperty.call(memorySizes, deviceId)) { + memorySize = memorySizes[deviceId]; + } + } + + // PCI\VEN_v(4)&DEV_d(4) + if (memorySize == null) { + const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase(); + if ({}.hasOwnProperty.call(memorySizes, deviceId)) { + memorySize = memorySizes[deviceId]; + } + } + } + + controllers.push({ + vendor: util$c.getValue(lines, 'AdapterCompatibility', ':'), + model: util$c.getValue(lines, 'name', ':'), + bus: util$c.getValue(lines, 'PNPDeviceID', ':').startsWith('PCI') ? 'PCI' : '', + vram: (memorySize == null ? util$c.toInt(util$c.getValue(lines, 'AdapterRAM', ':')) : memorySize) / 1024 / 1024, + vramDynamic: (util$c.getValue(lines, 'VideoMemoryType', ':') === '2'), + subDeviceId + }); + _resolutionX = util$c.toInt(util$c.getValue(lines, 'CurrentHorizontalResolution', ':')) || _resolutionX; + _resolutionY = util$c.toInt(util$c.getValue(lines, 'CurrentVerticalResolution', ':')) || _resolutionY; + _refreshRate = util$c.toInt(util$c.getValue(lines, 'CurrentRefreshRate', ':')) || _refreshRate; + _pixelDepth = util$c.toInt(util$c.getValue(lines, 'CurrentBitsPerPixel', ':')) || _pixelDepth; + } + } + } + return controllers; + } + + function parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections) { + let displays = []; + let vendor = ''; + let model = ''; + let deviceID = ''; + let resolutionX = 0; + let resolutionY = 0; + if (dsections && dsections.length) { + let linesDisplay = dsections[0].split('\n'); + vendor = util$c.getValue(linesDisplay, 'MonitorManufacturer', ':'); + model = util$c.getValue(linesDisplay, 'Name', ':'); + deviceID = util$c.getValue(linesDisplay, 'PNPDeviceID', ':').replace(/&/g, '&').toLowerCase(); + resolutionX = util$c.toInt(util$c.getValue(linesDisplay, 'ScreenWidth', ':')); + resolutionY = util$c.toInt(util$c.getValue(linesDisplay, 'ScreenHeight', ':')); + } + for (let i = 0; i < ssections.length; i++) { + if (ssections[i].trim() !== '') { + ssections[i] = 'BitsPerPixel ' + ssections[i]; + msections[i] = 'Active ' + msections[i]; + // tsections can be empty OR undefined on earlier versions of powershell (<=2.0) + // Tag connection type as UNKNOWN by default if this information is missing + if (tsections.length === 0 || tsections[i] === undefined) { + tsections[i] = 'Unknown'; + } + let linesScreen = ssections[i].split('\n'); + let linesMonitor = msections[i].split('\n'); + + let linesConnection = tsections[i].split('\n'); + const bitsPerPixel = util$c.getValue(linesScreen, 'BitsPerPixel'); + const bounds = util$c.getValue(linesScreen, 'Bounds').replace('{', '').replace('}', '').replace(/=/g, ':').split(','); + const primary = util$c.getValue(linesScreen, 'Primary'); + const sizeX = util$c.getValue(linesMonitor, 'MaxHorizontalImageSize'); + const sizeY = util$c.getValue(linesMonitor, 'MaxVerticalImageSize'); + const instanceName = util$c.getValue(linesMonitor, 'InstanceName').toLowerCase(); + const videoOutputTechnology = util$c.getValue(linesConnection, 'VideoOutputTechnology'); + const deviceName = util$c.getValue(linesScreen, 'DeviceName'); + let displayVendor = ''; + let displayModel = ''; + isections.forEach(element => { + if (element.instanceId.toLowerCase().startsWith(instanceName) && vendor.startsWith('(') && model.startsWith('PnP')) { + displayVendor = element.vendor; + displayModel = element.model; + } + }); + displays.push({ + vendor: instanceName.startsWith(deviceID) && displayVendor === '' ? vendor : displayVendor, + model: instanceName.startsWith(deviceID) && displayModel === '' ? model : displayModel, + deviceName, + main: primary.toLowerCase() === 'true', + builtin: videoOutputTechnology === '2147483648', + connection: videoOutputTechnology && videoTypes[videoOutputTechnology] ? videoTypes[videoOutputTechnology] : '', + resolutionX: util$c.toInt(util$c.getValue(bounds, 'Width', ':')), + resolutionY: util$c.toInt(util$c.getValue(bounds, 'Height', ':')), + sizeX: sizeX ? parseInt(sizeX, 10) : null, + sizeY: sizeY ? parseInt(sizeY, 10) : null, + pixelDepth: bitsPerPixel, + currentResX: util$c.toInt(util$c.getValue(bounds, 'Width', ':')), + currentResY: util$c.toInt(util$c.getValue(bounds, 'Height', ':')), + positionX: util$c.toInt(util$c.getValue(bounds, 'X', ':')), + positionY: util$c.toInt(util$c.getValue(bounds, 'Y', ':')), + }); + } + } + if (ssections.length === 0) { + displays.push({ + vendor, + model, + main: true, + sizeX: null, + sizeY: null, + resolutionX, + resolutionY, + pixelDepth: null, + currentResX: resolutionX, + currentResY: resolutionY, + positionX: 0, + positionY: 0 + }); + } + return displays; + } } -memory.memLayout = memLayout; +graphics$1.graphics = graphics; -// @ts-check; +var filesystem = {}; + +// @ts-check // ================================================================================== -// battery.js +// filesystem.js // ---------------------------------------------------------------------------------- // Description: System Information - library // for Node.js @@ -62211,1435 +58345,1510 @@ memory.memLayout = memLayout; // ---------------------------------------------------------------------------------- // License: MIT // ================================================================================== -// 6. Battery +// 8. File System // ---------------------------------------------------------------------------------- -const exec$b = require$$1$2.exec; -const fs$5 = require$$0$5; -const util$d = util$j; - -let _platform$c = process.platform; +const util$b = util$j; +const fs$3 = require$$0$5; -const _linux$b = (_platform$c === 'linux' || _platform$c === 'android'); -const _darwin$b = (_platform$c === 'darwin'); -const _windows$c = (_platform$c === 'win32'); -const _freebsd$a = (_platform$c === 'freebsd'); -const _openbsd$a = (_platform$c === 'openbsd'); -const _netbsd$a = (_platform$c === 'netbsd'); -const _sunos$a = (_platform$c === 'sunos'); +const exec$9 = require$$1$2.exec; +const execSync$5 = require$$1$2.execSync; +const execPromiseSave = util$b.promisifySave(require$$1$2.exec); -function parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity) { - const result = {}; - let status = util$d.getValue(lines, 'BatteryStatus', ':').trim(); - // 1 = "Discharging" - // 2 = "On A/C" - // 3 = "Fully Charged" - // 4 = "Low" - // 5 = "Critical" - // 6 = "Charging" - // 7 = "Charging High" - // 8 = "Charging Low" - // 9 = "Charging Critical" - // 10 = "Undefined" - // 11 = "Partially Charged" - if (status >= 0) { - const statusValue = status ? parseInt(status) : 0; - result.status = statusValue; - result.hasBattery = true; - result.maxCapacity = fullChargeCapacity || parseInt(util$d.getValue(lines, 'DesignCapacity', ':') || 0); - result.designedCapacity = parseInt(util$d.getValue(lines, 'DesignCapacity', ':') || designedCapacity); - result.voltage = parseInt(util$d.getValue(lines, 'DesignVoltage', ':') || 0) / 1000.0; - result.capacityUnit = 'mWh'; - result.percent = parseInt(util$d.getValue(lines, 'EstimatedChargeRemaining', ':') || 0); - result.currentCapacity = parseInt(result.maxCapacity * result.percent / 100); - result.isCharging = (statusValue >= 6 && statusValue <= 9) || statusValue === 11 || ((statusValue !== 3) && (statusValue !== 1) && result.percent < 100); - result.acConnected = result.isCharging || statusValue === 2; - result.model = util$d.getValue(lines, 'DeviceID', ':'); - } else { - result.status = -1; - } +let _platform$a = process.platform; - return result; -} +const _linux$9 = (_platform$a === 'linux' || _platform$a === 'android'); +const _darwin$9 = (_platform$a === 'darwin'); +const _windows$a = (_platform$a === 'win32'); +const _freebsd$8 = (_platform$a === 'freebsd'); +const _openbsd$8 = (_platform$a === 'openbsd'); +const _netbsd$8 = (_platform$a === 'netbsd'); +const _sunos$8 = (_platform$a === 'sunos'); -var battery = function (callback) { +let _fs_speed = {}; +let _disk_io = {}; - return new Promise((resolve) => { - process.nextTick(() => { - let result = { - hasBattery: false, - cycleCount: 0, - isCharging: false, - designedCapacity: 0, - maxCapacity: 0, - currentCapacity: 0, - voltage: 0, - capacityUnit: '', - percent: 0, - timeRemaining: null, - acConnected: true, - type: '', - model: '', - manufacturer: '', - serial: '' - }; +// -------------------------- +// FS - mounted file systems - if (_linux$b) { - let battery_path = ''; - if (fs$5.existsSync('/sys/class/power_supply/BAT1/uevent')) { - battery_path = '/sys/class/power_supply/BAT1/'; - } else if (fs$5.existsSync('/sys/class/power_supply/BAT0/uevent')) { - battery_path = '/sys/class/power_supply/BAT0/'; - } +function fsSize(drive, callback) { - let acConnected = false; - let acPath = ''; - if (fs$5.existsSync('/sys/class/power_supply/AC/online')) { - acPath = '/sys/class/power_supply/AC/online'; - } else if (fs$5.existsSync('/sys/class/power_supply/AC0/online')) { - acPath = '/sys/class/power_supply/AC0/online'; - } + if (util$b.isFunction(drive)) { + callback = drive; + drive = ''; + } - if (acPath) { - const file = fs$5.readFileSync(acPath); - acConnected = file.toString().trim() === '1'; - } + let macOsDisks = []; + let osMounts = []; - if (battery_path) { - fs$5.readFile(battery_path + 'uevent', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); + function getmacOsFsType(fs) { + if (!fs.startsWith('/')) { return 'NFS'; } + const parts = fs.split('/'); + const fsShort = parts[parts.length - 1]; + const macOsDisksSingle = macOsDisks.filter(item => item.indexOf(fsShort) >= 0); + if (macOsDisksSingle.length === 1 && macOsDisksSingle[0].indexOf('APFS') >= 0) { return 'APFS'; } + return 'HFS'; + } - result.isCharging = (util$d.getValue(lines, 'POWER_SUPPLY_STATUS', '=').toLowerCase() === 'charging'); - result.acConnected = acConnected || result.isCharging; - result.voltage = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_VOLTAGE_NOW', '='), 10) / 1000000.0; - result.capacityUnit = result.voltage ? 'mWh' : 'mAh'; - result.cycleCount = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CYCLE_COUNT', '='), 10); - result.maxCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL', '=', true, true), 10) / 1000.0 * (result.voltage || 1)); - const desingedMinVoltage = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_VOLTAGE_MIN_DESIGN', '='), 10) / 1000000.0; - result.designedCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL_DESIGN', '=', true, true), 10) / 1000.0 * (desingedMinVoltage || result.voltage || 1)); - result.currentCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10) / 1000.0 * (result.voltage || 1)); - if (!result.maxCapacity) { - result.maxCapacity = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL', '=', true, true), 10) / 1000.0; - result.designedCapacity = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL_DESIGN', '=', true, true), 10) / 1000.0 | result.maxCapacity; - result.currentCapacity = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10) / 1000.0; - } - const percent = util$d.getValue(lines, 'POWER_SUPPLY_CAPACITY', '='); - const energy = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10); - const power = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_POWER_NOW', '='), 10); - const current = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CURRENT_NOW', '='), 10); - const charge = parseInt('0' + util$d.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10); + function isLinuxTmpFs(fs) { + const linuxTmpFileSystems = ['rootfs', 'unionfs', 'squashfs', 'cramfs', 'initrd', 'initramfs', 'devtmpfs', 'tmpfs', 'udev', 'devfs', 'specfs', 'type', 'appimaged']; + let result = false; + linuxTmpFileSystems.forEach(linuxFs => { + if (fs.toLowerCase().indexOf(linuxFs) >= 0) { result = true; } + }); + return result; + } - result.percent = parseInt('0' + percent, 10); - if (result.maxCapacity && result.currentCapacity) { - result.hasBattery = true; - if (!percent) { - result.percent = 100.0 * result.currentCapacity / result.maxCapacity; - } - } - if (result.isCharging) { - result.hasBattery = true; - } - if (energy && power) { - result.timeRemaining = Math.floor(energy / power * 60); - } else if (current && charge) { - result.timeRemaining = Math.floor(charge / current * 60); - } else if (current && result.currentCapacity) { - result.timeRemaining = Math.floor(result.currentCapacity / current * 60); - } - result.type = util$d.getValue(lines, 'POWER_SUPPLY_TECHNOLOGY', '='); - result.model = util$d.getValue(lines, 'POWER_SUPPLY_MODEL_NAME', '='); - result.manufacturer = util$d.getValue(lines, 'POWER_SUPPLY_MANUFACTURER', '='); - result.serial = util$d.getValue(lines, 'POWER_SUPPLY_SERIAL_NUMBER', '='); - if (callback) { callback(result); } - resolve(result); - } else { - if (callback) { callback(result); } - resolve(result); - } - }); - } else { - if (callback) { callback(result); } - resolve(result); + function filterLines(stdout) { + let lines = stdout.toString().split('\n'); + lines.shift(); + if (stdout.toString().toLowerCase().indexOf('filesystem')) { + let removeLines = 0; + for (let i = 0; i < lines.length; i++) { + if (lines[i] && lines[i].toLowerCase().startsWith('filesystem')) { + removeLines = i; } } - if (_freebsd$a || _openbsd$a || _netbsd$a) { - exec$b('sysctl -i hw.acpi.battery hw.acpi.acline', function (error, stdout) { - let lines = stdout.toString().split('\n'); - const batteries = parseInt('0' + util$d.getValue(lines, 'hw.acpi.battery.units'), 10); - const percent = parseInt('0' + util$d.getValue(lines, 'hw.acpi.battery.life'), 10); - result.hasBattery = (batteries > 0); - result.cycleCount = null; - result.isCharging = util$d.getValue(lines, 'hw.acpi.acline') !== '1'; - result.acConnected = result.isCharging; - result.maxCapacity = null; - result.currentCapacity = null; - result.capacityUnit = 'unknown'; - result.percent = batteries ? percent : null; - if (callback) { callback(result); } - resolve(result); - }); + for (let i = 0; i < removeLines; i++) { + lines.shift(); } + } + return lines; + } - if (_darwin$b) { - exec$b('ioreg -n AppleSmartBattery -r | egrep "CycleCount|IsCharging|DesignCapacity|MaxCapacity|CurrentCapacity|BatterySerialNumber|TimeRemaining|Voltage"; pmset -g batt | grep %', function (error, stdout) { - if (stdout) { - let lines = stdout.toString().replace(/ +/g, '').replace(/"+/g, '').replace(/-/g, '').split('\n'); - result.cycleCount = parseInt('0' + util$d.getValue(lines, 'cyclecount', '='), 10); - result.voltage = parseInt('0' + util$d.getValue(lines, 'voltage', '='), 10) / 1000.0; - result.capacityUnit = result.voltage ? 'mWh' : 'mAh'; - result.maxCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'applerawmaxcapacity', '='), 10) * (result.voltage || 1)); - result.currentCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'applerawcurrentcapacity', '='), 10) * (result.voltage || 1)); - result.designedCapacity = Math.round(parseInt('0' + util$d.getValue(lines, 'DesignCapacity', '='), 10) * (result.voltage || 1)); - result.manufacturer = 'Apple'; - result.serial = util$d.getValue(lines, 'BatterySerialNumber', '='); - let percent = null; - const line = util$d.getValue(lines, 'internal', 'Battery'); - let parts = line.split(';'); - if (parts && parts[0]) { - let parts2 = parts[0].split('\t'); - if (parts2 && parts2[1]) { - percent = parseFloat(parts2[1].trim().replace(/%/g, '')); - } - } - if (parts && parts[1]) { - result.isCharging = (parts[1].trim() === 'charging'); - result.acConnected = (parts[1].trim() !== 'discharging'); - } else { - result.isCharging = util$d.getValue(lines, 'ischarging', '=').toLowerCase() === 'yes'; - result.acConnected = result.isCharging; - } - if (result.maxCapacity && result.currentCapacity) { - result.hasBattery = true; - result.type = 'Li-ion'; - result.percent = percent !== null ? percent : Math.round(100.0 * result.currentCapacity / result.maxCapacity); - if (!result.isCharging) { - result.timeRemaining = parseInt('0' + util$d.getValue(lines, 'TimeRemaining', '='), 10); + function parseDf(lines) { + let data = []; + lines.forEach(function (line) { + if (line !== '') { + line = line.replace(/ +/g, ' ').split(' '); + if (line && ((line[0].startsWith('/')) || (line[6] && line[6] === '/') || (line[0].indexOf('/') > 0) || (line[0].indexOf(':') === 1) || !_darwin$9 && !isLinuxTmpFs(line[1]))) { + const fs = line[0]; + const fsType = ((_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? line[1] : getmacOsFsType(line[0])); + const size = parseInt(((_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? line[2] : line[1])) * 1024; + const used = parseInt(((_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? line[3] : line[2])) * 1024; + const available = parseInt(((_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? line[4] : line[3])) * 1024; + const use = parseFloat((100.0 * (used / (used + available))).toFixed(2)); + let rw = osMounts && Object.keys(osMounts).length > 0 ? osMounts[fs] || false : null; + line.splice(0, (_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? 6 : 5); + const mount = line.join(' '); + if (!data.find(el => (el.fs === fs && el.type === fsType))) { + data.push({ + fs, + type: fsType, + size, + used, + available, + use, + mount, + rw + }); + } + } + } + }); + return data; + } + + return new Promise((resolve) => { + process.nextTick(() => { + let data = []; + if (_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8 || _darwin$9) { + let cmd = ''; + macOsDisks = []; + osMounts = {}; + if (_darwin$9) { + cmd = 'df -kP'; + try { + macOsDisks = execSync$5('diskutil list').toString().split('\n').filter(line => { + return !line.startsWith('/') && line.indexOf(':') > 0; + }); + execSync$5('mount').toString().split('\n').filter(line => { + return line.startsWith('/'); + }).forEach((line) => { + osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1; + }); + } catch (e) { + util$b.noop(); + } + } + if (_linux$9) { + try { + cmd = 'export LC_ALL=C; df -lkPTx squashfs; unset LC_ALL'; + execSync$5('cat /proc/mounts 2>/dev/null').toString().split('\n').filter(line => { + return line.startsWith('/'); + }).forEach((line) => { + osMounts[line.split(' ')[0]] = osMounts[line.split(' ')[0]] || false; + if (line.toLowerCase().indexOf('/snap/') === -1) { + osMounts[line.split(' ')[0]] = ((line.toLowerCase().indexOf('rw,') >= 0 || line.toLowerCase().indexOf(' rw ') >= 0)); } + }); + } catch (e) { + util$b.noop(); + } + } + if (_freebsd$8 || _openbsd$8 || _netbsd$8) { + try { + cmd = 'df -lkPT'; + execSync$5('mount').toString().split('\n').forEach((line) => { + osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1; + }); + } catch (e) { + util$b.noop(); + } + } + exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { + let lines = filterLines(stdout); + data = parseDf(lines); + if (drive) { + data = data.filter(item => { + return item.fs.toLowerCase().indexOf(drive.toLowerCase()) >= 0 || item.mount.toLowerCase().indexOf(drive.toLowerCase()) >= 0; + }); + } + if ((!error || data.length) && stdout.toString().trim() !== '') { + if (callback) { + callback(data); } + resolve(data); + } else { + exec$9('df -kPT', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = filterLines(stdout); + data = parseDf(lines); + } + if (callback) { + callback(data); + } + resolve(data); + }); } - if (callback) { callback(result); } - resolve(result); }); } - if (_sunos$a) { - if (callback) { callback(result); } - resolve(result); + if (_sunos$8) { + if (callback) { callback(data); } + resolve(data); } - if (_windows$c) { + if (_windows$a) { try { - const workload = []; - workload.push(util$d.powerShell('Get-CimInstance Win32_Battery | select BatteryStatus, DesignCapacity, DesignVoltage, EstimatedChargeRemaining, DeviceID | fl')); - workload.push(util$d.powerShell('(Get-CimInstance -Class BatteryStaticData -Namespace ROOT/WMI).DesignedCapacity')); - workload.push(util$d.powerShell('(Get-CimInstance -Class BatteryFullChargedCapacity -Namespace ROOT/WMI).FullChargedCapacity')); - util$d.promiseAll( - workload - ).then((data) => { - if (data) { - let parts = data.results[0].split(/\n\s*\n/); - let batteries = []; - const hasValue = value => /\S/.test(value); - for (let i = 0; i < parts.length; i++) { - if (hasValue(parts[i]) && (!batteries.length || !hasValue(parts[i - 1]))) { - batteries.push([]); - } - if (hasValue(parts[i])) { - batteries[batteries.length - 1].push(parts[i]); - } - } - let designCapacities = data.results[1].split('\r\n').filter(e => e); - let fullChargeCapacities = data.results[2].split('\r\n').filter(e => e); - if (batteries.length) { - let first = false; - let additionalBatteries = []; - for (let i = 0; i < batteries.length; i++) { - let lines = batteries[i][0].split('\r\n'); - const designedCapacity = designCapacities && designCapacities.length >= (i + 1) && designCapacities[i] ? util$d.toInt(designCapacities[i]) : 0; - const fullChargeCapacity = fullChargeCapacities && fullChargeCapacities.length >= (i + 1) && fullChargeCapacities[i] ? util$d.toInt(fullChargeCapacities[i]) : 0; - const parsed = parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity); - if (!first && parsed.status > 0 && parsed.status !== 10) { - result.hasBattery = parsed.hasBattery; - result.maxCapacity = parsed.maxCapacity; - result.designedCapacity = parsed.designedCapacity; - result.voltage = parsed.voltage; - result.capacityUnit = parsed.capacityUnit; - result.percent = parsed.percent; - result.currentCapacity = parsed.currentCapacity; - result.isCharging = parsed.isCharging; - result.acConnected = parsed.acConnected; - result.model = parsed.model; - first = true; - } else if (parsed.status !== -1) { - additionalBatteries.push( - { - hasBattery: parsed.hasBattery, - maxCapacity: parsed.maxCapacity, - designedCapacity: parsed.designedCapacity, - voltage: parsed.voltage, - capacityUnit: parsed.capacityUnit, - percent: parsed.percent, - currentCapacity: parsed.currentCapacity, - isCharging: parsed.isCharging, - timeRemaining: null, - acConnected: parsed.acConnected, - model: parsed.model, - type: '', - manufacturer: '', - serial: '' - } - ); - } - } - if (!first && additionalBatteries.length) { - result = additionalBatteries[0]; - additionalBatteries.shift(); - } - if (additionalBatteries.length) { - result.additionalBatteries = additionalBatteries; + const cmd = `Get-WmiObject Win32_logicaldisk | select Access,Caption,FileSystem,FreeSpace,Size ${drive ? '| where -property Caption -eq ' + drive : ''} | fl`; + util$b.powerShell(cmd).then((stdout, error) => { + if (!error) { + let devices = stdout.toString().split(/\n\s*\n/); + devices.forEach(function (device) { + let lines = device.split('\r\n'); + const size = util$b.toInt(util$b.getValue(lines, 'size', ':')); + const free = util$b.toInt(util$b.getValue(lines, 'freespace', ':')); + const caption = util$b.getValue(lines, 'caption', ':'); + const rwValue = util$b.getValue(lines, 'access', ':'); + const rw = rwValue ? (util$b.toInt(rwValue) !== 1) : null; + if (size) { + data.push({ + fs: caption, + type: util$b.getValue(lines, 'filesystem', ':'), + size, + used: size - free, + available: free, + use: parseFloat(((100.0 * (size - free)) / size).toFixed(2)), + mount: caption, + rw + }); } - } + }); } - if (callback) { callback(result); } - resolve(result); + if (callback) { + callback(data); + } + resolve(data); }); } catch (e) { - if (callback) { callback(result); } - resolve(result); + if (callback) { callback(data); } + resolve(data); } } }); }); -}; - -var graphics$1 = {}; - -// @ts-check -// ================================================================================== -// graphics.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 7. Graphics (controller, display) -// ---------------------------------------------------------------------------------- - -const fs$4 = require$$0$5; -const exec$a = require$$1$2.exec; -const execSync$6 = require$$1$2.execSync; -const util$c = util$j; - -let _platform$b = process.platform; -let _nvidiaSmiPath = ''; - -const _linux$a = (_platform$b === 'linux' || _platform$b === 'android'); -const _darwin$a = (_platform$b === 'darwin'); -const _windows$b = (_platform$b === 'win32'); -const _freebsd$9 = (_platform$b === 'freebsd'); -const _openbsd$9 = (_platform$b === 'openbsd'); -const _netbsd$9 = (_platform$b === 'netbsd'); -const _sunos$9 = (_platform$b === 'sunos'); - -let _resolutionX = 0; -let _resolutionY = 0; -let _pixelDepth = 0; -let _refreshRate = 0; - -const videoTypes = { - '-2': 'UNINITIALIZED', - '-1': 'OTHER', - '0': 'HD15', - '1': 'SVIDEO', - '2': 'Composite video', - '3': 'Component video', - '4': 'DVI', - '5': 'HDMI', - '6': 'LVDS', - '8': 'D_JPN', - '9': 'SDI', - '10': 'DP', - '11': 'DP embedded', - '12': 'UDI', - '13': 'UDI embedded', - '14': 'SDTVDONGLE', - '15': 'MIRACAST', - '2147483648': 'INTERNAL' -}; - -function getVendorFromModel(model) { - const manufacturers = [ - { pattern: '^LG.+', manufacturer: 'LG' }, - { pattern: '^BENQ.+', manufacturer: 'BenQ' }, - { pattern: '^ASUS.+', manufacturer: 'Asus' }, - { pattern: '^DELL.+', manufacturer: 'Dell' }, - { pattern: '^SAMSUNG.+', manufacturer: 'Samsung' }, - { pattern: '^VIEWSON.+', manufacturer: 'ViewSonic' }, - { pattern: '^SONY.+', manufacturer: 'Sony' }, - { pattern: '^ACER.+', manufacturer: 'Acer' }, - { pattern: '^AOC.+', manufacturer: 'AOC Monitors' }, - { pattern: '^HP.+', manufacturer: 'HP' }, - { pattern: '^EIZO.?', manufacturer: 'Eizo' }, - { pattern: '^PHILIPS.?', manufacturer: 'Philips' }, - { pattern: '^IIYAMA.?', manufacturer: 'Iiyama' }, - { pattern: '^SHARP.?', manufacturer: 'Sharp' }, - { pattern: '^NEC.?', manufacturer: 'NEC' }, - { pattern: '^LENOVO.?', manufacturer: 'Lenovo' }, - { pattern: 'COMPAQ.?', manufacturer: 'Compaq' }, - { pattern: 'APPLE.?', manufacturer: 'Apple' }, - { pattern: 'INTEL.?', manufacturer: 'Intel' }, - { pattern: 'AMD.?', manufacturer: 'AMD' }, - { pattern: 'NVIDIA.?', manufacturer: 'NVDIA' }, - ]; - - let result = ''; - if (model) { - model = model.toUpperCase(); - manufacturers.forEach((manufacturer) => { - const re = RegExp(manufacturer.pattern); - if (re.test(model)) { result = manufacturer.manufacturer; } - }); - } - return result; -} - -function getVendorFromId(id) { - const vendors = { - '610': 'Apple', - '1e6d': 'LG', - '10ac': 'DELL', - '4dd9': 'Sony', - '38a3': 'NEC', - }; - return vendors[id] || ''; } -function vendorToId(str) { - let result = ''; - str = (str || '').toLowerCase(); - if (str.indexOf('apple') >= 0) { result = '0x05ac'; } - else if (str.indexOf('nvidia') >= 0) { result = '0x10de'; } - else if (str.indexOf('intel') >= 0) { result = '0x8086'; } - else if (str.indexOf('ati') >= 0 || str.indexOf('amd') >= 0) { result = '0x1002'; } - - return result; -} +filesystem.fsSize = fsSize; -function getMetalVersion(id) { - const families = { - 'spdisplays_mtlgpufamilymac1': 'mac1', - 'spdisplays_mtlgpufamilymac2': 'mac2', - 'spdisplays_mtlgpufamilyapple1': 'apple1', - 'spdisplays_mtlgpufamilyapple2': 'apple2', - 'spdisplays_mtlgpufamilyapple3': 'apple3', - 'spdisplays_mtlgpufamilyapple4': 'apple4', - 'spdisplays_mtlgpufamilyapple5': 'apple5', - 'spdisplays_mtlgpufamilyapple6': 'apple6', - 'spdisplays_mtlgpufamilyapple7': 'apple7', - 'spdisplays_metalfeaturesetfamily11': 'family1_v1', - 'spdisplays_metalfeaturesetfamily12': 'family1_v2', - 'spdisplays_metalfeaturesetfamily13': 'family1_v3', - 'spdisplays_metalfeaturesetfamily14': 'family1_v4', - 'spdisplays_metalfeaturesetfamily21': 'family2_v1' - }; - return families[id] || ''; -} +// -------------------------- +// FS - open files count -function graphics(callback) { +function fsOpenFiles(callback) { - function parseLinesDarwin(graphicsArr) { - const res = { - controllers: [], - displays: [] - }; - try { - graphicsArr.forEach(function (item) { - // controllers - const bus = ((item.sppci_bus || '').indexOf('builtin') > -1 ? 'Built-In' : ((item.sppci_bus || '').indexOf('pcie') > -1 ? 'PCIe' : '')); - const vram = (parseInt((item.spdisplays_vram || ''), 10) || 0) * (((item.spdisplays_vram || '').indexOf('GB') > -1) ? 1024 : 1); - const vramDyn = (parseInt((item.spdisplays_vram_shared || ''), 10) || 0) * (((item.spdisplays_vram_shared || '').indexOf('GB') > -1) ? 1024 : 1); - let metalVersion = getMetalVersion(item.spdisplays_metal || item.spdisplays_metalfamily || ''); - res.controllers.push({ - vendor: getVendorFromModel(item.spdisplays_vendor || '') || item.spdisplays_vendor || '', - model: item.sppci_model || '', - bus, - vramDynamic: bus === 'Built-In', - vram: vram || vramDyn || null, - deviceId: item['spdisplays_device-id'] || '', - vendorId: item['spdisplays_vendor-id'] || vendorToId((item['spdisplays_vendor'] || '') + (item.sppci_model || '')), - external: (item.sppci_device_type === 'spdisplays_egpu'), - cores: item['sppci_cores'] || null, - metalVersion + return new Promise((resolve) => { + process.nextTick(() => { + const result = { + max: null, + allocated: null, + available: null + }; + if (_freebsd$8 || _openbsd$8 || _netbsd$8 || _darwin$9) { + let cmd = 'sysctl -i kern.maxfiles kern.num_files kern.open_files'; + exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + result.max = parseInt(util$b.getValue(lines, 'kern.maxfiles', ':'), 10); + result.allocated = parseInt(util$b.getValue(lines, 'kern.num_files', ':'), 10) || parseInt(util$b.getValue(lines, 'kern.open_files', ':'), 10); + result.available = result.max - result.allocated; + } + if (callback) { + callback(result); + } + resolve(result); }); - - // displays - if (item.spdisplays_ndrvs && item.spdisplays_ndrvs.length) { - item.spdisplays_ndrvs.forEach(function (displayItem) { - const connectionType = displayItem['spdisplays_connection_type'] || ''; - const currentResolutionParts = (displayItem['_spdisplays_resolution'] || '').split('@'); - const currentResolution = currentResolutionParts[0].split('x'); - const pixelParts = (displayItem['_spdisplays_pixels'] || '').split('x'); - const pixelDepthString = displayItem['spdisplays_depth'] || ''; - const serial = displayItem['_spdisplays_display-serial-number'] || displayItem['_spdisplays_display-serial-number2'] || null; - res.displays.push({ - vendor: getVendorFromId(displayItem['_spdisplays_display-vendor-id'] || '') || getVendorFromModel(displayItem['_name'] || ''), - vendorId: displayItem['_spdisplays_display-vendor-id'] || '', - model: displayItem['_name'] || '', - productionYear: displayItem['_spdisplays_display-year'] || null, - serial: serial !== '0' ? serial : null, - displayId: displayItem['_spdisplays_displayID'] || null, - main: displayItem['spdisplays_main'] ? displayItem['spdisplays_main'] === 'spdisplays_yes' : false, - builtin: (displayItem['spdisplays_display_type'] || '').indexOf('built-in') > -1, - connection: ((connectionType.indexOf('_internal') > -1) ? 'Internal' : ((connectionType.indexOf('_displayport') > -1) ? 'Display Port' : ((connectionType.indexOf('_hdmi') > -1) ? 'HDMI' : null))), - sizeX: null, - sizeY: null, - pixelDepth: (pixelDepthString === 'CGSThirtyBitColor' ? 30 : (pixelDepthString === 'CGSThirtytwoBitColor' ? 32 : (pixelDepthString === 'CGSTwentyfourBitColor' ? 24 : null))), - resolutionX: pixelParts.length > 1 ? parseInt(pixelParts[0], 10) : null, - resolutionY: pixelParts.length > 1 ? parseInt(pixelParts[1], 10) : null, - currentResX: currentResolution.length > 1 ? parseInt(currentResolution[0], 10) : null, - currentResY: currentResolution.length > 1 ? parseInt(currentResolution[1], 10) : null, - positionX: 0, - positionY: 0, - currentRefreshRate: currentResolutionParts.length > 1 ? parseInt(currentResolutionParts[1], 10) : null, - - }); - }); - } - }); - return res; - } catch (e) { - return res; - } - } - - function parseLinesLinuxControllers(lines) { - let controllers = []; - let currentController = { - vendor: '', - subVendor: '', - model: '', - bus: '', - busAddress: '', - vram: null, - vramDynamic: false, - pciID: '' - }; - let isGraphicsController = false; - // PCI bus IDs - let pciIDs = []; - try { - pciIDs = execSync$6('export LC_ALL=C; dmidecode -t 9 2>/dev/null; unset LC_ALL | grep "Bus Address: "').toString().split('\n'); - for (let i = 0; i < pciIDs.length; i++) { - pciIDs[i] = pciIDs[i].replace('Bus Address:', '').replace('0000:', '').trim(); - } - pciIDs = pciIDs.filter(function (el) { - return el != null && el; - }); - } catch (e) { - util$c.noop(); - } - let i = 1; - lines.forEach((line) => { - let subsystem = ''; - if (i < lines.length && lines[i]) { // get next line; - subsystem = lines[i]; - if (subsystem.indexOf(':') > 0) { - subsystem = subsystem.split(':')[1]; - } } - if ('' !== line.trim()) { - if (' ' !== line[0] && '\t' !== line[0]) { // first line of new entry - let isExternal = (pciIDs.indexOf(line.split(' ')[0]) >= 0); - let vgapos = line.toLowerCase().indexOf(' vga '); - let _3dcontrollerpos = line.toLowerCase().indexOf('3d controller'); - if (vgapos !== -1 || _3dcontrollerpos !== -1) { // VGA - if (_3dcontrollerpos !== -1 && vgapos === -1) { - vgapos = _3dcontrollerpos; - } - if (currentController.vendor || currentController.model || currentController.bus || currentController.vram !== null || currentController.vramDynamic) { // already a controller found - controllers.push(currentController); - currentController = { - vendor: '', - model: '', - bus: '', - busAddress: '', - vram: null, - vramDynamic: false, - }; + if (_linux$9) { + fs$3.readFile('/proc/sys/fs/file-nr', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + if (lines[0]) { + const parts = lines[0].replace(/\s+/g, ' ').split(' '); + if (parts.length === 3) { + result.allocated = parseInt(parts[0], 10); + result.available = parseInt(parts[1], 10); + result.max = parseInt(parts[2], 10); + if (!result.available) { result.available = result.max - result.allocated; } + } } - - const pciIDCandidate = line.split(' ')[0]; - if (/[\da-fA-F]{2}:[\da-fA-F]{2}\.[\da-fA-F]/.test(pciIDCandidate)) { - currentController.busAddress = pciIDCandidate; + if (callback) { + callback(result); } - isGraphicsController = true; - let endpos = line.search(/\[[0-9a-f]{4}:[0-9a-f]{4}]|$/); - let parts = line.substr(vgapos, endpos - vgapos).split(':'); - currentController.busAddress = line.substr(0, vgapos).trim(); - if (parts.length > 1) { - parts[1] = parts[1].trim(); - if (parts[1].toLowerCase().indexOf('corporation') >= 0) { - currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf('corporation') + 11).trim(); - currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf('corporation') + 11, 200).split('(')[0].trim(); - currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard'; - currentController.vram = null; - currentController.vramDynamic = false; - } else if (parts[1].toLowerCase().indexOf(' inc.') >= 0) { - if ((parts[1].match(/]/g) || []).length > 1) { - currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim(); - currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim(); - } else { - currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' inc.') + 5).trim(); - currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' inc.') + 5, 200).trim().split('(')[0].trim(); - } - currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard'; - currentController.vram = null; - currentController.vramDynamic = false; - } else if (parts[1].toLowerCase().indexOf(' ltd.') >= 0) { - if ((parts[1].match(/]/g) || []).length > 1) { - currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim(); - currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim(); - } else { - currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' ltd.') + 5).trim(); - currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' ltd.') + 5, 200).trim().split('(')[0].trim(); + resolve(result); + } else { + fs$3.readFile('/proc/sys/fs/file-max', function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + if (lines[0]) { + result.max = parseInt(lines[0], 10); } } - if (currentController.model && subsystem.indexOf(currentController.model) !== -1) { - const subVendor = subsystem.split(currentController.model)[0].trim(); - if (subVendor) { - currentController.subVendor = subVendor; - } + if (callback) { + callback(result); } - } - - } else { - isGraphicsController = false; - } - } - if (isGraphicsController) { // within VGA details - let parts = line.split(':'); - if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('devicename') !== -1 && parts[1].toLowerCase().indexOf('onboard') !== -1) { currentController.bus = 'Onboard'; } - if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('region') !== -1 && parts[1].toLowerCase().indexOf('memory') !== -1) { - let memparts = parts[1].split('='); - if (memparts.length > 1) { - currentController.vram = parseInt(memparts[1]); - } + resolve(result); + }); } - } + }); + } + if (_sunos$8) { + if (callback) { callback(null); } + resolve(null); + } + if (_windows$a) { + if (callback) { callback(null); } + resolve(null); } - i++; }); + }); +} - if (currentController.vendor || currentController.model || currentController.bus || currentController.busAddress || currentController.vram !== null || currentController.vramDynamic) { // already a controller found - controllers.push(currentController); - } - return (controllers); - } +filesystem.fsOpenFiles = fsOpenFiles; - function parseLinesLinuxClinfo(controllers, lines) { - const fieldPattern = /\[([^\]]+)\]\s+(\w+)\s+(.*)/; - const devices = lines.reduce((devices, line) => { - const field = fieldPattern.exec(line.trim()); - if (field) { - if (!devices[field[1]]) { - devices[field[1]] = {}; - } - devices[field[1]][field[2]] = field[3]; - } - return devices; - }, {}); - for (let deviceId in devices) { - const device = devices[deviceId]; - if (device['CL_DEVICE_TYPE'] === 'CL_DEVICE_TYPE_GPU') { - let busAddress; - if (device['CL_DEVICE_TOPOLOGY_AMD']) { - const bdf = device['CL_DEVICE_TOPOLOGY_AMD'].match(/[a-zA-Z0-9]+:\d+\.\d+/); - if (bdf) { - busAddress = bdf[0]; - } - } else if (device['CL_DEVICE_PCI_BUS_ID_NV'] && device['CL_DEVICE_PCI_SLOT_ID_NV']) { - const bus = parseInt(device['CL_DEVICE_PCI_BUS_ID_NV']); - const slot = parseInt(device['CL_DEVICE_PCI_SLOT_ID_NV']); - if (!isNaN(bus) && !isNaN(slot)) { - const b = bus & 0xff; - const d = (slot >> 3) & 0xff; - const f = slot & 0x07; - busAddress = `${b.toString().padStart(2, '0')}:${d.toString().padStart(2, '0')}.${f}`; - } - } - if (busAddress) { - let controller = controllers.find(controller => controller.busAddress === busAddress); - if (!controller) { - controller = { - vendor: '', +// -------------------------- +// disks + +function parseBytes(s) { + return parseInt(s.substr(s.indexOf(' (') + 2, s.indexOf(' Bytes)') - 10)); +} + +function parseDevices(lines) { + let devices = []; + let i = 0; + lines.forEach(line => { + if (line.length > 0) { + if (line[0] === '*') { + i++; + } else { + let parts = line.split(':'); + if (parts.length > 1) { + if (!devices[i]) { + devices[i] = { + name: '', + identifier: '', + type: 'disk', + fsType: '', + mount: '', + size: 0, + physical: 'HDD', + uuid: '', + label: '', model: '', - bus: '', - busAddress, - vram: null, - vramDynamic: false + serial: '', + removable: false, + protocol: '', + group: '', + device: '' }; - controllers.push(controller); - } - controller.vendor = device['CL_DEVICE_VENDOR']; - if (device['CL_DEVICE_BOARD_NAME_AMD']) { - controller.model = device['CL_DEVICE_BOARD_NAME_AMD']; - } else { - controller.model = device['CL_DEVICE_NAME']; } - const memory = parseInt(device['CL_DEVICE_GLOBAL_MEM_SIZE']); - if (!isNaN(memory)) { - controller.vram = Math.round(memory / 1024 / 1024); + parts[0] = parts[0].trim().toUpperCase().replace(/ +/g, ''); + parts[1] = parts[1].trim(); + if ('DEVICEIDENTIFIER' === parts[0]) { devices[i].identifier = parts[1]; } + if ('DEVICENODE' === parts[0]) { devices[i].name = parts[1]; } + if ('VOLUMENAME' === parts[0]) { + if (parts[1].indexOf('Not applicable') === -1) { devices[i].label = parts[1]; } } + if ('PROTOCOL' === parts[0]) { devices[i].protocol = parts[1]; } + if ('DISKSIZE' === parts[0]) { devices[i].size = parseBytes(parts[1]); } + if ('FILESYSTEMPERSONALITY' === parts[0]) { devices[i].fsType = parts[1]; } + if ('MOUNTPOINT' === parts[0]) { devices[i].mount = parts[1]; } + if ('VOLUMEUUID' === parts[0]) { devices[i].uuid = parts[1]; } + if ('READ-ONLYMEDIA' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'CD/DVD'; } + if ('SOLIDSTATE' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'SSD'; } + if ('VIRTUAL' === parts[0]) { devices[i].type = 'virtual'; } + if ('REMOVABLEMEDIA' === parts[0]) { devices[i].removable = (parts[1] === 'Removable'); } + if ('PARTITIONTYPE' === parts[0]) { devices[i].type = 'part'; } + if ('DEVICE/MEDIANAME' === parts[0]) { devices[i].model = parts[1]; } } } } - return controllers; - } + }); + return devices; +} - function getNvidiaSmi() { - if (_nvidiaSmiPath) { - return _nvidiaSmiPath; +function parseBlk(lines) { + let data = []; + + lines.filter(line => line !== '').forEach((line) => { + try { + line = decodeURIComponent(line.replace(/\\x/g, '%')); + line = line.replace(/\\/g, '\\\\'); + let disk = JSON.parse(line); + data.push({ + 'name': disk.name, + 'type': disk.type, + 'fsType': disk.fsType, + 'mount': disk.mountpoint, + 'size': parseInt(disk.size), + 'physical': (disk.type === 'disk' ? (disk.rota === '0' ? 'SSD' : 'HDD') : (disk.type === 'rom' ? 'CD/DVD' : '')), + 'uuid': disk.uuid, + 'label': disk.label, + 'model': (disk.model || '').trim(), + 'serial': disk.serial, + 'removable': disk.rm === '1', + 'protocol': disk.tran, + 'group': disk.group || '', + }); + } catch (e) { + util$b.noop(); } + }); + data = util$b.unique(data); + data = util$b.sortByKey(data, ['type', 'name']); + return data; +} - if (_windows$b) { - try { - const basePath = util$c.WINDIR + '\\System32\\DriverStore\\FileRepository'; - // find all directories that have an nvidia-smi.exe file - const candidateDirs = fs$4.readdirSync(basePath).filter(dir => { - return fs$4.readdirSync([basePath, dir].join('/')).includes('nvidia-smi.exe'); - }); - // use the directory with the most recently created nvidia-smi.exe file - const targetDir = candidateDirs.reduce((prevDir, currentDir) => { - const previousNvidiaSmi = fs$4.statSync([basePath, prevDir, 'nvidia-smi.exe'].join('/')); - const currentNvidiaSmi = fs$4.statSync([basePath, currentDir, 'nvidia-smi.exe'].join('/')); - return (previousNvidiaSmi.ctimeMs > currentNvidiaSmi.ctimeMs) ? prevDir : currentDir; - }); +function decodeMdabmData(lines) { + const raid = util$b.getValue(lines, 'md_level', '='); + const label = util$b.getValue(lines, 'md_name', '='); // <- get label info + const uuid = util$b.getValue(lines, 'md_uuid', '='); // <- get uuid info + const members = []; + lines.forEach(line => { + if (line.toLowerCase().startsWith('md_device_dev') && line.toLowerCase().indexOf('/dev/') > 0) { + members.push(line.split('/dev/')[1]); + } + }); + return { + raid, + label, + uuid, + members + }; +} - if (targetDir) { - _nvidiaSmiPath = [basePath, targetDir, 'nvidia-smi.exe'].join('/'); +function raidMatchLinux(data) { + // for all block devices of type "raid%" + let result = data; + try { + data.forEach(element => { + if (element.type.startsWith('raid')) { + const lines = execSync$5(`mdadm --export --detail /dev/${element.name}`).toString().split('\n'); + const mdData = decodeMdabmData(lines); + + element.label = mdData.label; // <- assign label info + element.uuid = mdData.uuid; // <- assign uuid info + + if (mdData.members && mdData.members.length && mdData.raid === element.type) { + result = result.map(blockdevice => { + if (blockdevice.fsType === 'linux_raid_member' && mdData.members.indexOf(blockdevice.name) >= 0) { + blockdevice.group = element.name; + } + return blockdevice; + }); } - } catch (e) { - util$c.noop(); } - } else if (_linux$a) { - _nvidiaSmiPath = 'nvidia-smi'; - } - return _nvidiaSmiPath; + }); + } catch (e) { + util$b.noop(); } + return result; +} - function nvidiaSmi(options) { - const nvidiaSmiExe = getNvidiaSmi(); - options = options || util$c.execOptsWin; - if (nvidiaSmiExe) { - const nvidiaSmiOpts = '--query-gpu=driver_version,pci.sub_device_id,name,pci.bus_id,fan.speed,memory.total,memory.used,memory.free,utilization.gpu,utilization.memory,temperature.gpu,temperature.memory,power.draw,power.limit,clocks.gr,clocks.mem --format=csv,noheader,nounits'; - const cmd = nvidiaSmiExe + ' ' + nvidiaSmiOpts + (_linux$a ? ' 2>/dev/null' : ''); - try { - const res = execSync$6(cmd, options).toString(); - return res; - } catch (e) { - util$c.noop(); - } +function getDevicesLinux(data) { + const result = []; + data.forEach(element => { + if (element.type.startsWith('disk')) { + result.push(element.name); } - return ''; + }); + return result; +} + +function matchDevicesLinux(data) { + let result = data; + try { + const devices = getDevicesLinux(data); + result = result.map(blockdevice => { + if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk')) { + devices.forEach(element => { + if (blockdevice.name.startsWith(element)) { + blockdevice.device = '/dev/' + element; + } + }); + } + return blockdevice; + }); + } catch (e) { + util$b.noop(); } + return result; +} - function nvidiaDevices() { +function getDevicesMac(data) { + const result = []; + data.forEach(element => { + if (element.type.startsWith('disk')) { + result.push({ name: element.name, model: element.model, device: element.name }); + } + if (element.type.startsWith('virtual')) { + let device = ''; + result.forEach(e => { + if (e.model === element.model) { + device = e.device; + } + }); + if (device) { + result.push({ name: element.name, model: element.model, device }); + } + } + }); + return result; +} - function safeParseNumber(value) { - if ([null, undefined].includes(value)) { - return value; +function matchDevicesMac(data) { + let result = data; + try { + const devices = getDevicesMac(data); + result = result.map(blockdevice => { + if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk') || blockdevice.type.startsWith('virtual')) { + devices.forEach(element => { + if (blockdevice.name.startsWith(element.name)) { + blockdevice.device = element.device; + } + }); } - return parseFloat(value); + return blockdevice; + }); + } catch (e) { + util$b.noop(); + } + return result; +} + +function getDevicesWin(diskDrives) { + const result = []; + diskDrives.forEach(element => { + const lines = element.split('\r\n'); + const device = util$b.getValue(lines, 'DeviceID', ':'); + let partitions = element.split('@{DeviceID='); + if (partitions.length > 1) { + partitions = partitions.slice(1); + partitions.forEach(partition => { + result.push({ name: partition.split(';')[0].toUpperCase(), device }); + }); } + }); + return result; +} - const stdout = nvidiaSmi(); - if (!stdout) { - return []; +function matchDevicesWin(data, diskDrives) { + const devices = getDevicesWin(diskDrives); + data.map(element => { + const filteresDevices = devices.filter((e) => { return e.name === element.name.toUpperCase(); }); + if (filteresDevices.length > 0) { + element.device = filteresDevices[0].device; } + return element; + }); + return data; +} - const gpus = stdout.split('\n').filter(Boolean); - let results = gpus.map(gpu => { - const splittedData = gpu.split(', ').map(value => value.includes('N/A') ? undefined : value); - if (splittedData.length === 16) { - return { - driverVersion: splittedData[0], - subDeviceId: splittedData[1], - name: splittedData[2], - pciBus: splittedData[3], - fanSpeed: safeParseNumber(splittedData[4]), - memoryTotal: safeParseNumber(splittedData[5]), - memoryUsed: safeParseNumber(splittedData[6]), - memoryFree: safeParseNumber(splittedData[7]), - utilizationGpu: safeParseNumber(splittedData[8]), - utilizationMemory: safeParseNumber(splittedData[9]), - temperatureGpu: safeParseNumber(splittedData[10]), - temperatureMemory: safeParseNumber(splittedData[11]), - powerDraw: safeParseNumber(splittedData[12]), - powerLimit: safeParseNumber(splittedData[13]), - clockCore: safeParseNumber(splittedData[14]), - clockMemory: safeParseNumber(splittedData[15]), - }; - } else { - return {}; +function blkStdoutToObject(stdout) { + return stdout.toString() + .replace(/NAME=/g, '{"name":') + .replace(/FSTYPE=/g, ',"fsType":') + .replace(/TYPE=/g, ',"type":') + .replace(/SIZE=/g, ',"size":') + .replace(/MOUNTPOINT=/g, ',"mountpoint":') + .replace(/UUID=/g, ',"uuid":') + .replace(/ROTA=/g, ',"rota":') + .replace(/RO=/g, ',"ro":') + .replace(/RM=/g, ',"rm":') + .replace(/TRAN=/g, ',"tran":') + .replace(/SERIAL=/g, ',"serial":') + .replace(/LABEL=/g, ',"label":') + .replace(/MODEL=/g, ',"model":') + .replace(/OWNER=/g, ',"owner":') + .replace(/GROUP=/g, ',"group":') + .replace(/\n/g, '}\n'); +} + +function blockDevices(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + let data = []; + if (_linux$9) { + // see https://wiki.ubuntuusers.de/lsblk/ + // exec("lsblk -bo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,TRAN,SERIAL,LABEL,MODEL,OWNER,GROUP,MODE,ALIGNMENT,MIN-IO,OPT-IO,PHY-SEC,LOG-SEC,SCHED,RQ-SIZE,RA,WSAME", function (error, stdout) { + exec$9('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = blkStdoutToObject(stdout).split('\n'); + data = parseBlk(lines); + data = raidMatchLinux(data); + data = matchDevicesLinux(data); + if (callback) { + callback(data); + } + resolve(data); + } else { + exec$9('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = blkStdoutToObject(stdout).split('\n'); + data = parseBlk(lines); + data = raidMatchLinux(data); + } + if (callback) { + callback(data); + } + resolve(data); + }); + } + }); } + if (_darwin$9) { + exec$9('diskutil info -all', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + // parse lines into temp array of devices + data = parseDevices(lines); + data = matchDevicesMac(data); + } + if (callback) { + callback(data); + } + resolve(data); + }); + } + if (_sunos$8) { + if (callback) { callback(data); } + resolve(data); + } + if (_windows$a) { + let drivetypes = ['Unknown', 'NoRoot', 'Removable', 'Local', 'Network', 'CD/DVD', 'RAM']; + try { + // util.wmic('logicaldisk get Caption,Description,DeviceID,DriveType,FileSystem,FreeSpace,Name,Size,VolumeName,VolumeSerialNumber /value').then((stdout, error) => { + // util.powerShell('Get-CimInstance Win32_logicaldisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl').then((stdout, error) => { + const workload = []; + workload.push(util$b.powerShell('Get-CimInstance -ClassName Win32_LogicalDisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl')); + workload.push(util$b.powerShell('Get-WmiObject -Class Win32_diskdrive | Select-Object -Property PNPDeviceId,DeviceID, Model, Size, @{L=\'Partitions\'; E={$_.GetRelated(\'Win32_DiskPartition\').GetRelated(\'Win32_LogicalDisk\') | Select-Object -Property DeviceID, VolumeName, Size, FreeSpace}} | fl')); + util$b.promiseAll( + workload + ).then((res) => { + let logicalDisks = res.results[0].toString().split(/\n\s*\n/); + let diskDrives = res.results[1].toString().split(/\n\s*\n/); + logicalDisks.forEach(function (device) { + let lines = device.split('\r\n'); + let drivetype = util$b.getValue(lines, 'drivetype', ':'); + if (drivetype) { + data.push({ + name: util$b.getValue(lines, 'name', ':'), + identifier: util$b.getValue(lines, 'caption', ':'), + type: 'disk', + fsType: util$b.getValue(lines, 'filesystem', ':').toLowerCase(), + mount: util$b.getValue(lines, 'caption', ':'), + size: util$b.getValue(lines, 'size', ':'), + physical: (drivetype >= 0 && drivetype <= 6) ? drivetypes[drivetype] : drivetypes[0], + uuid: util$b.getValue(lines, 'volumeserialnumber', ':'), + label: util$b.getValue(lines, 'volumename', ':'), + model: '', + serial: util$b.getValue(lines, 'volumeserialnumber', ':'), + removable: drivetype === '2', + protocol: '', + group: '', + device: '' + }); + } + }); + // match devices + data = matchDevicesWin(data, diskDrives); + if (callback) { + callback(data); + } + resolve(data); + }); + } catch (e) { + if (callback) { callback(data); } + resolve(data); + } + } + if (_freebsd$8 || _openbsd$8 || _netbsd$8) { + // will follow + if (callback) { callback(null); } + resolve(null); + } + }); - results = results.filter((item) => { - return ('pciBus' in item); - }); - return results; + }); +} + +filesystem.blockDevices = blockDevices; + +// -------------------------- +// FS - speed + +function calcFsSpeed(rx, wx) { + let result = { + rx: 0, + wx: 0, + tx: 0, + rx_sec: null, + wx_sec: null, + tx_sec: null, + ms: 0 + }; + + if (_fs_speed && _fs_speed.ms) { + result.rx = rx; + result.wx = wx; + result.tx = result.rx + result.wx; + result.ms = Date.now() - _fs_speed.ms; + result.rx_sec = (result.rx - _fs_speed.bytes_read) / (result.ms / 1000); + result.wx_sec = (result.wx - _fs_speed.bytes_write) / (result.ms / 1000); + result.tx_sec = result.rx_sec + result.wx_sec; + _fs_speed.rx_sec = result.rx_sec; + _fs_speed.wx_sec = result.wx_sec; + _fs_speed.tx_sec = result.tx_sec; + _fs_speed.bytes_read = result.rx; + _fs_speed.bytes_write = result.wx; + _fs_speed.bytes_overall = result.rx + result.wx; + _fs_speed.ms = Date.now(); + _fs_speed.last_ms = result.ms; + } else { + result.rx = rx; + result.wx = wx; + result.tx = result.rx + result.wx; + _fs_speed.rx_sec = null; + _fs_speed.wx_sec = null; + _fs_speed.tx_sec = null; + _fs_speed.bytes_read = result.rx; + _fs_speed.bytes_write = result.wx; + _fs_speed.bytes_overall = result.rx + result.wx; + _fs_speed.ms = Date.now(); + _fs_speed.last_ms = 0; } + return result; +} - function mergeControllerNvidia(controller, nvidia) { - if (nvidia.driverVersion) { controller.driverVersion = nvidia.driverVersion; } - if (nvidia.subDeviceId) { controller.subDeviceId = nvidia.subDeviceId; } - if (nvidia.name) { controller.name = nvidia.name; } - if (nvidia.pciBus) { controller.pciBus = nvidia.pciBus; } - if (nvidia.fanSpeed) { controller.fanSpeed = nvidia.fanSpeed; } - if (nvidia.memoryTotal) { - controller.memoryTotal = nvidia.memoryTotal; - controller.vram = nvidia.memoryTotal; - controller.vramDynamic = false; - } - if (nvidia.memoryUsed) { controller.memoryUsed = nvidia.memoryUsed; } - if (nvidia.memoryFree) { controller.memoryFree = nvidia.memoryFree; } - if (nvidia.utilizationGpu) { controller.utilizationGpu = nvidia.utilizationGpu; } - if (nvidia.utilizationMemory) { controller.utilizationMemory = nvidia.utilizationMemory; } - if (nvidia.temperatureGpu) { controller.temperatureGpu = nvidia.temperatureGpu; } - if (nvidia.temperatureMemory) { controller.temperatureMemory = nvidia.temperatureMemory; } - if (nvidia.powerDraw) { controller.powerDraw = nvidia.powerDraw; } - if (nvidia.powerLimit) { controller.powerLimit = nvidia.powerLimit; } - if (nvidia.clockCore) { controller.clockCore = nvidia.clockCore; } - if (nvidia.clockMemory) { controller.clockMemory = nvidia.clockMemory; } - return controller; - } +function fsStats(callback) { - function parseLinesLinuxEdid(edid) { - // parsen EDID - // --> model - // --> resolutionx - // --> resolutiony - // --> builtin = false - // --> pixeldepth (?) - // --> sizex - // --> sizey - let result = { - vendor: '', - model: '', - deviceName: '', - main: false, - builtin: false, - connection: '', - sizeX: null, - sizeY: null, - pixelDepth: null, - resolutionX: null, - resolutionY: null, - currentResX: null, - currentResY: null, - positionX: 0, - positionY: 0, - currentRefreshRate: null - }; - // find first "Detailed Timing Description" - let start = 108; - if (edid.substr(start, 6) === '000000') { - start += 36; - } - if (edid.substr(start, 6) === '000000') { - start += 36; - } - if (edid.substr(start, 6) === '000000') { - start += 36; - } - if (edid.substr(start, 6) === '000000') { - start += 36; - } - result.resolutionX = parseInt('0x0' + edid.substr(start + 8, 1) + edid.substr(start + 4, 2)); - result.resolutionY = parseInt('0x0' + edid.substr(start + 14, 1) + edid.substr(start + 10, 2)); - result.sizeX = parseInt('0x0' + edid.substr(start + 28, 1) + edid.substr(start + 24, 2)); - result.sizeY = parseInt('0x0' + edid.substr(start + 29, 1) + edid.substr(start + 26, 2)); - // monitor name - start = edid.indexOf('000000fc00'); // find first "Monitor Description Data" - if (start >= 0) { - let model_raw = edid.substr(start + 10, 26); - if (model_raw.indexOf('0a') !== -1) { - model_raw = model_raw.substr(0, model_raw.indexOf('0a')); - } - try { - if (model_raw.length > 2) { - result.model = model_raw.match(/.{1,2}/g).map(function (v) { - return String.fromCharCode(parseInt(v, 16)); - }).join(''); - } - } catch (e) { - util$c.noop(); + return new Promise((resolve) => { + process.nextTick(() => { + if (_windows$a || _freebsd$8 || _openbsd$8 || _netbsd$8 || _sunos$8) { + return resolve(null); } - } else { - result.model = ''; - } - return result; - } - function parseLinesLinuxDisplays(lines, depth) { - let displays = []; - let currentDisplay = { - vendor: '', - model: '', - deviceName: '', - main: false, - builtin: false, - connection: '', - sizeX: null, - sizeY: null, - pixelDepth: null, - resolutionX: null, - resolutionY: null, - currentResX: null, - currentResY: null, - positionX: 0, - positionY: 0, - currentRefreshRate: null - }; - let is_edid = false; - let is_current = false; - let edid_raw = ''; - let start = 0; - for (let i = 1; i < lines.length; i++) { // start with second line - if ('' !== lines[i].trim()) { - if (' ' !== lines[i][0] && '\t' !== lines[i][0] && lines[i].toLowerCase().indexOf(' connected ') !== -1) { // first line of new entry - if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // push last display to array - displays.push(currentDisplay); - currentDisplay = { - vendor: '', - model: '', - main: false, - builtin: false, - connection: '', - sizeX: null, - sizeY: null, - pixelDepth: null, - resolutionX: null, - resolutionY: null, - currentResX: null, - currentResY: null, - positionX: 0, - positionY: 0, - currentRefreshRate: null - }; - } - let parts = lines[i].split(' '); - currentDisplay.connection = parts[0]; - currentDisplay.main = lines[i].toLowerCase().indexOf(' primary ') >= 0; - currentDisplay.builtin = (parts[0].toLowerCase().indexOf('edp') >= 0); - } + let result = { + rx: 0, + wx: 0, + tx: 0, + rx_sec: null, + wx_sec: null, + tx_sec: null, + ms: 0 + }; - // try to read EDID information - if (is_edid) { - if (lines[i].search(/\S|$/) > start) { - edid_raw += lines[i].toLowerCase().trim(); - } else { - // parsen EDID - let edid_decoded = parseLinesLinuxEdid(edid_raw); - currentDisplay.vendor = edid_decoded.vendor; - currentDisplay.model = edid_decoded.model; - currentDisplay.resolutionX = edid_decoded.resolutionX; - currentDisplay.resolutionY = edid_decoded.resolutionY; - currentDisplay.sizeX = edid_decoded.sizeX; - currentDisplay.sizeY = edid_decoded.sizeY; - currentDisplay.pixelDepth = depth; - is_edid = false; - } - } - if (lines[i].toLowerCase().indexOf('edid:') >= 0) { - is_edid = true; - start = lines[i].search(/\S|$/); + let rx = 0; + let wx = 0; + if ((_fs_speed && !_fs_speed.ms) || (_fs_speed && _fs_speed.ms && Date.now() - _fs_speed.ms >= 500)) { + if (_linux$9) { + // exec("df -k | grep /dev/", function(error, stdout) { + exec$9('lsblk -r 2>/dev/null | grep /', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + let fs_filter = []; + lines.forEach(function (line) { + if (line !== '') { + line = line.trim().split(' '); + if (fs_filter.indexOf(line[0]) === -1) { fs_filter.push(line[0]); } + } + }); + + let output = fs_filter.join('|'); + exec$9('cat /proc/diskstats | egrep "' + output + '"', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + lines.forEach(function (line) { + line = line.trim(); + if (line !== '') { + line = line.replace(/ +/g, ' ').split(' '); + + rx += parseInt(line[5]) * 512; + wx += parseInt(line[9]) * 512; + } + }); + result = calcFsSpeed(rx, wx); + } + if (callback) { + callback(result); + } + resolve(result); + }); + } else { + if (callback) { + callback(result); + } + resolve(result); + } + }); } - if (lines[i].toLowerCase().indexOf('*current') >= 0) { - const parts1 = lines[i].split('('); - if (parts1 && parts1.length > 1 && parts1[0].indexOf('x') >= 0) { - const resParts = parts1[0].trim().split('x'); - currentDisplay.currentResX = util$c.toInt(resParts[0]); - currentDisplay.currentResY = util$c.toInt(resParts[1]); - } - is_current = true; + if (_darwin$9) { + exec$9('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + lines.forEach(function (line) { + line = line.trim(); + if (line !== '') { + line = line.split(','); + + rx += parseInt(line[2]); + wx += parseInt(line[9]); + } + }); + result = calcFsSpeed(rx, wx); + } + if (callback) { + callback(result); + } + resolve(result); + }); } - if (is_current && lines[i].toLowerCase().indexOf('clock') >= 0 && lines[i].toLowerCase().indexOf('hz') >= 0 && lines[i].toLowerCase().indexOf('v: height') >= 0) { - const parts1 = lines[i].split('clock'); - if (parts1 && parts1.length > 1 && parts1[1].toLowerCase().indexOf('hz') >= 0) { - currentDisplay.currentRefreshRate = util$c.toInt(parts1[1]); - } - is_current = false; + } else { + result.ms = _fs_speed.last_ms; + result.rx = _fs_speed.bytes_read; + result.wx = _fs_speed.bytes_write; + result.tx = _fs_speed.bytes_read + _fs_speed.bytes_write; + result.rx_sec = _fs_speed.rx_sec; + result.wx_sec = _fs_speed.wx_sec; + result.tx_sec = _fs_speed.tx_sec; + if (callback) { + callback(result); } + resolve(result); } - } + }); + }); +} - // pushen displays - if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // still information there - displays.push(currentDisplay); - } - return displays; +filesystem.fsStats = fsStats; + +function calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime) { + let result = { + rIO: 0, + wIO: 0, + tIO: 0, + rIO_sec: null, + wIO_sec: null, + tIO_sec: null, + rWaitTime: 0, + wWaitTime: 0, + tWaitTime: 0, + rWaitPercent: null, + wWaitPercent: null, + tWaitPercent: null, + ms: 0 + }; + if (_disk_io && _disk_io.ms) { + result.rIO = rIO; + result.wIO = wIO; + result.tIO = rIO + wIO; + result.ms = Date.now() - _disk_io.ms; + result.rIO_sec = (result.rIO - _disk_io.rIO) / (result.ms / 1000); + result.wIO_sec = (result.wIO - _disk_io.wIO) / (result.ms / 1000); + result.tIO_sec = result.rIO_sec + result.wIO_sec; + result.rWaitTime = rWaitTime; + result.wWaitTime = wWaitTime; + result.tWaitTime = tWaitTime; + result.rWaitPercent = (result.rWaitTime - _disk_io.rWaitTime) * 100 / (result.ms); + result.wWaitPercent = (result.wWaitTime - _disk_io.wWaitTime) * 100 / (result.ms); + result.tWaitPercent = (result.tWaitTime - _disk_io.tWaitTime) * 100 / (result.ms); + _disk_io.rIO = rIO; + _disk_io.wIO = wIO; + _disk_io.rIO_sec = result.rIO_sec; + _disk_io.wIO_sec = result.wIO_sec; + _disk_io.tIO_sec = result.tIO_sec; + _disk_io.rWaitTime = rWaitTime; + _disk_io.wWaitTime = wWaitTime; + _disk_io.tWaitTime = tWaitTime; + _disk_io.rWaitPercent = result.rWaitPercent; + _disk_io.wWaitPercent = result.wWaitPercent; + _disk_io.tWaitPercent = result.tWaitPercent; + _disk_io.last_ms = result.ms; + _disk_io.ms = Date.now(); + } else { + result.rIO = rIO; + result.wIO = wIO; + result.tIO = rIO + wIO; + result.rWaitTime = rWaitTime; + result.wWaitTime = wWaitTime; + result.tWaitTime = tWaitTime; + _disk_io.rIO = rIO; + _disk_io.wIO = wIO; + _disk_io.rIO_sec = null; + _disk_io.wIO_sec = null; + _disk_io.tIO_sec = null; + _disk_io.rWaitTime = rWaitTime; + _disk_io.wWaitTime = wWaitTime; + _disk_io.tWaitTime = tWaitTime; + _disk_io.rWaitPercent = null; + _disk_io.wWaitPercent = null; + _disk_io.tWaitPercent = null; + _disk_io.last_ms = 0; + _disk_io.ms = Date.now(); } + return result; +} + +function disksIO(callback) { - // function starts here return new Promise((resolve) => { process.nextTick(() => { + if (_windows$a) { + return resolve(null); + } + if (_sunos$8) { + return resolve(null); + } + let result = { - controllers: [], - displays: [] + rIO: 0, + wIO: 0, + tIO: 0, + rIO_sec: null, + wIO_sec: null, + tIO_sec: null, + rWaitTime: 0, + wWaitTime: 0, + tWaitTime: 0, + rWaitPercent: null, + wWaitPercent: null, + tWaitPercent: null, + ms: 0 }; - if (_darwin$a) { - let cmd = 'system_profiler -xml -detailLevel full SPDisplaysDataType'; - exec$a(cmd, function (error, stdout) { - if (!error) { - try { - const output = stdout.toString(); - result = parseLinesDarwin(util$c.plistParser(output)[0]._items); - } catch (e) { - util$c.noop(); - } - try { - stdout = execSync$6('defaults read /Library/Preferences/com.apple.windowserver.plist 2>/dev/null;defaults read /Library/Preferences/com.apple.windowserver.displays.plist 2>/dev/null; echo ""', { maxBuffer: 1024 * 20000 }); - const output = (stdout || '').toString(); - const obj = util$c.plistReader(output); - if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets']['Configs'] && obj['DisplayAnyUserSets']['Configs'][0] && obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig']) { - const current = obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig']; - let i = 0; - current.forEach((o) => { - if (o['CurrentInfo'] && o['CurrentInfo']['OriginX'] !== undefined && result.displays && result.displays[i]) { - result.displays[i].positionX = o['CurrentInfo']['OriginX']; - } - if (o['CurrentInfo'] && o['CurrentInfo']['OriginY'] !== undefined && result.displays && result.displays[i]) { - result.displays[i].positionY = o['CurrentInfo']['OriginY']; - } - i++; - }); - } - if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets'].length > 0 && obj['DisplayAnyUserSets'][0].length > 0 && obj['DisplayAnyUserSets'][0][0]['DisplayID']) { - const current = obj['DisplayAnyUserSets'][0]; - let i = 0; - current.forEach((o) => { - if ('OriginX' in o && result.displays && result.displays[i]) { - result.displays[i].positionX = o['OriginX']; - } - if ('OriginY' in o && result.displays && result.displays[i]) { - result.displays[i].positionY = o['OriginY']; - } - if (o['Mode'] && o['Mode']['BitsPerPixel'] !== undefined && result.displays && result.displays[i]) { - result.displays[i].pixelDepth = o['Mode']['BitsPerPixel']; - } - i++; - }); + let rIO = 0; + let wIO = 0; + let rWaitTime = 0; + let wWaitTime = 0; + let tWaitTime = 0; + + if ((_disk_io && !_disk_io.ms) || (_disk_io && _disk_io.ms && Date.now() - _disk_io.ms >= 500)) { + if (_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) { + // prints Block layer statistics for all mounted volumes + // var cmd = "for mount in `lsblk | grep / | sed -r 's/│ └─//' | cut -d ' ' -f 1`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done"; + // var cmd = "for mount in `lsblk | grep / | sed 's/[│└─├]//g' | awk '{$1=$1};1' | cut -d ' ' -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done"; + let cmd = 'for mount in `lsblk 2>/dev/null | grep " disk " | sed "s/[│└─├]//g" | awk \'{$1=$1};1\' | cut -d " " -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r "s/ +/;/g" | sed -r "s/^;//"; done'; + + exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = stdout.split('\n'); + lines.forEach(function (line) { + // ignore empty lines + if (!line) { return; } + + // sum r/wIO of all disks to compute all disks IO + let stats = line.split(';'); + rIO += parseInt(stats[0]); + wIO += parseInt(stats[4]); + rWaitTime += parseInt(stats[3]); + wWaitTime += parseInt(stats[7]); + tWaitTime += parseInt(stats[10]); + }); + result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime); + + if (callback) { + callback(result); } - } catch (e) { - util$c.noop(); - } - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_linux$a) { - // Raspberry: https://elinux.org/RPI_vcgencmd_usage - if (util$c.isRaspberry() && util$c.isRaspbian()) { - let cmd = 'fbset -s | grep \'mode "\'; vcgencmd get_mem gpu; tvservice -s; tvservice -n;'; - exec$a(cmd, function (error, stdout) { - let lines = stdout.toString().split('\n'); - if (lines.length > 3 && lines[0].indexOf('mode "') >= -1 && lines[2].indexOf('0x12000a') > -1) { - const parts = lines[0].replace('mode', '').replace(/"/g, '').trim().split('x'); - if (parts.length === 2) { - result.displays.push({ - vendor: '', - model: util$c.getValue(lines, 'device_name', '='), - main: true, - builtin: false, - connection: 'HDMI', - sizeX: null, - sizeY: null, - pixelDepth: null, - resolutionX: parseInt(parts[0], 10), - resolutionY: parseInt(parts[1], 10), - currentResX: null, - currentResY: null, - positionX: 0, - positionY: 0, - currentRefreshRate: null - }); + resolve(result); + } else { + if (callback) { + callback(result); } + resolve(result); } - if (lines.length > 1 && stdout.toString().indexOf('gpu=') >= -1) { - result.controllers.push({ - vendor: 'Broadcom', - model: util$c.getRpiGpu(), - bus: '', - vram: util$c.getValue(lines, 'gpu', '=').replace('M', ''), - vramDynamic: true + }); + } + if (_darwin$9) { + exec$9('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + lines.forEach(function (line) { + line = line.trim(); + if (line !== '') { + line = line.split(','); + + rIO += parseInt(line[10]); + wIO += parseInt(line[0]); + } }); + result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime); } if (callback) { callback(result); } resolve(result); }); - } else { - let cmd = 'lspci -vvv 2>/dev/null'; - exec$a(cmd, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - result.controllers = parseLinesLinuxControllers(lines); - const nvidiaData = nvidiaDevices(); - // needs to be rewritten ... using no spread operators - result.controllers = result.controllers.map((controller) => { // match by busAddress - return mergeControllerNvidia(controller, nvidiaData.find((contr) => contr.pciBus.toLowerCase().endsWith(controller.busAddress.toLowerCase())) || {}); - }); - } - let cmd = 'clinfo --raw'; - exec$a(cmd, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - result.controllers = parseLinesLinuxClinfo(result.controllers, lines); - } - let cmd = 'xdpyinfo 2>/dev/null | grep \'depth of root window\' | awk \'{ print $5 }\''; - exec$a(cmd, function (error, stdout) { - let depth = 0; - if (!error) { - let lines = stdout.toString().split('\n'); - depth = parseInt(lines[0]) || 0; - } - let cmd = 'xrandr --verbose 2>/dev/null'; - exec$a(cmd, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - result.displays = parseLinesLinuxDisplays(lines, depth); - } - if (callback) { - callback(result); - } - resolve(result); - }); - }); - }); - }); } + } else { + result.rIO = _disk_io.rIO; + result.wIO = _disk_io.wIO; + result.tIO = _disk_io.rIO + _disk_io.wIO; + result.ms = _disk_io.last_ms; + result.rIO_sec = _disk_io.rIO_sec; + result.wIO_sec = _disk_io.wIO_sec; + result.tIO_sec = _disk_io.tIO_sec; + result.rWaitTime = _disk_io.rWaitTime; + result.wWaitTime = _disk_io.wWaitTime; + result.tWaitTime = _disk_io.tWaitTime; + result.rWaitPercent = _disk_io.rWaitPercent; + result.wWaitPercent = _disk_io.wWaitPercent; + result.tWaitPercent = _disk_io.tWaitPercent; + if (callback) { + callback(result); + } + resolve(result); } - if (_freebsd$9 || _openbsd$9 || _netbsd$9) { - if (callback) { callback(null); } - resolve(null); - } - if (_sunos$9) { - if (callback) { callback(null); } - resolve(null); - } - if (_windows$b) { + }); + }); +} - // https://blogs.technet.microsoft.com/heyscriptingguy/2013/10/03/use-powershell-to-discover-multi-monitor-information/ - // https://devblogs.microsoft.com/scripting/use-powershell-to-discover-multi-monitor-information/ - try { - const workload = []; - workload.push(util$c.powerShell('Get-CimInstance win32_VideoController | fl *')); - workload.push(util$c.powerShell('gp "HKLM:\\SYSTEM\\ControlSet001\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}\\*" -ErrorAction SilentlyContinue | where MatchingDeviceId $null -NE | select MatchingDeviceId,HardwareInformation.qwMemorySize | fl')); - workload.push(util$c.powerShell('Get-CimInstance win32_desktopmonitor | fl *')); - workload.push(util$c.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorBasicDisplayParams | fl')); - workload.push(util$c.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Screen]::AllScreens')); - workload.push(util$c.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorConnectionParams | fl')); - workload.push(util$c.powerShell('gwmi WmiMonitorID -Namespace root\\wmi | ForEach-Object {(($_.ManufacturerName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.ProductCodeID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.UserFriendlyName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.SerialNumberID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + $_.InstanceName}')); +filesystem.disksIO = disksIO; - const nvidiaData = nvidiaDevices(); +function diskLayout(callback) { - Promise.all( - workload - ).then((data) => { - // controller + vram - let csections = data[0].replace(/\r/g, '').split(/\n\s*\n/); - let vsections = data[1].replace(/\r/g, '').split(/\n\s*\n/); - result.controllers = parseLinesWindowsControllers(csections, vsections); - result.controllers = result.controllers.map((controller) => { // match by subDeviceId - if (controller.vendor.toLowerCase() === 'nvidia') { - return mergeControllerNvidia(controller, nvidiaData.find(device => { - let windowsSubDeviceId = (controller.subDeviceId || '').toLowerCase(); - const nvidiaSubDeviceIdParts = device.subDeviceId.split('x'); - let nvidiaSubDeviceId = nvidiaSubDeviceIdParts.length > 1 ? nvidiaSubDeviceIdParts[1].toLowerCase() : nvidiaSubDeviceIdParts[0].toLowerCase(); - const lengthDifference = Math.abs(windowsSubDeviceId.length - nvidiaSubDeviceId.length); - if (windowsSubDeviceId.length > nvidiaSubDeviceId.length) { - for (let i = 0; i < lengthDifference; i++) { - nvidiaSubDeviceId = '0' + nvidiaSubDeviceId; - } - } else if (windowsSubDeviceId.length < nvidiaSubDeviceId.length) { - for (let i = 0; i < lengthDifference; i++) { - windowsSubDeviceId = '0' + windowsSubDeviceId; - } - } - return windowsSubDeviceId === nvidiaSubDeviceId; - }) || {}); - } else { - return controller; - } - }); + function getVendorFromModel(model) { + const diskManufacturers = [ + { pattern: 'WESTERN.*', manufacturer: 'Western Digital' }, + { pattern: '^WDC.*', manufacturer: 'Western Digital' }, + { pattern: 'WD.*', manufacturer: 'Western Digital' }, + { pattern: 'TOSHIBA.*', manufacturer: 'Toshiba' }, + { pattern: 'HITACHI.*', manufacturer: 'Hitachi' }, + { pattern: '^IC.*', manufacturer: 'Hitachi' }, + { pattern: '^HTS.*', manufacturer: 'Hitachi' }, + { pattern: 'SANDISK.*', manufacturer: 'SanDisk' }, + { pattern: 'KINGSTON.*', manufacturer: 'Kingston Technology' }, + { pattern: '^SONY.*', manufacturer: 'Sony' }, + { pattern: 'TRANSCEND.*', manufacturer: 'Transcend' }, + { pattern: 'SAMSUNG.*', manufacturer: 'Samsung' }, + { pattern: '^ST(?!I\\ ).*', manufacturer: 'Seagate' }, + { pattern: '^STI\\ .*', manufacturer: 'SimpleTech' }, + { pattern: '^D...-.*', manufacturer: 'IBM' }, + { pattern: '^IBM.*', manufacturer: 'IBM' }, + { pattern: '^FUJITSU.*', manufacturer: 'Fujitsu' }, + { pattern: '^MP.*', manufacturer: 'Fujitsu' }, + { pattern: '^MK.*', manufacturer: 'Toshiba' }, + { pattern: 'MAXTO.*', manufacturer: 'Maxtor' }, + { pattern: 'PIONEER.*', manufacturer: 'Pioneer' }, + { pattern: 'PHILIPS.*', manufacturer: 'Philips' }, + { pattern: 'QUANTUM.*', manufacturer: 'Quantum Technology' }, + { pattern: 'FIREBALL.*', manufacturer: 'Quantum Technology' }, + { pattern: '^VBOX.*', manufacturer: 'VirtualBox' }, + { pattern: 'CORSAIR.*', manufacturer: 'Corsair Components' }, + { pattern: 'CRUCIAL.*', manufacturer: 'Crucial' }, + { pattern: 'ECM.*', manufacturer: 'ECM' }, + { pattern: 'INTEL.*', manufacturer: 'INTEL' }, + { pattern: 'EVO.*', manufacturer: 'Samsung' }, + { pattern: 'APPLE.*', manufacturer: 'Apple' }, + ]; - // displays - let dsections = data[2].replace(/\r/g, '').split(/\n\s*\n/); - // result.displays = parseLinesWindowsDisplays(dsections); - if (dsections[0].trim() === '') { dsections.shift(); } - if (dsections.length && dsections[dsections.length - 1].trim() === '') { dsections.pop(); } + let result = ''; + if (model) { + model = model.toUpperCase(); + diskManufacturers.forEach((manufacturer) => { + const re = RegExp(manufacturer.pattern); + if (re.test(model)) { result = manufacturer.manufacturer; } + }); + } + return result; + } - // monitor (powershell) - let msections = data[3].replace(/\r/g, '').split('Active '); - msections.shift(); + return new Promise((resolve) => { + process.nextTick(() => { - // forms.screens (powershell) - let ssections = data[4].replace(/\r/g, '').split('BitsPerPixel '); - ssections.shift(); + const commitResult = res => { + for (let i = 0; i < res.length; i++) { + delete res[i].BSDName; + } + if (callback) { + callback(res); + } + resolve(res); + }; - // connection params (powershell) - video type - let tsections = data[5].replace(/\r/g, '').split(/\n\s*\n/); - tsections.shift(); + let result = []; + let cmd = ''; - // monitor ID (powershell) - model / vendor - const res = data[6].replace(/\r/g, '').split(/\n/); - let isections = []; - res.forEach(element => { - const parts = element.split('|'); - if (parts.length === 5) { - isections.push({ - vendor: parts[0], - code: parts[1], - model: parts[2], - serial: parts[3], - instanceId: parts[4] + if (_linux$9) { + let cmdFullSmart = ''; + + exec$9('export LC_ALL=C; lsblk -ablJO 2>/dev/null; unset LC_ALL', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + try { + const out = stdout.toString().trim(); + let devices = []; + try { + const outJSON = JSON.parse(out); + if (outJSON && {}.hasOwnProperty.call(outJSON, 'blockdevices')) { + devices = outJSON.blockdevices.filter(item => { return (item.type === 'disk') && item.size > 0 && (item.model !== null || (item.mountpoint === null && item.label === null && item.fstype === null && item.parttype === null && item.path && item.path.indexOf('/ram') !== 0 && item.path.indexOf('/loop') !== 0 && item['disc-max'] && item['disc-max'] !== 0)); }); + } + } catch (e) { + // fallback to older version of lsblk + try { + const out2 = execSync$5('export LC_ALL=C; lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER,GROUP 2>/dev/null; unset LC_ALL').toString(); + let lines = blkStdoutToObject(out2).split('\n'); + const data = parseBlk(lines); + devices = data.filter(item => { return (item.type === 'disk') && item.size > 0 && ((item.model !== null && item.model !== '') || (item.mount === '' && item.label === '' && item.fsType === '')); }); + } catch (e) { + util$b.noop(); + } + } + devices.forEach((device) => { + let mediumType = ''; + const BSDName = '/dev/' + device.name; + const logical = device.name; + try { + mediumType = execSync$5('cat /sys/block/' + logical + '/queue/rotational 2>/dev/null').toString().split('\n')[0]; + } catch (e) { + util$b.noop(); + } + let interfaceType = device.tran ? device.tran.toUpperCase().trim() : ''; + if (interfaceType === 'NVME') { + mediumType = '2'; + interfaceType = 'PCIe'; + } + result.push({ + device: BSDName, + type: (mediumType === '0' ? 'SSD' : (mediumType === '1' ? 'HD' : (mediumType === '2' ? 'NVMe' : (device.model && device.model.indexOf('SSD') > -1 ? 'SSD' : (device.model && device.model.indexOf('NVM') > -1 ? 'NVMe' : 'HD'))))), + name: device.model || '', + vendor: getVendorFromModel(device.model) || (device.vendor ? device.vendor.trim() : ''), + size: device.size || 0, + bytesPerSector: null, + totalCylinders: null, + totalHeads: null, + totalSectors: null, + totalTracks: null, + tracksPerCylinder: null, + sectorsPerTrack: null, + firmwareRevision: device.rev ? device.rev.trim() : '', + serialNum: device.serial ? device.serial.trim() : '', + interfaceType: interfaceType, + smartStatus: 'unknown', + temperature: null, + BSDName: BSDName + }); + cmd += `printf "\n${BSDName}|"; smartctl -H ${BSDName} | grep overall;`; + cmdFullSmart += `${cmdFullSmart ? 'printf ",";' : ''}smartctl -a -j ${BSDName};`; + }); + } catch (e) { + util$b.noop(); + } + } + // check S.M.A.R.T. status + if (cmdFullSmart) { + exec$9(cmdFullSmart, { maxBuffer: 1024 * 1024 }, function (error, stdout) { + try { + const data = JSON.parse(`[${stdout}]`); + data.forEach(disk => { + const diskBSDName = disk.smartctl.argv[disk.smartctl.argv.length - 1]; + + for (let i = 0; i < result.length; i++) { + if (result[i].BSDName === diskBSDName) { + result[i].smartStatus = (disk.smart_status.passed ? 'Ok' : (disk.smart_status.passed === false ? 'Predicted Failure' : 'unknown')); + if (disk.temperature && disk.temperature.current) { + result[i].temperature = disk.temperature.current; + } + result[i].smartData = disk; + } + } }); + commitResult(result); + } catch (e) { + if (cmd) { + cmd = cmd + 'printf "\n"'; + exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { + let lines = stdout.toString().split('\n'); + lines.forEach(line => { + if (line) { + let parts = line.split('|'); + if (parts.length === 2) { + let BSDName = parts[0]; + parts[1] = parts[1].trim(); + let parts2 = parts[1].split(':'); + if (parts2.length === 2) { + parts2[1] = parts2[1].trim(); + let status = parts2[1].toLowerCase(); + for (let i = 0; i < result.length; i++) { + if (result[i].BSDName === BSDName) { + result[i].smartStatus = (status === 'passed' ? 'Ok' : (status === 'failed!' ? 'Predicted Failure' : 'unknown')); + } + } + } + } + } + }); + commitResult(result); + }); + } else { + commitResult(result); + } } }); + } else { + commitResult(result); + } + }); + } + if (_freebsd$8 || _openbsd$8 || _netbsd$8) { + if (callback) { callback(result); } + resolve(result); + } + if (_sunos$8) { + if (callback) { callback(result); } + resolve(result); + } + if (_darwin$9) { + exec$9('system_profiler SPSerialATADataType SPNVMeDataType SPUSBDataType', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (!error) { + // split by type: + let lines = stdout.toString().split('\n'); + let linesSATA = []; + let linesNVMe = []; + let linesUSB = []; + let dataType = 'SATA'; + lines.forEach(line => { + if (line === 'NVMExpress:') { dataType = 'NVMe'; } + else if (line === 'USB:') { dataType = 'USB'; } + else if (line === 'SATA/SATA Express:') { dataType = 'SATA'; } + else if (dataType === 'SATA') { linesSATA.push(line); } + else if (dataType === 'NVMe') { linesNVMe.push(line); } + else if (dataType === 'USB') { linesUSB.push(line); } + }); + try { + // Serial ATA Drives + let devices = linesSATA.join('\n').split(' Physical Interconnect: '); + devices.shift(); + devices.forEach(function (device) { + device = 'InterfaceType: ' + device; + let lines = device.split('\n'); + const mediumType = util$b.getValue(lines, 'Medium Type', ':', true).trim(); + const sizeStr = util$b.getValue(lines, 'capacity', ':', true).trim(); + const BSDName = util$b.getValue(lines, 'BSD Name', ':', true).trim(); + if (sizeStr) { + let sizeValue = 0; + if (sizeStr.indexOf('(') >= 0) { + sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, '')); + } + if (!sizeValue) { + sizeValue = parseInt(sizeStr); + } + if (sizeValue) { + const smartStatusString = util$b.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase(); + result.push({ + device: BSDName, + type: mediumType.startsWith('Solid') ? 'SSD' : 'HD', + name: util$b.getValue(lines, 'Model', ':', true).trim(), + vendor: getVendorFromModel(util$b.getValue(lines, 'Model', ':', true).trim()) || util$b.getValue(lines, 'Manufacturer', ':', true), + size: sizeValue, + bytesPerSector: null, + totalCylinders: null, + totalHeads: null, + totalSectors: null, + totalTracks: null, + tracksPerCylinder: null, + sectorsPerTrack: null, + firmwareRevision: util$b.getValue(lines, 'Revision', ':', true).trim(), + serialNum: util$b.getValue(lines, 'Serial Number', ':', true).trim(), + interfaceType: util$b.getValue(lines, 'InterfaceType', ':', true).trim(), + smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown', + temperature: null, + BSDName: BSDName + }); + cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;'; + } + } + }); + } catch (e) { + util$b.noop(); + } - result.displays = parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections); - - if (result.displays.length === 1) { - if (_resolutionX) { - result.displays[0].resolutionX = _resolutionX; - if (!result.displays[0].currentResX) { - result.displays[0].currentResX = _resolutionX; + // NVME Drives + try { + let devices = linesNVMe.join('\n').split('\n\n Capacity:'); + devices.shift(); + devices.forEach(function (device) { + device = '!Capacity: ' + device; + let lines = device.split('\n'); + const linkWidth = util$b.getValue(lines, 'link width', ':', true).trim(); + const sizeStr = util$b.getValue(lines, '!capacity', ':', true).trim(); + const BSDName = util$b.getValue(lines, 'BSD Name', ':', true).trim(); + if (sizeStr) { + let sizeValue = 0; + if (sizeStr.indexOf('(') >= 0) { + sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, '')); + } + if (!sizeValue) { + sizeValue = parseInt(sizeStr); + } + if (sizeValue) { + const smartStatusString = util$b.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase(); + result.push({ + device: BSDName, + type: 'NVMe', + name: util$b.getValue(lines, 'Model', ':', true).trim(), + vendor: getVendorFromModel(util$b.getValue(lines, 'Model', ':', true).trim()), + size: sizeValue, + bytesPerSector: null, + totalCylinders: null, + totalHeads: null, + totalSectors: null, + totalTracks: null, + tracksPerCylinder: null, + sectorsPerTrack: null, + firmwareRevision: util$b.getValue(lines, 'Revision', ':', true).trim(), + serialNum: util$b.getValue(lines, 'Serial Number', ':', true).trim(), + interfaceType: ('PCIe ' + linkWidth).trim(), + smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown', + temperature: null, + BSDName: BSDName + }); + cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;'; + } + } + }); + } catch (e) { + util$b.noop(); + } + // USB Drives + try { + let devices = linesUSB.join('\n').replaceAll('Media:\n ', 'Model:').split('\n\n Product ID:'); + devices.shift(); + devices.forEach(function (device) { + let lines = device.split('\n'); + const sizeStr = util$b.getValue(lines, 'Capacity', ':', true).trim(); + const BSDName = util$b.getValue(lines, 'BSD Name', ':', true).trim(); + if (sizeStr) { + let sizeValue = 0; + if (sizeStr.indexOf('(') >= 0) { + sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, '')); + } + if (!sizeValue) { + sizeValue = parseInt(sizeStr); + } + if (sizeValue) { + const smartStatusString = util$b.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase(); + result.push({ + device: BSDName, + type: 'USB', + name: util$b.getValue(lines, 'Model', ':', true).trim().replaceAll(':', ''), + vendor: getVendorFromModel(util$b.getValue(lines, 'Model', ':', true).trim()), + size: sizeValue, + bytesPerSector: null, + totalCylinders: null, + totalHeads: null, + totalSectors: null, + totalTracks: null, + tracksPerCylinder: null, + sectorsPerTrack: null, + firmwareRevision: util$b.getValue(lines, 'Revision', ':', true).trim(), + serialNum: util$b.getValue(lines, 'Serial Number', ':', true).trim(), + interfaceType: 'USB', + smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown', + temperature: null, + BSDName: BSDName + }); + cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;'; + } + } + }); + } catch (e) { + util$b.noop(); + } + if (cmd) { + cmd = cmd + 'printf "\n"'; + exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { + let lines = stdout.toString().split('\n'); + lines.forEach(line => { + if (line) { + let parts = line.split('|'); + if (parts.length === 2) { + let BSDName = parts[0]; + parts[1] = parts[1].trim(); + let parts2 = parts[1].split(':'); + if (parts2.length === 2) { + parts2[1] = parts2[1].trim(); + let status = parts2[1].toLowerCase(); + for (let i = 0; i < result.length; i++) { + if (result[i].BSDName === BSDName) { + result[i].smartStatus = (status === 'not supported' ? 'not supported' : (status === 'verified' ? 'Ok' : (status === 'failing' ? 'Predicted Failure' : 'unknown'))); + } + } + } + } + } + }); + for (let i = 0; i < result.length; i++) { + delete result[i].BSDName; } - } - if (_resolutionY) { - result.displays[0].resolutionY = _resolutionY; - if (result.displays[0].currentResY === 0) { - result.displays[0].currentResY = _resolutionY; + if (callback) { + callback(result); } + resolve(result); + }); + } else { + for (let i = 0; i < result.length; i++) { + delete result[i].BSDName; } - if (_pixelDepth) { - result.displays[0].pixelDepth = _pixelDepth; - } - } - result.displays = result.displays.map(element => { - if (_refreshRate && !element.currentRefreshRate) { - element.currentRefreshRate = _refreshRate; - } - return element; - }); - - if (callback) { - callback(result); - } - resolve(result); - }) - .catch(() => { if (callback) { callback(result); } resolve(result); - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } - } - }); - }); - - function parseLinesWindowsControllers(sections, vections) { - const memorySizes = {}; - for (const i in vections) { - if ({}.hasOwnProperty.call(vections, i)) { - if (vections[i].trim() !== '') { - const lines = vections[i].trim().split('\n'); - const matchingDeviceId = util$c.getValue(lines, 'MatchingDeviceId').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i); - if (matchingDeviceId) { - const quadWordmemorySize = parseInt(util$c.getValue(lines, 'HardwareInformation.qwMemorySize')); - if (!isNaN(quadWordmemorySize)) { - let deviceId = matchingDeviceId[1].toUpperCase() + '&' + matchingDeviceId[2].toUpperCase(); - if (matchingDeviceId[3]) { - deviceId += '&' + matchingDeviceId[3].toUpperCase(); - } - if (matchingDeviceId[4]) { - deviceId += '&' + matchingDeviceId[4].toUpperCase(); - } - memorySizes[deviceId] = quadWordmemorySize; } } - } + }); } - } - - let controllers = []; - for (let i in sections) { - if ({}.hasOwnProperty.call(sections, i)) { - if (sections[i].trim() !== '') { - let lines = sections[i].trim().split('\n'); - let pnpDeviceId = util$c.getValue(lines, 'PNPDeviceID', ':').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i); - let subDeviceId = null; - let memorySize = null; - if (pnpDeviceId) { - subDeviceId = pnpDeviceId[3] || ''; - if (subDeviceId) { - subDeviceId = subDeviceId.split('_')[1]; - } - - // Match PCI device identifier (there's an order of increasing generality): - // https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices - - // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)&REV_r(2) - if (memorySize == null && pnpDeviceId[3] && pnpDeviceId[4]) { - const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase(); - if ({}.hasOwnProperty.call(memorySizes, deviceId)) { - memorySize = memorySizes[deviceId]; + if (_windows$a) { + try { + const workload = []; + workload.push(util$b.powerShell('Get-CimInstance Win32_DiskDrive | select Caption,Size,Status,PNPDeviceId,DeviceId,BytesPerSector,TotalCylinders,TotalHeads,TotalSectors,TotalTracks,TracksPerCylinder,SectorsPerTrack,FirmwareRevision,SerialNumber,InterfaceType | fl')); + workload.push(util$b.powerShell('Get-PhysicalDisk | select BusType,MediaType,FriendlyName,Model,SerialNumber,Size | fl')); + if (util$b.smartMonToolsInstalled()) { + try { + const smartDev = JSON.parse(execSync$5('smartctl --scan -j').toString()); + if (smartDev && smartDev.devices && smartDev.devices.length > 0) { + smartDev.devices.forEach((dev) => { + workload.push(execPromiseSave(`smartctl -j -a ${dev.name}`, util$b.execOptsWin)); + }); } + } catch (e) { + util$b.noop(); } - - // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4) - if (memorySize == null && pnpDeviceId[3]) { - const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase(); - if ({}.hasOwnProperty.call(memorySizes, deviceId)) { - memorySize = memorySizes[deviceId]; + } + util$b.promiseAll( + workload + ).then((data) => { + let devices = data.results[0].toString().split(/\n\s*\n/); + devices.forEach(function (device) { + let lines = device.split('\r\n'); + const size = util$b.getValue(lines, 'Size', ':').trim(); + const status = util$b.getValue(lines, 'Status', ':').trim().toLowerCase(); + if (size) { + result.push({ + device: util$b.getValue(lines, 'DeviceId', ':'), // changed from PNPDeviceId to DeviceID (be be able to match devices) + type: device.indexOf('SSD') > -1 ? 'SSD' : 'HD', // just a starting point ... better: MSFT_PhysicalDisk - Media Type ... see below + name: util$b.getValue(lines, 'Caption', ':'), + vendor: getVendorFromModel(util$b.getValue(lines, 'Caption', ':', true).trim()), + size: parseInt(size), + bytesPerSector: parseInt(util$b.getValue(lines, 'BytesPerSector', ':')), + totalCylinders: parseInt(util$b.getValue(lines, 'TotalCylinders', ':')), + totalHeads: parseInt(util$b.getValue(lines, 'TotalHeads', ':')), + totalSectors: parseInt(util$b.getValue(lines, 'TotalSectors', ':')), + totalTracks: parseInt(util$b.getValue(lines, 'TotalTracks', ':')), + tracksPerCylinder: parseInt(util$b.getValue(lines, 'TracksPerCylinder', ':')), + sectorsPerTrack: parseInt(util$b.getValue(lines, 'SectorsPerTrack', ':')), + firmwareRevision: util$b.getValue(lines, 'FirmwareRevision', ':').trim(), + serialNum: util$b.getValue(lines, 'SerialNumber', ':').trim(), + interfaceType: util$b.getValue(lines, 'InterfaceType', ':').trim(), + smartStatus: (status === 'ok' ? 'Ok' : (status === 'degraded' ? 'Degraded' : (status === 'pred fail' ? 'Predicted Failure' : 'Unknown'))), + temperature: null, + }); } - } - - // PCI\VEN_v(4)&DEV_d(4)&REV_r(2) - if (memorySize == null && pnpDeviceId[4]) { - const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase(); - if ({}.hasOwnProperty.call(memorySizes, deviceId)) { - memorySize = memorySizes[deviceId]; + }); + devices = data.results[1].split(/\n\s*\n/); + devices.forEach(function (device) { + let lines = device.split('\r\n'); + const serialNum = util$b.getValue(lines, 'SerialNumber', ':').trim(); + const name = util$b.getValue(lines, 'FriendlyName', ':').trim().replace('Msft ', 'Microsoft'); + const size = util$b.getValue(lines, 'Size', ':').trim(); + const model = util$b.getValue(lines, 'Model', ':').trim(); + const interfaceType = util$b.getValue(lines, 'BusType', ':').trim(); + let mediaType = util$b.getValue(lines, 'MediaType', ':').trim(); + if (mediaType === '3' || mediaType === 'HDD') { mediaType = 'HD'; } + if (mediaType === '4') { mediaType = 'SSD'; } + if (mediaType === '5') { mediaType = 'SCM'; } + if (mediaType === 'Unspecified' && (model.toLowerCase().indexOf('virtual') > -1 || model.toLowerCase().indexOf('vbox') > -1)) { mediaType = 'Virtual'; } + if (size) { + let i = util$b.findObjectByKey(result, 'serialNum', serialNum); + if (i === -1 || serialNum === '') { + i = util$b.findObjectByKey(result, 'name', name); + } + if (i != -1) { + result[i].type = mediaType; + result[i].interfaceType = interfaceType; + } } + }); + // S.M.A.R.T + data.results.shift(); + data.results.shift(); + if (data.results.length) { + data.results.forEach((smartStr) => { + try { + const smartData = JSON.parse(smartStr); + if (smartData.serial_number) { + const serialNum = smartData.serial_number; + let i = util$b.findObjectByKey(result, 'serialNum', serialNum); + if (i != -1) { + result[i].smartStatus = (smartData.smart_status && smartData.smart_status.passed ? 'Ok' : (smartData.smart_status && smartData.smart_status.passed === false ? 'Predicted Failure' : 'unknown')); + if (smartData.temperature && smartData.temperature.current) { + result[i].temperature = smartData.temperature.current; + } + result[i].smartData = smartData; + } + } + } catch (e) { + util$b.noop(); + } + }); } - - // PCI\VEN_v(4)&DEV_d(4) - if (memorySize == null) { - const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase(); - if ({}.hasOwnProperty.call(memorySizes, deviceId)) { - memorySize = memorySizes[deviceId]; - } + if (callback) { + callback(result); } - } - - controllers.push({ - vendor: util$c.getValue(lines, 'AdapterCompatibility', ':'), - model: util$c.getValue(lines, 'name', ':'), - bus: util$c.getValue(lines, 'PNPDeviceID', ':').startsWith('PCI') ? 'PCI' : '', - vram: (memorySize == null ? util$c.toInt(util$c.getValue(lines, 'AdapterRAM', ':')) : memorySize) / 1024 / 1024, - vramDynamic: (util$c.getValue(lines, 'VideoMemoryType', ':') === '2'), - subDeviceId + resolve(result); }); - _resolutionX = util$c.toInt(util$c.getValue(lines, 'CurrentHorizontalResolution', ':')) || _resolutionX; - _resolutionY = util$c.toInt(util$c.getValue(lines, 'CurrentVerticalResolution', ':')) || _resolutionY; - _refreshRate = util$c.toInt(util$c.getValue(lines, 'CurrentRefreshRate', ':')) || _refreshRate; - _pixelDepth = util$c.toInt(util$c.getValue(lines, 'CurrentBitsPerPixel', ':')) || _pixelDepth; - } - } - } - return controllers; - } - - function parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections) { - let displays = []; - let vendor = ''; - let model = ''; - let deviceID = ''; - let resolutionX = 0; - let resolutionY = 0; - if (dsections && dsections.length) { - let linesDisplay = dsections[0].split('\n'); - vendor = util$c.getValue(linesDisplay, 'MonitorManufacturer', ':'); - model = util$c.getValue(linesDisplay, 'Name', ':'); - deviceID = util$c.getValue(linesDisplay, 'PNPDeviceID', ':').replace(/&/g, '&').toLowerCase(); - resolutionX = util$c.toInt(util$c.getValue(linesDisplay, 'ScreenWidth', ':')); - resolutionY = util$c.toInt(util$c.getValue(linesDisplay, 'ScreenHeight', ':')); - } - for (let i = 0; i < ssections.length; i++) { - if (ssections[i].trim() !== '') { - ssections[i] = 'BitsPerPixel ' + ssections[i]; - msections[i] = 'Active ' + msections[i]; - // tsections can be empty OR undefined on earlier versions of powershell (<=2.0) - // Tag connection type as UNKNOWN by default if this information is missing - if (tsections.length === 0 || tsections[i] === undefined) { - tsections[i] = 'Unknown'; + } catch (e) { + if (callback) { callback(result); } + resolve(result); } - let linesScreen = ssections[i].split('\n'); - let linesMonitor = msections[i].split('\n'); - - let linesConnection = tsections[i].split('\n'); - const bitsPerPixel = util$c.getValue(linesScreen, 'BitsPerPixel'); - const bounds = util$c.getValue(linesScreen, 'Bounds').replace('{', '').replace('}', '').replace(/=/g, ':').split(','); - const primary = util$c.getValue(linesScreen, 'Primary'); - const sizeX = util$c.getValue(linesMonitor, 'MaxHorizontalImageSize'); - const sizeY = util$c.getValue(linesMonitor, 'MaxVerticalImageSize'); - const instanceName = util$c.getValue(linesMonitor, 'InstanceName').toLowerCase(); - const videoOutputTechnology = util$c.getValue(linesConnection, 'VideoOutputTechnology'); - const deviceName = util$c.getValue(linesScreen, 'DeviceName'); - let displayVendor = ''; - let displayModel = ''; - isections.forEach(element => { - if (element.instanceId.toLowerCase().startsWith(instanceName) && vendor.startsWith('(') && model.startsWith('PnP')) { - displayVendor = element.vendor; - displayModel = element.model; - } - }); - displays.push({ - vendor: instanceName.startsWith(deviceID) && displayVendor === '' ? vendor : displayVendor, - model: instanceName.startsWith(deviceID) && displayModel === '' ? model : displayModel, - deviceName, - main: primary.toLowerCase() === 'true', - builtin: videoOutputTechnology === '2147483648', - connection: videoOutputTechnology && videoTypes[videoOutputTechnology] ? videoTypes[videoOutputTechnology] : '', - resolutionX: util$c.toInt(util$c.getValue(bounds, 'Width', ':')), - resolutionY: util$c.toInt(util$c.getValue(bounds, 'Height', ':')), - sizeX: sizeX ? parseInt(sizeX, 10) : null, - sizeY: sizeY ? parseInt(sizeY, 10) : null, - pixelDepth: bitsPerPixel, - currentResX: util$c.toInt(util$c.getValue(bounds, 'Width', ':')), - currentResY: util$c.toInt(util$c.getValue(bounds, 'Height', ':')), - positionX: util$c.toInt(util$c.getValue(bounds, 'X', ':')), - positionY: util$c.toInt(util$c.getValue(bounds, 'Y', ':')), - }); } - } - if (ssections.length === 0) { - displays.push({ - vendor, - model, - main: true, - sizeX: null, - sizeY: null, - resolutionX, - resolutionY, - pixelDepth: null, - currentResX: resolutionX, - currentResY: resolutionY, - positionX: 0, - positionY: 0 - }); - } - return displays; - } + }); + }); } -graphics$1.graphics = graphics; +filesystem.diskLayout = diskLayout; -var filesystem = {}; +var network = {}; // @ts-check // ================================================================================== -// filesystem.js +// network.js // ---------------------------------------------------------------------------------- // Description: System Information - library // for Node.js @@ -63648,1493 +59857,1766 @@ var filesystem = {}; // ---------------------------------------------------------------------------------- // License: MIT // ================================================================================== -// 8. File System +// 9. Network // ---------------------------------------------------------------------------------- -const util$b = util$j; -const fs$3 = require$$0$5; +const os$3 = require$$0$7; +const exec$8 = require$$1$2.exec; +const execSync$4 = require$$1$2.execSync; +const fs$2 = require$$0$5; +const util$a = util$j; -const exec$9 = require$$1$2.exec; -const execSync$5 = require$$1$2.execSync; -const execPromiseSave = util$b.promisifySave(require$$1$2.exec); +let _platform$9 = process.platform; -let _platform$a = process.platform; +const _linux$8 = (_platform$9 === 'linux' || _platform$9 === 'android'); +const _darwin$8 = (_platform$9 === 'darwin'); +const _windows$9 = (_platform$9 === 'win32'); +const _freebsd$7 = (_platform$9 === 'freebsd'); +const _openbsd$7 = (_platform$9 === 'openbsd'); +const _netbsd$7 = (_platform$9 === 'netbsd'); +const _sunos$7 = (_platform$9 === 'sunos'); -const _linux$9 = (_platform$a === 'linux' || _platform$a === 'android'); -const _darwin$9 = (_platform$a === 'darwin'); -const _windows$a = (_platform$a === 'win32'); -const _freebsd$8 = (_platform$a === 'freebsd'); -const _openbsd$8 = (_platform$a === 'openbsd'); -const _netbsd$8 = (_platform$a === 'netbsd'); -const _sunos$8 = (_platform$a === 'sunos'); +let _network = {}; +let _default_iface = ''; +let _ifaces = {}; +let _dhcpNics = []; +let _networkInterfaces = []; +let _mac = {}; +let pathToIp; -let _fs_speed = {}; -let _disk_io = {}; +function getDefaultNetworkInterface() { -// -------------------------- -// FS - mounted file systems + let ifacename = ''; + let ifacenameFirst = ''; + try { + let ifaces = os$3.networkInterfaces(); -function fsSize(drive, callback) { + let scopeid = 9999; - if (util$b.isFunction(drive)) { - callback = drive; - drive = ''; - } + // fallback - "first" external interface (sorted by scopeid) + for (let dev in ifaces) { + if ({}.hasOwnProperty.call(ifaces, dev)) { + ifaces[dev].forEach(function (details) { + if (details && details.internal === false) { + ifacenameFirst = ifacenameFirst || dev; // fallback if no scopeid + if (details.scopeid && details.scopeid < scopeid) { + ifacename = dev; + scopeid = details.scopeid; + } + } + }); + } + } + ifacename = ifacename || ifacenameFirst || ''; - let macOsDisks = []; - let osMounts = []; + if (_windows$9) { + // https://www.inetdaemon.com/tutorials/internet/ip/routing/default_route.shtml + let defaultIp = ''; + const cmd = 'netstat -r'; + const result = execSync$4(cmd, util$a.execOptsWin); + const lines = result.toString().split(os$3.EOL); + lines.forEach(line => { + line = line.replace(/\s+/g, ' ').trim(); + if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) { + const parts = line.split(' '); + if (parts.length >= 5) { + defaultIp = parts[parts.length - 2]; + } + } + }); + if (defaultIp) { + for (let dev in ifaces) { + if ({}.hasOwnProperty.call(ifaces, dev)) { + ifaces[dev].forEach(function (details) { + if (details && details.address && details.address === defaultIp) { + ifacename = dev; + } + }); + } + } + } + } + if (_linux$8) { + let cmd = 'ip route 2> /dev/null | grep default'; + let result = execSync$4(cmd); + let parts = result.toString().split('\n')[0].split(/\s+/); + if (parts[0] === 'none' && parts[5]) { + ifacename = parts[5]; + } else if (parts[4]) { + ifacename = parts[4]; + } - function getmacOsFsType(fs) { - if (!fs.startsWith('/')) { return 'NFS'; } - const parts = fs.split('/'); - const fsShort = parts[parts.length - 1]; - const macOsDisksSingle = macOsDisks.filter(item => item.indexOf(fsShort) >= 0); - if (macOsDisksSingle.length === 1 && macOsDisksSingle[0].indexOf('APFS') >= 0) { return 'APFS'; } - return 'HFS'; + if (ifacename.indexOf(':') > -1) { + ifacename = ifacename.split(':')[1].trim(); + } + } + if (_darwin$8 || _freebsd$7 || _openbsd$7 || _netbsd$7 || _sunos$7) { + let cmd = ''; + if (_linux$8) { cmd = 'ip route 2> /dev/null | grep default | awk \'{print $5}\''; } + if (_darwin$8) { cmd = 'route -n get default 2>/dev/null | grep interface: | awk \'{print $2}\''; } + if (_freebsd$7 || _openbsd$7 || _netbsd$7 || _sunos$7) { cmd = 'route get 0.0.0.0 | grep interface:'; } + let result = execSync$4(cmd); + ifacename = result.toString().split('\n')[0]; + if (ifacename.indexOf(':') > -1) { + ifacename = ifacename.split(':')[1].trim(); + } + } + } catch (e) { + util$a.noop(); } + if (ifacename) { _default_iface = ifacename; } + return _default_iface; +} - function isLinuxTmpFs(fs) { - const linuxTmpFileSystems = ['rootfs', 'unionfs', 'squashfs', 'cramfs', 'initrd', 'initramfs', 'devtmpfs', 'tmpfs', 'udev', 'devfs', 'specfs', 'type', 'appimaged']; - let result = false; - linuxTmpFileSystems.forEach(linuxFs => { - if (fs.toLowerCase().indexOf(linuxFs) >= 0) { result = true; } - }); - return result; - } +network.getDefaultNetworkInterface = getDefaultNetworkInterface; - function filterLines(stdout) { - let lines = stdout.toString().split('\n'); - lines.shift(); - if (stdout.toString().toLowerCase().indexOf('filesystem')) { - let removeLines = 0; +function getMacAddresses() { + let iface = ''; + let mac = ''; + let result = {}; + if (_linux$8 || _freebsd$7 || _openbsd$7 || _netbsd$7) { + if (typeof pathToIp === 'undefined') { + try { + const lines = execSync$4('which ip').toString().split('\n'); + if (lines.length && lines[0].indexOf(':') === -1 && lines[0].indexOf('/') === 0) { + pathToIp = lines[0]; + } else { + pathToIp = ''; + } + } catch (e) { + pathToIp = ''; + } + } + try { + const cmd = 'export LC_ALL=C; ' + ((pathToIp) ? pathToIp + ' link show up' : '/sbin/ifconfig') + '; unset LC_ALL'; + let res = execSync$4(cmd); + const lines = res.toString().split('\n'); for (let i = 0; i < lines.length; i++) { - if (lines[i] && lines[i].toLowerCase().startsWith('filesystem')) { - removeLines = i; + if (lines[i] && lines[i][0] !== ' ') { + if (pathToIp) { + let nextline = lines[i + 1].trim().split(' '); + if (nextline[0] === 'link/ether') { + iface = lines[i].split(' ')[1]; + iface = iface.slice(0, iface.length - 1); + mac = nextline[1]; + } + } else { + iface = lines[i].split(' ')[0]; + mac = lines[i].split('HWaddr ')[1]; + } + + if (iface && mac) { + result[iface] = mac.trim(); + iface = ''; + mac = ''; + } } } - for (let i = 0; i < removeLines; i++) { - lines.shift(); + } catch (e) { + util$a.noop(); + } + } + if (_darwin$8) { + try { + const cmd = '/sbin/ifconfig'; + let res = execSync$4(cmd); + const lines = res.toString().split('\n'); + for (let i = 0; i < lines.length; i++) { + if (lines[i] && lines[i][0] !== '\t' && lines[i].indexOf(':') > 0) { + iface = lines[i].split(':')[0]; + } else if (lines[i].indexOf('\tether ') === 0) { + mac = lines[i].split('\tether ')[1]; + if (iface && mac) { + result[iface] = mac.trim(); + iface = ''; + mac = ''; + } + } } + } catch (e) { + util$a.noop(); } - return lines; } + return result; +} - function parseDf(lines) { - let data = []; - lines.forEach(function (line) { - if (line !== '') { - line = line.replace(/ +/g, ' ').split(' '); - if (line && ((line[0].startsWith('/')) || (line[6] && line[6] === '/') || (line[0].indexOf('/') > 0) || (line[0].indexOf(':') === 1) || !_darwin$9 && !isLinuxTmpFs(line[1]))) { - const fs = line[0]; - const fsType = ((_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? line[1] : getmacOsFsType(line[0])); - const size = parseInt(((_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? line[2] : line[1])) * 1024; - const used = parseInt(((_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? line[3] : line[2])) * 1024; - const available = parseInt(((_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? line[4] : line[3])) * 1024; - const use = parseFloat((100.0 * (used / (used + available))).toFixed(2)); - let rw = osMounts && Object.keys(osMounts).length > 0 ? osMounts[fs] || false : null; - line.splice(0, (_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) ? 6 : 5); - const mount = line.join(' '); - if (!data.find(el => (el.fs === fs && el.type === fsType))) { - data.push({ - fs, - type: fsType, - size, - used, - available, - use, - mount, - rw - }); - } +function networkInterfaceDefault(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + let result = getDefaultNetworkInterface(); + if (callback) { callback(result); } + resolve(result); + }); + }); +} + +network.networkInterfaceDefault = networkInterfaceDefault; + +// -------------------------- +// NET - interfaces + +function parseLinesWindowsNics(sections, nconfigsections) { + let nics = []; + for (let i in sections) { + if ({}.hasOwnProperty.call(sections, i)) { + + if (sections[i].trim() !== '') { + + let lines = sections[i].trim().split('\r\n'); + let linesNicConfig = nconfigsections && nconfigsections[i] ? nconfigsections[i].trim().split('\r\n') : []; + let netEnabled = util$a.getValue(lines, 'NetEnabled', ':'); + let adapterType = util$a.getValue(lines, 'AdapterTypeID', ':') === '9' ? 'wireless' : 'wired'; + let ifacename = util$a.getValue(lines, 'Name', ':').replace(/\]/g, ')').replace(/\[/g, '('); + let iface = util$a.getValue(lines, 'NetConnectionID', ':').replace(/\]/g, ')').replace(/\[/g, '('); + if (ifacename.toLowerCase().indexOf('wi-fi') >= 0 || ifacename.toLowerCase().indexOf('wireless') >= 0) { + adapterType = 'wireless'; + } + if (netEnabled !== '') { + const speed = parseInt(util$a.getValue(lines, 'speed', ':').trim(), 10) / 1000000; + nics.push({ + mac: util$a.getValue(lines, 'MACAddress', ':').toLowerCase(), + dhcp: util$a.getValue(linesNicConfig, 'dhcpEnabled', ':').toLowerCase() === 'true', + name: ifacename, + iface, + netEnabled: netEnabled === 'TRUE', + speed: isNaN(speed) ? null : speed, + operstate: util$a.getValue(lines, 'NetConnectionStatus', ':') === '2' ? 'up' : 'down', + type: adapterType + }); } } - }); - return data; + } } + return nics; +} +function getWindowsNics() { return new Promise((resolve) => { process.nextTick(() => { - let data = []; - if (_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8 || _darwin$9) { - let cmd = ''; - macOsDisks = []; - osMounts = {}; - if (_darwin$9) { - cmd = 'df -kP'; - try { - macOsDisks = execSync$5('diskutil list').toString().split('\n').filter(line => { - return !line.startsWith('/') && line.indexOf(':') > 0; - }); - execSync$5('mount').toString().split('\n').filter(line => { - return line.startsWith('/'); - }).forEach((line) => { - osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1; - }); - } catch (e) { - util$b.noop(); - } - } - if (_linux$9) { - try { - cmd = 'export LC_ALL=C; df -lkPTx squashfs; unset LC_ALL'; - execSync$5('cat /proc/mounts 2>/dev/null').toString().split('\n').filter(line => { - return line.startsWith('/'); - }).forEach((line) => { - osMounts[line.split(' ')[0]] = osMounts[line.split(' ')[0]] || false; - if (line.toLowerCase().indexOf('/snap/') === -1) { - osMounts[line.split(' ')[0]] = ((line.toLowerCase().indexOf('rw,') >= 0 || line.toLowerCase().indexOf(' rw ') >= 0)); - } - }); - } catch (e) { - util$b.noop(); - } - } - if (_freebsd$8 || _openbsd$8 || _netbsd$8) { - try { - cmd = 'df -lkPT'; - execSync$5('mount').toString().split('\n').forEach((line) => { - osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1; - }); - } catch (e) { - util$b.noop(); - } - } - exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { - let lines = filterLines(stdout); - data = parseDf(lines); - if (drive) { - data = data.filter(item => { - return item.fs.toLowerCase().indexOf(drive.toLowerCase()) >= 0 || item.mount.toLowerCase().indexOf(drive.toLowerCase()) >= 0; - }); - } - if ((!error || data.length) && stdout.toString().trim() !== '') { - if (callback) { - callback(data); - } - resolve(data); - } else { - exec$9('df -kPT', { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - let lines = filterLines(stdout); - data = parseDf(lines); - } - if (callback) { - callback(data); - } - resolve(data); - }); - } + let cmd = 'Get-CimInstance Win32_NetworkAdapter | fl *' + '; echo \'#-#-#-#\';'; + cmd += 'Get-CimInstance Win32_NetworkAdapterConfiguration | fl DHCPEnabled' + ''; + try { + util$a.powerShell(cmd).then((data) => { + data = data.split('#-#-#-#'); + const nsections = (data[0] || '').split(/\n\s*\n/); + const nconfigsections = (data[1] || '').split(/\n\s*\n/); + resolve(parseLinesWindowsNics(nsections, nconfigsections)); }); + } catch (e) { + resolve([]); } - if (_sunos$8) { - if (callback) { callback(data); } - resolve(data); + }); + }); +} + +function getWindowsDNSsuffixes() { + + let iface = {}; + + let dnsSuffixes = { + primaryDNS: '', + exitCode: 0, + ifaces: [], + }; + + try { + const ipconfig = execSync$4('ipconfig /all', util$a.execOptsWin); + const ipconfigArray = ipconfig.split('\r\n\r\n'); + + ipconfigArray.forEach((element, index) => { + + if (index == 1) { + const longPrimaryDNS = element.split('\r\n').filter((element) => { + return element.toUpperCase().includes('DNS'); + }); + const primaryDNS = longPrimaryDNS[0].substring(longPrimaryDNS[0].lastIndexOf(':') + 1); + dnsSuffixes.primaryDNS = primaryDNS.trim(); + if (!dnsSuffixes.primaryDNS) { dnsSuffixes.primaryDNS = 'Not defined'; } } - if (_windows$a) { - try { - const cmd = `Get-WmiObject Win32_logicaldisk | select Access,Caption,FileSystem,FreeSpace,Size ${drive ? '| where -property Caption -eq ' + drive : ''} | fl`; - util$b.powerShell(cmd).then((stdout, error) => { - if (!error) { - let devices = stdout.toString().split(/\n\s*\n/); - devices.forEach(function (device) { - let lines = device.split('\r\n'); - const size = util$b.toInt(util$b.getValue(lines, 'size', ':')); - const free = util$b.toInt(util$b.getValue(lines, 'freespace', ':')); - const caption = util$b.getValue(lines, 'caption', ':'); - const rwValue = util$b.getValue(lines, 'access', ':'); - const rw = rwValue ? (util$b.toInt(rwValue) !== 1) : null; - if (size) { - data.push({ - fs: caption, - type: util$b.getValue(lines, 'filesystem', ':'), - size, - used: size - free, - available: free, - use: parseFloat(((100.0 * (size - free)) / size).toFixed(2)), - mount: caption, - rw - }); - } - }); - } - if (callback) { - callback(data); - } - resolve(data); + if (index > 1) { + if (index % 2 == 0) { + const name = element.substring(element.lastIndexOf(' ') + 1).replace(':', ''); + iface.name = name; + } else { + const connectionSpecificDNS = element.split('\r\n').filter((element) => { + return element.toUpperCase().includes('DNS'); }); - } catch (e) { - if (callback) { callback(data); } - resolve(data); + const dnsSuffix = connectionSpecificDNS[0].substring(connectionSpecificDNS[0].lastIndexOf(':') + 1); + iface.dnsSuffix = dnsSuffix.trim(); + dnsSuffixes.ifaces.push(iface); + iface = {}; } } }); - }); + + return dnsSuffixes; + } catch (error) { + return { + primaryDNS: '', + exitCode: 0, + ifaces: [], + }; + } } -filesystem.fsSize = fsSize; +function getWindowsIfaceDNSsuffix(ifaces, ifacename) { + let dnsSuffix = ''; + // Adding (.) to ensure ifacename compatibility when duplicated iface-names + const interfaceName = ifacename + '.'; + try { + const connectionDnsSuffix = ifaces.filter((iface) => { + return interfaceName.includes(iface.name + '.'); + }).map((iface) => iface.dnsSuffix); + if (connectionDnsSuffix[0]) { + dnsSuffix = connectionDnsSuffix[0]; + } + if (!dnsSuffix) { dnsSuffix = ''; } + return dnsSuffix; + } catch (error) { + return 'Unknown'; + } +} -// -------------------------- -// FS - open files count +function getWindowsWiredProfilesInformation() { + try { + const result = execSync$4('netsh lan show profiles', util$a.execOptsWin); + const profileList = result.split('\r\nProfile on interface'); + return profileList; + } catch (error) { + if (error.status === 1 && error.stdout.includes('AutoConfig')) { + return 'Disabled'; + } + return []; + } +} -function fsOpenFiles(callback) { +function getWindowsWirelessIfaceSSID(interfaceName) { + try { + const result = execSync$4(`netsh wlan show interface name="${interfaceName}" | findstr "SSID"`, util$a.execOptsWin); + const SSID = result.split('\r\n').shift(); + const parseSSID = SSID.split(':').pop(); + return parseSSID; + } catch (error) { + return 'Unknown'; + } +} +function getWindowsIEEE8021x(connectionType, iface, ifaces) { + let i8021x = { + state: 'Unknown', + protocol: 'Unknown', + }; - return new Promise((resolve) => { - process.nextTick(() => { - const result = { - max: null, - allocated: null, - available: null - }; - if (_freebsd$8 || _openbsd$8 || _netbsd$8 || _darwin$9) { - let cmd = 'sysctl -i kern.maxfiles kern.num_files kern.open_files'; - exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - result.max = parseInt(util$b.getValue(lines, 'kern.maxfiles', ':'), 10); - result.allocated = parseInt(util$b.getValue(lines, 'kern.num_files', ':'), 10) || parseInt(util$b.getValue(lines, 'kern.open_files', ':'), 10); - result.available = result.max - result.allocated; - } - if (callback) { - callback(result); - } - resolve(result); + if (ifaces === 'Disabled') { + i8021x.state = 'Disabled'; + i8021x.protocol = 'Not defined'; + return i8021x; + } + + if (connectionType == 'wired' && ifaces.length > 0) { + try { + // Get 802.1x information by interface name + const iface8021xInfo = ifaces.find((element) => { + return element.includes(iface + '\r\n'); + }); + const arrayIface8021xInfo = iface8021xInfo.split('\r\n'); + const state8021x = arrayIface8021xInfo.find((element) => { + return element.includes('802.1x'); + }); + + if (state8021x.includes('Disabled')) { + i8021x.state = 'Disabled'; + i8021x.protocol = 'Not defined'; + } else if (state8021x.includes('Enabled')) { + const protocol8021x = arrayIface8021xInfo.find((element) => { + return element.includes('EAP'); }); + i8021x.protocol = protocol8021x.split(':').pop(); + i8021x.state = 'Enabled'; } - if (_linux$9) { - fs$3.readFile('/proc/sys/fs/file-nr', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - if (lines[0]) { - const parts = lines[0].replace(/\s+/g, ' ').split(' '); - if (parts.length === 3) { - result.allocated = parseInt(parts[0], 10); - result.available = parseInt(parts[1], 10); - result.max = parseInt(parts[2], 10); - if (!result.available) { result.available = result.max - result.allocated; } - } - } - if (callback) { - callback(result); - } - resolve(result); - } else { - fs$3.readFile('/proc/sys/fs/file-max', function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - if (lines[0]) { - result.max = parseInt(lines[0], 10); - } - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - }); + } catch (error) { + return i8021x; + } + } else if (connectionType == 'wireless') { + + let i8021xState = ''; + let i8021xProtocol = ''; + + + + try { + const SSID = getWindowsWirelessIfaceSSID(iface); + if (SSID !== 'Unknown') { + i8021xState = execSync$4(`netsh wlan show profiles "${SSID}" | findstr "802.1X"`, util$a.execOptsWin); + i8021xProtocol = execSync$4(`netsh wlan show profiles "${SSID}" | findstr "EAP"`, util$a.execOptsWin); } - if (_sunos$8) { - if (callback) { callback(null); } - resolve(null); + + if (i8021xState.includes(':') && i8021xProtocol.includes(':')) { + i8021x.state = i8021xState.split(':').pop(); + i8021x.protocol = i8021xProtocol.split(':').pop(); } - if (_windows$a) { - if (callback) { callback(null); } - resolve(null); + } catch (error) { + if (error.status === 1 && error.stdout.includes('AutoConfig')) { + i8021x.state = 'Disabled'; + i8021x.protocol = 'Not defined'; } - }); - }); -} - -filesystem.fsOpenFiles = fsOpenFiles; + return i8021x; + } + } -// -------------------------- -// disks + return i8021x; +} -function parseBytes(s) { - return parseInt(s.substr(s.indexOf(' (') + 2, s.indexOf(' Bytes)') - 10)); +function splitSectionsNics(lines) { + const result = []; + let section = []; + lines.forEach(function (line) { + if (!line.startsWith('\t') && !line.startsWith(' ')) { + if (section.length) { + result.push(section); + section = []; + } + } + section.push(line); + }); + if (section.length) { + result.push(section); + } + return result; } -function parseDevices(lines) { - let devices = []; - let i = 0; - lines.forEach(line => { - if (line.length > 0) { - if (line[0] === '*') { - i++; - } else { - let parts = line.split(':'); - if (parts.length > 1) { - if (!devices[i]) { - devices[i] = { - name: '', - identifier: '', - type: 'disk', - fsType: '', - mount: '', - size: 0, - physical: 'HDD', - uuid: '', - label: '', - model: '', - serial: '', - removable: false, - protocol: '', - group: '', - device: '' - }; - } - parts[0] = parts[0].trim().toUpperCase().replace(/ +/g, ''); - parts[1] = parts[1].trim(); - if ('DEVICEIDENTIFIER' === parts[0]) { devices[i].identifier = parts[1]; } - if ('DEVICENODE' === parts[0]) { devices[i].name = parts[1]; } - if ('VOLUMENAME' === parts[0]) { - if (parts[1].indexOf('Not applicable') === -1) { devices[i].label = parts[1]; } - } - if ('PROTOCOL' === parts[0]) { devices[i].protocol = parts[1]; } - if ('DISKSIZE' === parts[0]) { devices[i].size = parseBytes(parts[1]); } - if ('FILESYSTEMPERSONALITY' === parts[0]) { devices[i].fsType = parts[1]; } - if ('MOUNTPOINT' === parts[0]) { devices[i].mount = parts[1]; } - if ('VOLUMEUUID' === parts[0]) { devices[i].uuid = parts[1]; } - if ('READ-ONLYMEDIA' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'CD/DVD'; } - if ('SOLIDSTATE' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'SSD'; } - if ('VIRTUAL' === parts[0]) { devices[i].type = 'virtual'; } - if ('REMOVABLEMEDIA' === parts[0]) { devices[i].removable = (parts[1] === 'Removable'); } - if ('PARTITIONTYPE' === parts[0]) { devices[i].type = 'part'; } - if ('DEVICE/MEDIANAME' === parts[0]) { devices[i].model = parts[1]; } - } +function parseLinesDarwinNics(sections) { + let nics = []; + sections.forEach(section => { + let nic = { + iface: '', + mtu: null, + mac: '', + ip6: '', + ip4: '', + speed: null, + type: '', + operstate: '', + duplex: '', + internal: false + }; + const first = section[0]; + nic.iface = first.split(':')[0].trim(); + let parts = first.split('> mtu'); + nic.mtu = parts.length > 1 ? parseInt(parts[1], 10) : null; + if (isNaN(nic.mtu)) { + nic.mtu = null; + } + nic.internal = parts[0].toLowerCase().indexOf('loopback') > -1; + section.forEach(line => { + if (line.trim().startsWith('ether ')) { + nic.mac = line.split('ether ')[1].toLowerCase().trim(); + } + if (line.trim().startsWith('inet6 ') && !nic.ip6) { + nic.ip6 = line.split('inet6 ')[1].toLowerCase().split('%')[0].split(' ')[0]; + } + if (line.trim().startsWith('inet ') && !nic.ip4) { + nic.ip4 = line.split('inet ')[1].toLowerCase().split(' ')[0]; + } + }); + let speed = util$a.getValue(section, 'link rate'); + nic.speed = speed ? parseFloat(speed) : null; + if (nic.speed === null) { + speed = util$a.getValue(section, 'uplink rate'); + nic.speed = speed ? parseFloat(speed) : null; + if (nic.speed !== null && speed.toLowerCase().indexOf('gbps') >= 0) { + nic.speed = nic.speed * 1000; + } + } else { + if (speed.toLowerCase().indexOf('gbps') >= 0) { + nic.speed = nic.speed * 1000; } } - }); - return devices; -} - -function parseBlk(lines) { - let data = []; - - lines.filter(line => line !== '').forEach((line) => { - try { - line = decodeURIComponent(line.replace(/\\x/g, '%')); - line = line.replace(/\\/g, '\\\\'); - let disk = JSON.parse(line); - data.push({ - 'name': disk.name, - 'type': disk.type, - 'fsType': disk.fsType, - 'mount': disk.mountpoint, - 'size': parseInt(disk.size), - 'physical': (disk.type === 'disk' ? (disk.rota === '0' ? 'SSD' : 'HDD') : (disk.type === 'rom' ? 'CD/DVD' : '')), - 'uuid': disk.uuid, - 'label': disk.label, - 'model': (disk.model || '').trim(), - 'serial': disk.serial, - 'removable': disk.rm === '1', - 'protocol': disk.tran, - 'group': disk.group || '', - }); - } catch (e) { - util$b.noop(); + nic.type = util$a.getValue(section, 'type').toLowerCase().indexOf('wi-fi') > -1 ? 'wireless' : 'wired'; + const operstate = util$a.getValue(section, 'status').toLowerCase(); + nic.operstate = (operstate === 'active' ? 'up' : (operstate === 'inactive' ? 'down' : 'unknown')); + nic.duplex = util$a.getValue(section, 'media').toLowerCase().indexOf('half-duplex') > -1 ? 'half' : 'full'; + if (nic.ip6 || nic.ip4 || nic.mac) { + nics.push(nic); } }); - data = util$b.unique(data); - data = util$b.sortByKey(data, ['type', 'name']); - return data; + return nics; } -function decodeMdabmData(lines) { - const raid = util$b.getValue(lines, 'md_level', '='); - const label = util$b.getValue(lines, 'md_name', '='); // <- get label info - const uuid = util$b.getValue(lines, 'md_uuid', '='); // <- get uuid info - const members = []; - lines.forEach(line => { - if (line.toLowerCase().startsWith('md_device_dev') && line.toLowerCase().indexOf('/dev/') > 0) { - members.push(line.split('/dev/')[1]); - } - }); - return { - raid, - label, - uuid, - members - }; +function getDarwinNics() { + const cmd = '/sbin/ifconfig -v'; + try { + const lines = execSync$4(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n'); + const nsections = splitSectionsNics(lines); + return (parseLinesDarwinNics(nsections)); + } catch (e) { + return []; + } } -function raidMatchLinux(data) { - // for all block devices of type "raid%" - let result = data; +function getLinuxIfaceConnectionName(interfaceName) { + const cmd = `nmcli device status 2>/dev/null | grep ${interfaceName}`; + try { - data.forEach(element => { - if (element.type.startsWith('raid')) { - const lines = execSync$5(`mdadm --export --detail /dev/${element.name}`).toString().split('\n'); - const mdData = decodeMdabmData(lines); + const result = execSync$4(cmd).toString(); + const resultFormat = result.replace(/\s+/g, ' ').trim(); + const connectionNameLines = resultFormat.split(' ').slice(3); + const connectionName = connectionNameLines.join(' '); + return connectionName != '--' ? connectionName : ''; + } catch (e) { + return ''; + } +} - element.label = mdData.label; // <- assign label info - element.uuid = mdData.uuid; // <- assign uuid info +function checkLinuxDCHPInterfaces(file) { + let result = []; + try { + let cmd = `cat ${file} 2> /dev/null | grep 'iface\\|source'`; + const lines = execSync$4(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n'); - if (mdData.members && mdData.members.length && mdData.raid === element.type) { - result = result.map(blockdevice => { - if (blockdevice.fsType === 'linux_raid_member' && mdData.members.indexOf(blockdevice.name) >= 0) { - blockdevice.group = element.name; - } - return blockdevice; - }); + lines.forEach(line => { + const parts = line.replace(/\s+/g, ' ').trim().split(' '); + if (parts.length >= 4) { + if (line.toLowerCase().indexOf(' inet ') >= 0 && line.toLowerCase().indexOf('dhcp') >= 0) { + result.push(parts[1]); } } + if (line.toLowerCase().includes('source')) { + let file = line.split(' ')[1]; + result = result.concat(checkLinuxDCHPInterfaces(file)); + } }); } catch (e) { - util$b.noop(); + util$a.noop(); } return result; } -function getDevicesLinux(data) { - const result = []; - data.forEach(element => { - if (element.type.startsWith('disk')) { - result.push(element.name); - } - }); +function getLinuxDHCPNics() { + // alternate methods getting interfaces using DHCP + let cmd = 'ip a 2> /dev/null'; + let result = []; + try { + const lines = execSync$4(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n'); + const nsections = splitSectionsNics(lines); + result = (parseLinuxDHCPNics(nsections)); + } catch (e) { + util$a.noop(); + } + try { + result = checkLinuxDCHPInterfaces('/etc/network/interfaces'); + } catch (e) { + util$a.noop(); + } return result; } -function matchDevicesLinux(data) { - let result = data; - try { - const devices = getDevicesLinux(data); - result = result.map(blockdevice => { - if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk')) { - devices.forEach(element => { - if (blockdevice.name.startsWith(element)) { - blockdevice.device = '/dev/' + element; +function parseLinuxDHCPNics(sections) { + const result = []; + if (sections && sections.length) { + sections.forEach(lines => { + if (lines && lines.length) { + const parts = lines[0].split(':'); + if (parts.length > 2) { + for (let line of lines) { + if (line.indexOf(' inet ') >= 0 && line.indexOf(' dynamic ') >= 0) { + const parts2 = line.split(' '); + const nic = parts2[parts2.length - 1].trim(); + result.push(nic); + break; + } } - }); + } } - return blockdevice; }); - } catch (e) { - util$b.noop(); } return result; } -function getDevicesMac(data) { - const result = []; - data.forEach(element => { - if (element.type.startsWith('disk')) { - result.push({ name: element.name, model: element.model, device: element.name }); - } - if (element.type.startsWith('virtual')) { - let device = ''; - result.forEach(e => { - if (e.model === element.model) { - device = e.device; - } - }); - if (device) { - result.push({ name: element.name, model: element.model, device }); +function getLinuxIfaceDHCPstatus(iface, connectionName, DHCPNics) { + let result = false; + if (connectionName) { + const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.method;`; + try { + const lines = execSync$4(cmd).toString(); + const resultFormat = lines.replace(/\s+/g, ' ').trim(); + + let dhcStatus = resultFormat.split(' ').slice(1).toString(); + switch (dhcStatus) { + case 'auto': + result = true; + break; + + default: + result = false; + break; } + return result; + } catch (e) { + return (DHCPNics.indexOf(iface) >= 0); } - }); - return result; + } else { + return (DHCPNics.indexOf(iface) >= 0); + } } -function matchDevicesMac(data) { - let result = data; +function getDarwinIfaceDHCPstatus(iface) { + let result = false; + const cmd = `ipconfig getpacket "${iface}" 2>/dev/null | grep lease_time;`; try { - const devices = getDevicesMac(data); - result = result.map(blockdevice => { - if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk') || blockdevice.type.startsWith('virtual')) { - devices.forEach(element => { - if (blockdevice.name.startsWith(element.name)) { - blockdevice.device = element.device; - } - }); - } - return blockdevice; - }); + const lines = execSync$4(cmd).toString().split('\n'); + if (lines.length && lines[0].startsWith('lease_time')) { + result = true; + } } catch (e) { - util$b.noop(); + util$a.noop(); } return result; } -function getDevicesWin(diskDrives) { - const result = []; - diskDrives.forEach(element => { - const lines = element.split('\r\n'); - const device = util$b.getValue(lines, 'DeviceID', ':'); - let partitions = element.split('@{DeviceID='); - if (partitions.length > 1) { - partitions = partitions.slice(1); - partitions.forEach(partition => { - result.push({ name: partition.split(';')[0].toUpperCase(), device }); - }); +function getLinuxIfaceDNSsuffix(connectionName) { + if (connectionName) { + const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.dns-search;`; + try { + const result = execSync$4(cmd).toString(); + const resultFormat = result.replace(/\s+/g, ' ').trim(); + const dnsSuffix = resultFormat.split(' ').slice(1).toString(); + return dnsSuffix == '--' ? 'Not defined' : dnsSuffix; + } catch (e) { + return 'Unknown'; } - }); - return result; + } else { + return 'Unknown'; + } } -function matchDevicesWin(data, diskDrives) { - const devices = getDevicesWin(diskDrives); - data.map(element => { - const filteresDevices = devices.filter((e) => { return e.name === element.name.toUpperCase(); }); - if (filteresDevices.length > 0) { - element.device = filteresDevices[0].device; +function getLinuxIfaceIEEE8021xAuth(connectionName) { + if (connectionName) { + const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep 802-1x.eap;`; + try { + const result = execSync$4(cmd).toString(); + const resultFormat = result.replace(/\s+/g, ' ').trim(); + const authenticationProtocol = resultFormat.split(' ').slice(1).toString(); + + + return authenticationProtocol == '--' ? '' : authenticationProtocol; + } catch (e) { + return 'Not defined'; } - return element; - }); - return data; + } else { + return 'Not defined'; + } } -function blkStdoutToObject(stdout) { - return stdout.toString() - .replace(/NAME=/g, '{"name":') - .replace(/FSTYPE=/g, ',"fsType":') - .replace(/TYPE=/g, ',"type":') - .replace(/SIZE=/g, ',"size":') - .replace(/MOUNTPOINT=/g, ',"mountpoint":') - .replace(/UUID=/g, ',"uuid":') - .replace(/ROTA=/g, ',"rota":') - .replace(/RO=/g, ',"ro":') - .replace(/RM=/g, ',"rm":') - .replace(/TRAN=/g, ',"tran":') - .replace(/SERIAL=/g, ',"serial":') - .replace(/LABEL=/g, ',"label":') - .replace(/MODEL=/g, ',"model":') - .replace(/OWNER=/g, ',"owner":') - .replace(/GROUP=/g, ',"group":') - .replace(/\n/g, '}\n'); +function getLinuxIfaceIEEE8021xState(authenticationProtocol) { + if (authenticationProtocol) { + if (authenticationProtocol == 'Not defined') { + return 'Disabled'; + } + return 'Enabled'; + } else { + return 'Unknown'; + } } -function blockDevices(callback) { +function testVirtualNic(iface, ifaceName, mac) { + const virtualMacs = ['00:00:00:00:00:00', '00:03:FF', '00:05:69', '00:0C:29', '00:0F:4B', '00:13:07', '00:13:BE', '00:15:5d', '00:16:3E', '00:1C:42', '00:21:F6', '00:24:0B', '00:50:56', '00:A0:B1', '00:E0:C8', '08:00:27', '0A:00:27', '18:92:2C', '16:DF:49', '3C:F3:92', '54:52:00', 'FC:15:97']; + if (mac) { + return virtualMacs.filter(item => { return mac.toUpperCase().toUpperCase().startsWith(item.substring(0, mac.length)); }).length > 0 || + iface.toLowerCase().indexOf(' virtual ') > -1 || + ifaceName.toLowerCase().indexOf(' virtual ') > -1 || + iface.toLowerCase().indexOf('vethernet ') > -1 || + ifaceName.toLowerCase().indexOf('vethernet ') > -1 || + iface.toLowerCase().startsWith('veth') || + ifaceName.toLowerCase().startsWith('veth') || + iface.toLowerCase().startsWith('vboxnet') || + ifaceName.toLowerCase().startsWith('vboxnet'); + } else { return false; } +} + +function networkInterfaces(callback, rescan, defaultString) { + + if (typeof callback === 'string') { + defaultString = callback; + rescan = true; + callback = null; + } + + if (typeof callback === 'boolean') { + rescan = callback; + callback = null; + defaultString = ''; + } + if (typeof rescan === 'undefined') { + rescan = true; + } + defaultString = defaultString || ''; + defaultString = '' + defaultString; + + return new Promise((resolve) => { + process.nextTick(() => { + + let ifaces = os$3.networkInterfaces(); + + let result = []; + let nics = []; + let dnsSuffixes = []; + let nics8021xInfo = []; + // seperate handling in OSX + if (_darwin$8 || _freebsd$7 || _openbsd$7 || _netbsd$7) { + if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) { + // no changes - just return object + result = _networkInterfaces; + + if (callback) { callback(result); } + resolve(result); + } else { + const defaultInterface = getDefaultNetworkInterface(); + _ifaces = JSON.parse(JSON.stringify(ifaces)); + + nics = getDarwinNics(); + + + nics.forEach(nic => { + + if ({}.hasOwnProperty.call(ifaces, nic.iface)) { + ifaces[nic.iface].forEach(function (details) { + if (details.family === 'IPv4' || details.family === 4) { + nic.ip4subnet = details.netmask; + } + if (details.family === 'IPv6' || details.family === 6) { + nic.ip6subnet = details.netmask; + } + }); + } + + let ifaceSanitized = ''; + const s = util$a.isPrototypePolluted() ? '---' : util$a.sanitizeShellString(nic.iface); + const l = util$a.mathMin(s.length, 2000); + for (let i = 0; i <= l; i++) { + if (s[i] !== undefined) { + ifaceSanitized = ifaceSanitized + s[i]; + } + } + + result.push({ + iface: nic.iface, + ifaceName: nic.iface, + default: nic.iface === defaultInterface, + ip4: nic.ip4, + ip4subnet: nic.ip4subnet || '', + ip6: nic.ip6, + ip6subnet: nic.ip6subnet || '', + mac: nic.mac, + internal: nic.internal, + virtual: nic.internal ? false : testVirtualNic(nic.iface, nic.iface, nic.mac), + operstate: nic.operstate, + type: nic.type, + duplex: nic.duplex, + mtu: nic.mtu, + speed: nic.speed, + dhcp: getDarwinIfaceDHCPstatus(ifaceSanitized), + dnsSuffix: '', + ieee8021xAuth: '', + ieee8021xState: '', + carrierChanges: 0 + }); + }); + _networkInterfaces = result; + if (defaultString.toLowerCase().indexOf('default') >= 0) { + result = result.filter(item => item.default); + if (result.length > 0) { + result = result[0]; + } else { + result = []; + } + } + if (callback) { callback(result); } + resolve(result); + } + } + if (_linux$8) { + if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) { + // no changes - just return object + result = _networkInterfaces; + + if (callback) { callback(result); } + resolve(result); + } else { + _ifaces = JSON.parse(JSON.stringify(ifaces)); + _dhcpNics = getLinuxDHCPNics(); + const defaultInterface = getDefaultNetworkInterface(); + for (let dev in ifaces) { + let ip4 = ''; + let ip4subnet = ''; + let ip6 = ''; + let ip6subnet = ''; + let mac = ''; + let duplex = ''; + let mtu = ''; + let speed = null; + let carrierChanges = 0; + let dhcp = false; + let dnsSuffix = ''; + let ieee8021xAuth = ''; + let ieee8021xState = ''; + let type = ''; + + if ({}.hasOwnProperty.call(ifaces, dev)) { + let ifaceName = dev; + ifaces[dev].forEach(function (details) { + if (details.family === 'IPv4' || details.family === 4) { + ip4 = details.address; + ip4subnet = details.netmask; + } + if (details.family === 'IPv6' || details.family === 6) { + if (!ip6 || ip6.match(/^fe80::/i)) { + ip6 = details.address; + ip6subnet = details.netmask; + } + } + mac = details.mac; + // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2) + const nodeMainVersion = parseInt(process.versions.node.split('.'), 10); + if (mac.indexOf('00:00:0') > -1 && (_linux$8 || _darwin$8) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) { + if (Object.keys(_mac).length === 0) { + _mac = getMacAddresses(); + } + mac = _mac[dev] || ''; + } + }); + let iface = dev.split(':')[0].trim().toLowerCase(); + let ifaceSanitized = ''; + const s = util$a.isPrototypePolluted() ? '---' : util$a.sanitizeShellString(iface); + const l = util$a.mathMin(s.length, 2000); + for (let i = 0; i <= l; i++) { + if (s[i] !== undefined) { + ifaceSanitized = ifaceSanitized + s[i]; + } + } + const cmd = `echo -n "addr_assign_type: "; cat /sys/class/net/${ifaceSanitized}/addr_assign_type 2>/dev/null; echo; + echo -n "address: "; cat /sys/class/net/${ifaceSanitized}/address 2>/dev/null; echo; + echo -n "addr_len: "; cat /sys/class/net/${ifaceSanitized}/addr_len 2>/dev/null; echo; + echo -n "broadcast: "; cat /sys/class/net/${ifaceSanitized}/broadcast 2>/dev/null; echo; + echo -n "carrier: "; cat /sys/class/net/${ifaceSanitized}/carrier 2>/dev/null; echo; + echo -n "carrier_changes: "; cat /sys/class/net/${ifaceSanitized}/carrier_changes 2>/dev/null; echo; + echo -n "dev_id: "; cat /sys/class/net/${ifaceSanitized}/dev_id 2>/dev/null; echo; + echo -n "dev_port: "; cat /sys/class/net/${ifaceSanitized}/dev_port 2>/dev/null; echo; + echo -n "dormant: "; cat /sys/class/net/${ifaceSanitized}/dormant 2>/dev/null; echo; + echo -n "duplex: "; cat /sys/class/net/${ifaceSanitized}/duplex 2>/dev/null; echo; + echo -n "flags: "; cat /sys/class/net/${ifaceSanitized}/flags 2>/dev/null; echo; + echo -n "gro_flush_timeout: "; cat /sys/class/net/${ifaceSanitized}/gro_flush_timeout 2>/dev/null; echo; + echo -n "ifalias: "; cat /sys/class/net/${ifaceSanitized}/ifalias 2>/dev/null; echo; + echo -n "ifindex: "; cat /sys/class/net/${ifaceSanitized}/ifindex 2>/dev/null; echo; + echo -n "iflink: "; cat /sys/class/net/${ifaceSanitized}/iflink 2>/dev/null; echo; + echo -n "link_mode: "; cat /sys/class/net/${ifaceSanitized}/link_mode 2>/dev/null; echo; + echo -n "mtu: "; cat /sys/class/net/${ifaceSanitized}/mtu 2>/dev/null; echo; + echo -n "netdev_group: "; cat /sys/class/net/${ifaceSanitized}/netdev_group 2>/dev/null; echo; + echo -n "operstate: "; cat /sys/class/net/${ifaceSanitized}/operstate 2>/dev/null; echo; + echo -n "proto_down: "; cat /sys/class/net/${ifaceSanitized}/proto_down 2>/dev/null; echo; + echo -n "speed: "; cat /sys/class/net/${ifaceSanitized}/speed 2>/dev/null; echo; + echo -n "tx_queue_len: "; cat /sys/class/net/${ifaceSanitized}/tx_queue_len 2>/dev/null; echo; + echo -n "type: "; cat /sys/class/net/${ifaceSanitized}/type 2>/dev/null; echo; + echo -n "wireless: "; cat /proc/net/wireless 2>/dev/null | grep ${ifaceSanitized}; echo; + echo -n "wirelessspeed: "; iw dev ${ifaceSanitized} link 2>&1 | grep bitrate; echo;`; - return new Promise((resolve) => { - process.nextTick(() => { - let data = []; - if (_linux$9) { - // see https://wiki.ubuntuusers.de/lsblk/ - // exec("lsblk -bo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,TRAN,SERIAL,LABEL,MODEL,OWNER,GROUP,MODE,ALIGNMENT,MIN-IO,OPT-IO,PHY-SEC,LOG-SEC,SCHED,RQ-SIZE,RA,WSAME", function (error, stdout) { - exec$9('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - let lines = blkStdoutToObject(stdout).split('\n'); - data = parseBlk(lines); - data = raidMatchLinux(data); - data = matchDevicesLinux(data); - if (callback) { - callback(data); - } - resolve(data); - } else { - exec$9('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - let lines = blkStdoutToObject(stdout).split('\n'); - data = parseBlk(lines); - data = raidMatchLinux(data); + let lines = []; + try { + lines = execSync$4(cmd).toString().split('\n'); + const connectionName = getLinuxIfaceConnectionName(ifaceSanitized); + dhcp = getLinuxIfaceDHCPstatus(ifaceSanitized, connectionName, _dhcpNics); + dnsSuffix = getLinuxIfaceDNSsuffix(connectionName); + ieee8021xAuth = getLinuxIfaceIEEE8021xAuth(connectionName); + ieee8021xState = getLinuxIfaceIEEE8021xState(ieee8021xAuth); + } catch (e) { + util$a.noop(); } - if (callback) { - callback(data); + duplex = util$a.getValue(lines, 'duplex'); + duplex = duplex.startsWith('cat') ? '' : duplex; + mtu = parseInt(util$a.getValue(lines, 'mtu'), 10); + let myspeed = parseInt(util$a.getValue(lines, 'speed'), 10); + speed = isNaN(myspeed) ? null : myspeed; + let wirelessspeed = util$a.getValue(lines, 'wirelessspeed').split('tx bitrate: '); + if (speed === null && wirelessspeed.length === 2) { + myspeed = parseFloat(wirelessspeed[1]); + speed = isNaN(myspeed) ? null : myspeed; } - resolve(data); - }); - } - }); - } - if (_darwin$9) { - exec$9('diskutil info -all', { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - // parse lines into temp array of devices - data = parseDevices(lines); - data = matchDevicesMac(data); - } - if (callback) { - callback(data); - } - resolve(data); - }); - } - if (_sunos$8) { - if (callback) { callback(data); } - resolve(data); - } - if (_windows$a) { - let drivetypes = ['Unknown', 'NoRoot', 'Removable', 'Local', 'Network', 'CD/DVD', 'RAM']; - try { - // util.wmic('logicaldisk get Caption,Description,DeviceID,DriveType,FileSystem,FreeSpace,Name,Size,VolumeName,VolumeSerialNumber /value').then((stdout, error) => { - // util.powerShell('Get-CimInstance Win32_logicaldisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl').then((stdout, error) => { - const workload = []; - workload.push(util$b.powerShell('Get-CimInstance -ClassName Win32_LogicalDisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl')); - workload.push(util$b.powerShell('Get-WmiObject -Class Win32_diskdrive | Select-Object -Property PNPDeviceId,DeviceID, Model, Size, @{L=\'Partitions\'; E={$_.GetRelated(\'Win32_DiskPartition\').GetRelated(\'Win32_LogicalDisk\') | Select-Object -Property DeviceID, VolumeName, Size, FreeSpace}} | fl')); - util$b.promiseAll( - workload - ).then((res) => { - let logicalDisks = res.results[0].toString().split(/\n\s*\n/); - let diskDrives = res.results[1].toString().split(/\n\s*\n/); - logicalDisks.forEach(function (device) { - let lines = device.split('\r\n'); - let drivetype = util$b.getValue(lines, 'drivetype', ':'); - if (drivetype) { - data.push({ - name: util$b.getValue(lines, 'name', ':'), - identifier: util$b.getValue(lines, 'caption', ':'), - type: 'disk', - fsType: util$b.getValue(lines, 'filesystem', ':').toLowerCase(), - mount: util$b.getValue(lines, 'caption', ':'), - size: util$b.getValue(lines, 'size', ':'), - physical: (drivetype >= 0 && drivetype <= 6) ? drivetypes[drivetype] : drivetypes[0], - uuid: util$b.getValue(lines, 'volumeserialnumber', ':'), - label: util$b.getValue(lines, 'volumename', ':'), - model: '', - serial: util$b.getValue(lines, 'volumeserialnumber', ':'), - removable: drivetype === '2', - protocol: '', - group: '', - device: '' - }); + carrierChanges = parseInt(util$a.getValue(lines, 'carrier_changes'), 10); + const operstate = util$a.getValue(lines, 'operstate'); + type = operstate === 'up' ? (util$a.getValue(lines, 'wireless').trim() ? 'wireless' : 'wired') : 'unknown'; + if (ifaceSanitized === 'lo' || ifaceSanitized.startsWith('bond')) { type = 'virtual'; } + + let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false; + if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) { + internal = true; } - }); - // match devices - data = matchDevicesWin(data, diskDrives); - if (callback) { - callback(data); + const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac); + result.push({ + iface: ifaceSanitized, + ifaceName, + default: iface === defaultInterface, + ip4, + ip4subnet, + ip6, + ip6subnet, + mac, + internal, + virtual, + operstate, + type, + duplex, + mtu, + speed, + dhcp, + dnsSuffix, + ieee8021xAuth, + ieee8021xState, + carrierChanges, + }); } - resolve(data); - }); - } catch (e) { - if (callback) { callback(data); } - resolve(data); + } + _networkInterfaces = result; + if (defaultString.toLowerCase().indexOf('default') >= 0) { + result = result.filter(item => item.default); + if (result.length > 0) { + result = result[0]; + } else { + result = []; + } + } + if (callback) { callback(result); } + resolve(result); } } - if (_freebsd$8 || _openbsd$8 || _netbsd$8) { - // will follow - if (callback) { callback(null); } - resolve(null); - } - - }); - }); -} + if (_windows$9) { + if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) { + // no changes - just return object + result = _networkInterfaces; -filesystem.blockDevices = blockDevices; + if (callback) { callback(result); } + resolve(result); + } else { + _ifaces = JSON.parse(JSON.stringify(ifaces)); + const defaultInterface = getDefaultNetworkInterface(); -// -------------------------- -// FS - speed + getWindowsNics().then(function (nics) { + nics.forEach(nic => { + let found = false; + Object.keys(ifaces).forEach(key => { + if (!found) { + ifaces[key].forEach(value => { + if (Object.keys(value).indexOf('mac') >= 0) { + found = value['mac'] === nic.mac; + } + }); + } + }); -function calcFsSpeed(rx, wx) { - let result = { - rx: 0, - wx: 0, - tx: 0, - rx_sec: null, - wx_sec: null, - tx_sec: null, - ms: 0 - }; + if (!found) { + ifaces[nic.name] = [{ mac: nic.mac }]; + } + }); + nics8021xInfo = getWindowsWiredProfilesInformation(); + dnsSuffixes = getWindowsDNSsuffixes(); + for (let dev in ifaces) { - if (_fs_speed && _fs_speed.ms) { - result.rx = rx; - result.wx = wx; - result.tx = result.rx + result.wx; - result.ms = Date.now() - _fs_speed.ms; - result.rx_sec = (result.rx - _fs_speed.bytes_read) / (result.ms / 1000); - result.wx_sec = (result.wx - _fs_speed.bytes_write) / (result.ms / 1000); - result.tx_sec = result.rx_sec + result.wx_sec; - _fs_speed.rx_sec = result.rx_sec; - _fs_speed.wx_sec = result.wx_sec; - _fs_speed.tx_sec = result.tx_sec; - _fs_speed.bytes_read = result.rx; - _fs_speed.bytes_write = result.wx; - _fs_speed.bytes_overall = result.rx + result.wx; - _fs_speed.ms = Date.now(); - _fs_speed.last_ms = result.ms; - } else { - result.rx = rx; - result.wx = wx; - result.tx = result.rx + result.wx; - _fs_speed.rx_sec = null; - _fs_speed.wx_sec = null; - _fs_speed.tx_sec = null; - _fs_speed.bytes_read = result.rx; - _fs_speed.bytes_write = result.wx; - _fs_speed.bytes_overall = result.rx + result.wx; - _fs_speed.ms = Date.now(); - _fs_speed.last_ms = 0; - } - return result; -} + let ifaceSanitized = ''; + const s = util$a.isPrototypePolluted() ? '---' : util$a.sanitizeShellString(dev); + const l = util$a.mathMin(s.length, 2000); + for (let i = 0; i <= l; i++) { + if (s[i] !== undefined) { + ifaceSanitized = ifaceSanitized + s[i]; + } + } -function fsStats(callback) { + let iface = dev; + let ip4 = ''; + let ip4subnet = ''; + let ip6 = ''; + let ip6subnet = ''; + let mac = ''; + let duplex = ''; + let mtu = ''; + let speed = null; + let carrierChanges = 0; + let operstate = 'down'; + let dhcp = false; + let dnsSuffix = ''; + let ieee8021xAuth = ''; + let ieee8021xState = ''; + let type = ''; - return new Promise((resolve) => { - process.nextTick(() => { - if (_windows$a || _freebsd$8 || _openbsd$8 || _netbsd$8 || _sunos$8) { - return resolve(null); - } + if ({}.hasOwnProperty.call(ifaces, dev)) { + let ifaceName = dev; + ifaces[dev].forEach(function (details) { + if (details.family === 'IPv4' || details.family === 4) { + ip4 = details.address; + ip4subnet = details.netmask; + } + if (details.family === 'IPv6' || details.family === 6) { + if (!ip6 || ip6.match(/^fe80::/i)) { + ip6 = details.address; + ip6subnet = details.netmask; + } + } + mac = details.mac; + // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2) + const nodeMainVersion = parseInt(process.versions.node.split('.'), 10); + if (mac.indexOf('00:00:0') > -1 && (_linux$8 || _darwin$8) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) { + if (Object.keys(_mac).length === 0) { + _mac = getMacAddresses(); + } + mac = _mac[dev] || ''; + } + }); - let result = { - rx: 0, - wx: 0, - tx: 0, - rx_sec: null, - wx_sec: null, - tx_sec: null, - ms: 0 - }; - let rx = 0; - let wx = 0; - if ((_fs_speed && !_fs_speed.ms) || (_fs_speed && _fs_speed.ms && Date.now() - _fs_speed.ms >= 500)) { - if (_linux$9) { - // exec("df -k | grep /dev/", function(error, stdout) { - exec$9('lsblk -r 2>/dev/null | grep /', { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - let fs_filter = []; - lines.forEach(function (line) { - if (line !== '') { - line = line.trim().split(' '); - if (fs_filter.indexOf(line[0]) === -1) { fs_filter.push(line[0]); } - } - }); - let output = fs_filter.join('|'); - exec$9('cat /proc/diskstats | egrep "' + output + '"', { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - lines.forEach(function (line) { - line = line.trim(); - if (line !== '') { - line = line.replace(/ +/g, ' ').split(' '); + dnsSuffix = getWindowsIfaceDNSsuffix(dnsSuffixes.ifaces, ifaceSanitized); + let foundFirst = false; + nics.forEach(detail => { + if (detail.mac === mac && !foundFirst) { + iface = detail.iface || iface; + ifaceName = detail.name; + dhcp = detail.dhcp; + operstate = detail.operstate; + speed = detail.speed; + type = detail.type; + foundFirst = true; + } + }); - rx += parseInt(line[5]) * 512; - wx += parseInt(line[9]) * 512; - } - }); - result = calcFsSpeed(rx, wx); - } - if (callback) { - callback(result); + if (dev.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('802.11n') >= 0 || ifaceName.toLowerCase().indexOf('wireless') >= 0 || ifaceName.toLowerCase().indexOf('wi-fi') >= 0 || ifaceName.toLowerCase().indexOf('wifi') >= 0) { + type = 'wireless'; } - resolve(result); - }); - } else { - if (callback) { - callback(result); - } - resolve(result); - } - }); - } - if (_darwin$9) { - exec$9('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - lines.forEach(function (line) { - line = line.trim(); - if (line !== '') { - line = line.split(','); - rx += parseInt(line[2]); - wx += parseInt(line[9]); + const IEEE8021x = getWindowsIEEE8021x(type, ifaceSanitized, nics8021xInfo); + ieee8021xAuth = IEEE8021x.protocol; + ieee8021xState = IEEE8021x.state; + let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false; + if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) { + internal = true; } - }); - result = calcFsSpeed(rx, wx); + const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac); + result.push({ + iface, + ifaceName, + default: iface === defaultInterface, + ip4, + ip4subnet, + ip6, + ip6subnet, + mac, + internal, + virtual, + operstate, + type, + duplex, + mtu, + speed, + dhcp, + dnsSuffix, + ieee8021xAuth, + ieee8021xState, + carrierChanges, + }); + } } - if (callback) { - callback(result); + _networkInterfaces = result; + if (defaultString.toLowerCase().indexOf('default') >= 0) { + result = result.filter(item => item.default); + if (result.length > 0) { + result = result[0]; + } else { + result = []; + } } + if (callback) { callback(result); } resolve(result); }); } - } else { - result.ms = _fs_speed.last_ms; - result.rx = _fs_speed.bytes_read; - result.wx = _fs_speed.bytes_write; - result.tx = _fs_speed.bytes_read + _fs_speed.bytes_write; - result.rx_sec = _fs_speed.rx_sec; - result.wx_sec = _fs_speed.wx_sec; - result.tx_sec = _fs_speed.tx_sec; - if (callback) { - callback(result); - } - resolve(result); } }); }); } -filesystem.fsStats = fsStats; +network.networkInterfaces = networkInterfaces; -function calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime) { +// -------------------------- +// NET - Speed + +function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors) { let result = { - rIO: 0, - wIO: 0, - tIO: 0, - rIO_sec: null, - wIO_sec: null, - tIO_sec: null, - rWaitTime: 0, - wWaitTime: 0, - tWaitTime: 0, - rWaitPercent: null, - wWaitPercent: null, - tWaitPercent: null, + iface, + operstate, + rx_bytes, + rx_dropped, + rx_errors, + tx_bytes, + tx_dropped, + tx_errors, + rx_sec: null, + tx_sec: null, ms: 0 }; - if (_disk_io && _disk_io.ms) { - result.rIO = rIO; - result.wIO = wIO; - result.tIO = rIO + wIO; - result.ms = Date.now() - _disk_io.ms; - result.rIO_sec = (result.rIO - _disk_io.rIO) / (result.ms / 1000); - result.wIO_sec = (result.wIO - _disk_io.wIO) / (result.ms / 1000); - result.tIO_sec = result.rIO_sec + result.wIO_sec; - result.rWaitTime = rWaitTime; - result.wWaitTime = wWaitTime; - result.tWaitTime = tWaitTime; - result.rWaitPercent = (result.rWaitTime - _disk_io.rWaitTime) * 100 / (result.ms); - result.wWaitPercent = (result.wWaitTime - _disk_io.wWaitTime) * 100 / (result.ms); - result.tWaitPercent = (result.tWaitTime - _disk_io.tWaitTime) * 100 / (result.ms); - _disk_io.rIO = rIO; - _disk_io.wIO = wIO; - _disk_io.rIO_sec = result.rIO_sec; - _disk_io.wIO_sec = result.wIO_sec; - _disk_io.tIO_sec = result.tIO_sec; - _disk_io.rWaitTime = rWaitTime; - _disk_io.wWaitTime = wWaitTime; - _disk_io.tWaitTime = tWaitTime; - _disk_io.rWaitPercent = result.rWaitPercent; - _disk_io.wWaitPercent = result.wWaitPercent; - _disk_io.tWaitPercent = result.tWaitPercent; - _disk_io.last_ms = result.ms; - _disk_io.ms = Date.now(); + + if (_network[iface] && _network[iface].ms) { + result.ms = Date.now() - _network[iface].ms; + result.rx_sec = (rx_bytes - _network[iface].rx_bytes) >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0; + result.tx_sec = (tx_bytes - _network[iface].tx_bytes) >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0; + _network[iface].rx_bytes = rx_bytes; + _network[iface].tx_bytes = tx_bytes; + _network[iface].rx_sec = result.rx_sec; + _network[iface].tx_sec = result.tx_sec; + _network[iface].ms = Date.now(); + _network[iface].last_ms = result.ms; + _network[iface].operstate = operstate; } else { - result.rIO = rIO; - result.wIO = wIO; - result.tIO = rIO + wIO; - result.rWaitTime = rWaitTime; - result.wWaitTime = wWaitTime; - result.tWaitTime = tWaitTime; - _disk_io.rIO = rIO; - _disk_io.wIO = wIO; - _disk_io.rIO_sec = null; - _disk_io.wIO_sec = null; - _disk_io.tIO_sec = null; - _disk_io.rWaitTime = rWaitTime; - _disk_io.wWaitTime = wWaitTime; - _disk_io.tWaitTime = tWaitTime; - _disk_io.rWaitPercent = null; - _disk_io.wWaitPercent = null; - _disk_io.tWaitPercent = null; - _disk_io.last_ms = 0; - _disk_io.ms = Date.now(); + if (!_network[iface]) { _network[iface] = {}; } + _network[iface].rx_bytes = rx_bytes; + _network[iface].tx_bytes = tx_bytes; + _network[iface].rx_sec = null; + _network[iface].tx_sec = null; + _network[iface].ms = Date.now(); + _network[iface].last_ms = 0; + _network[iface].operstate = operstate; } return result; } -function disksIO(callback) { +function networkStats(ifaces, callback) { + + let ifacesArray = []; return new Promise((resolve) => { process.nextTick(() => { - if (_windows$a) { - return resolve(null); + + // fallback - if only callback is given + if (util$a.isFunction(ifaces) && !callback) { + callback = ifaces; + ifacesArray = [getDefaultNetworkInterface()]; + } else { + if (typeof ifaces !== 'string' && ifaces !== undefined) { + if (callback) { callback([]); } + return resolve([]); + } + ifaces = ifaces || getDefaultNetworkInterface(); + + ifaces.__proto__.toLowerCase = util$a.stringToLower; + ifaces.__proto__.replace = util$a.stringReplace; + ifaces.__proto__.trim = util$a.stringTrim; + + ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|'); + ifacesArray = ifaces.split('|'); } - if (_sunos$8) { - return resolve(null); + + const result = []; + + const workload = []; + if (ifacesArray.length && ifacesArray[0].trim() === '*') { + ifacesArray = []; + networkInterfaces(false).then(allIFaces => { + for (let iface of allIFaces) { + ifacesArray.push(iface.iface); + } + networkStats(ifacesArray.join(',')).then(result => { + if (callback) { callback(result); } + resolve(result); + }); + }); + } else { + for (let iface of ifacesArray) { + workload.push(networkStatsSingle(iface.trim())); + } + if (workload.length) { + Promise.all( + workload + ).then((data) => { + if (callback) { callback(data); } + resolve(data); + }); + } else { + if (callback) { callback(result); } + resolve(result); + } + } + }); + }); +} + +function networkStatsSingle(iface) { + + function parseLinesWindowsPerfData(sections) { + let perfData = []; + for (let i in sections) { + if ({}.hasOwnProperty.call(sections, i)) { + if (sections[i].trim() !== '') { + let lines = sections[i].trim().split('\r\n'); + perfData.push({ + name: util$a.getValue(lines, 'Name', ':').replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase(), + rx_bytes: parseInt(util$a.getValue(lines, 'BytesReceivedPersec', ':'), 10), + rx_errors: parseInt(util$a.getValue(lines, 'PacketsReceivedErrors', ':'), 10), + rx_dropped: parseInt(util$a.getValue(lines, 'PacketsReceivedDiscarded', ':'), 10), + tx_bytes: parseInt(util$a.getValue(lines, 'BytesSentPersec', ':'), 10), + tx_errors: parseInt(util$a.getValue(lines, 'PacketsOutboundErrors', ':'), 10), + tx_dropped: parseInt(util$a.getValue(lines, 'PacketsOutboundDiscarded', ':'), 10) + }); + } + } + } + return perfData; + } + + return new Promise((resolve) => { + process.nextTick(() => { + let ifaceSanitized = ''; + const s = util$a.isPrototypePolluted() ? '---' : util$a.sanitizeShellString(iface); + const l = util$a.mathMin(s.length, 2000); + for (let i = 0; i <= l; i++) { + if (s[i] !== undefined) { + ifaceSanitized = ifaceSanitized + s[i]; + } } let result = { - rIO: 0, - wIO: 0, - tIO: 0, - rIO_sec: null, - wIO_sec: null, - tIO_sec: null, - rWaitTime: 0, - wWaitTime: 0, - tWaitTime: 0, - rWaitPercent: null, - wWaitPercent: null, - tWaitPercent: null, + iface: ifaceSanitized, + operstate: 'unknown', + rx_bytes: 0, + rx_dropped: 0, + rx_errors: 0, + tx_bytes: 0, + tx_dropped: 0, + tx_errors: 0, + rx_sec: null, + tx_sec: null, ms: 0 }; - let rIO = 0; - let wIO = 0; - let rWaitTime = 0; - let wWaitTime = 0; - let tWaitTime = 0; - if ((_disk_io && !_disk_io.ms) || (_disk_io && _disk_io.ms && Date.now() - _disk_io.ms >= 500)) { - if (_linux$9 || _freebsd$8 || _openbsd$8 || _netbsd$8) { - // prints Block layer statistics for all mounted volumes - // var cmd = "for mount in `lsblk | grep / | sed -r 's/│ └─//' | cut -d ' ' -f 1`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done"; - // var cmd = "for mount in `lsblk | grep / | sed 's/[│└─├]//g' | awk '{$1=$1};1' | cut -d ' ' -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done"; - let cmd = 'for mount in `lsblk 2>/dev/null | grep " disk " | sed "s/[│└─├]//g" | awk \'{$1=$1};1\' | cut -d " " -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r "s/ +/;/g" | sed -r "s/^;//"; done'; + let operstate = 'unknown'; + let rx_bytes = 0; + let tx_bytes = 0; + let rx_dropped = 0; + let rx_errors = 0; + let tx_dropped = 0; + let tx_errors = 0; - exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - let lines = stdout.split('\n'); - lines.forEach(function (line) { - // ignore empty lines - if (!line) { return; } + let cmd, lines, stats; + if (!_network[ifaceSanitized] || (_network[ifaceSanitized] && !_network[ifaceSanitized].ms) || (_network[ifaceSanitized] && _network[ifaceSanitized].ms && Date.now() - _network[ifaceSanitized].ms >= 500)) { + if (_linux$8) { + if (fs$2.existsSync('/sys/class/net/' + ifaceSanitized)) { + cmd = + 'cat /sys/class/net/' + ifaceSanitized + '/operstate; ' + + 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_bytes; ' + + 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_bytes; ' + + 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_dropped; ' + + 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_errors; ' + + 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_dropped; ' + + 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_errors; '; + exec$8(cmd, function (error, stdout) { + if (!error) { + lines = stdout.toString().split('\n'); + operstate = lines[0].trim(); + rx_bytes = parseInt(lines[1], 10); + tx_bytes = parseInt(lines[2], 10); + rx_dropped = parseInt(lines[3], 10); + rx_errors = parseInt(lines[4], 10); + tx_dropped = parseInt(lines[5], 10); + tx_errors = parseInt(lines[6], 10); - // sum r/wIO of all disks to compute all disks IO - let stats = line.split(';'); - rIO += parseInt(stats[0]); - wIO += parseInt(stats[4]); - rWaitTime += parseInt(stats[3]); - wWaitTime += parseInt(stats[7]); - tWaitTime += parseInt(stats[10]); - }); - result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime); + result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); - if (callback) { - callback(result); } resolve(result); - } else { - if (callback) { - callback(result); + }); + } else { + resolve(result); + } + } + if (_freebsd$7 || _openbsd$7 || _netbsd$7) { + cmd = 'netstat -ibndI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input] + exec$8(cmd, function (error, stdout) { + if (!error) { + lines = stdout.toString().split('\n'); + for (let i = 1; i < lines.length; i++) { + const line = lines[i].replace(/ +/g, ' ').split(' '); + if (line && line[0] && line[7] && line[10]) { + rx_bytes = rx_bytes + parseInt(line[7]); + if (line[6].trim() !== '-') { rx_dropped = rx_dropped + parseInt(line[6]); } + if (line[5].trim() !== '-') { rx_errors = rx_errors + parseInt(line[5]); } + tx_bytes = tx_bytes + parseInt(line[10]); + if (line[12].trim() !== '-') { tx_dropped = tx_dropped + parseInt(line[12]); } + if (line[9].trim() !== '-') { tx_errors = tx_errors + parseInt(line[9]); } + operstate = 'up'; + } } - resolve(result); + result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); } + resolve(result); }); } - if (_darwin$9) { - exec$9('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (_darwin$8) { + cmd = 'ifconfig ' + ifaceSanitized + ' | grep "status"'; // lgtm [js/shell-command-constructed-from-input] + exec$8(cmd, function (error, stdout) { + result.operstate = (stdout.toString().split(':')[1] || '').trim(); + result.operstate = (result.operstate || '').toLowerCase(); + result.operstate = (result.operstate === 'active' ? 'up' : (result.operstate === 'inactive' ? 'down' : 'unknown')); + cmd = 'netstat -bdI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input] + exec$8(cmd, function (error, stdout) { + if (!error) { + lines = stdout.toString().split('\n'); + // if there is less than 2 lines, no information for this interface was found + if (lines.length > 1 && lines[1].trim() !== '') { + // skip header line + // use the second line because it is tied to the NIC instead of the ipv4 or ipv6 address + stats = lines[1].replace(/ +/g, ' ').split(' '); + const offset = stats.length > 11 ? 1 : 0; + rx_bytes = parseInt(stats[offset + 5]); + rx_dropped = parseInt(stats[offset + 10]); + rx_errors = parseInt(stats[offset + 4]); + tx_bytes = parseInt(stats[offset + 8]); + tx_dropped = parseInt(stats[offset + 10]); + tx_errors = parseInt(stats[offset + 7]); + result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, result.operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); + } + } + resolve(result); + }); + }); + } + if (_windows$9) { + let perfData = []; + let ifaceName = ifaceSanitized; + + // Performance Data + util$a.powerShell('Get-CimInstance Win32_PerfRawData_Tcpip_NetworkInterface | select Name,BytesReceivedPersec,PacketsReceivedErrors,PacketsReceivedDiscarded,BytesSentPersec,PacketsOutboundErrors,PacketsOutboundDiscarded | fl').then((stdout, error) => { if (!error) { - let lines = stdout.toString().split('\n'); - lines.forEach(function (line) { - line = line.trim(); - if (line !== '') { - line = line.split(','); + const psections = stdout.toString().split(/\n\s*\n/); + perfData = parseLinesWindowsPerfData(psections); + } - rIO += parseInt(line[10]); - wIO += parseInt(line[0]); - } + // Network Interfaces + networkInterfaces(false).then(interfaces => { + // get bytes sent, received from perfData by name + rx_bytes = 0; + tx_bytes = 0; + perfData.forEach(detail => { + interfaces.forEach(det => { + if ((det.iface.toLowerCase() === ifaceSanitized.toLowerCase() || + det.mac.toLowerCase() === ifaceSanitized.toLowerCase() || + det.ip4.toLowerCase() === ifaceSanitized.toLowerCase() || + det.ip6.toLowerCase() === ifaceSanitized.toLowerCase() || + det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === ifaceSanitized.replace(/[()[\] ]+/g, '').replace('#', '_').toLowerCase()) && + (det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === detail.name)) { + ifaceName = det.iface; + rx_bytes = detail.rx_bytes; + rx_dropped = detail.rx_dropped; + rx_errors = detail.rx_errors; + tx_bytes = detail.tx_bytes; + tx_dropped = detail.tx_dropped; + tx_errors = detail.tx_errors; + operstate = det.operstate; + } + }); }); - result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime); - } - if (callback) { - callback(result); - } - resolve(result); + if (rx_bytes && tx_bytes) { + result = calcNetworkSpeed(ifaceName, parseInt(rx_bytes), parseInt(tx_bytes), operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); + } + resolve(result); + }); }); } } else { - result.rIO = _disk_io.rIO; - result.wIO = _disk_io.wIO; - result.tIO = _disk_io.rIO + _disk_io.wIO; - result.ms = _disk_io.last_ms; - result.rIO_sec = _disk_io.rIO_sec; - result.wIO_sec = _disk_io.wIO_sec; - result.tIO_sec = _disk_io.tIO_sec; - result.rWaitTime = _disk_io.rWaitTime; - result.wWaitTime = _disk_io.wWaitTime; - result.tWaitTime = _disk_io.tWaitTime; - result.rWaitPercent = _disk_io.rWaitPercent; - result.wWaitPercent = _disk_io.wWaitPercent; - result.tWaitPercent = _disk_io.tWaitPercent; - if (callback) { - callback(result); - } + result.rx_bytes = _network[ifaceSanitized].rx_bytes; + result.tx_bytes = _network[ifaceSanitized].tx_bytes; + result.rx_sec = _network[ifaceSanitized].rx_sec; + result.tx_sec = _network[ifaceSanitized].tx_sec; + result.ms = _network[ifaceSanitized].last_ms; + result.operstate = _network[ifaceSanitized].operstate; resolve(result); } }); }); } -filesystem.disksIO = disksIO; - -function diskLayout(callback) { +network.networkStats = networkStats; - function getVendorFromModel(model) { - const diskManufacturers = [ - { pattern: 'WESTERN.*', manufacturer: 'Western Digital' }, - { pattern: '^WDC.*', manufacturer: 'Western Digital' }, - { pattern: 'WD.*', manufacturer: 'Western Digital' }, - { pattern: 'TOSHIBA.*', manufacturer: 'Toshiba' }, - { pattern: 'HITACHI.*', manufacturer: 'Hitachi' }, - { pattern: '^IC.*', manufacturer: 'Hitachi' }, - { pattern: '^HTS.*', manufacturer: 'Hitachi' }, - { pattern: 'SANDISK.*', manufacturer: 'SanDisk' }, - { pattern: 'KINGSTON.*', manufacturer: 'Kingston Technology' }, - { pattern: '^SONY.*', manufacturer: 'Sony' }, - { pattern: 'TRANSCEND.*', manufacturer: 'Transcend' }, - { pattern: 'SAMSUNG.*', manufacturer: 'Samsung' }, - { pattern: '^ST(?!I\\ ).*', manufacturer: 'Seagate' }, - { pattern: '^STI\\ .*', manufacturer: 'SimpleTech' }, - { pattern: '^D...-.*', manufacturer: 'IBM' }, - { pattern: '^IBM.*', manufacturer: 'IBM' }, - { pattern: '^FUJITSU.*', manufacturer: 'Fujitsu' }, - { pattern: '^MP.*', manufacturer: 'Fujitsu' }, - { pattern: '^MK.*', manufacturer: 'Toshiba' }, - { pattern: 'MAXTO.*', manufacturer: 'Maxtor' }, - { pattern: 'PIONEER.*', manufacturer: 'Pioneer' }, - { pattern: 'PHILIPS.*', manufacturer: 'Philips' }, - { pattern: 'QUANTUM.*', manufacturer: 'Quantum Technology' }, - { pattern: 'FIREBALL.*', manufacturer: 'Quantum Technology' }, - { pattern: '^VBOX.*', manufacturer: 'VirtualBox' }, - { pattern: 'CORSAIR.*', manufacturer: 'Corsair Components' }, - { pattern: 'CRUCIAL.*', manufacturer: 'Crucial' }, - { pattern: 'ECM.*', manufacturer: 'ECM' }, - { pattern: 'INTEL.*', manufacturer: 'INTEL' }, - { pattern: 'EVO.*', manufacturer: 'Samsung' }, - { pattern: 'APPLE.*', manufacturer: 'Apple' }, - ]; +// -------------------------- +// NET - connections (sockets) - let result = ''; - if (model) { - model = model.toUpperCase(); - diskManufacturers.forEach((manufacturer) => { - const re = RegExp(manufacturer.pattern); - if (re.test(model)) { result = manufacturer.manufacturer; } - }); +function getProcessName(processes, pid) { + let cmd = ''; + processes.forEach(line => { + const parts = line.split(' '); + const id = parseInt(parts[0], 10) || -1; + if (id === pid) { + parts.shift(); + cmd = parts.join(' ').split(':')[0]; } - return result; - } + }); + cmd = cmd.split(' -')[0]; + // return cmd; + const cmdParts = cmd.split('/'); + return cmdParts[cmdParts.length - 1]; +} + +function networkConnections(callback) { return new Promise((resolve) => { process.nextTick(() => { - - const commitResult = res => { - for (let i = 0; i < res.length; i++) { - delete res[i].BSDName; - } - if (callback) { - callback(res); - } - resolve(res); - }; - let result = []; - let cmd = ''; - - if (_linux$9) { - let cmdFullSmart = ''; - - exec$9('export LC_ALL=C; lsblk -ablJO 2>/dev/null; unset LC_ALL', { maxBuffer: 1024 * 1024 }, function (error, stdout) { - if (!error) { - try { - const out = stdout.toString().trim(); - let devices = []; - try { - const outJSON = JSON.parse(out); - if (outJSON && {}.hasOwnProperty.call(outJSON, 'blockdevices')) { - devices = outJSON.blockdevices.filter(item => { return (item.type === 'disk') && item.size > 0 && (item.model !== null || (item.mountpoint === null && item.label === null && item.fstype === null && item.parttype === null && item.path && item.path.indexOf('/ram') !== 0 && item.path.indexOf('/loop') !== 0 && item['disc-max'] && item['disc-max'] !== 0)); }); - } - } catch (e) { - // fallback to older version of lsblk - try { - const out2 = execSync$5('export LC_ALL=C; lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER,GROUP 2>/dev/null; unset LC_ALL').toString(); - let lines = blkStdoutToObject(out2).split('\n'); - const data = parseBlk(lines); - devices = data.filter(item => { return (item.type === 'disk') && item.size > 0 && ((item.model !== null && item.model !== '') || (item.mount === '' && item.label === '' && item.fsType === '')); }); - } catch (e) { - util$b.noop(); + if (_linux$8 || _freebsd$7 || _openbsd$7 || _netbsd$7) { + let cmd = 'export LC_ALL=C; netstat -tunap | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; + if (_freebsd$7 || _openbsd$7 || _netbsd$7) { cmd = 'export LC_ALL=C; netstat -na | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; } + exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + let lines = stdout.toString().split('\n'); + if (!error && (lines.length > 1 || lines[0] != '')) { + lines.forEach(function (line) { + line = line.replace(/ +/g, ' ').split(' '); + if (line.length >= 7) { + let localip = line[3]; + let localport = ''; + let localaddress = line[3].split(':'); + if (localaddress.length > 1) { + localport = localaddress[localaddress.length - 1]; + localaddress.pop(); + localip = localaddress.join(':'); } - } - devices.forEach((device) => { - let mediumType = ''; - const BSDName = '/dev/' + device.name; - const logical = device.name; - try { - mediumType = execSync$5('cat /sys/block/' + logical + '/queue/rotational 2>/dev/null').toString().split('\n')[0]; - } catch (e) { - util$b.noop(); + let peerip = line[4]; + let peerport = ''; + let peeraddress = line[4].split(':'); + if (peeraddress.length > 1) { + peerport = peeraddress[peeraddress.length - 1]; + peeraddress.pop(); + peerip = peeraddress.join(':'); } - let interfaceType = device.tran ? device.tran.toUpperCase().trim() : ''; - if (interfaceType === 'NVME') { - mediumType = '2'; - interfaceType = 'PCIe'; + let connstate = line[5]; + let proc = line[6].split('/'); + + if (connstate) { + result.push({ + protocol: line[0], + localAddress: localip, + localPort: localport, + peerAddress: peerip, + peerPort: peerport, + state: connstate, + pid: proc[0] && proc[0] !== '-' ? parseInt(proc[0], 10) : null, + process: proc[1] ? proc[1].split(' ')[0].split(':')[0] : '' + }); } - result.push({ - device: BSDName, - type: (mediumType === '0' ? 'SSD' : (mediumType === '1' ? 'HD' : (mediumType === '2' ? 'NVMe' : (device.model && device.model.indexOf('SSD') > -1 ? 'SSD' : (device.model && device.model.indexOf('NVM') > -1 ? 'NVMe' : 'HD'))))), - name: device.model || '', - vendor: getVendorFromModel(device.model) || (device.vendor ? device.vendor.trim() : ''), - size: device.size || 0, - bytesPerSector: null, - totalCylinders: null, - totalHeads: null, - totalSectors: null, - totalTracks: null, - tracksPerCylinder: null, - sectorsPerTrack: null, - firmwareRevision: device.rev ? device.rev.trim() : '', - serialNum: device.serial ? device.serial.trim() : '', - interfaceType: interfaceType, - smartStatus: 'unknown', - temperature: null, - BSDName: BSDName - }); - cmd += `printf "\n${BSDName}|"; smartctl -H ${BSDName} | grep overall;`; - cmdFullSmart += `${cmdFullSmart ? 'printf ",";' : ''}smartctl -a -j ${BSDName};`; - }); - } catch (e) { - util$b.noop(); + } + }); + if (callback) { + callback(result); } - } - // check S.M.A.R.T. status - if (cmdFullSmart) { - exec$9(cmdFullSmart, { maxBuffer: 1024 * 1024 }, function (error, stdout) { - try { - const data = JSON.parse(`[${stdout}]`); - data.forEach(disk => { - const diskBSDName = disk.smartctl.argv[disk.smartctl.argv.length - 1]; + resolve(result); + } else { + cmd = 'ss -tunap | grep "ESTAB\\|SYN-SENT\\|SYN-RECV\\|FIN-WAIT1\\|FIN-WAIT2\\|TIME-WAIT\\|CLOSE\\|CLOSE-WAIT\\|LAST-ACK\\|LISTEN\\|CLOSING"'; + exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - for (let i = 0; i < result.length; i++) { - if (result[i].BSDName === diskBSDName) { - result[i].smartStatus = (disk.smart_status.passed ? 'Ok' : (disk.smart_status.passed === false ? 'Predicted Failure' : 'unknown')); - if (disk.temperature && disk.temperature.current) { - result[i].temperature = disk.temperature.current; + if (!error) { + let lines = stdout.toString().split('\n'); + lines.forEach(function (line) { + line = line.replace(/ +/g, ' ').split(' '); + if (line.length >= 6) { + let localip = line[4]; + let localport = ''; + let localaddress = line[4].split(':'); + if (localaddress.length > 1) { + localport = localaddress[localaddress.length - 1]; + localaddress.pop(); + localip = localaddress.join(':'); + } + let peerip = line[5]; + let peerport = ''; + let peeraddress = line[5].split(':'); + if (peeraddress.length > 1) { + peerport = peeraddress[peeraddress.length - 1]; + peeraddress.pop(); + peerip = peeraddress.join(':'); + } + let connstate = line[1]; + if (connstate === 'ESTAB') { connstate = 'ESTABLISHED'; } + if (connstate === 'TIME-WAIT') { connstate = 'TIME_WAIT'; } + let pid = null; + let process = ''; + if (line.length >= 7 && line[6].indexOf('users:') > -1) { + let proc = line[6].replace('users:(("', '').replace(/"/g, '').split(','); + if (proc.length > 2) { + process = proc[0].split(' ')[0].split(':')[0]; + pid = parseInt(proc[1], 10); } - result[i].smartData = disk; + } + if (connstate) { + result.push({ + protocol: line[0], + localAddress: localip, + localPort: localport, + peerAddress: peerip, + peerPort: peerport, + state: connstate, + pid, + process + }); } } }); - commitResult(result); - } catch (e) { - if (cmd) { - cmd = cmd + 'printf "\n"'; - exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { - let lines = stdout.toString().split('\n'); - lines.forEach(line => { - if (line) { - let parts = line.split('|'); - if (parts.length === 2) { - let BSDName = parts[0]; - parts[1] = parts[1].trim(); - let parts2 = parts[1].split(':'); - if (parts2.length === 2) { - parts2[1] = parts2[1].trim(); - let status = parts2[1].toLowerCase(); - for (let i = 0; i < result.length; i++) { - if (result[i].BSDName === BSDName) { - result[i].smartStatus = (status === 'passed' ? 'Ok' : (status === 'failed!' ? 'Predicted Failure' : 'unknown')); - } - } - } - } - } - }); - commitResult(result); - }); - } else { - commitResult(result); - } } + if (callback) { + callback(result); + } + resolve(result); }); - } else { - commitResult(result); } }); } - if (_freebsd$8 || _openbsd$8 || _netbsd$8) { - if (callback) { callback(result); } - resolve(result); - } - if (_sunos$8) { - if (callback) { callback(result); } - resolve(result); - } - if (_darwin$9) { - exec$9('system_profiler SPSerialATADataType SPNVMeDataType SPUSBDataType', { maxBuffer: 1024 * 1024 }, function (error, stdout) { + if (_darwin$8) { + // let cmd = 'netstat -natv | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"'; + let cmd = 'netstat -natvln | grep "tcp4\\|tcp6\\|udp4\\|udp6"'; + const states = 'ESTABLISHED|SYN_SENT|SYN_RECV|FIN_WAIT1|FIN_WAIT2|TIME_WAIT|CLOSE|CLOSE_WAIT|LAST_ACK|LISTEN|CLOSING|UNKNOWN'; + exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { if (!error) { - // split by type: - let lines = stdout.toString().split('\n'); - let linesSATA = []; - let linesNVMe = []; - let linesUSB = []; - let dataType = 'SATA'; - lines.forEach(line => { - if (line === 'NVMExpress:') { dataType = 'NVMe'; } - else if (line === 'USB:') { dataType = 'USB'; } - else if (line === 'SATA/SATA Express:') { dataType = 'SATA'; } - else if (dataType === 'SATA') { linesSATA.push(line); } - else if (dataType === 'NVMe') { linesNVMe.push(line); } - else if (dataType === 'USB') { linesUSB.push(line); } - }); - try { - // Serial ATA Drives - let devices = linesSATA.join('\n').split(' Physical Interconnect: '); - devices.shift(); - devices.forEach(function (device) { - device = 'InterfaceType: ' + device; - let lines = device.split('\n'); - const mediumType = util$b.getValue(lines, 'Medium Type', ':', true).trim(); - const sizeStr = util$b.getValue(lines, 'capacity', ':', true).trim(); - const BSDName = util$b.getValue(lines, 'BSD Name', ':', true).trim(); - if (sizeStr) { - let sizeValue = 0; - if (sizeStr.indexOf('(') >= 0) { - sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, '')); + exec$8('ps -axo pid,command', { maxBuffer: 1024 * 20000 }, function (err2, stdout2) { + let processes = stdout2.toString().split('\n'); + processes = processes.map((line => { return line.trim().replace(/ +/g, ' '); })); + let lines = stdout.toString().split('\n'); + + lines.forEach(function (line) { + line = line.replace(/ +/g, ' ').split(' '); + if (line.length >= 8) { + let localip = line[3]; + let localport = ''; + let localaddress = line[3].split('.'); + if (localaddress.length > 1) { + localport = localaddress[localaddress.length - 1]; + localaddress.pop(); + localip = localaddress.join('.'); } - if (!sizeValue) { - sizeValue = parseInt(sizeStr); + let peerip = line[4]; + let peerport = ''; + let peeraddress = line[4].split('.'); + if (peeraddress.length > 1) { + peerport = peeraddress[peeraddress.length - 1]; + peeraddress.pop(); + peerip = peeraddress.join('.'); } - if (sizeValue) { - const smartStatusString = util$b.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase(); + const hasState = states.indexOf(line[5]) >= 0; + let connstate = hasState ? line[5] : 'UNKNOWN'; + let pid = parseInt(line[8 + (hasState ? 0 : -1)], 10); + if (connstate) { result.push({ - device: BSDName, - type: mediumType.startsWith('Solid') ? 'SSD' : 'HD', - name: util$b.getValue(lines, 'Model', ':', true).trim(), - vendor: getVendorFromModel(util$b.getValue(lines, 'Model', ':', true).trim()) || util$b.getValue(lines, 'Manufacturer', ':', true), - size: sizeValue, - bytesPerSector: null, - totalCylinders: null, - totalHeads: null, - totalSectors: null, - totalTracks: null, - tracksPerCylinder: null, - sectorsPerTrack: null, - firmwareRevision: util$b.getValue(lines, 'Revision', ':', true).trim(), - serialNum: util$b.getValue(lines, 'Serial Number', ':', true).trim(), - interfaceType: util$b.getValue(lines, 'InterfaceType', ':', true).trim(), - smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown', - temperature: null, - BSDName: BSDName + protocol: line[0], + localAddress: localip, + localPort: localport, + peerAddress: peerip, + peerPort: peerport, + state: connstate, + pid: pid, + process: getProcessName(processes, pid) }); - cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;'; } } }); - } catch (e) { - util$b.noop(); - } + if (callback) { + callback(result); + } + resolve(result); + }); - // NVME Drives - try { - let devices = linesNVMe.join('\n').split('\n\n Capacity:'); - devices.shift(); - devices.forEach(function (device) { - device = '!Capacity: ' + device; - let lines = device.split('\n'); - const linkWidth = util$b.getValue(lines, 'link width', ':', true).trim(); - const sizeStr = util$b.getValue(lines, '!capacity', ':', true).trim(); - const BSDName = util$b.getValue(lines, 'BSD Name', ':', true).trim(); - if (sizeStr) { - let sizeValue = 0; - if (sizeStr.indexOf('(') >= 0) { - sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, '')); + } + }); + } + if (_windows$9) { + let cmd = 'netstat -nao'; + try { + exec$8(cmd, util$a.execOptsWin, function (error, stdout) { + if (!error) { + + let lines = stdout.toString().split('\r\n'); + + lines.forEach(function (line) { + line = line.trim().replace(/ +/g, ' ').split(' '); + if (line.length >= 4) { + let localip = line[1]; + let localport = ''; + let localaddress = line[1].split(':'); + if (localaddress.length > 1) { + localport = localaddress[localaddress.length - 1]; + localaddress.pop(); + localip = localaddress.join(':'); } - if (!sizeValue) { - sizeValue = parseInt(sizeStr); + localip = localip.replace(/\[/g, '').replace(/\]/g, ''); + let peerip = line[2]; + let peerport = ''; + let peeraddress = line[2].split(':'); + if (peeraddress.length > 1) { + peerport = peeraddress[peeraddress.length - 1]; + peeraddress.pop(); + peerip = peeraddress.join(':'); } - if (sizeValue) { - const smartStatusString = util$b.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase(); + peerip = peerip.replace(/\[/g, '').replace(/\]/g, ''); + let pid = util$a.toInt(line[4]); + let connstate = line[3]; + if (connstate === 'HERGESTELLT') { connstate = 'ESTABLISHED'; } + if (connstate.startsWith('ABH')) { connstate = 'LISTEN'; } + if (connstate === 'SCHLIESSEN_WARTEN') { connstate = 'CLOSE_WAIT'; } + if (connstate === 'WARTEND') { connstate = 'TIME_WAIT'; } + if (connstate === 'SYN_GESENDET') { connstate = 'SYN_SENT'; } + + if (connstate === 'LISTENING') { connstate = 'LISTEN'; } + if (connstate === 'SYN_RECEIVED') { connstate = 'SYN_RECV'; } + if (connstate === 'FIN_WAIT_1') { connstate = 'FIN_WAIT1'; } + if (connstate === 'FIN_WAIT_2') { connstate = 'FIN_WAIT2'; } + if (line[0].toLowerCase() !== 'udp' && connstate) { result.push({ - device: BSDName, - type: 'NVMe', - name: util$b.getValue(lines, 'Model', ':', true).trim(), - vendor: getVendorFromModel(util$b.getValue(lines, 'Model', ':', true).trim()), - size: sizeValue, - bytesPerSector: null, - totalCylinders: null, - totalHeads: null, - totalSectors: null, - totalTracks: null, - tracksPerCylinder: null, - sectorsPerTrack: null, - firmwareRevision: util$b.getValue(lines, 'Revision', ':', true).trim(), - serialNum: util$b.getValue(lines, 'Serial Number', ':', true).trim(), - interfaceType: ('PCIe ' + linkWidth).trim(), - smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown', - temperature: null, - BSDName: BSDName + protocol: line[0].toLowerCase(), + localAddress: localip, + localPort: localport, + peerAddress: peerip, + peerPort: peerport, + state: connstate, + pid, + process: '' }); - cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;'; - } - } - }); - } catch (e) { - util$b.noop(); - } - // USB Drives - try { - let devices = linesUSB.join('\n').replaceAll('Media:\n ', 'Model:').split('\n\n Product ID:'); - devices.shift(); - devices.forEach(function (device) { - let lines = device.split('\n'); - const sizeStr = util$b.getValue(lines, 'Capacity', ':', true).trim(); - const BSDName = util$b.getValue(lines, 'BSD Name', ':', true).trim(); - if (sizeStr) { - let sizeValue = 0; - if (sizeStr.indexOf('(') >= 0) { - sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, '')); - } - if (!sizeValue) { - sizeValue = parseInt(sizeStr); - } - if (sizeValue) { - const smartStatusString = util$b.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase(); + } else if (line[0].toLowerCase() === 'udp') { result.push({ - device: BSDName, - type: 'USB', - name: util$b.getValue(lines, 'Model', ':', true).trim().replaceAll(':', ''), - vendor: getVendorFromModel(util$b.getValue(lines, 'Model', ':', true).trim()), - size: sizeValue, - bytesPerSector: null, - totalCylinders: null, - totalHeads: null, - totalSectors: null, - totalTracks: null, - tracksPerCylinder: null, - sectorsPerTrack: null, - firmwareRevision: util$b.getValue(lines, 'Revision', ':', true).trim(), - serialNum: util$b.getValue(lines, 'Serial Number', ':', true).trim(), - interfaceType: 'USB', - smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown', - temperature: null, - BSDName: BSDName + protocol: line[0].toLowerCase(), + localAddress: localip, + localPort: localport, + peerAddress: peerip, + peerPort: peerport, + state: '', + pid: parseInt(line[3], 10), + process: '' }); - cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;'; } } }); - } catch (e) { - util$b.noop(); + if (callback) { + callback(result); + } + resolve(result); } - if (cmd) { - cmd = cmd + 'printf "\n"'; - exec$9(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) { - let lines = stdout.toString().split('\n'); - lines.forEach(line => { - if (line) { - let parts = line.split('|'); - if (parts.length === 2) { - let BSDName = parts[0]; - parts[1] = parts[1].trim(); - let parts2 = parts[1].split(':'); - if (parts2.length === 2) { - parts2[1] = parts2[1].trim(); - let status = parts2[1].toLowerCase(); - for (let i = 0; i < result.length; i++) { - if (result[i].BSDName === BSDName) { - result[i].smartStatus = (status === 'not supported' ? 'not supported' : (status === 'verified' ? 'Ok' : (status === 'failing' ? 'Predicted Failure' : 'unknown'))); - } - } - } - } - } - }); - for (let i = 0; i < result.length; i++) { - delete result[i].BSDName; - } + }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } + } + }); + }); +} + +network.networkConnections = networkConnections; + +function networkGatewayDefault(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + let result = ''; + if (_linux$8 || _freebsd$7 || _openbsd$7 || _netbsd$7) { + let cmd = 'ip route get 1'; + try { + exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + const line = lines && lines[0] ? lines[0] : ''; + let parts = line.split(' via '); + if (parts && parts[1]) { + parts = parts[1].split(' '); + result = parts[0]; + } + if (callback) { + callback(result); + } + resolve(result); + } else { + if (callback) { + callback(result); + } + resolve(result); + } + }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } + } + if (_darwin$8) { + let cmd = 'route -n get default'; + try { + exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + if (!error) { + const lines = stdout.toString().split('\n').map(line => line.trim()); + result = util$a.getValue(lines, 'gateway'); + } + if (!result) { + cmd = 'netstat -rn | awk \'/default/ {print $2}\''; + exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + const lines = stdout.toString().split('\n').map(line => line.trim()); + result = lines.find(line => (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(line))); if (callback) { callback(result); } resolve(result); }); } else { - for (let i = 0; i < result.length; i++) { - delete result[i].BSDName; - } if (callback) { callback(result); } resolve(result); } - } - }); + }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } } - if (_windows$a) { + if (_windows$9) { try { - const workload = []; - workload.push(util$b.powerShell('Get-CimInstance Win32_DiskDrive | select Caption,Size,Status,PNPDeviceId,DeviceId,BytesPerSector,TotalCylinders,TotalHeads,TotalSectors,TotalTracks,TracksPerCylinder,SectorsPerTrack,FirmwareRevision,SerialNumber,InterfaceType | fl')); - workload.push(util$b.powerShell('Get-PhysicalDisk | select BusType,MediaType,FriendlyName,Model,SerialNumber,Size | fl')); - if (util$b.smartMonToolsInstalled()) { - try { - const smartDev = JSON.parse(execSync$5('smartctl --scan -j').toString()); - if (smartDev && smartDev.devices && smartDev.devices.length > 0) { - smartDev.devices.forEach((dev) => { - workload.push(execPromiseSave(`smartctl -j -a ${dev.name}`, util$b.execOptsWin)); - }); - } - } catch (e) { - util$b.noop(); - } - } - util$b.promiseAll( - workload - ).then((data) => { - let devices = data.results[0].toString().split(/\n\s*\n/); - devices.forEach(function (device) { - let lines = device.split('\r\n'); - const size = util$b.getValue(lines, 'Size', ':').trim(); - const status = util$b.getValue(lines, 'Status', ':').trim().toLowerCase(); - if (size) { - result.push({ - device: util$b.getValue(lines, 'DeviceId', ':'), // changed from PNPDeviceId to DeviceID (be be able to match devices) - type: device.indexOf('SSD') > -1 ? 'SSD' : 'HD', // just a starting point ... better: MSFT_PhysicalDisk - Media Type ... see below - name: util$b.getValue(lines, 'Caption', ':'), - vendor: getVendorFromModel(util$b.getValue(lines, 'Caption', ':', true).trim()), - size: parseInt(size), - bytesPerSector: parseInt(util$b.getValue(lines, 'BytesPerSector', ':')), - totalCylinders: parseInt(util$b.getValue(lines, 'TotalCylinders', ':')), - totalHeads: parseInt(util$b.getValue(lines, 'TotalHeads', ':')), - totalSectors: parseInt(util$b.getValue(lines, 'TotalSectors', ':')), - totalTracks: parseInt(util$b.getValue(lines, 'TotalTracks', ':')), - tracksPerCylinder: parseInt(util$b.getValue(lines, 'TracksPerCylinder', ':')), - sectorsPerTrack: parseInt(util$b.getValue(lines, 'SectorsPerTrack', ':')), - firmwareRevision: util$b.getValue(lines, 'FirmwareRevision', ':').trim(), - serialNum: util$b.getValue(lines, 'SerialNumber', ':').trim(), - interfaceType: util$b.getValue(lines, 'InterfaceType', ':').trim(), - smartStatus: (status === 'ok' ? 'Ok' : (status === 'degraded' ? 'Degraded' : (status === 'pred fail' ? 'Predicted Failure' : 'Unknown'))), - temperature: null, - }); - } - }); - devices = data.results[1].split(/\n\s*\n/); - devices.forEach(function (device) { - let lines = device.split('\r\n'); - const serialNum = util$b.getValue(lines, 'SerialNumber', ':').trim(); - const name = util$b.getValue(lines, 'FriendlyName', ':').trim().replace('Msft ', 'Microsoft'); - const size = util$b.getValue(lines, 'Size', ':').trim(); - const model = util$b.getValue(lines, 'Model', ':').trim(); - const interfaceType = util$b.getValue(lines, 'BusType', ':').trim(); - let mediaType = util$b.getValue(lines, 'MediaType', ':').trim(); - if (mediaType === '3' || mediaType === 'HDD') { mediaType = 'HD'; } - if (mediaType === '4') { mediaType = 'SSD'; } - if (mediaType === '5') { mediaType = 'SCM'; } - if (mediaType === 'Unspecified' && (model.toLowerCase().indexOf('virtual') > -1 || model.toLowerCase().indexOf('vbox') > -1)) { mediaType = 'Virtual'; } - if (size) { - let i = util$b.findObjectByKey(result, 'serialNum', serialNum); - if (i === -1 || serialNum === '') { - i = util$b.findObjectByKey(result, 'name', name); - } - if (i != -1) { - result[i].type = mediaType; - result[i].interfaceType = interfaceType; - } - } - }); - // S.M.A.R.T - data.results.shift(); - data.results.shift(); - if (data.results.length) { - data.results.forEach((smartStr) => { - try { - const smartData = JSON.parse(smartStr); - if (smartData.serial_number) { - const serialNum = smartData.serial_number; - let i = util$b.findObjectByKey(result, 'serialNum', serialNum); - if (i != -1) { - result[i].smartStatus = (smartData.smart_status && smartData.smart_status.passed ? 'Ok' : (smartData.smart_status && smartData.smart_status.passed === false ? 'Predicted Failure' : 'unknown')); - if (smartData.temperature && smartData.temperature.current) { - result[i].temperature = smartData.temperature.current; - } - result[i].smartData = smartData; + exec$8('netstat -r', util$a.execOptsWin, function (error, stdout) { + const lines = stdout.toString().split(os$3.EOL); + lines.forEach(line => { + line = line.replace(/\s+/g, ' ').trim(); + if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) { + const parts = line.split(' '); + if (parts.length >= 5 && (parts[parts.length - 3]).indexOf('.') > -1) { + result = parts[parts.length - 3]; + } + } + }); + if (!result) { + util$a.powerShell('Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq \'0.0.0.0\' -and $_.Mask -eq \'0.0.0.0\' }') + .then((data) => { + let lines = data.toString().split('\r\n'); + if (lines.length > 1 && !result) { + result = util$a.getValue(lines, 'NextHop'); + if (callback) { + callback(result); } + resolve(result); + // } else { + // exec('ipconfig', util.execOptsWin, function (error, stdout) { + // let lines = stdout.toString().split('\r\n'); + // lines.forEach(function (line) { + // line = line.trim().replace(/\. /g, ''); + // line = line.trim().replace(/ +/g, ''); + // const parts = line.split(':'); + // if ((parts[0].toLowerCase().startsWith('standardgate') || parts[0].toLowerCase().indexOf('gateway') > -1 || parts[0].toLowerCase().indexOf('enlace') > -1) && parts[1]) { + // result = parts[1]; + // } + // }); + // if (callback) { callback(result); } + // resolve(result); + // }); } - } catch (e) { - util$b.noop(); - } - }); - } - if (callback) { - callback(result); + }); + } else { + if (callback) { + callback(result); + } + resolve(result); } - resolve(result); }); } catch (e) { if (callback) { callback(result); } @@ -65145,13 +61627,13 @@ function diskLayout(callback) { }); } -filesystem.diskLayout = diskLayout; +network.networkGatewayDefault = networkGatewayDefault; -var network = {}; +var wifi = {}; // @ts-check // ================================================================================== -// network.js +// wifi.js // ---------------------------------------------------------------------------------- // Description: System Information - library // for Node.js @@ -65160,2574 +61642,2687 @@ var network = {}; // ---------------------------------------------------------------------------------- // License: MIT // ================================================================================== -// 9. Network +// 9. wifi // ---------------------------------------------------------------------------------- -const os$3 = require$$0$7; -const exec$8 = require$$1$2.exec; -const execSync$4 = require$$1$2.execSync; -const fs$2 = require$$0$5; -const util$a = util$j; +const os$2 = require$$0$7; +const exec$7 = require$$1$2.exec; +const execSync$3 = require$$1$2.execSync; +const util$9 = util$j; -let _platform$9 = process.platform; +let _platform$8 = process.platform; -const _linux$8 = (_platform$9 === 'linux' || _platform$9 === 'android'); -const _darwin$8 = (_platform$9 === 'darwin'); -const _windows$9 = (_platform$9 === 'win32'); -const _freebsd$7 = (_platform$9 === 'freebsd'); -const _openbsd$7 = (_platform$9 === 'openbsd'); -const _netbsd$7 = (_platform$9 === 'netbsd'); -const _sunos$7 = (_platform$9 === 'sunos'); +const _linux$7 = (_platform$8 === 'linux' || _platform$8 === 'android'); +const _darwin$7 = (_platform$8 === 'darwin'); +const _windows$8 = (_platform$8 === 'win32'); -let _network = {}; -let _default_iface = ''; -let _ifaces = {}; -let _dhcpNics = []; -let _networkInterfaces = []; -let _mac = {}; -let pathToIp; +function wifiDBFromQuality(quality) { + return (parseFloat(quality) / 2 - 100); +} -function getDefaultNetworkInterface() { +function wifiQualityFromDB(db) { + const result = 2 * (parseFloat(db) + 100); + return result <= 100 ? result : 100; +} - let ifacename = ''; - let ifacenameFirst = ''; - try { - let ifaces = os$3.networkInterfaces(); +const _wifi_frequencies = { + 1: 2412, + 2: 2417, + 3: 2422, + 4: 2427, + 5: 2432, + 6: 2437, + 7: 2442, + 8: 2447, + 9: 2452, + 10: 2457, + 11: 2462, + 12: 2467, + 13: 2472, + 14: 2484, + 32: 5160, + 34: 5170, + 36: 5180, + 38: 5190, + 40: 5200, + 42: 5210, + 44: 5220, + 46: 5230, + 48: 5240, + 50: 5250, + 52: 5260, + 54: 5270, + 56: 5280, + 58: 5290, + 60: 5300, + 62: 5310, + 64: 5320, + 68: 5340, + 96: 5480, + 100: 5500, + 102: 5510, + 104: 5520, + 106: 5530, + 108: 5540, + 110: 5550, + 112: 5560, + 114: 5570, + 116: 5580, + 118: 5590, + 120: 5600, + 122: 5610, + 124: 5620, + 126: 5630, + 128: 5640, + 132: 5660, + 134: 5670, + 136: 5680, + 138: 5690, + 140: 5700, + 142: 5710, + 144: 5720, + 149: 5745, + 151: 5755, + 153: 5765, + 155: 5775, + 157: 5785, + 159: 5795, + 161: 5805, + 165: 5825, + 169: 5845, + 173: 5865, + 183: 4915, + 184: 4920, + 185: 4925, + 187: 4935, + 188: 4940, + 189: 4945, + 192: 4960, + 196: 4980 +}; - let scopeid = 9999; +function wifiFrequencyFromChannel(channel) { + return {}.hasOwnProperty.call(_wifi_frequencies, channel) ? _wifi_frequencies[channel] : null; +} - // fallback - "first" external interface (sorted by scopeid) - for (let dev in ifaces) { - if ({}.hasOwnProperty.call(ifaces, dev)) { - ifaces[dev].forEach(function (details) { - if (details && details.internal === false) { - ifacenameFirst = ifacenameFirst || dev; // fallback if no scopeid - if (details.scopeid && details.scopeid < scopeid) { - ifacename = dev; - scopeid = details.scopeid; - } - } - }); - } +function wifiChannelFromFrequencs(frequency) { + let channel = 0; + for (let key in _wifi_frequencies) { + if ({}.hasOwnProperty.call(_wifi_frequencies, key)) { + if (_wifi_frequencies[key] === frequency) { channel = util$9.toInt(key); } } - ifacename = ifacename || ifacenameFirst || ''; + } + return channel; +} - if (_windows$9) { - // https://www.inetdaemon.com/tutorials/internet/ip/routing/default_route.shtml - let defaultIp = ''; - const cmd = 'netstat -r'; - const result = execSync$4(cmd, util$a.execOptsWin); - const lines = result.toString().split(os$3.EOL); - lines.forEach(line => { - line = line.replace(/\s+/g, ' ').trim(); - if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) { - const parts = line.split(' '); - if (parts.length >= 5) { - defaultIp = parts[parts.length - 2]; - } - } +function ifaceListLinux() { + const result = []; + const cmd = 'iw dev 2>/dev/null'; + try { + const all = execSync$3(cmd).toString().split('\n').map(line => line.trim()).join('\n'); + const parts = all.split('\nInterface '); + parts.shift(); + parts.forEach(ifaceDetails => { + const lines = ifaceDetails.split('\n'); + const iface = lines[0]; + const id = util$9.toInt(util$9.getValue(lines, 'ifindex', ' ')); + const mac = util$9.getValue(lines, 'addr', ' '); + const channel = util$9.toInt(util$9.getValue(lines, 'channel', ' ')); + result.push({ + id, + iface, + mac, + channel }); - if (defaultIp) { - for (let dev in ifaces) { - if ({}.hasOwnProperty.call(ifaces, dev)) { - ifaces[dev].forEach(function (details) { - if (details && details.address && details.address === defaultIp) { - ifacename = dev; - } - }); - } + }); + return result; + } catch (e) { + try { + const all = execSync$3('nmcli -t -f general,wifi-properties,wired-properties,interface-flags,capabilities,nsp device show 2>/dev/null').toString(); + const parts = all.split('\n\n'); + let i = 1; + parts.forEach(ifaceDetails => { + const lines = ifaceDetails.split('\n'); + const iface = util$9.getValue(lines, 'GENERAL.DEVICE'); + const type = util$9.getValue(lines, 'GENERAL.TYPE'); + const id = i++; // // util.getValue(lines, 'GENERAL.PATH'); + const mac = util$9.getValue(lines, 'GENERAL.HWADDR'); + const channel = ''; + if (type.toLowerCase() === 'wifi') { + result.push({ + id, + iface, + mac, + channel + }); } - } + }); + return result; + } catch (e) { + return []; } - if (_linux$8) { - let cmd = 'ip route 2> /dev/null | grep default'; - let result = execSync$4(cmd); - let parts = result.toString().split('\n')[0].split(/\s+/); - if (parts[0] === 'none' && parts[5]) { - ifacename = parts[5]; - } else if (parts[4]) { - ifacename = parts[4]; - } + } +} - if (ifacename.indexOf(':') > -1) { - ifacename = ifacename.split(':')[1].trim(); - } - } - if (_darwin$8 || _freebsd$7 || _openbsd$7 || _netbsd$7 || _sunos$7) { - let cmd = ''; - if (_linux$8) { cmd = 'ip route 2> /dev/null | grep default | awk \'{print $5}\''; } - if (_darwin$8) { cmd = 'route -n get default 2>/dev/null | grep interface: | awk \'{print $2}\''; } - if (_freebsd$7 || _openbsd$7 || _netbsd$7 || _sunos$7) { cmd = 'route get 0.0.0.0 | grep interface:'; } - let result = execSync$4(cmd); - ifacename = result.toString().split('\n')[0]; - if (ifacename.indexOf(':') > -1) { - ifacename = ifacename.split(':')[1].trim(); - } - } +function nmiDeviceLinux(iface) { + const cmd = `nmcli -t -f general,wifi-properties,capabilities,ip4,ip6 device show ${iface} 2>/dev/null`; + try { + const lines = execSync$3(cmd).toString().split('\n'); + const ssid = util$9.getValue(lines, 'GENERAL.CONNECTION'); + return { + iface, + type: util$9.getValue(lines, 'GENERAL.TYPE'), + vendor: util$9.getValue(lines, 'GENERAL.VENDOR'), + product: util$9.getValue(lines, 'GENERAL.PRODUCT'), + mac: util$9.getValue(lines, 'GENERAL.HWADDR').toLowerCase(), + ssid: ssid !== '--' ? ssid : null + }; } catch (e) { - util$a.noop(); + return {}; } - if (ifacename) { _default_iface = ifacename; } - return _default_iface; } -network.getDefaultNetworkInterface = getDefaultNetworkInterface; +function nmiConnectionLinux(ssid) { + const cmd = `nmcli -t --show-secrets connection show ${ssid} 2>/dev/null`; + try { + const lines = execSync$3(cmd).toString().split('\n'); + const bssid = util$9.getValue(lines, '802-11-wireless.seen-bssids').toLowerCase(); + return { + ssid: ssid !== '--' ? ssid : null, + uuid: util$9.getValue(lines, 'connection.uuid'), + type: util$9.getValue(lines, 'connection.type'), + autoconnect: util$9.getValue(lines, 'connection.autoconnect') === 'yes', + security: util$9.getValue(lines, '802-11-wireless-security.key-mgmt'), + bssid: bssid !== '--' ? bssid : null + }; + } catch (e) { + return {}; + } +} -function getMacAddresses() { - let iface = ''; - let mac = ''; - let result = {}; - if (_linux$8 || _freebsd$7 || _openbsd$7 || _netbsd$7) { - if (typeof pathToIp === 'undefined') { - try { - const lines = execSync$4('which ip').toString().split('\n'); - if (lines.length && lines[0].indexOf(':') === -1 && lines[0].indexOf('/') === 0) { - pathToIp = lines[0]; - } else { - pathToIp = ''; - } - } catch (e) { - pathToIp = ''; - } - } - try { - const cmd = 'export LC_ALL=C; ' + ((pathToIp) ? pathToIp + ' link show up' : '/sbin/ifconfig') + '; unset LC_ALL'; - let res = execSync$4(cmd); - const lines = res.toString().split('\n'); - for (let i = 0; i < lines.length; i++) { - if (lines[i] && lines[i][0] !== ' ') { - if (pathToIp) { - let nextline = lines[i + 1].trim().split(' '); - if (nextline[0] === 'link/ether') { - iface = lines[i].split(' ')[1]; - iface = iface.slice(0, iface.length - 1); - mac = nextline[1]; +function wpaConnectionLinux(iface) { + if (!iface) { + return {}; + } + const cmd = `wpa_cli -i ${iface} status 2>&1`; + try { + const lines = execSync$3(cmd).toString().split('\n'); + const freq = util$9.toInt(util$9.getValue(lines, 'freq', '=')); + return { + ssid: util$9.getValue(lines, 'ssid', '='), + uuid: util$9.getValue(lines, 'uuid', '='), + security: util$9.getValue(lines, 'key_mgmt', '='), + freq, + channel: wifiChannelFromFrequencs(freq), + bssid: util$9.getValue(lines, 'bssid', '=').toLowerCase() + }; + } catch (e) { + return {}; + } +} + +function getWifiNetworkListNmi() { + const result = []; + const cmd = 'nmcli -t -m multiline --fields active,ssid,bssid,mode,chan,freq,signal,security,wpa-flags,rsn-flags device wifi list 2>/dev/null'; + try { + const stdout = execSync$3(cmd, { maxBuffer: 1024 * 20000 }); + const parts = stdout.toString().split('ACTIVE:'); + parts.shift(); + parts.forEach(part => { + part = 'ACTIVE:' + part; + const lines = part.split(os$2.EOL); + const channel = util$9.getValue(lines, 'CHAN'); + const frequency = util$9.getValue(lines, 'FREQ').toLowerCase().replace('mhz', '').trim(); + const security = util$9.getValue(lines, 'SECURITY').replace('(', '').replace(')', ''); + const wpaFlags = util$9.getValue(lines, 'WPA-FLAGS').replace('(', '').replace(')', ''); + const rsnFlags = util$9.getValue(lines, 'RSN-FLAGS').replace('(', '').replace(')', ''); + result.push({ + ssid: util$9.getValue(lines, 'SSID'), + bssid: util$9.getValue(lines, 'BSSID').toLowerCase(), + mode: util$9.getValue(lines, 'MODE'), + channel: channel ? parseInt(channel, 10) : null, + frequency: frequency ? parseInt(frequency, 10) : null, + signalLevel: wifiDBFromQuality(util$9.getValue(lines, 'SIGNAL')), + quality: parseFloat(util$9.getValue(lines, 'SIGNAL')), + security: security && security !== 'none' ? security.split(' ') : [], + wpaFlags: wpaFlags && wpaFlags !== 'none' ? wpaFlags.split(' ') : [], + rsnFlags: rsnFlags && rsnFlags !== 'none' ? rsnFlags.split(' ') : [] + }); + }); + return result; + } catch (e) { + return []; + } +} + +function getWifiNetworkListIw(iface) { + const result = []; + try { + let iwlistParts = execSync$3(`export LC_ALL=C; iwlist ${iface} scan 2>&1; unset LC_ALL`).toString().split(' Cell '); + if (iwlistParts[0].indexOf('resource busy') >= 0) { return -1; } + if (iwlistParts.length > 1) { + iwlistParts.shift(); + iwlistParts.forEach(element => { + const lines = element.split('\n'); + const channel = util$9.getValue(lines, 'channel', ':', true); + const address = (lines && lines.length && lines[0].indexOf('Address:') >= 0 ? lines[0].split('Address:')[1].trim().toLowerCase() : ''); + const mode = util$9.getValue(lines, 'mode', ':', true); + const frequency = util$9.getValue(lines, 'frequency', ':', true); + const qualityString = util$9.getValue(lines, 'Quality', '=', true); + const dbParts = qualityString.toLowerCase().split('signal level='); + const db = dbParts.length > 1 ? util$9.toInt(dbParts[1]) : 0; + const quality = db ? wifiQualityFromDB(db) : 0; + const ssid = util$9.getValue(lines, 'essid', ':', true); + + // security and wpa-flags + const isWpa = element.indexOf(' WPA ') >= 0; + const isWpa2 = element.indexOf('WPA2 ') >= 0; + const security = []; + if (isWpa) { security.push('WPA'); } + if (isWpa2) { security.push('WPA2'); } + const wpaFlags = []; + let wpaFlag = ''; + lines.forEach(function (line) { + const l = line.trim().toLowerCase(); + if (l.indexOf('group cipher') >= 0) { + if (wpaFlag) { + wpaFlags.push(wpaFlag); + } + const parts = l.split(':'); + if (parts.length > 1) { + wpaFlag = parts[1].trim().toUpperCase(); } - } else { - iface = lines[i].split(' ')[0]; - mac = lines[i].split('HWaddr ')[1]; } - - if (iface && mac) { - result[iface] = mac.trim(); - iface = ''; - mac = ''; + if (l.indexOf('pairwise cipher') >= 0) { + const parts = l.split(':'); + if (parts.length > 1) { + if (parts[1].indexOf('tkip')) { wpaFlag = (wpaFlag ? 'TKIP/' + wpaFlag : 'TKIP'); } + else if (parts[1].indexOf('ccmp')) { wpaFlag = (wpaFlag ? 'CCMP/' + wpaFlag : 'CCMP'); } + else if (parts[1].indexOf('proprietary')) { wpaFlag = (wpaFlag ? 'PROP/' + wpaFlag : 'PROP'); } + } } - } - } - } catch (e) { - util$a.noop(); - } - } - if (_darwin$8) { - try { - const cmd = '/sbin/ifconfig'; - let res = execSync$4(cmd); - const lines = res.toString().split('\n'); - for (let i = 0; i < lines.length; i++) { - if (lines[i] && lines[i][0] !== '\t' && lines[i].indexOf(':') > 0) { - iface = lines[i].split(':')[0]; - } else if (lines[i].indexOf('\tether ') === 0) { - mac = lines[i].split('\tether ')[1]; - if (iface && mac) { - result[iface] = mac.trim(); - iface = ''; - mac = ''; + if (l.indexOf('authentication suites') >= 0) { + const parts = l.split(':'); + if (parts.length > 1) { + if (parts[1].indexOf('802.1x')) { wpaFlag = (wpaFlag ? '802.1x/' + wpaFlag : '802.1x'); } + else if (parts[1].indexOf('psk')) { wpaFlag = (wpaFlag ? 'PSK/' + wpaFlag : 'PSK'); } + } } + }); + if (wpaFlag) { + wpaFlags.push(wpaFlag); } - } - } catch (e) { - util$a.noop(); - } - } - return result; -} -function networkInterfaceDefault(callback) { - - return new Promise((resolve) => { - process.nextTick(() => { - let result = getDefaultNetworkInterface(); - if (callback) { callback(result); } - resolve(result); - }); - }); + result.push({ + ssid, + bssid: address, + mode, + channel: channel ? util$9.toInt(channel) : null, + frequency: frequency ? util$9.toInt(frequency.replace('.', '')) : null, + signalLevel: db, + quality, + security, + wpaFlags, + rsnFlags: [] + }); + }); + } + return result; + } catch (e) { + return -1; + } } -network.networkInterfaceDefault = networkInterfaceDefault; - -// -------------------------- -// NET - interfaces - -function parseLinesWindowsNics(sections, nconfigsections) { - let nics = []; - for (let i in sections) { - if ({}.hasOwnProperty.call(sections, i)) { - - if (sections[i].trim() !== '') { - - let lines = sections[i].trim().split('\r\n'); - let linesNicConfig = nconfigsections && nconfigsections[i] ? nconfigsections[i].trim().split('\r\n') : []; - let netEnabled = util$a.getValue(lines, 'NetEnabled', ':'); - let adapterType = util$a.getValue(lines, 'AdapterTypeID', ':') === '9' ? 'wireless' : 'wired'; - let ifacename = util$a.getValue(lines, 'Name', ':').replace(/\]/g, ')').replace(/\[/g, '('); - let iface = util$a.getValue(lines, 'NetConnectionID', ':').replace(/\]/g, ')').replace(/\[/g, '('); - if (ifacename.toLowerCase().indexOf('wi-fi') >= 0 || ifacename.toLowerCase().indexOf('wireless') >= 0) { - adapterType = 'wireless'; +function parseWifiDarwin(wifiObj) { + const result = []; + if (wifiObj) { + wifiObj.forEach(function (wifiItem) { + const signalLevel = wifiItem.RSSI; + let security = []; + let wpaFlags = []; + let ssid = wifiItem.SSID_STR || ''; + if (wifiItem.WPA_IE) { + security.push('WPA'); + if (wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS) { + wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS.forEach(function (ciphers) { + if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); } + if (ciphers === 2 && wpaFlags.indexOf('PSK/TKIP') === -1) { wpaFlags.push('PSK/TKIP'); } + if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); } + }); } - if (netEnabled !== '') { - const speed = parseInt(util$a.getValue(lines, 'speed', ':').trim(), 10) / 1000000; - nics.push({ - mac: util$a.getValue(lines, 'MACAddress', ':').toLowerCase(), - dhcp: util$a.getValue(linesNicConfig, 'dhcpEnabled', ':').toLowerCase() === 'true', - name: ifacename, - iface, - netEnabled: netEnabled === 'TRUE', - speed: isNaN(speed) ? null : speed, - operstate: util$a.getValue(lines, 'NetConnectionStatus', ':') === '2' ? 'up' : 'down', - type: adapterType + } + if (wifiItem.RSN_IE) { + security.push('WPA2'); + if (wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS) { + wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS.forEach(function (ciphers) { + if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); } + if (ciphers === 2 && wpaFlags.indexOf('TKIP/TKIP') === -1) { wpaFlags.push('TKIP/TKIP'); } + if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); } }); } } - } + if (wifiItem.SSID && ssid === '') { + try { + ssid = Buffer.from(wifiItem.SSID, 'base64').toString('utf8'); + } catch (err) { + util$9.noop(); + } + } + result.push({ + ssid, + bssid: wifiItem.BSSID || '', + mode: '', + channel: wifiItem.CHANNEL, + frequency: wifiFrequencyFromChannel(wifiItem.CHANNEL), + signalLevel: signalLevel ? parseInt(signalLevel, 10) : null, + quality: wifiQualityFromDB(signalLevel), + security, + wpaFlags, + rsnFlags: [] + }); + }); } - return nics; + return result; } - -function getWindowsNics() { +function wifiNetworks(callback) { return new Promise((resolve) => { process.nextTick(() => { - let cmd = 'Get-CimInstance Win32_NetworkAdapter | fl *' + '; echo \'#-#-#-#\';'; - cmd += 'Get-CimInstance Win32_NetworkAdapterConfiguration | fl DHCPEnabled' + ''; - try { - util$a.powerShell(cmd).then((data) => { - data = data.split('#-#-#-#'); - const nsections = (data[0] || '').split(/\n\s*\n/); - const nconfigsections = (data[1] || '').split(/\n\s*\n/); - resolve(parseLinesWindowsNics(nsections, nconfigsections)); - }); - } catch (e) { - resolve([]); - } - }); - }); -} + let result = []; + if (_linux$7) { + result = getWifiNetworkListNmi(); + if (result.length === 0) { + try { + const iwconfigParts = execSync$3('export LC_ALL=C; iwconfig 2>/dev/null; unset LC_ALL').toString().split('\n\n'); + let iface = ''; + iwconfigParts.forEach(element => { + if (element.indexOf('no wireless') === -1 && element.trim() !== '') { + iface = element.split(' ')[0]; + } + }); + if (iface) { + let ifaceSanitized = ''; + const s = util$9.isPrototypePolluted() ? '---' : util$9.sanitizeShellString(iface, true); + const l = util$9.mathMin(s.length, 2000); -function getWindowsDNSsuffixes() { + for (let i = 0; i <= l; i++) { + if (s[i] !== undefined) { + ifaceSanitized = ifaceSanitized + s[i]; + } + } - let iface = {}; + const res = getWifiNetworkListIw(ifaceSanitized); + if (res === -1) { + // try again after 4 secs + setTimeout(function (iface) { + const res = getWifiNetworkListIw(iface); + if (res != -1) { result = res; } + if (callback) { + callback(result); + } + resolve(result); + }, 4000); + } else { + result = res; + if (callback) { + callback(result); + } + resolve(result); + } + } else { + if (callback) { + callback(result); + } + resolve(result); + } + } catch (e) { + if (callback) { + callback(result); + } + resolve(result); + } + } else { + if (callback) { + callback(result); + } + resolve(result); + } + } else if (_darwin$7) { + let cmd = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s -x'; + exec$7(cmd, { maxBuffer: 1024 * 40000 }, function (error, stdout) { + const output = stdout.toString(); + result = parseWifiDarwin(util$9.plistParser(output)); + if (callback) { + callback(result); + } + resolve(result); + }); + } else if (_windows$8) { + let cmd = 'netsh wlan show networks mode=Bssid'; + util$9.powerShell(cmd).then((stdout) => { + const ssidParts = stdout.toString('utf8').split(os$2.EOL + os$2.EOL + 'SSID '); + ssidParts.shift(); - let dnsSuffixes = { - primaryDNS: '', - exitCode: 0, - ifaces: [], - }; + ssidParts.forEach(ssidPart => { + const ssidLines = ssidPart.split(os$2.EOL); + if (ssidLines && ssidLines.length >= 8 && ssidLines[0].indexOf(':') >= 0) { + const bssidsParts = ssidPart.split(' BSSID'); + bssidsParts.shift(); - try { - const ipconfig = execSync$4('ipconfig /all', util$a.execOptsWin); - const ipconfigArray = ipconfig.split('\r\n\r\n'); + bssidsParts.forEach((bssidPart) => { + const bssidLines = bssidPart.split(os$2.EOL); + const bssidLine = bssidLines[0].split(':'); + bssidLine.shift(); + const bssid = bssidLine.join(':').trim().toLowerCase(); + const channel = bssidLines[3].split(':').pop().trim(); + const quality = bssidLines[1].split(':').pop().trim(); - ipconfigArray.forEach((element, index) => { + result.push({ + ssid: ssidLines[0].split(':').pop().trim(), + bssid, + mode: '', + channel: channel ? parseInt(channel, 10) : null, + frequency: wifiFrequencyFromChannel(channel), + signalLevel: wifiDBFromQuality(quality), + quality: quality ? parseInt(quality, 10) : null, + security: [ssidLines[2].split(':').pop().trim()], + wpaFlags: [ssidLines[3].split(':').pop().trim()], + rsnFlags: [] + }); + }); + } + }); - if (index == 1) { - const longPrimaryDNS = element.split('\r\n').filter((element) => { - return element.toUpperCase().includes('DNS'); + if (callback) { + callback(result); + } + resolve(result); }); - const primaryDNS = longPrimaryDNS[0].substring(longPrimaryDNS[0].lastIndexOf(':') + 1); - dnsSuffixes.primaryDNS = primaryDNS.trim(); - if (!dnsSuffixes.primaryDNS) { dnsSuffixes.primaryDNS = 'Not defined'; } - } - if (index > 1) { - if (index % 2 == 0) { - const name = element.substring(element.lastIndexOf(' ') + 1).replace(':', ''); - iface.name = name; - } else { - const connectionSpecificDNS = element.split('\r\n').filter((element) => { - return element.toUpperCase().includes('DNS'); - }); - const dnsSuffix = connectionSpecificDNS[0].substring(connectionSpecificDNS[0].lastIndexOf(':') + 1); - iface.dnsSuffix = dnsSuffix.trim(); - dnsSuffixes.ifaces.push(iface); - iface = {}; + } else { + if (callback) { + callback(result); } + resolve(result); } }); - - return dnsSuffixes; - } catch (error) { - return { - primaryDNS: '', - exitCode: 0, - ifaces: [], - }; - } -} - -function getWindowsIfaceDNSsuffix(ifaces, ifacename) { - let dnsSuffix = ''; - // Adding (.) to ensure ifacename compatibility when duplicated iface-names - const interfaceName = ifacename + '.'; - try { - const connectionDnsSuffix = ifaces.filter((iface) => { - return interfaceName.includes(iface.name + '.'); - }).map((iface) => iface.dnsSuffix); - if (connectionDnsSuffix[0]) { - dnsSuffix = connectionDnsSuffix[0]; - } - if (!dnsSuffix) { dnsSuffix = ''; } - return dnsSuffix; - } catch (error) { - return 'Unknown'; - } + }); } -function getWindowsWiredProfilesInformation() { - try { - const result = execSync$4('netsh lan show profiles', util$a.execOptsWin); - const profileList = result.split('\r\nProfile on interface'); - return profileList; - } catch (error) { - if (error.status === 1 && error.stdout.includes('AutoConfig')) { - return 'Disabled'; - } - return []; - } -} +wifi.wifiNetworks = wifiNetworks; -function getWindowsWirelessIfaceSSID(interfaceName) { - try { - const result = execSync$4(`netsh wlan show interface name="${interfaceName}" | findstr "SSID"`, util$a.execOptsWin); - const SSID = result.split('\r\n').shift(); - const parseSSID = SSID.split(':').pop(); - return parseSSID; - } catch (error) { - return 'Unknown'; - } +function getVendor(model) { + model = model.toLowerCase(); + let result = ''; + if (model.indexOf('intel') >= 0) { result = 'Intel'; } + else if (model.indexOf('realtek') >= 0) { result = 'Realtek'; } + else if (model.indexOf('qualcom') >= 0) { result = 'Qualcom'; } + else if (model.indexOf('broadcom') >= 0) { result = 'Broadcom'; } + else if (model.indexOf('cavium') >= 0) { result = 'Cavium'; } + else if (model.indexOf('cisco') >= 0) { result = 'Cisco'; } + else if (model.indexOf('marvel') >= 0) { result = 'Marvel'; } + else if (model.indexOf('zyxel') >= 0) { result = 'Zyxel'; } + else if (model.indexOf('melanox') >= 0) { result = 'Melanox'; } + else if (model.indexOf('d-link') >= 0) { result = 'D-Link'; } + else if (model.indexOf('tp-link') >= 0) { result = 'TP-Link'; } + else if (model.indexOf('asus') >= 0) { result = 'Asus'; } + else if (model.indexOf('linksys') >= 0) { result = 'Linksys'; } + return result; } -function getWindowsIEEE8021x(connectionType, iface, ifaces) { - let i8021x = { - state: 'Unknown', - protocol: 'Unknown', - }; - - if (ifaces === 'Disabled') { - i8021x.state = 'Disabled'; - i8021x.protocol = 'Not defined'; - return i8021x; - } - - if (connectionType == 'wired' && ifaces.length > 0) { - try { - // Get 802.1x information by interface name - const iface8021xInfo = ifaces.find((element) => { - return element.includes(iface + '\r\n'); - }); - const arrayIface8021xInfo = iface8021xInfo.split('\r\n'); - const state8021x = arrayIface8021xInfo.find((element) => { - return element.includes('802.1x'); - }); - - if (state8021x.includes('Disabled')) { - i8021x.state = 'Disabled'; - i8021x.protocol = 'Not defined'; - } else if (state8021x.includes('Enabled')) { - const protocol8021x = arrayIface8021xInfo.find((element) => { - return element.includes('EAP'); - }); - i8021x.protocol = protocol8021x.split(':').pop(); - i8021x.state = 'Enabled'; - } - } catch (error) { - return i8021x; - } - } else if (connectionType == 'wireless') { - - let i8021xState = ''; - let i8021xProtocol = ''; - +function wifiConnections(callback) { - try { - const SSID = getWindowsWirelessIfaceSSID(iface); - if (SSID !== 'Unknown') { - i8021xState = execSync$4(`netsh wlan show profiles "${SSID}" | findstr "802.1X"`, util$a.execOptsWin); - i8021xProtocol = execSync$4(`netsh wlan show profiles "${SSID}" | findstr "EAP"`, util$a.execOptsWin); - } + return new Promise((resolve) => { + process.nextTick(() => { + const result = []; - if (i8021xState.includes(':') && i8021xProtocol.includes(':')) { - i8021x.state = i8021xState.split(':').pop(); - i8021x.protocol = i8021xProtocol.split(':').pop(); - } - } catch (error) { - if (error.status === 1 && error.stdout.includes('AutoConfig')) { - i8021x.state = 'Disabled'; - i8021x.protocol = 'Not defined'; - } - return i8021x; - } - } + if (_linux$7) { + const ifaces = ifaceListLinux(); + const networkList = getWifiNetworkListNmi(); + ifaces.forEach(ifaceDetail => { + let ifaceSanitized = ''; + const s = util$9.isPrototypePolluted() ? '---' : util$9.sanitizeShellString(ifaceDetail.iface, true); + const ll = util$9.mathMin(s.length, 2000); - return i8021x; -} + for (let i = 0; i <= ll; i++) { + if (s[i] !== undefined) { + ifaceSanitized = ifaceSanitized + s[i]; + } + } -function splitSectionsNics(lines) { - const result = []; - let section = []; - lines.forEach(function (line) { - if (!line.startsWith('\t') && !line.startsWith(' ')) { - if (section.length) { - result.push(section); - section = []; - } - } - section.push(line); - }); - if (section.length) { - result.push(section); - } - return result; -} + const nmiDetails = nmiDeviceLinux(ifaceSanitized); + const wpaDetails = wpaConnectionLinux(ifaceSanitized); + const ssid = nmiDetails.ssid || wpaDetails.ssid; + const network = networkList.filter(nw => nw.ssid === ssid); + let ssidSanitized = ''; + const t = util$9.isPrototypePolluted() ? '---' : util$9.sanitizeShellString(ssid, true); + const l = util$9.mathMin(t.length, 2000); + for (let i = 0; i <= l; i++) { + if (t[i] !== undefined) { + ssidSanitized = ssidSanitized + t[i]; + } + } -function parseLinesDarwinNics(sections) { - let nics = []; - sections.forEach(section => { - let nic = { - iface: '', - mtu: null, - mac: '', - ip6: '', - ip4: '', - speed: null, - type: '', - operstate: '', - duplex: '', - internal: false - }; - const first = section[0]; - nic.iface = first.split(':')[0].trim(); - let parts = first.split('> mtu'); - nic.mtu = parts.length > 1 ? parseInt(parts[1], 10) : null; - if (isNaN(nic.mtu)) { - nic.mtu = null; - } - nic.internal = parts[0].toLowerCase().indexOf('loopback') > -1; - section.forEach(line => { - if (line.trim().startsWith('ether ')) { - nic.mac = line.split('ether ')[1].toLowerCase().trim(); - } - if (line.trim().startsWith('inet6 ') && !nic.ip6) { - nic.ip6 = line.split('inet6 ')[1].toLowerCase().split('%')[0].split(' ')[0]; - } - if (line.trim().startsWith('inet ') && !nic.ip4) { - nic.ip4 = line.split('inet ')[1].toLowerCase().split(' ')[0]; + const nmiConnection = nmiConnectionLinux(ssidSanitized); + const channel = network && network.length && network[0].channel ? network[0].channel : (wpaDetails.channel ? wpaDetails.channel : null); + const bssid = network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null); + if (ssid && bssid) { + result.push({ + id: ifaceDetail.id, + iface: ifaceDetail.iface, + model: nmiDetails.product, + ssid, + bssid: network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null), + channel, + frequency: channel ? wifiFrequencyFromChannel(channel) : null, + type: nmiConnection.type ? nmiConnection.type : '802.11', + security: nmiConnection.security ? nmiConnection.security : (wpaDetails.security ? wpaDetails.security : null), + signalLevel: network && network.length && network[0].signalLevel ? network[0].signalLevel : null, + txRate: null + }); + } + }); + if (callback) { + callback(result); + } + resolve(result); + } else if (_darwin$7) { + let cmd = 'system_profiler SPNetworkDataType'; + exec$7(cmd, function (error, stdout) { + const parts1 = stdout.toString().split('\n\n Wi-Fi:\n\n'); + if (parts1.length > 1) { + const lines = parts1[1].split('\n\n')[0].split('\n'); + const iface = util$9.getValue(lines, 'BSD Device Name', ':', true); + const model = util$9.getValue(lines, 'hardware', ':', true); + cmd = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I'; + exec$7(cmd, function (error, stdout) { + const lines2 = stdout.toString().split('\n'); + if (lines.length > 10) { + const ssid = util$9.getValue(lines2, 'ssid', ':', true); + const bssid = util$9.getValue(lines2, 'bssid', ':', true); + const security = util$9.getValue(lines2, 'link auth', ':', true); + const txRate = util$9.getValue(lines2, 'lastTxRate', ':', true); + const channel = util$9.getValue(lines2, 'channel', ':', true).split(',')[0]; + const type = '802.11'; + const rssi = util$9.toInt(util$9.getValue(lines2, 'agrCtlRSSI', ':', true)); + const noise = util$9.toInt(util$9.getValue(lines2, 'agrCtlNoise', ':', true)); + const signalLevel = rssi - noise; + if (ssid || bssid) { + result.push({ + id: 'Wi-Fi', + iface, + model, + ssid, + bssid, + channel: util$9.toInt(channel), + frequency: channel ? wifiFrequencyFromChannel(channel) : null, + type, + security, + signalLevel, + txRate + }); + } + } + if (callback) { + callback(result); + } + resolve(result); + }); + } else { + if (callback) { + callback(result); + } + resolve(result); + } + }); + } else if (_windows$8) { + let cmd = 'netsh wlan show interfaces'; + util$9.powerShell(cmd).then(function (stdout) { + const allLines = stdout.toString().split('\r\n'); + for (let i = 0; i < allLines.length; i++) { + allLines[i] = allLines[i].trim(); + } + const parts = allLines.join('\r\n').split(':\r\n\r\n'); + parts.shift(); + parts.forEach(part => { + const lines = part.split('\r\n'); + if (lines.length >= 5) { + const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : ''; + const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : ''; + const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : ''; + const ssid = util$9.getValue(lines, 'SSID', ':', true); + const bssid = util$9.getValue(lines, 'BSSID', ':', true); + const signalLevel = util$9.getValue(lines, 'Signal', ':', true); + const type = util$9.getValue(lines, 'Radio type', ':', true) || util$9.getValue(lines, 'Type de radio', ':', true) || util$9.getValue(lines, 'Funktyp', ':', true) || null; + const security = util$9.getValue(lines, 'authentication', ':', true) || util$9.getValue(lines, 'Authentification', ':', true) || util$9.getValue(lines, 'Authentifizierung', ':', true) || null; + const channel = util$9.getValue(lines, 'Channel', ':', true) || util$9.getValue(lines, 'Canal', ':', true) || util$9.getValue(lines, 'Kanal', ':', true) || null; + const txRate = util$9.getValue(lines, 'Transmit rate (mbps)', ':', true) || util$9.getValue(lines, 'Transmission (mbit/s)', ':', true) || util$9.getValue(lines, 'Empfangsrate (MBit/s)', ':', true) || null; + if (model && id && ssid && bssid) { + result.push({ + id, + iface, + model, + ssid, + bssid, + channel: util$9.toInt(channel), + frequency: channel ? wifiFrequencyFromChannel(channel) : null, + type, + security, + signalLevel, + txRate: util$9.toInt(txRate) || null + }); + } + } + }); + if (callback) { + callback(result); + } + resolve(result); + }); + } else { + if (callback) { + callback(result); + } + resolve(result); } }); - let speed = util$a.getValue(section, 'link rate'); - nic.speed = speed ? parseFloat(speed) : null; - if (nic.speed === null) { - speed = util$a.getValue(section, 'uplink rate'); - nic.speed = speed ? parseFloat(speed) : null; - if (nic.speed !== null && speed.toLowerCase().indexOf('gbps') >= 0) { - nic.speed = nic.speed * 1000; - } - } else { - if (speed.toLowerCase().indexOf('gbps') >= 0) { - nic.speed = nic.speed * 1000; - } - } - nic.type = util$a.getValue(section, 'type').toLowerCase().indexOf('wi-fi') > -1 ? 'wireless' : 'wired'; - const operstate = util$a.getValue(section, 'status').toLowerCase(); - nic.operstate = (operstate === 'active' ? 'up' : (operstate === 'inactive' ? 'down' : 'unknown')); - nic.duplex = util$a.getValue(section, 'media').toLowerCase().indexOf('half-duplex') > -1 ? 'half' : 'full'; - if (nic.ip6 || nic.ip4 || nic.mac) { - nics.push(nic); - } }); - return nics; -} - -function getDarwinNics() { - const cmd = '/sbin/ifconfig -v'; - try { - const lines = execSync$4(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n'); - const nsections = splitSectionsNics(lines); - return (parseLinesDarwinNics(nsections)); - } catch (e) { - return []; - } } -function getLinuxIfaceConnectionName(interfaceName) { - const cmd = `nmcli device status 2>/dev/null | grep ${interfaceName}`; +wifi.wifiConnections = wifiConnections; - try { - const result = execSync$4(cmd).toString(); - const resultFormat = result.replace(/\s+/g, ' ').trim(); - const connectionNameLines = resultFormat.split(' ').slice(3); - const connectionName = connectionNameLines.join(' '); - return connectionName != '--' ? connectionName : ''; - } catch (e) { - return ''; - } -} +function wifiInterfaces(callback) { -function checkLinuxDCHPInterfaces(file) { - let result = []; - try { - let cmd = `cat ${file} 2> /dev/null | grep 'iface\\|source'`; - const lines = execSync$4(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n'); + return new Promise((resolve) => { + process.nextTick(() => { + const result = []; - lines.forEach(line => { - const parts = line.replace(/\s+/g, ' ').trim().split(' '); - if (parts.length >= 4) { - if (line.toLowerCase().indexOf(' inet ') >= 0 && line.toLowerCase().indexOf('dhcp') >= 0) { - result.push(parts[1]); + if (_linux$7) { + const ifaces = ifaceListLinux(); + ifaces.forEach(ifaceDetail => { + const nmiDetails = nmiDeviceLinux(ifaceDetail.iface); + result.push({ + id: ifaceDetail.id, + iface: ifaceDetail.iface, + model: nmiDetails.product ? nmiDetails.product : null, + vendor: nmiDetails.vendor ? nmiDetails.vendor : null, + mac: ifaceDetail.mac, + }); + }); + if (callback) { + callback(result); } - } - if (line.toLowerCase().includes('source')) { - let file = line.split(' ')[1]; - result = result.concat(checkLinuxDCHPInterfaces(file)); - } - }); - } catch (e) { - util$a.noop(); - } - return result; -} - -function getLinuxDHCPNics() { - // alternate methods getting interfaces using DHCP - let cmd = 'ip a 2> /dev/null'; - let result = []; - try { - const lines = execSync$4(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n'); - const nsections = splitSectionsNics(lines); - result = (parseLinuxDHCPNics(nsections)); - } catch (e) { - util$a.noop(); - } - try { - result = checkLinuxDCHPInterfaces('/etc/network/interfaces'); - } catch (e) { - util$a.noop(); - } - return result; -} - -function parseLinuxDHCPNics(sections) { - const result = []; - if (sections && sections.length) { - sections.forEach(lines => { - if (lines && lines.length) { - const parts = lines[0].split(':'); - if (parts.length > 2) { - for (let line of lines) { - if (line.indexOf(' inet ') >= 0 && line.indexOf(' dynamic ') >= 0) { - const parts2 = line.split(' '); - const nic = parts2[parts2.length - 1].trim(); - result.push(nic); - break; + resolve(result); + } else if (_darwin$7) { + let cmd = 'system_profiler SPNetworkDataType'; + exec$7(cmd, function (error, stdout) { + const parts1 = stdout.toString().split('\n\n Wi-Fi:\n\n'); + if (parts1.length > 1) { + const lines = parts1[1].split('\n\n')[0].split('\n'); + const iface = util$9.getValue(lines, 'BSD Device Name', ':', true); + const mac = util$9.getValue(lines, 'MAC Address', ':', true); + const model = util$9.getValue(lines, 'hardware', ':', true); + result.push({ + id: 'Wi-Fi', + iface, + model, + vendor: '', + mac + }); + } + if (callback) { + callback(result); + } + resolve(result); + }); + } else if (_windows$8) { + let cmd = 'netsh wlan show interfaces'; + util$9.powerShell(cmd).then(function (stdout) { + const allLines = stdout.toString().split('\r\n'); + for (let i = 0; i < allLines.length; i++) { + allLines[i] = allLines[i].trim(); + } + const parts = allLines.join('\r\n').split(':\r\n\r\n'); + parts.shift(); + parts.forEach(part => { + const lines = part.split('\r\n'); + if (lines.length >= 5) { + const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : ''; + const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : ''; + const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : ''; + const macParts = lines[3].indexOf(':') >= 0 ? lines[3].split(':') : []; + macParts.shift(); + const mac = macParts.join(':').trim(); + const vendor = getVendor(model); + if (iface && model && id && mac) { + result.push({ + id, + iface, + model, + vendor, + mac, + }); + } } + }); + if (callback) { + callback(result); } + resolve(result); + }); + } else { + if (callback) { + callback(result); } + resolve(result); } }); - } - return result; + }); } -function getLinuxIfaceDHCPstatus(iface, connectionName, DHCPNics) { - let result = false; - if (connectionName) { - const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.method;`; - try { - const lines = execSync$4(cmd).toString(); - const resultFormat = lines.replace(/\s+/g, ' ').trim(); +wifi.wifiInterfaces = wifiInterfaces; - let dhcStatus = resultFormat.split(' ').slice(1).toString(); - switch (dhcStatus) { - case 'auto': - result = true; - break; +var processes$1 = {}; - default: - result = false; - break; - } - return result; - } catch (e) { - return (DHCPNics.indexOf(iface) >= 0); - } - } else { - return (DHCPNics.indexOf(iface) >= 0); - } -} +// @ts-check +// ================================================================================== +// processes.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 10. Processes +// ---------------------------------------------------------------------------------- -function getDarwinIfaceDHCPstatus(iface) { - let result = false; - const cmd = `ipconfig getpacket "${iface}" 2>/dev/null | grep lease_time;`; - try { - const lines = execSync$4(cmd).toString().split('\n'); - if (lines.length && lines[0].startsWith('lease_time')) { - result = true; - } - } catch (e) { - util$a.noop(); +const os$1 = require$$0$7; +const fs$1 = require$$0$5; +const path$1 = require$$1$1; +const exec$6 = require$$1$2.exec; +const execSync$2 = require$$1$2.execSync; + +const util$8 = util$j; + +let _platform$7 = process.platform; + +const _linux$6 = (_platform$7 === 'linux' || _platform$7 === 'android'); +const _darwin$6 = (_platform$7 === 'darwin'); +const _windows$7 = (_platform$7 === 'win32'); +const _freebsd$6 = (_platform$7 === 'freebsd'); +const _openbsd$6 = (_platform$7 === 'openbsd'); +const _netbsd$6 = (_platform$7 === 'netbsd'); +const _sunos$6 = (_platform$7 === 'sunos'); + +const _processes_cpu = { + all: 0, + all_utime: 0, + all_stime: 0, + list: {}, + ms: 0, + result: {} +}; +const _services_cpu = { + all: 0, + all_utime: 0, + all_stime: 0, + list: {}, + ms: 0, + result: {} +}; +const _process_cpu = { + all: 0, + all_utime: 0, + all_stime: 0, + list: {}, + ms: 0, + result: {} +}; + +const _winStatusValues = { + '0': 'unknown', + '1': 'other', + '2': 'ready', + '3': 'running', + '4': 'blocked', + '5': 'suspended blocked', + '6': 'suspended ready', + '7': 'terminated', + '8': 'stopped', + '9': 'growing', +}; + +function parseTimeUnix(time) { + let result = time; + let parts = time.replace(/ +/g, ' ').split(' '); + if (parts.length === 5) { + result = parts[4] + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(parts[1].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + parts[2]).slice(-2) + ' ' + parts[3]; } return result; } -function getLinuxIfaceDNSsuffix(connectionName) { - if (connectionName) { - const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.dns-search;`; - try { - const result = execSync$4(cmd).toString(); - const resultFormat = result.replace(/\s+/g, ' ').trim(); - const dnsSuffix = resultFormat.split(' ').slice(1).toString(); - return dnsSuffix == '--' ? 'Not defined' : dnsSuffix; - } catch (e) { - return 'Unknown'; - } - } else { - return 'Unknown'; - } -} +function parseElapsedTime(etime) { + let current = new Date(); + current = new Date(current.getTime() - current.getTimezoneOffset() * 60000); -function getLinuxIfaceIEEE8021xAuth(connectionName) { - if (connectionName) { - const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep 802-1x.eap;`; - try { - const result = execSync$4(cmd).toString(); - const resultFormat = result.replace(/\s+/g, ' ').trim(); - const authenticationProtocol = resultFormat.split(' ').slice(1).toString(); + const elapsed = etime.split('-'); + const timeIndex = elapsed.length - 1; + const days = timeIndex > 0 ? parseInt(elapsed[timeIndex - 1]) : 0; - return authenticationProtocol == '--' ? '' : authenticationProtocol; - } catch (e) { - return 'Not defined'; - } - } else { - return 'Not defined'; - } -} + const timeStr = elapsed[timeIndex].split(':'); + const hours = timeStr.length === 3 ? parseInt(timeStr[0] || 0) : 0; + const mins = parseInt(timeStr[timeStr.length === 3 ? 1 : 0] || 0); + const secs = parseInt(timeStr[timeStr.length === 3 ? 2 : 1] || 0); + const ms = (((((days * 24 + hours) * 60) + mins) * 60 + secs) * 1000); -function getLinuxIfaceIEEE8021xState(authenticationProtocol) { - if (authenticationProtocol) { - if (authenticationProtocol == 'Not defined') { - return 'Disabled'; - } - return 'Enabled'; - } else { - return 'Unknown'; + let res = new Date(current.getTime()); + let result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19); + try { + res = new Date(current.getTime() - ms); + result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19); + } catch (e) { + util$8.noop(); } + return result; } -function testVirtualNic(iface, ifaceName, mac) { - const virtualMacs = ['00:00:00:00:00:00', '00:03:FF', '00:05:69', '00:0C:29', '00:0F:4B', '00:13:07', '00:13:BE', '00:15:5d', '00:16:3E', '00:1C:42', '00:21:F6', '00:24:0B', '00:50:56', '00:A0:B1', '00:E0:C8', '08:00:27', '0A:00:27', '18:92:2C', '16:DF:49', '3C:F3:92', '54:52:00', 'FC:15:97']; - if (mac) { - return virtualMacs.filter(item => { return mac.toUpperCase().toUpperCase().startsWith(item.substring(0, mac.length)); }).length > 0 || - iface.toLowerCase().indexOf(' virtual ') > -1 || - ifaceName.toLowerCase().indexOf(' virtual ') > -1 || - iface.toLowerCase().indexOf('vethernet ') > -1 || - ifaceName.toLowerCase().indexOf('vethernet ') > -1 || - iface.toLowerCase().startsWith('veth') || - ifaceName.toLowerCase().startsWith('veth') || - iface.toLowerCase().startsWith('vboxnet') || - ifaceName.toLowerCase().startsWith('vboxnet'); - } else { return false; } -} - -function networkInterfaces(callback, rescan, defaultString) { +// -------------------------- +// PS - services +// pass a comma separated string with services to check (mysql, apache, postgresql, ...) +// this function gives an array back, if the services are running. - if (typeof callback === 'string') { - defaultString = callback; - rescan = true; - callback = null; - } +function services(srv, callback) { - if (typeof callback === 'boolean') { - rescan = callback; - callback = null; - defaultString = ''; - } - if (typeof rescan === 'undefined') { - rescan = true; + // fallback - if only callback is given + if (util$8.isFunction(srv) && !callback) { + callback = srv; + srv = ''; } - defaultString = defaultString || ''; - defaultString = '' + defaultString; return new Promise((resolve) => { process.nextTick(() => { - - let ifaces = os$3.networkInterfaces(); - - let result = []; - let nics = []; - let dnsSuffixes = []; - let nics8021xInfo = []; - // seperate handling in OSX - if (_darwin$8 || _freebsd$7 || _openbsd$7 || _netbsd$7) { - if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) { - // no changes - just return object - result = _networkInterfaces; - - if (callback) { callback(result); } - resolve(result); - } else { - const defaultInterface = getDefaultNetworkInterface(); - _ifaces = JSON.parse(JSON.stringify(ifaces)); - - nics = getDarwinNics(); - - - nics.forEach(nic => { - - if ({}.hasOwnProperty.call(ifaces, nic.iface)) { - ifaces[nic.iface].forEach(function (details) { - if (details.family === 'IPv4' || details.family === 4) { - nic.ip4subnet = details.netmask; - } - if (details.family === 'IPv6' || details.family === 6) { - nic.ip6subnet = details.netmask; - } - }); - } - - let ifaceSanitized = ''; - const s = util$a.isPrototypePolluted() ? '---' : util$a.sanitizeShellString(nic.iface); - const l = util$a.mathMin(s.length, 2000); - for (let i = 0; i <= l; i++) { - if (s[i] !== undefined) { - ifaceSanitized = ifaceSanitized + s[i]; - } - } - - result.push({ - iface: nic.iface, - ifaceName: nic.iface, - default: nic.iface === defaultInterface, - ip4: nic.ip4, - ip4subnet: nic.ip4subnet || '', - ip6: nic.ip6, - ip6subnet: nic.ip6subnet || '', - mac: nic.mac, - internal: nic.internal, - virtual: nic.internal ? false : testVirtualNic(nic.iface, nic.iface, nic.mac), - operstate: nic.operstate, - type: nic.type, - duplex: nic.duplex, - mtu: nic.mtu, - speed: nic.speed, - dhcp: getDarwinIfaceDHCPstatus(ifaceSanitized), - dnsSuffix: '', - ieee8021xAuth: '', - ieee8021xState: '', - carrierChanges: 0 - }); - }); - _networkInterfaces = result; - if (defaultString.toLowerCase().indexOf('default') >= 0) { - result = result.filter(item => item.default); - if (result.length > 0) { - result = result[0]; - } else { - result = []; - } + if (typeof srv !== 'string') { + if (callback) { callback([]); } + return resolve([]); + } + + if (srv) { + let srvString = ''; + srvString.__proto__.toLowerCase = util$8.stringToLower; + srvString.__proto__.replace = util$8.stringReplace; + srvString.__proto__.trim = util$8.stringTrim; + + const s = util$8.sanitizeShellString(srv); + const l = util$8.mathMin(s.length, 2000); + for (let i = 0; i <= l; i++) { + if (s[i] !== undefined) { + srvString = srvString + s[i]; } - if (callback) { callback(result); } - resolve(result); } - } - if (_linux$8) { - if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) { - // no changes - just return object - result = _networkInterfaces; - if (callback) { callback(result); } - resolve(result); - } else { - _ifaces = JSON.parse(JSON.stringify(ifaces)); - _dhcpNics = getLinuxDHCPNics(); - const defaultInterface = getDefaultNetworkInterface(); - for (let dev in ifaces) { - let ip4 = ''; - let ip4subnet = ''; - let ip6 = ''; - let ip6subnet = ''; - let mac = ''; - let duplex = ''; - let mtu = ''; - let speed = null; - let carrierChanges = 0; - let dhcp = false; - let dnsSuffix = ''; - let ieee8021xAuth = ''; - let ieee8021xState = ''; - let type = ''; + srvString = srvString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|'); + if (srvString === '') { + srvString = '*'; + } + if (util$8.isPrototypePolluted() && srvString !== '*') { + srvString = '------'; + } + let srvs = srvString.split('|'); + let result = []; + let dataSrv = []; - if ({}.hasOwnProperty.call(ifaces, dev)) { - let ifaceName = dev; - ifaces[dev].forEach(function (details) { - if (details.family === 'IPv4' || details.family === 4) { - ip4 = details.address; - ip4subnet = details.netmask; + if (_linux$6 || _freebsd$6 || _openbsd$6 || _netbsd$6 || _darwin$6) { + if ((_linux$6 || _freebsd$6 || _openbsd$6 || _netbsd$6) && srvString === '*') { + try { + const tmpsrv = execSync$2('systemctl --all --type=service --no-legend 2> /dev/null').toString().split('\n'); + srvs = []; + for (const s of tmpsrv) { + const name = s.split('.service')[0]; + if (name && s.indexOf(' not-found ') === -1) { + srvs.push(name.trim()); } - if (details.family === 'IPv6' || details.family === 6) { - if (!ip6 || ip6.match(/^fe80::/i)) { - ip6 = details.address; - ip6subnet = details.netmask; + } + srvString = srvs.join('|'); + } catch (d) { + try { + srvString = ''; + const tmpsrv = execSync$2('service --status-all 2> /dev/null').toString().split('\n'); + for (const s of tmpsrv) { + const parts = s.split(']'); + if (parts.length === 2) { + srvString += (srvString !== '' ? '|' : '') + parts[1].trim(); } } - mac = details.mac; - // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2) - const nodeMainVersion = parseInt(process.versions.node.split('.'), 10); - if (mac.indexOf('00:00:0') > -1 && (_linux$8 || _darwin$8) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) { - if (Object.keys(_mac).length === 0) { - _mac = getMacAddresses(); + srvs = srvString.split('|'); + } catch (e) { + try { + const srvStr = execSync$2('ls /etc/init.d/ -m 2> /dev/null').toString().split('\n').join(''); + srvString = ''; + if (srvStr) { + const tmpsrv = srvStr.split(','); + for (const s of tmpsrv) { + const name = s.trim(); + if (name) { + srvString += (srvString !== '' ? '|' : '') + name; + } + } + srvs = srvString.split('|'); } - mac = _mac[dev] || ''; - } - }); - let iface = dev.split(':')[0].trim().toLowerCase(); - let ifaceSanitized = ''; - const s = util$a.isPrototypePolluted() ? '---' : util$a.sanitizeShellString(iface); - const l = util$a.mathMin(s.length, 2000); - for (let i = 0; i <= l; i++) { - if (s[i] !== undefined) { - ifaceSanitized = ifaceSanitized + s[i]; + } catch (f) { + srvString = ''; + srvs = []; } } - const cmd = `echo -n "addr_assign_type: "; cat /sys/class/net/${ifaceSanitized}/addr_assign_type 2>/dev/null; echo; - echo -n "address: "; cat /sys/class/net/${ifaceSanitized}/address 2>/dev/null; echo; - echo -n "addr_len: "; cat /sys/class/net/${ifaceSanitized}/addr_len 2>/dev/null; echo; - echo -n "broadcast: "; cat /sys/class/net/${ifaceSanitized}/broadcast 2>/dev/null; echo; - echo -n "carrier: "; cat /sys/class/net/${ifaceSanitized}/carrier 2>/dev/null; echo; - echo -n "carrier_changes: "; cat /sys/class/net/${ifaceSanitized}/carrier_changes 2>/dev/null; echo; - echo -n "dev_id: "; cat /sys/class/net/${ifaceSanitized}/dev_id 2>/dev/null; echo; - echo -n "dev_port: "; cat /sys/class/net/${ifaceSanitized}/dev_port 2>/dev/null; echo; - echo -n "dormant: "; cat /sys/class/net/${ifaceSanitized}/dormant 2>/dev/null; echo; - echo -n "duplex: "; cat /sys/class/net/${ifaceSanitized}/duplex 2>/dev/null; echo; - echo -n "flags: "; cat /sys/class/net/${ifaceSanitized}/flags 2>/dev/null; echo; - echo -n "gro_flush_timeout: "; cat /sys/class/net/${ifaceSanitized}/gro_flush_timeout 2>/dev/null; echo; - echo -n "ifalias: "; cat /sys/class/net/${ifaceSanitized}/ifalias 2>/dev/null; echo; - echo -n "ifindex: "; cat /sys/class/net/${ifaceSanitized}/ifindex 2>/dev/null; echo; - echo -n "iflink: "; cat /sys/class/net/${ifaceSanitized}/iflink 2>/dev/null; echo; - echo -n "link_mode: "; cat /sys/class/net/${ifaceSanitized}/link_mode 2>/dev/null; echo; - echo -n "mtu: "; cat /sys/class/net/${ifaceSanitized}/mtu 2>/dev/null; echo; - echo -n "netdev_group: "; cat /sys/class/net/${ifaceSanitized}/netdev_group 2>/dev/null; echo; - echo -n "operstate: "; cat /sys/class/net/${ifaceSanitized}/operstate 2>/dev/null; echo; - echo -n "proto_down: "; cat /sys/class/net/${ifaceSanitized}/proto_down 2>/dev/null; echo; - echo -n "speed: "; cat /sys/class/net/${ifaceSanitized}/speed 2>/dev/null; echo; - echo -n "tx_queue_len: "; cat /sys/class/net/${ifaceSanitized}/tx_queue_len 2>/dev/null; echo; - echo -n "type: "; cat /sys/class/net/${ifaceSanitized}/type 2>/dev/null; echo; - echo -n "wireless: "; cat /proc/net/wireless 2>/dev/null | grep ${ifaceSanitized}; echo; - echo -n "wirelessspeed: "; iw dev ${ifaceSanitized} link 2>&1 | grep bitrate; echo;`; - - let lines = []; - try { - lines = execSync$4(cmd).toString().split('\n'); - const connectionName = getLinuxIfaceConnectionName(ifaceSanitized); - dhcp = getLinuxIfaceDHCPstatus(ifaceSanitized, connectionName, _dhcpNics); - dnsSuffix = getLinuxIfaceDNSsuffix(connectionName); - ieee8021xAuth = getLinuxIfaceIEEE8021xAuth(connectionName); - ieee8021xState = getLinuxIfaceIEEE8021xState(ieee8021xAuth); - } catch (e) { - util$a.noop(); - } - duplex = util$a.getValue(lines, 'duplex'); - duplex = duplex.startsWith('cat') ? '' : duplex; - mtu = parseInt(util$a.getValue(lines, 'mtu'), 10); - let myspeed = parseInt(util$a.getValue(lines, 'speed'), 10); - speed = isNaN(myspeed) ? null : myspeed; - let wirelessspeed = util$a.getValue(lines, 'wirelessspeed').split('tx bitrate: '); - if (speed === null && wirelessspeed.length === 2) { - myspeed = parseFloat(wirelessspeed[1]); - speed = isNaN(myspeed) ? null : myspeed; - } - carrierChanges = parseInt(util$a.getValue(lines, 'carrier_changes'), 10); - const operstate = util$a.getValue(lines, 'operstate'); - type = operstate === 'up' ? (util$a.getValue(lines, 'wireless').trim() ? 'wireless' : 'wired') : 'unknown'; - if (ifaceSanitized === 'lo' || ifaceSanitized.startsWith('bond')) { type = 'virtual'; } - - let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false; - if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) { - internal = true; - } - const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac); - result.push({ - iface: ifaceSanitized, - ifaceName, - default: iface === defaultInterface, - ip4, - ip4subnet, - ip6, - ip6subnet, - mac, - internal, - virtual, - operstate, - type, - duplex, - mtu, - speed, - dhcp, - dnsSuffix, - ieee8021xAuth, - ieee8021xState, - carrierChanges, - }); } } - _networkInterfaces = result; - if (defaultString.toLowerCase().indexOf('default') >= 0) { - result = result.filter(item => item.default); - if (result.length > 0) { - result = result[0]; - } else { - result = []; - } + if ((_darwin$6) && srvString === '*') { // service enumeration not yet suported on mac OS + if (callback) { callback(result); } + resolve(result); } - if (callback) { callback(result); } - resolve(result); - } - } - if (_windows$9) { - if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) { - // no changes - just return object - result = _networkInterfaces; - - if (callback) { callback(result); } - resolve(result); - } else { - _ifaces = JSON.parse(JSON.stringify(ifaces)); - const defaultInterface = getDefaultNetworkInterface(); - - getWindowsNics().then(function (nics) { - nics.forEach(nic => { - let found = false; - Object.keys(ifaces).forEach(key => { - if (!found) { - ifaces[key].forEach(value => { - if (Object.keys(value).indexOf('mac') >= 0) { - found = value['mac'] === nic.mac; - } - }); - } - }); - - if (!found) { - ifaces[nic.name] = [{ mac: nic.mac }]; - } - }); - nics8021xInfo = getWindowsWiredProfilesInformation(); - dnsSuffixes = getWindowsDNSsuffixes(); - for (let dev in ifaces) { - - let ifaceSanitized = ''; - const s = util$a.isPrototypePolluted() ? '---' : util$a.sanitizeShellString(dev); - const l = util$a.mathMin(s.length, 2000); - for (let i = 0; i <= l; i++) { - if (s[i] !== undefined) { - ifaceSanitized = ifaceSanitized + s[i]; - } - } - - let iface = dev; - let ip4 = ''; - let ip4subnet = ''; - let ip6 = ''; - let ip6subnet = ''; - let mac = ''; - let duplex = ''; - let mtu = ''; - let speed = null; - let carrierChanges = 0; - let operstate = 'down'; - let dhcp = false; - let dnsSuffix = ''; - let ieee8021xAuth = ''; - let ieee8021xState = ''; - let type = ''; + let args = (_darwin$6) ? ['-caxo', 'pcpu,pmem,pid,command'] : ['-axo', 'pcpu,pmem,pid,command']; + if (srvString !== '' && srvs.length > 0) { + util$8.execSafe('ps', args).then((stdout) => { + if (stdout) { + let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n'); + srvs.forEach(function (srv) { + let ps; + if (_darwin$6) { + ps = lines.filter(function (e) { + return (e.toLowerCase().indexOf(srv) !== -1); + }); - if ({}.hasOwnProperty.call(ifaces, dev)) { - let ifaceName = dev; - ifaces[dev].forEach(function (details) { - if (details.family === 'IPv4' || details.family === 4) { - ip4 = details.address; - ip4subnet = details.netmask; + } else { + ps = lines.filter(function (e) { + return (e.toLowerCase().indexOf(' ' + srv.toLowerCase() + ':') !== -1) || (e.toLowerCase().indexOf('/' + srv.toLowerCase()) !== -1); + }); } - if (details.family === 'IPv6' || details.family === 6) { - if (!ip6 || ip6.match(/^fe80::/i)) { - ip6 = details.address; - ip6subnet = details.netmask; + const pids = []; + for (const p of ps) { + const pid = p.trim().split(' ')[2]; + if (pid) { + pids.push(parseInt(pid, 10)); } } - mac = details.mac; - // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2) - const nodeMainVersion = parseInt(process.versions.node.split('.'), 10); - if (mac.indexOf('00:00:0') > -1 && (_linux$8 || _darwin$8) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) { - if (Object.keys(_mac).length === 0) { - _mac = getMacAddresses(); + result.push({ + name: srv, + running: ps.length > 0, + startmode: '', + pids: pids, + cpu: parseFloat((ps.reduce(function (pv, cv) { + return pv + parseFloat(cv.trim().split(' ')[0]); + }, 0)).toFixed(2)), + mem: parseFloat((ps.reduce(function (pv, cv) { + return pv + parseFloat(cv.trim().split(' ')[1]); + }, 0)).toFixed(2)) + }); + }); + if (_linux$6) { + // calc process_cpu - ps is not accurate in linux! + let cmd = 'cat /proc/stat | grep "cpu "'; + for (let i in result) { + for (let j in result[i].pids) { + cmd += (';cat /proc/' + result[i].pids[j] + '/stat'); } - mac = _mac[dev] || ''; } - }); + exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + let curr_processes = stdout.toString().split('\n'); + // first line (all - /proc/stat) + let all = parseProcStat(curr_processes.shift()); + // process + let list_new = {}; + let resultProcess = {}; + curr_processes.forEach((element) => { + resultProcess = calcProcStatLinux(element, all, _services_cpu); - dnsSuffix = getWindowsIfaceDNSsuffix(dnsSuffixes.ifaces, ifaceSanitized); - let foundFirst = false; - nics.forEach(detail => { - if (detail.mac === mac && !foundFirst) { - iface = detail.iface || iface; - ifaceName = detail.name; - dhcp = detail.dhcp; - operstate = detail.operstate; - speed = detail.speed; - type = detail.type; - foundFirst = true; - } - }); + if (resultProcess.pid) { + let listPos = -1; + for (let i in result) { + for (let j in result[i].pids) { + if (parseInt(result[i].pids[j]) === parseInt(resultProcess.pid)) { + listPos = i; + } + } + } + if (listPos >= 0) { + result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus; + } - if (dev.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('802.11n') >= 0 || ifaceName.toLowerCase().indexOf('wireless') >= 0 || ifaceName.toLowerCase().indexOf('wi-fi') >= 0 || ifaceName.toLowerCase().indexOf('wifi') >= 0) { - type = 'wireless'; - } + // save new values + list_new[resultProcess.pid] = { + cpuu: resultProcess.cpuu, + cpus: resultProcess.cpus, + utime: resultProcess.utime, + stime: resultProcess.stime, + cutime: resultProcess.cutime, + cstime: resultProcess.cstime + }; + } + }); - const IEEE8021x = getWindowsIEEE8021x(type, ifaceSanitized, nics8021xInfo); - ieee8021xAuth = IEEE8021x.protocol; - ieee8021xState = IEEE8021x.state; - let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false; - if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) { - internal = true; + // store old values + _services_cpu.all = all; + _services_cpu.list = Object.assign({}, list_new); + _services_cpu.ms = Date.now() - _services_cpu.ms; + _services_cpu.result = Object.assign({}, result); + if (callback) { callback(result); } + resolve(result); + }); + } else { + if (callback) { callback(result); } + resolve(result); } - const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac); - result.push({ - iface, - ifaceName, - default: iface === defaultInterface, - ip4, - ip4subnet, - ip6, - ip6subnet, - mac, - internal, - virtual, - operstate, - type, - duplex, - mtu, - speed, - dhcp, - dnsSuffix, - ieee8021xAuth, - ieee8021xState, - carrierChanges, + } else { + args = ['-o', 'comm']; + util$8.execSafe('ps', args).then((stdout) => { + if (stdout) { + let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n'); + srvs.forEach(function (srv) { + let ps = lines.filter(function (e) { + return e.indexOf(srv) !== -1; + }); + result.push({ + name: srv, + running: ps.length > 0, + startmode: '', + cpu: 0, + mem: 0 + }); + }); + if (callback) { callback(result); } + resolve(result); + } else { + srvs.forEach(function (srv) { + result.push({ + name: srv, + running: false, + startmode: '', + cpu: 0, + mem: 0 + }); + }); + if (callback) { callback(result); } + resolve(result); + } }); } + }); + } else { + if (callback) { callback(result); } + resolve(result); + } + } + if (_windows$7) { + try { + let wincommand = 'Get-CimInstance Win32_Service'; + if (srvs[0] !== '*') { + wincommand += ' -Filter "'; + srvs.forEach((srv) => { + wincommand += `Name='${srv}' or `; + }); + wincommand = `${wincommand.slice(0, -4)}"`; } - _networkInterfaces = result; - if (defaultString.toLowerCase().indexOf('default') >= 0) { - result = result.filter(item => item.default); - if (result.length > 0) { - result = result[0]; + wincommand += ' | select Name,Caption,Started,StartMode,ProcessId | fl'; + util$8.powerShell(wincommand).then((stdout, error) => { + if (!error) { + let serviceSections = stdout.split(/\n\s*\n/); + serviceSections.forEach((element) => { + if (element.trim() !== '') { + let lines = element.trim().split('\r\n'); + let srvName = util$8.getValue(lines, 'Name', ':', true).toLowerCase(); + let srvCaption = util$8.getValue(lines, 'Caption', ':', true).toLowerCase(); + let started = util$8.getValue(lines, 'Started', ':', true); + let startMode = util$8.getValue(lines, 'StartMode', ':', true); + let pid = util$8.getValue(lines, 'ProcessId', ':', true); + if (srvString === '*' || srvs.indexOf(srvName) >= 0 || srvs.indexOf(srvCaption) >= 0) { + result.push({ + name: srvName, + running: (started.toLowerCase() === 'true'), + startmode: startMode, + pids: [pid], + cpu: 0, + mem: 0 + }); + dataSrv.push(srvName); + dataSrv.push(srvCaption); + } + } + + }); + + if (srvString !== '*') { + let srvsMissing = srvs.filter(function (e) { + return dataSrv.indexOf(e) === -1; + }); + srvsMissing.forEach(function (srvName) { + result.push({ + name: srvName, + running: false, + startmode: '', + pids: [], + cpu: 0, + mem: 0 + }); + }); + } + if (callback) { callback(result); } + resolve(result); } else { - result = []; + srvs.forEach(function (srvName) { + result.push({ + name: srvName, + running: false, + startmode: '', + cpu: 0, + mem: 0 + }); + }); + if (callback) { callback(result); } + resolve(result); } - } + }); + } catch (e) { if (callback) { callback(result); } resolve(result); - }); + } } + } else { + if (callback) { callback([]); } + resolve([]); } }); }); } -network.networkInterfaces = networkInterfaces; +processes$1.services = services; -// -------------------------- -// NET - Speed +function parseProcStat(line) { + let parts = line.replace(/ +/g, ' ').split(' '); + let user = (parts.length >= 2 ? parseInt(parts[1]) : 0); + let nice = (parts.length >= 3 ? parseInt(parts[2]) : 0); + let system = (parts.length >= 4 ? parseInt(parts[3]) : 0); + let idle = (parts.length >= 5 ? parseInt(parts[4]) : 0); + let iowait = (parts.length >= 6 ? parseInt(parts[5]) : 0); + let irq = (parts.length >= 7 ? parseInt(parts[6]) : 0); + let softirq = (parts.length >= 8 ? parseInt(parts[7]) : 0); + let steal = (parts.length >= 9 ? parseInt(parts[8]) : 0); + let guest = (parts.length >= 10 ? parseInt(parts[9]) : 0); + let guest_nice = (parts.length >= 11 ? parseInt(parts[10]) : 0); + return user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice; +} -function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors) { - let result = { - iface, - operstate, - rx_bytes, - rx_dropped, - rx_errors, - tx_bytes, - tx_dropped, - tx_errors, - rx_sec: null, - tx_sec: null, - ms: 0 - }; +function calcProcStatLinux(line, all, _cpu_old) { + let statparts = line.replace(/ +/g, ' ').split(')'); + if (statparts.length >= 2) { + let parts = statparts[1].split(' '); + if (parts.length >= 16) { + let pid = parseInt(statparts[0].split(' ')[0]); + let utime = parseInt(parts[12]); + let stime = parseInt(parts[13]); + let cutime = parseInt(parts[14]); + let cstime = parseInt(parts[15]); - if (_network[iface] && _network[iface].ms) { - result.ms = Date.now() - _network[iface].ms; - result.rx_sec = (rx_bytes - _network[iface].rx_bytes) >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0; - result.tx_sec = (tx_bytes - _network[iface].tx_bytes) >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0; - _network[iface].rx_bytes = rx_bytes; - _network[iface].tx_bytes = tx_bytes; - _network[iface].rx_sec = result.rx_sec; - _network[iface].tx_sec = result.tx_sec; - _network[iface].ms = Date.now(); - _network[iface].last_ms = result.ms; - _network[iface].operstate = operstate; + // calc + let cpuu = 0; + let cpus = 0; + if (_cpu_old.all > 0 && _cpu_old.list[pid]) { + cpuu = (utime + cutime - _cpu_old.list[pid].utime - _cpu_old.list[pid].cutime) / (all - _cpu_old.all) * 100; // user + cpus = (stime + cstime - _cpu_old.list[pid].stime - _cpu_old.list[pid].cstime) / (all - _cpu_old.all) * 100; // system + } else { + cpuu = (utime + cutime) / (all) * 100; // user + cpus = (stime + cstime) / (all) * 100; // system + } + return { + pid: pid, + utime: utime, + stime: stime, + cutime: cutime, + cstime: cstime, + cpuu: cpuu, + cpus: cpus + }; + } else { + return { + pid: 0, + utime: 0, + stime: 0, + cutime: 0, + cstime: 0, + cpuu: 0, + cpus: 0 + }; + } } else { - if (!_network[iface]) { _network[iface] = {}; } - _network[iface].rx_bytes = rx_bytes; - _network[iface].tx_bytes = tx_bytes; - _network[iface].rx_sec = null; - _network[iface].tx_sec = null; - _network[iface].ms = Date.now(); - _network[iface].last_ms = 0; - _network[iface].operstate = operstate; + return { + pid: 0, + utime: 0, + stime: 0, + cutime: 0, + cstime: 0, + cpuu: 0, + cpus: 0 + }; } - return result; } -function networkStats(ifaces, callback) { +function calcProcStatWin(procStat, all, _cpu_old) { + // calc + let cpuu = 0; + let cpus = 0; + if (_cpu_old.all > 0 && _cpu_old.list[procStat.pid]) { + cpuu = (procStat.utime - _cpu_old.list[procStat.pid].utime) / (all - _cpu_old.all) * 100; // user + cpus = (procStat.stime - _cpu_old.list[procStat.pid].stime) / (all - _cpu_old.all) * 100; // system + } else { + cpuu = (procStat.utime) / (all) * 100; // user + cpus = (procStat.stime) / (all) * 100; // system + } + return { + pid: procStat.pid, + utime: procStat.utime, + stime: procStat.stime, + cpuu: cpuu > 0 ? cpuu : 0, + cpus: cpus > 0 ? cpus : 0 + }; +} - let ifacesArray = []; - return new Promise((resolve) => { - process.nextTick(() => { - // fallback - if only callback is given - if (util$a.isFunction(ifaces) && !callback) { - callback = ifaces; - ifacesArray = [getDefaultNetworkInterface()]; - } else { - if (typeof ifaces !== 'string' && ifaces !== undefined) { - if (callback) { callback([]); } - return resolve([]); - } - ifaces = ifaces || getDefaultNetworkInterface(); +// -------------------------- +// running processes - ifaces.__proto__.toLowerCase = util$a.stringToLower; - ifaces.__proto__.replace = util$a.stringReplace; - ifaces.__proto__.trim = util$a.stringTrim; +function processes(callback) { - ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|'); - ifacesArray = ifaces.split('|'); + let parsedhead = []; + + function getName(command) { + command = command || ''; + let result = command.split(' ')[0]; + if (result.substr(-1) === ':') { + result = result.substr(0, result.length - 1); + } + if (result.substr(0, 1) !== '[') { + let parts = result.split('/'); + if (isNaN(parseInt(parts[parts.length - 1]))) { + result = parts[parts.length - 1]; + } else { + result = parts[0]; } + } + return result; + } - const result = []; + function parseLine(line) { - const workload = []; - if (ifacesArray.length && ifacesArray[0].trim() === '*') { - ifacesArray = []; - networkInterfaces(false).then(allIFaces => { - for (let iface of allIFaces) { - ifacesArray.push(iface.iface); - } - networkStats(ifacesArray.join(',')).then(result => { - if (callback) { callback(result); } - resolve(result); - }); - }); + let offset = 0; + let offset2 = 0; + + function checkColumn(i) { + offset = offset2; + if (parsedhead[i]) { + offset2 = line.substring(parsedhead[i].to + offset, 10000).indexOf(' '); } else { - for (let iface of ifacesArray) { - workload.push(networkStatsSingle(iface.trim())); - } - if (workload.length) { - Promise.all( - workload - ).then((data) => { - if (callback) { callback(data); } - resolve(data); - }); + offset2 = 10000; + } + } + + checkColumn(0); + const pid = parseInt(line.substring(parsedhead[0].from + offset, parsedhead[0].to + offset2)); + checkColumn(1); + const ppid = parseInt(line.substring(parsedhead[1].from + offset, parsedhead[1].to + offset2)); + checkColumn(2); + const cpu = parseFloat(line.substring(parsedhead[2].from + offset, parsedhead[2].to + offset2).replace(/,/g, '.')); + checkColumn(3); + const mem = parseFloat(line.substring(parsedhead[3].from + offset, parsedhead[3].to + offset2).replace(/,/g, '.')); + checkColumn(4); + const priority = parseInt(line.substring(parsedhead[4].from + offset, parsedhead[4].to + offset2)); + checkColumn(5); + const vsz = parseInt(line.substring(parsedhead[5].from + offset, parsedhead[5].to + offset2)); + checkColumn(6); + const rss = parseInt(line.substring(parsedhead[6].from + offset, parsedhead[6].to + offset2)); + checkColumn(7); + const nice = parseInt(line.substring(parsedhead[7].from + offset, parsedhead[7].to + offset2)) || 0; + checkColumn(8); + const started = !_sunos$6 ? parseElapsedTime(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()) : parseTimeUnix(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()); + checkColumn(9); + let state = line.substring(parsedhead[9].from + offset, parsedhead[9].to + offset2).trim(); + state = (state[0] === 'R' ? 'running' : (state[0] === 'S' ? 'sleeping' : (state[0] === 'T' ? 'stopped' : (state[0] === 'W' ? 'paging' : (state[0] === 'X' ? 'dead' : (state[0] === 'Z' ? 'zombie' : ((state[0] === 'D' || state[0] === 'U') ? 'blocked' : 'unknown'))))))); + checkColumn(10); + let tty = line.substring(parsedhead[10].from + offset, parsedhead[10].to + offset2).trim(); + if (tty === '?' || tty === '??') { tty = ''; } + checkColumn(11); + const user = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim(); + checkColumn(12); + let cmdPath = ''; + let command = ''; + let params = ''; + let fullcommand = line.substring(parsedhead[12].from + offset, parsedhead[12].to + offset2).trim(); + if (fullcommand.substr(fullcommand.length - 1) === ']') { fullcommand = fullcommand.slice(0, -1); } + if (fullcommand.substr(0, 1) === '[') { command = fullcommand.substring(1); } + else { + const p1 = fullcommand.indexOf('('); + const p2 = fullcommand.indexOf(')'); + const p3 = fullcommand.indexOf('/'); + const p4 = fullcommand.indexOf(':'); + if (p1 < p2 && p1 < p3 && p3 < p2) { + command = fullcommand.split(' ')[0]; + command = command.replace(/:/g, ''); + } else { + if (p4 > 0 && (p3 === -1 || p3 > 3)) { + command = fullcommand.split(' ')[0]; + command = command.replace(/:/g, ''); } else { - if (callback) { callback(result); } - resolve(result); + // try to figure out where parameter starts + let firstParamPos = fullcommand.indexOf(' -'); + let firstParamPathPos = fullcommand.indexOf(' /'); + firstParamPos = (firstParamPos >= 0 ? firstParamPos : 10000); + firstParamPathPos = (firstParamPathPos >= 0 ? firstParamPathPos : 10000); + const firstPos = Math.min(firstParamPos, firstParamPathPos); + let tmpCommand = fullcommand.substr(0, firstPos); + const tmpParams = fullcommand.substr(firstPos); + const lastSlashPos = tmpCommand.lastIndexOf('/'); + if (lastSlashPos >= 0) { + cmdPath = tmpCommand.substr(0, lastSlashPos); + tmpCommand = tmpCommand.substr(lastSlashPos + 1); + } + + if (firstPos === 10000 && tmpCommand.indexOf(' ') > -1) { + const parts = tmpCommand.split(' '); + if (fs$1.existsSync(path$1.join(cmdPath, parts[0]))) { + command = parts.shift(); + params = (parts.join(' ') + ' ' + tmpParams).trim(); + } else { + command = tmpCommand.trim(); + params = tmpParams.trim(); + } + } else { + command = tmpCommand.trim(); + params = tmpParams.trim(); + } } } - }); - }); -} -function networkStatsSingle(iface) { + } - function parseLinesWindowsPerfData(sections) { - let perfData = []; - for (let i in sections) { - if ({}.hasOwnProperty.call(sections, i)) { - if (sections[i].trim() !== '') { - let lines = sections[i].trim().split('\r\n'); - perfData.push({ - name: util$a.getValue(lines, 'Name', ':').replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase(), - rx_bytes: parseInt(util$a.getValue(lines, 'BytesReceivedPersec', ':'), 10), - rx_errors: parseInt(util$a.getValue(lines, 'PacketsReceivedErrors', ':'), 10), - rx_dropped: parseInt(util$a.getValue(lines, 'PacketsReceivedDiscarded', ':'), 10), - tx_bytes: parseInt(util$a.getValue(lines, 'BytesSentPersec', ':'), 10), - tx_errors: parseInt(util$a.getValue(lines, 'PacketsOutboundErrors', ':'), 10), - tx_dropped: parseInt(util$a.getValue(lines, 'PacketsOutboundDiscarded', ':'), 10) - }); + return ({ + pid: pid, + parentPid: ppid, + name: _linux$6 ? getName(command) : command, + cpu: cpu, + cpuu: 0, + cpus: 0, + mem: mem, + priority: priority, + memVsz: vsz, + memRss: rss, + nice: nice, + started: started, + state: state, + tty: tty, + user: user, + command: command, + params: params, + path: cmdPath + }); + } + + function parseProcesses(lines) { + let result = []; + if (lines.length > 1) { + let head = lines[0]; + parsedhead = util$8.parseHead(head, 8); + lines.shift(); + lines.forEach(function (line) { + if (line.trim() !== '') { + result.push(parseLine(line)); } + }); + } + return result; + } + function parseProcesses2(lines) { + + function formatDateTime(time) { + const month = ('0' + (time.getMonth() + 1).toString()).slice(-2); + const year = time.getFullYear().toString(); + const day = ('0' + time.getDate().toString()).slice(-2); + const hours = ('0' + time.getHours().toString()).slice(-2); + const mins = ('0' + time.getMinutes().toString()).slice(-2); + const secs = ('0' + time.getSeconds().toString()).slice(-2); + + return (year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + secs); + } + + function parseElapsed(etime) { + let started = ''; + if (etime.indexOf('d') >= 0) { + const elapsed_parts = etime.split('d'); + started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 24 + elapsed_parts[1] * 1) * 60 * 60 * 1000)); + } else if (etime.indexOf('h') >= 0) { + const elapsed_parts = etime.split('h'); + started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 60 + elapsed_parts[1] * 1) * 60 * 1000)); + } else if (etime.indexOf(':') >= 0) { + const elapsed_parts = etime.split(':'); + started = formatDateTime(new Date(Date.now() - (elapsed_parts.length > 1 ? (elapsed_parts[0] * 60 + elapsed_parts[1]) * 1000 : elapsed_parts[0] * 1000))); } + return started; } - return perfData; + + let result = []; + lines.forEach(function (line) { + if (line.trim() !== '') { + line = line.trim().replace(/ +/g, ' ').replace(/,+/g, '.'); + const parts = line.split(' '); + const command = parts.slice(9).join(' '); + const pmem = parseFloat((1.0 * parseInt(parts[3]) * 1024 / os$1.totalmem()).toFixed(1)); + const started = parseElapsed(parts[5]); + + result.push({ + pid: parseInt(parts[0]), + parentPid: parseInt(parts[1]), + name: getName(command), + cpu: 0, + cpuu: 0, + cpus: 0, + mem: pmem, + priority: 0, + memVsz: parseInt(parts[2]), + memRss: parseInt(parts[3]), + nice: parseInt(parts[4]), + started: started, + state: (parts[6] === 'R' ? 'running' : (parts[6] === 'S' ? 'sleeping' : (parts[6] === 'T' ? 'stopped' : (parts[6] === 'W' ? 'paging' : (parts[6] === 'X' ? 'dead' : (parts[6] === 'Z' ? 'zombie' : ((parts[6] === 'D' || parts[6] === 'U') ? 'blocked' : 'unknown'))))))), + tty: parts[7], + user: parts[8], + command: command + }); + } + }); + return result; } return new Promise((resolve) => { process.nextTick(() => { - let ifaceSanitized = ''; - const s = util$a.isPrototypePolluted() ? '---' : util$a.sanitizeShellString(iface); - const l = util$a.mathMin(s.length, 2000); - for (let i = 0; i <= l; i++) { - if (s[i] !== undefined) { - ifaceSanitized = ifaceSanitized + s[i]; - } - } - let result = { - iface: ifaceSanitized, - operstate: 'unknown', - rx_bytes: 0, - rx_dropped: 0, - rx_errors: 0, - tx_bytes: 0, - tx_dropped: 0, - tx_errors: 0, - rx_sec: null, - tx_sec: null, - ms: 0 + all: 0, + running: 0, + blocked: 0, + sleeping: 0, + unknown: 0, + list: [] }; - let operstate = 'unknown'; - let rx_bytes = 0; - let tx_bytes = 0; - let rx_dropped = 0; - let rx_errors = 0; - let tx_dropped = 0; - let tx_errors = 0; + let cmd = ''; - let cmd, lines, stats; - if (!_network[ifaceSanitized] || (_network[ifaceSanitized] && !_network[ifaceSanitized].ms) || (_network[ifaceSanitized] && _network[ifaceSanitized].ms && Date.now() - _network[ifaceSanitized].ms >= 500)) { - if (_linux$8) { - if (fs$2.existsSync('/sys/class/net/' + ifaceSanitized)) { - cmd = - 'cat /sys/class/net/' + ifaceSanitized + '/operstate; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_bytes; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_bytes; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_dropped; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_errors; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_dropped; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_errors; '; - exec$8(cmd, function (error, stdout) { - if (!error) { - lines = stdout.toString().split('\n'); - operstate = lines[0].trim(); - rx_bytes = parseInt(lines[1], 10); - tx_bytes = parseInt(lines[2], 10); - rx_dropped = parseInt(lines[3], 10); - rx_errors = parseInt(lines[4], 10); - tx_dropped = parseInt(lines[5], 10); - tx_errors = parseInt(lines[6], 10); + if ((_processes_cpu.ms && Date.now() - _processes_cpu.ms >= 500) || _processes_cpu.ms === 0) { + if (_linux$6 || _freebsd$6 || _openbsd$6 || _netbsd$6 || _darwin$6 || _sunos$6) { + if (_linux$6) { cmd = 'export LC_ALL=C; ps -axo pid:11,ppid:11,pcpu:6,pmem:6,pri:5,vsz:11,rss:11,ni:5,etime:30,state:5,tty:15,user:20,command; unset LC_ALL'; } + if (_freebsd$6 || _openbsd$6 || _netbsd$6) { cmd = 'export LC_ALL=C; ps -axo pid,ppid,pcpu,pmem,pri,vsz,rss,ni,etime,state,tty,user,command; unset LC_ALL'; } + if (_darwin$6) { cmd = 'ps -axo pid,ppid,pcpu,pmem,pri,vsz=temp_title_1,rss=temp_title_2,nice,etime=temp_title_3,state,tty,user,command -r'; } + if (_sunos$6) { cmd = 'ps -Ao pid,ppid,pcpu,pmem,pri,vsz,rss,nice,stime,s,tty,user,comm'; } + exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + if (!error && stdout.toString().trim()) { + result.list = (parseProcesses(stdout.toString().split('\n'))).slice(); + result.all = result.list.length; + result.running = result.list.filter(function (e) { + return e.state === 'running'; + }).length; + result.blocked = result.list.filter(function (e) { + return e.state === 'blocked'; + }).length; + result.sleeping = result.list.filter(function (e) { + return e.state === 'sleeping'; + }).length; - result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); + if (_linux$6) { + // calc process_cpu - ps is not accurate in linux! + cmd = 'cat /proc/stat | grep "cpu "'; + result.list.forEach((element) => { + cmd += (';cat /proc/' + element.pid + '/stat'); + }); + exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + let curr_processes = stdout.toString().split('\n'); + + // first line (all - /proc/stat) + let all = parseProcStat(curr_processes.shift()); + + // process + let list_new = {}; + let resultProcess = {}; + curr_processes.forEach((element) => { + resultProcess = calcProcStatLinux(element, all, _processes_cpu); + + if (resultProcess.pid) { + + // store pcpu in outer array + let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid); + if (listPos >= 0) { + result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus; + result.list[listPos].cpuu = resultProcess.cpuu; + result.list[listPos].cpus = resultProcess.cpus; + } + + // save new values + list_new[resultProcess.pid] = { + cpuu: resultProcess.cpuu, + cpus: resultProcess.cpus, + utime: resultProcess.utime, + stime: resultProcess.stime, + cutime: resultProcess.cutime, + cstime: resultProcess.cstime + }; + } + }); + // store old values + _processes_cpu.all = all; + _processes_cpu.list = Object.assign({}, list_new); + _processes_cpu.ms = Date.now() - _processes_cpu.ms; + _processes_cpu.result = Object.assign({}, result); + if (callback) { callback(result); } + resolve(result); + }); + } else { + if (callback) { callback(result); } + resolve(result); } - resolve(result); - }); - } else { - resolve(result); - } - } - if (_freebsd$7 || _openbsd$7 || _netbsd$7) { - cmd = 'netstat -ibndI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input] - exec$8(cmd, function (error, stdout) { - if (!error) { - lines = stdout.toString().split('\n'); - for (let i = 1; i < lines.length; i++) { - const line = lines[i].replace(/ +/g, ' ').split(' '); - if (line && line[0] && line[7] && line[10]) { - rx_bytes = rx_bytes + parseInt(line[7]); - if (line[6].trim() !== '-') { rx_dropped = rx_dropped + parseInt(line[6]); } - if (line[5].trim() !== '-') { rx_errors = rx_errors + parseInt(line[5]); } - tx_bytes = tx_bytes + parseInt(line[10]); - if (line[12].trim() !== '-') { tx_dropped = tx_dropped + parseInt(line[12]); } - if (line[9].trim() !== '-') { tx_errors = tx_errors + parseInt(line[9]); } - operstate = 'up'; - } + } else { + cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,stat,tty,user,comm'; + if (_sunos$6) { + cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,s,tty,user,comm'; } - result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); + exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + if (!error) { + let lines = stdout.toString().split('\n'); + lines.shift(); + + result.list = parseProcesses2(lines).slice(); + result.all = result.list.length; + result.running = result.list.filter(function (e) { + return e.state === 'running'; + }).length; + result.blocked = result.list.filter(function (e) { + return e.state === 'blocked'; + }).length; + result.sleeping = result.list.filter(function (e) { + return e.state === 'sleeping'; + }).length; + if (callback) { callback(result); } + resolve(result); + } else { + if (callback) { callback(result); } + resolve(result); + } + }); } - resolve(result); }); - } - if (_darwin$8) { - cmd = 'ifconfig ' + ifaceSanitized + ' | grep "status"'; // lgtm [js/shell-command-constructed-from-input] - exec$8(cmd, function (error, stdout) { - result.operstate = (stdout.toString().split(':')[1] || '').trim(); - result.operstate = (result.operstate || '').toLowerCase(); - result.operstate = (result.operstate === 'active' ? 'up' : (result.operstate === 'inactive' ? 'down' : 'unknown')); - cmd = 'netstat -bdI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input] - exec$8(cmd, function (error, stdout) { + } else if (_windows$7) { + try { + util$8.powerShell('Get-CimInstance Win32_Process | select-Object ProcessId,ParentProcessId,ExecutionState,Caption,CommandLine,ExecutablePath,UserModeTime,KernelModeTime,WorkingSetSize,Priority,PageFileUsage, @{n="CreationDate";e={$_.CreationDate.ToString("yyyy-MM-dd HH:mm:ss")}} | fl').then((stdout, error) => { if (!error) { - lines = stdout.toString().split('\n'); - // if there is less than 2 lines, no information for this interface was found - if (lines.length > 1 && lines[1].trim() !== '') { - // skip header line - // use the second line because it is tied to the NIC instead of the ipv4 or ipv6 address - stats = lines[1].replace(/ +/g, ' ').split(' '); - const offset = stats.length > 11 ? 1 : 0; - rx_bytes = parseInt(stats[offset + 5]); - rx_dropped = parseInt(stats[offset + 10]); - rx_errors = parseInt(stats[offset + 4]); - tx_bytes = parseInt(stats[offset + 8]); - tx_dropped = parseInt(stats[offset + 10]); - tx_errors = parseInt(stats[offset + 7]); - result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, result.operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); - } - } - resolve(result); - }); - }); - } - if (_windows$9) { - let perfData = []; - let ifaceName = ifaceSanitized; + let processSections = stdout.split(/\n\s*\n/); + let procs = []; + let procStats = []; + let list_new = {}; + let allcpuu = 0; + let allcpus = 0; + processSections.forEach((element) => { + if (element.trim() !== '') { + let lines = element.trim().split('\r\n'); + let pid = parseInt(util$8.getValue(lines, 'ProcessId', ':', true), 10); + let parentPid = parseInt(util$8.getValue(lines, 'ParentProcessId', ':', true), 10); + let statusValue = util$8.getValue(lines, 'ExecutionState', ':'); + let name = util$8.getValue(lines, 'Caption', ':', true); + let commandLine = util$8.getValue(lines, 'CommandLine', ':', true); + // get additional command line data + let additionalCommand = false; + lines.forEach((line) => { + if (additionalCommand && line.toLowerCase().startsWith(' ')) { + commandLine += ' ' + line.trim(); + } else { + additionalCommand = false; + } + if (line.toLowerCase().startsWith('commandline')) { + additionalCommand = true; + } + }); + let commandPath = util$8.getValue(lines, 'ExecutablePath', ':', true); + let utime = parseInt(util$8.getValue(lines, 'UserModeTime', ':', true), 10); + let stime = parseInt(util$8.getValue(lines, 'KernelModeTime', ':', true), 10); + let memw = parseInt(util$8.getValue(lines, 'WorkingSetSize', ':', true), 10); + allcpuu = allcpuu + utime; + allcpus = allcpus + stime; + result.all++; + if (!statusValue) { result.unknown++; } + if (statusValue === '3') { result.running++; } + if (statusValue === '4' || statusValue === '5') { result.blocked++; } - // Performance Data - util$a.powerShell('Get-CimInstance Win32_PerfRawData_Tcpip_NetworkInterface | select Name,BytesReceivedPersec,PacketsReceivedErrors,PacketsReceivedDiscarded,BytesSentPersec,PacketsOutboundErrors,PacketsOutboundDiscarded | fl').then((stdout, error) => { - if (!error) { - const psections = stdout.toString().split(/\n\s*\n/); - perfData = parseLinesWindowsPerfData(psections); - } + procStats.push({ + pid: pid, + utime: utime, + stime: stime, + cpu: 0, + cpuu: 0, + cpus: 0, + }); + procs.push({ + pid: pid, + parentPid: parentPid, + name: name, + cpu: 0, + cpuu: 0, + cpus: 0, + mem: memw / os$1.totalmem() * 100, + priority: parseInt(util$8.getValue(lines, 'Priority', ':', true), 10), + memVsz: parseInt(util$8.getValue(lines, 'PageFileUsage', ':', true), 10), + memRss: Math.floor(parseInt(util$8.getValue(lines, 'WorkingSetSize', ':', true), 10) / 1024), + nice: 0, + started: util$8.getValue(lines, 'CreationDate', ':', true), + state: (!statusValue ? _winStatusValues[0] : _winStatusValues[statusValue]), + tty: '', + user: '', + command: commandLine || name, + path: commandPath, + params: '' + }); + } + }); - // Network Interfaces - networkInterfaces(false).then(interfaces => { - // get bytes sent, received from perfData by name - rx_bytes = 0; - tx_bytes = 0; - perfData.forEach(detail => { - interfaces.forEach(det => { - if ((det.iface.toLowerCase() === ifaceSanitized.toLowerCase() || - det.mac.toLowerCase() === ifaceSanitized.toLowerCase() || - det.ip4.toLowerCase() === ifaceSanitized.toLowerCase() || - det.ip6.toLowerCase() === ifaceSanitized.toLowerCase() || - det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === ifaceSanitized.replace(/[()[\] ]+/g, '').replace('#', '_').toLowerCase()) && - (det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === detail.name)) { - ifaceName = det.iface; - rx_bytes = detail.rx_bytes; - rx_dropped = detail.rx_dropped; - rx_errors = detail.rx_errors; - tx_bytes = detail.tx_bytes; - tx_dropped = detail.tx_dropped; - tx_errors = detail.tx_errors; - operstate = det.operstate; + result.sleeping = result.all - result.running - result.blocked - result.unknown; + result.list = procs; + procStats.forEach((element) => { + let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _processes_cpu); + + // store pcpu in outer array + let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid); + if (listPos >= 0) { + result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus; + result.list[listPos].cpuu = resultProcess.cpuu; + result.list[listPos].cpus = resultProcess.cpus; } + + // save new values + list_new[resultProcess.pid] = { + cpuu: resultProcess.cpuu, + cpus: resultProcess.cpus, + utime: resultProcess.utime, + stime: resultProcess.stime + }; }); - }); - if (rx_bytes && tx_bytes) { - result = calcNetworkSpeed(ifaceName, parseInt(rx_bytes), parseInt(tx_bytes), operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); + + // store old values + _processes_cpu.all = allcpuu + allcpus; + _processes_cpu.all_utime = allcpuu; + _processes_cpu.all_stime = allcpus; + _processes_cpu.list = Object.assign({}, list_new); + _processes_cpu.ms = Date.now() - _processes_cpu.ms; + _processes_cpu.result = Object.assign({}, result); + } + if (callback) { + callback(result); } resolve(result); }); - }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } + } else { + if (callback) { callback(result); } + resolve(result); } } else { - result.rx_bytes = _network[ifaceSanitized].rx_bytes; - result.tx_bytes = _network[ifaceSanitized].tx_bytes; - result.rx_sec = _network[ifaceSanitized].rx_sec; - result.tx_sec = _network[ifaceSanitized].tx_sec; - result.ms = _network[ifaceSanitized].last_ms; - result.operstate = _network[ifaceSanitized].operstate; - resolve(result); + if (callback) { callback(_processes_cpu.result); } + resolve(_processes_cpu.result); } }); }); } -network.networkStats = networkStats; +processes$1.processes = processes; // -------------------------- -// NET - connections (sockets) +// PS - process load +// get detailed information about a certain process +// (PID, CPU-Usage %, Mem-Usage %) -function getProcessName(processes, pid) { - let cmd = ''; - processes.forEach(line => { - const parts = line.split(' '); - const id = parseInt(parts[0], 10) || -1; - if (id === pid) { - parts.shift(); - cmd = parts.join(' ').split(':')[0]; - } - }); - cmd = cmd.split(' -')[0]; - // return cmd; - const cmdParts = cmd.split('/'); - return cmdParts[cmdParts.length - 1]; -} +function processLoad(proc, callback) { -function networkConnections(callback) { + // fallback - if only callback is given + if (util$8.isFunction(proc) && !callback) { + callback = proc; + proc = ''; + } return new Promise((resolve) => { process.nextTick(() => { - let result = []; - if (_linux$8 || _freebsd$7 || _openbsd$7 || _netbsd$7) { - let cmd = 'export LC_ALL=C; netstat -tunap | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; - if (_freebsd$7 || _openbsd$7 || _netbsd$7) { cmd = 'export LC_ALL=C; netstat -na | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; } - exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - let lines = stdout.toString().split('\n'); - if (!error && (lines.length > 1 || lines[0] != '')) { - lines.forEach(function (line) { - line = line.replace(/ +/g, ' ').split(' '); - if (line.length >= 7) { - let localip = line[3]; - let localport = ''; - let localaddress = line[3].split(':'); - if (localaddress.length > 1) { - localport = localaddress[localaddress.length - 1]; - localaddress.pop(); - localip = localaddress.join(':'); - } - let peerip = line[4]; - let peerport = ''; - let peeraddress = line[4].split(':'); - if (peeraddress.length > 1) { - peerport = peeraddress[peeraddress.length - 1]; - peeraddress.pop(); - peerip = peeraddress.join(':'); - } - let connstate = line[5]; - let proc = line[6].split('/'); - if (connstate) { - result.push({ - protocol: line[0], - localAddress: localip, - localPort: localport, - peerAddress: peerip, - peerPort: peerport, - state: connstate, - pid: proc[0] && proc[0] !== '-' ? parseInt(proc[0], 10) : null, - process: proc[1] ? proc[1].split(' ')[0].split(':')[0] : '' - }); - } - } - }); - if (callback) { - callback(result); - } - resolve(result); - } else { - cmd = 'ss -tunap | grep "ESTAB\\|SYN-SENT\\|SYN-RECV\\|FIN-WAIT1\\|FIN-WAIT2\\|TIME-WAIT\\|CLOSE\\|CLOSE-WAIT\\|LAST-ACK\\|LISTEN\\|CLOSING"'; - exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + proc = proc || ''; - if (!error) { - let lines = stdout.toString().split('\n'); - lines.forEach(function (line) { - line = line.replace(/ +/g, ' ').split(' '); - if (line.length >= 6) { - let localip = line[4]; - let localport = ''; - let localaddress = line[4].split(':'); - if (localaddress.length > 1) { - localport = localaddress[localaddress.length - 1]; - localaddress.pop(); - localip = localaddress.join(':'); - } - let peerip = line[5]; - let peerport = ''; - let peeraddress = line[5].split(':'); - if (peeraddress.length > 1) { - peerport = peeraddress[peeraddress.length - 1]; - peeraddress.pop(); - peerip = peeraddress.join(':'); - } - let connstate = line[1]; - if (connstate === 'ESTAB') { connstate = 'ESTABLISHED'; } - if (connstate === 'TIME-WAIT') { connstate = 'TIME_WAIT'; } - let pid = null; - let process = ''; - if (line.length >= 7 && line[6].indexOf('users:') > -1) { - let proc = line[6].replace('users:(("', '').replace(/"/g, '').split(','); - if (proc.length > 2) { - process = proc[0].split(' ')[0].split(':')[0]; - pid = parseInt(proc[1], 10); - } - } - if (connstate) { - result.push({ - protocol: line[0], - localAddress: localip, - localPort: localport, - peerAddress: peerip, - peerPort: peerport, - state: connstate, - pid, - process - }); - } - } - }); - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - }); + if (typeof proc !== 'string') { + if (callback) { callback([]); } + return resolve([]); } - if (_darwin$8) { - // let cmd = 'netstat -natv | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"'; - let cmd = 'netstat -natvln | grep "tcp4\\|tcp6\\|udp4\\|udp6"'; - const states = 'ESTABLISHED|SYN_SENT|SYN_RECV|FIN_WAIT1|FIN_WAIT2|TIME_WAIT|CLOSE|CLOSE_WAIT|LAST_ACK|LISTEN|CLOSING|UNKNOWN'; - exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - if (!error) { - exec$8('ps -axo pid,command', { maxBuffer: 1024 * 20000 }, function (err2, stdout2) { - let processes = stdout2.toString().split('\n'); - processes = processes.map((line => { return line.trim().replace(/ +/g, ' '); })); - let lines = stdout.toString().split('\n'); - lines.forEach(function (line) { - line = line.replace(/ +/g, ' ').split(' '); - if (line.length >= 8) { - let localip = line[3]; - let localport = ''; - let localaddress = line[3].split('.'); - if (localaddress.length > 1) { - localport = localaddress[localaddress.length - 1]; - localaddress.pop(); - localip = localaddress.join('.'); - } - let peerip = line[4]; - let peerport = ''; - let peeraddress = line[4].split('.'); - if (peeraddress.length > 1) { - peerport = peeraddress[peeraddress.length - 1]; - peeraddress.pop(); - peerip = peeraddress.join('.'); - } - const hasState = states.indexOf(line[5]) >= 0; - let connstate = hasState ? line[5] : 'UNKNOWN'; - let pid = parseInt(line[8 + (hasState ? 0 : -1)], 10); - if (connstate) { - result.push({ - protocol: line[0], - localAddress: localip, - localPort: localport, - peerAddress: peerip, - peerPort: peerport, - state: connstate, - pid: pid, - process: getProcessName(processes, pid) - }); - } - } - }); - if (callback) { - callback(result); - } - resolve(result); - }); + let processesString = ''; + processesString.__proto__.toLowerCase = util$8.stringToLower; + processesString.__proto__.replace = util$8.stringReplace; + processesString.__proto__.trim = util$8.stringTrim; - } - }); + const s = util$8.sanitizeShellString(proc); + const l = util$8.mathMin(s.length, 2000); + + for (let i = 0; i <= l; i++) { + if (s[i] !== undefined) { + processesString = processesString + s[i]; + } } - if (_windows$9) { - let cmd = 'netstat -nao'; - try { - exec$8(cmd, util$a.execOptsWin, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\r\n'); + processesString = processesString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|'); + if (processesString === '') { + processesString = '*'; + } + if (util$8.isPrototypePolluted() && processesString !== '*') { + processesString = '------'; + } + let processes = processesString.split('|'); + let result = []; - lines.forEach(function (line) { - line = line.trim().replace(/ +/g, ' ').split(' '); - if (line.length >= 4) { - let localip = line[1]; - let localport = ''; - let localaddress = line[1].split(':'); - if (localaddress.length > 1) { - localport = localaddress[localaddress.length - 1]; - localaddress.pop(); - localip = localaddress.join(':'); - } - localip = localip.replace(/\[/g, '').replace(/\]/g, ''); - let peerip = line[2]; - let peerport = ''; - let peeraddress = line[2].split(':'); - if (peeraddress.length > 1) { - peerport = peeraddress[peeraddress.length - 1]; - peeraddress.pop(); - peerip = peeraddress.join(':'); - } - peerip = peerip.replace(/\[/g, '').replace(/\]/g, ''); - let pid = util$a.toInt(line[4]); - let connstate = line[3]; - if (connstate === 'HERGESTELLT') { connstate = 'ESTABLISHED'; } - if (connstate.startsWith('ABH')) { connstate = 'LISTEN'; } - if (connstate === 'SCHLIESSEN_WARTEN') { connstate = 'CLOSE_WAIT'; } - if (connstate === 'WARTEND') { connstate = 'TIME_WAIT'; } - if (connstate === 'SYN_GESENDET') { connstate = 'SYN_SENT'; } + const procSanitized = util$8.isPrototypePolluted() ? '' : util$8.sanitizeShellString(proc); + + // from here new + // let result = { + // 'proc': procSanitized, + // 'pid': null, + // 'cpu': 0, + // 'mem': 0 + // }; + if (procSanitized && processes.length && processes[0] !== '------') { + if (_windows$7) { + try { + util$8.powerShell('Get-CimInstance Win32_Process | select ProcessId,Caption,UserModeTime,KernelModeTime,WorkingSetSize | fl').then((stdout, error) => { + if (!error) { + let processSections = stdout.split(/\n\s*\n/); + let procStats = []; + let list_new = {}; + let allcpuu = 0; + let allcpus = 0; + + // go through all processes + processSections.forEach((element) => { + if (element.trim() !== '') { + let lines = element.trim().split('\r\n'); + let pid = parseInt(util$8.getValue(lines, 'ProcessId', ':', true), 10); + let name = util$8.getValue(lines, 'Caption', ':', true); + let utime = parseInt(util$8.getValue(lines, 'UserModeTime', ':', true), 10); + let stime = parseInt(util$8.getValue(lines, 'KernelModeTime', ':', true), 10); + let mem = parseInt(util$8.getValue(lines, 'WorkingSetSize', ':', true), 10); + allcpuu = allcpuu + utime; + allcpus = allcpus + stime; - if (connstate === 'LISTENING') { connstate = 'LISTEN'; } - if (connstate === 'SYN_RECEIVED') { connstate = 'SYN_RECV'; } - if (connstate === 'FIN_WAIT_1') { connstate = 'FIN_WAIT1'; } - if (connstate === 'FIN_WAIT_2') { connstate = 'FIN_WAIT2'; } - if (line[0].toLowerCase() !== 'udp' && connstate) { - result.push({ - protocol: line[0].toLowerCase(), - localAddress: localip, - localPort: localport, - peerAddress: peerip, - peerPort: peerport, - state: connstate, - pid, - process: '' + procStats.push({ + pid: pid, + name, + utime: utime, + stime: stime, + cpu: 0, + cpuu: 0, + cpus: 0, + mem }); - } else if (line[0].toLowerCase() === 'udp') { - result.push({ - protocol: line[0].toLowerCase(), - localAddress: localip, - localPort: localport, - peerAddress: peerip, - peerPort: peerport, - state: '', - pid: parseInt(line[3], 10), - process: '' + let pname = ''; + let inList = false; + processes.forEach(function (proc) { + if (name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) { + inList = true; + pname = proc; + } }); + + if (processesString === '*' || inList) { + let processFound = false; + result.forEach(function (item) { + if (item.proc.toLowerCase() === pname.toLowerCase()) { + item.pids.push(pid); + item.mem += mem / os$1.totalmem() * 100; + processFound = true; + } + }); + if (!processFound) { + result.push({ + proc: pname, + pid: pid, + pids: [pid], + cpu: 0, + mem: mem / os$1.totalmem() * 100 + }); + } + } } + }); + + // add missing processes + if (processesString !== '*') { + let processesMissing = processes.filter(function (name) { + return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0; + + }); + processesMissing.forEach(function (procName) { + result.push({ + proc: procName, + pid: null, + pids: [], + cpu: 0, + mem: 0 + }); + }); } - }); - if (callback) { - callback(result); - } - resolve(result); - } - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } - } - }); - }); -} -network.networkConnections = networkConnections; + // calculate proc stats for each proc + procStats.forEach((element) => { + let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _process_cpu); -function networkGatewayDefault(callback) { + let listPos = -1; + for (let j = 0; j < result.length; j++) { + if (result[j].pid === resultProcess.pid || result[j].pids.indexOf(resultProcess.pid) >= 0) { listPos = j; } + } + if (listPos >= 0) { + result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus; + } - return new Promise((resolve) => { - process.nextTick(() => { - let result = ''; - if (_linux$8 || _freebsd$7 || _openbsd$7 || _netbsd$7) { - let cmd = 'ip route get 1'; - try { - exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - const line = lines && lines[0] ? lines[0] : ''; - let parts = line.split(' via '); - if (parts && parts[1]) { - parts = parts[1].split(' '); - result = parts[0]; - } - if (callback) { - callback(result); - } - resolve(result); - } else { - if (callback) { - callback(result); - } - resolve(result); - } - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } - } - if (_darwin$8) { - let cmd = 'route -n get default'; - try { - exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - if (!error) { - const lines = stdout.toString().split('\n').map(line => line.trim()); - result = util$a.getValue(lines, 'gateway'); - } - if (!result) { - cmd = 'netstat -rn | awk \'/default/ {print $2}\''; - exec$8(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - const lines = stdout.toString().split('\n').map(line => line.trim()); - result = lines.find(line => (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(line))); + // save new values + list_new[resultProcess.pid] = { + cpuu: resultProcess.cpuu, + cpus: resultProcess.cpus, + utime: resultProcess.utime, + stime: resultProcess.stime + }; + }); + + // store old values + _process_cpu.all = allcpuu + allcpus; + _process_cpu.all_utime = allcpuu; + _process_cpu.all_stime = allcpus; + _process_cpu.list = Object.assign({}, list_new); + _process_cpu.ms = Date.now() - _process_cpu.ms; + _process_cpu.result = JSON.parse(JSON.stringify(result)); if (callback) { callback(result); } resolve(result); - }); - } else { - if (callback) { - callback(result); - } - resolve(result); - } - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } - } - if (_windows$9) { - try { - exec$8('netstat -r', util$a.execOptsWin, function (error, stdout) { - const lines = stdout.toString().split(os$3.EOL); - lines.forEach(line => { - line = line.replace(/\s+/g, ' ').trim(); - if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) { - const parts = line.split(' '); - if (parts.length >= 5 && (parts[parts.length - 3]).indexOf('.') > -1) { - result = parts[parts.length - 3]; - } } }); - if (!result) { - util$a.powerShell('Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq \'0.0.0.0\' -and $_.Mask -eq \'0.0.0.0\' }') - .then((data) => { - let lines = data.toString().split('\r\n'); - if (lines.length > 1 && !result) { - result = util$a.getValue(lines, 'NextHop'); - if (callback) { - callback(result); - } - resolve(result); - // } else { - // exec('ipconfig', util.execOptsWin, function (error, stdout) { - // let lines = stdout.toString().split('\r\n'); - // lines.forEach(function (line) { - // line = line.trim().replace(/\. /g, ''); - // line = line.trim().replace(/ +/g, ''); - // const parts = line.split(':'); - // if ((parts[0].toLowerCase().startsWith('standardgate') || parts[0].toLowerCase().indexOf('gateway') > -1 || parts[0].toLowerCase().indexOf('enlace') > -1) && parts[1]) { - // result = parts[1]; - // } - // }); - // if (callback) { callback(result); } - // resolve(result); - // }); - } - }); - } else { - if (callback) { - callback(result); - } - resolve(result); - } - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } } - } - }); - }); -} -network.networkGatewayDefault = networkGatewayDefault; + if (_darwin$6 || _linux$6 || _freebsd$6 || _openbsd$6 || _netbsd$6) { + const params = ['-axo', 'pid,ppid,pcpu,pmem,comm']; + util$8.execSafe('ps', params).then((stdout) => { + if (stdout) { + let procStats = []; + let lines = stdout.toString().split('\n').filter(function (line) { + if (processesString === '*') { return true; } + if (line.toLowerCase().indexOf('grep') !== -1) { return false; } // remove this?? + let found = false; + processes.forEach(function (item) { + found = found || (line.toLowerCase().indexOf(item.toLowerCase()) >= 0); + }); + return found; + }); -var wifi = {}; + lines.forEach(function (line) { + let data = line.trim().replace(/ +/g, ' ').split(' '); + if (data.length > 4) { + procStats.push({ + name: data[4].substring(data[4].lastIndexOf('/') + 1), + pid: parseInt(data[0]) || 0, + ppid: parseInt(data[1]) || 0, + cpu: parseFloat(data[2].replace(',', '.')), + mem: parseFloat(data[3].replace(',', '.')) + }); + } + }); -// @ts-check -// ================================================================================== -// wifi.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 9. wifi -// ---------------------------------------------------------------------------------- + procStats.forEach(function (item) { + let listPos = -1; + let inList = false; + let name = ''; + for (let j = 0; j < result.length; j++) { + if (item.name.toLowerCase().indexOf(result[j].proc.toLowerCase()) >= 0) { + listPos = j; + } + } + processes.forEach(function (proc) { -const os$2 = require$$0$7; -const exec$7 = require$$1$2.exec; -const execSync$3 = require$$1$2.execSync; -const util$9 = util$j; + if (item.name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) { + inList = true; + name = proc; + } + }); + if ((processesString === '*') || inList) { + if (listPos < 0) { + result.push({ + proc: name, + pid: item.pid, + pids: [item.pid], + cpu: item.cpu, + mem: item.mem + }); + } else { + if (item.ppid < 10) { + result[listPos].pid = item.pid; + } + result[listPos].pids.push(item.pid); + result[listPos].cpu += item.cpu; + result[listPos].mem += item.mem; + } + } + }); -let _platform$8 = process.platform; + if (processesString !== '*') { + // add missing processes + let processesMissing = processes.filter(function (name) { + return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0; + }); + processesMissing.forEach(function (procName) { + result.push({ + proc: procName, + pid: null, + pids: [], + cpu: 0, + mem: 0 + }); + }); + } + if (_linux$6) { + // calc process_cpu - ps is not accurate in linux! + result.forEach(function (item) { + item.cpu = 0; + }); + let cmd = 'cat /proc/stat | grep "cpu "'; + for (let i in result) { + for (let j in result[i].pids) { + cmd += (';cat /proc/' + result[i].pids[j] + '/stat'); + } + } + exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + let curr_processes = stdout.toString().split('\n'); -const _linux$7 = (_platform$8 === 'linux' || _platform$8 === 'android'); -const _darwin$7 = (_platform$8 === 'darwin'); -const _windows$8 = (_platform$8 === 'win32'); + // first line (all - /proc/stat) + let all = parseProcStat(curr_processes.shift()); -function wifiDBFromQuality(quality) { - return (parseFloat(quality) / 2 - 100); -} + // process + let list_new = {}; + let resultProcess = {}; + curr_processes.forEach((element) => { + resultProcess = calcProcStatLinux(element, all, _process_cpu); -function wifiQualityFromDB(db) { - const result = 2 * (parseFloat(db) + 100); - return result <= 100 ? result : 100; -} + if (resultProcess.pid) { -const _wifi_frequencies = { - 1: 2412, - 2: 2417, - 3: 2422, - 4: 2427, - 5: 2432, - 6: 2437, - 7: 2442, - 8: 2447, - 9: 2452, - 10: 2457, - 11: 2462, - 12: 2467, - 13: 2472, - 14: 2484, - 32: 5160, - 34: 5170, - 36: 5180, - 38: 5190, - 40: 5200, - 42: 5210, - 44: 5220, - 46: 5230, - 48: 5240, - 50: 5250, - 52: 5260, - 54: 5270, - 56: 5280, - 58: 5290, - 60: 5300, - 62: 5310, - 64: 5320, - 68: 5340, - 96: 5480, - 100: 5500, - 102: 5510, - 104: 5520, - 106: 5530, - 108: 5540, - 110: 5550, - 112: 5560, - 114: 5570, - 116: 5580, - 118: 5590, - 120: 5600, - 122: 5610, - 124: 5620, - 126: 5630, - 128: 5640, - 132: 5660, - 134: 5670, - 136: 5680, - 138: 5690, - 140: 5700, - 142: 5710, - 144: 5720, - 149: 5745, - 151: 5755, - 153: 5765, - 155: 5775, - 157: 5785, - 159: 5795, - 161: 5805, - 165: 5825, - 169: 5845, - 173: 5865, - 183: 4915, - 184: 4920, - 185: 4925, - 187: 4935, - 188: 4940, - 189: 4945, - 192: 4960, - 196: 4980 -}; + // find result item + let resultItemId = -1; + for (let i in result) { + if (result[i].pids.indexOf(resultProcess.pid) >= 0) { + resultItemId = i; + } + } + // store pcpu in outer result + if (resultItemId >= 0) { + result[resultItemId].cpu += resultProcess.cpuu + resultProcess.cpus; + } -function wifiFrequencyFromChannel(channel) { - return {}.hasOwnProperty.call(_wifi_frequencies, channel) ? _wifi_frequencies[channel] : null; -} + // save new values + list_new[resultProcess.pid] = { + cpuu: resultProcess.cpuu, + cpus: resultProcess.cpus, + utime: resultProcess.utime, + stime: resultProcess.stime, + cutime: resultProcess.cutime, + cstime: resultProcess.cstime + }; + } + }); -function wifiChannelFromFrequencs(frequency) { - let channel = 0; - for (let key in _wifi_frequencies) { - if ({}.hasOwnProperty.call(_wifi_frequencies, key)) { - if (_wifi_frequencies[key] === frequency) { channel = util$9.toInt(key); } - } - } - return channel; -} + result.forEach(function (item) { + item.cpu = Math.round(item.cpu * 100) / 100; + }); -function ifaceListLinux() { - const result = []; - const cmd = 'iw dev 2>/dev/null'; - try { - const all = execSync$3(cmd).toString().split('\n').map(line => line.trim()).join('\n'); - const parts = all.split('\nInterface '); - parts.shift(); - parts.forEach(ifaceDetails => { - const lines = ifaceDetails.split('\n'); - const iface = lines[0]; - const id = util$9.toInt(util$9.getValue(lines, 'ifindex', ' ')); - const mac = util$9.getValue(lines, 'addr', ' '); - const channel = util$9.toInt(util$9.getValue(lines, 'channel', ' ')); - result.push({ - id, - iface, - mac, - channel - }); - }); - return result; - } catch (e) { - try { - const all = execSync$3('nmcli -t -f general,wifi-properties,wired-properties,interface-flags,capabilities,nsp device show 2>/dev/null').toString(); - const parts = all.split('\n\n'); - let i = 1; - parts.forEach(ifaceDetails => { - const lines = ifaceDetails.split('\n'); - const iface = util$9.getValue(lines, 'GENERAL.DEVICE'); - const type = util$9.getValue(lines, 'GENERAL.TYPE'); - const id = i++; // // util.getValue(lines, 'GENERAL.PATH'); - const mac = util$9.getValue(lines, 'GENERAL.HWADDR'); - const channel = ''; - if (type.toLowerCase() === 'wifi') { - result.push({ - id, - iface, - mac, - channel + _process_cpu.all = all; + _process_cpu.list = Object.assign({}, list_new); + _process_cpu.ms = Date.now() - _process_cpu.ms; + _process_cpu.result = Object.assign({}, result); + if (callback) { callback(result); } + resolve(result); + }); + } else { + if (callback) { callback(result); } + resolve(result); + } + } else { + if (callback) { callback(result); } + resolve(result); + } }); } - }); - return result; - } catch (e) { - return []; - } - } + } + }); + }); } -function nmiDeviceLinux(iface) { - const cmd = `nmcli -t -f general,wifi-properties,capabilities,ip4,ip6 device show ${iface} 2>/dev/null`; - try { - const lines = execSync$3(cmd).toString().split('\n'); - const ssid = util$9.getValue(lines, 'GENERAL.CONNECTION'); - return { - iface, - type: util$9.getValue(lines, 'GENERAL.TYPE'), - vendor: util$9.getValue(lines, 'GENERAL.VENDOR'), - product: util$9.getValue(lines, 'GENERAL.PRODUCT'), - mac: util$9.getValue(lines, 'GENERAL.HWADDR').toLowerCase(), - ssid: ssid !== '--' ? ssid : null - }; - } catch (e) { - return {}; - } -} +processes$1.processLoad = processLoad; -function nmiConnectionLinux(ssid) { - const cmd = `nmcli -t --show-secrets connection show ${ssid} 2>/dev/null`; - try { - const lines = execSync$3(cmd).toString().split('\n'); - const bssid = util$9.getValue(lines, '802-11-wireless.seen-bssids').toLowerCase(); - return { - ssid: ssid !== '--' ? ssid : null, - uuid: util$9.getValue(lines, 'connection.uuid'), - type: util$9.getValue(lines, 'connection.type'), - autoconnect: util$9.getValue(lines, 'connection.autoconnect') === 'yes', - security: util$9.getValue(lines, '802-11-wireless-security.key-mgmt'), - bssid: bssid !== '--' ? bssid : null - }; - } catch (e) { - return {}; - } -} +var users$1 = {}; -function wpaConnectionLinux(iface) { - if (!iface) { - return {}; - } - const cmd = `wpa_cli -i ${iface} status 2>&1`; - try { - const lines = execSync$3(cmd).toString().split('\n'); - const freq = util$9.toInt(util$9.getValue(lines, 'freq', '=')); - return { - ssid: util$9.getValue(lines, 'ssid', '='), - uuid: util$9.getValue(lines, 'uuid', '='), - security: util$9.getValue(lines, 'key_mgmt', '='), - freq, - channel: wifiChannelFromFrequencs(freq), - bssid: util$9.getValue(lines, 'bssid', '=').toLowerCase() - }; - } catch (e) { - return {}; - } -} +// @ts-check +// ================================================================================== +// users.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 11. Users/Sessions +// ---------------------------------------------------------------------------------- -function getWifiNetworkListNmi() { - const result = []; - const cmd = 'nmcli -t -m multiline --fields active,ssid,bssid,mode,chan,freq,signal,security,wpa-flags,rsn-flags device wifi list 2>/dev/null'; - try { - const stdout = execSync$3(cmd, { maxBuffer: 1024 * 20000 }); - const parts = stdout.toString().split('ACTIVE:'); - parts.shift(); - parts.forEach(part => { - part = 'ACTIVE:' + part; - const lines = part.split(os$2.EOL); - const channel = util$9.getValue(lines, 'CHAN'); - const frequency = util$9.getValue(lines, 'FREQ').toLowerCase().replace('mhz', '').trim(); - const security = util$9.getValue(lines, 'SECURITY').replace('(', '').replace(')', ''); - const wpaFlags = util$9.getValue(lines, 'WPA-FLAGS').replace('(', '').replace(')', ''); - const rsnFlags = util$9.getValue(lines, 'RSN-FLAGS').replace('(', '').replace(')', ''); - result.push({ - ssid: util$9.getValue(lines, 'SSID'), - bssid: util$9.getValue(lines, 'BSSID').toLowerCase(), - mode: util$9.getValue(lines, 'MODE'), - channel: channel ? parseInt(channel, 10) : null, - frequency: frequency ? parseInt(frequency, 10) : null, - signalLevel: wifiDBFromQuality(util$9.getValue(lines, 'SIGNAL')), - quality: parseFloat(util$9.getValue(lines, 'SIGNAL')), - security: security && security !== 'none' ? security.split(' ') : [], - wpaFlags: wpaFlags && wpaFlags !== 'none' ? wpaFlags.split(' ') : [], - rsnFlags: rsnFlags && rsnFlags !== 'none' ? rsnFlags.split(' ') : [] - }); - }); - return result; - } catch (e) { - return []; - } -} +const exec$5 = require$$1$2.exec; +const util$7 = util$j; -function getWifiNetworkListIw(iface) { - const result = []; - try { - let iwlistParts = execSync$3(`export LC_ALL=C; iwlist ${iface} scan 2>&1; unset LC_ALL`).toString().split(' Cell '); - if (iwlistParts[0].indexOf('resource busy') >= 0) { return -1; } - if (iwlistParts.length > 1) { - iwlistParts.shift(); - iwlistParts.forEach(element => { - const lines = element.split('\n'); - const channel = util$9.getValue(lines, 'channel', ':', true); - const address = (lines && lines.length && lines[0].indexOf('Address:') >= 0 ? lines[0].split('Address:')[1].trim().toLowerCase() : ''); - const mode = util$9.getValue(lines, 'mode', ':', true); - const frequency = util$9.getValue(lines, 'frequency', ':', true); - const qualityString = util$9.getValue(lines, 'Quality', '=', true); - const dbParts = qualityString.toLowerCase().split('signal level='); - const db = dbParts.length > 1 ? util$9.toInt(dbParts[1]) : 0; - const quality = db ? wifiQualityFromDB(db) : 0; - const ssid = util$9.getValue(lines, 'essid', ':', true); +let _platform$6 = process.platform; - // security and wpa-flags - const isWpa = element.indexOf(' WPA ') >= 0; - const isWpa2 = element.indexOf('WPA2 ') >= 0; - const security = []; - if (isWpa) { security.push('WPA'); } - if (isWpa2) { security.push('WPA2'); } - const wpaFlags = []; - let wpaFlag = ''; - lines.forEach(function (line) { - const l = line.trim().toLowerCase(); - if (l.indexOf('group cipher') >= 0) { - if (wpaFlag) { - wpaFlags.push(wpaFlag); - } - const parts = l.split(':'); - if (parts.length > 1) { - wpaFlag = parts[1].trim().toUpperCase(); - } - } - if (l.indexOf('pairwise cipher') >= 0) { - const parts = l.split(':'); - if (parts.length > 1) { - if (parts[1].indexOf('tkip')) { wpaFlag = (wpaFlag ? 'TKIP/' + wpaFlag : 'TKIP'); } - else if (parts[1].indexOf('ccmp')) { wpaFlag = (wpaFlag ? 'CCMP/' + wpaFlag : 'CCMP'); } - else if (parts[1].indexOf('proprietary')) { wpaFlag = (wpaFlag ? 'PROP/' + wpaFlag : 'PROP'); } - } - } - if (l.indexOf('authentication suites') >= 0) { - const parts = l.split(':'); - if (parts.length > 1) { - if (parts[1].indexOf('802.1x')) { wpaFlag = (wpaFlag ? '802.1x/' + wpaFlag : '802.1x'); } - else if (parts[1].indexOf('psk')) { wpaFlag = (wpaFlag ? 'PSK/' + wpaFlag : 'PSK'); } - } - } - }); - if (wpaFlag) { - wpaFlags.push(wpaFlag); - } +const _linux$5 = (_platform$6 === 'linux' || _platform$6 === 'android'); +const _darwin$5 = (_platform$6 === 'darwin'); +const _windows$6 = (_platform$6 === 'win32'); +const _freebsd$5 = (_platform$6 === 'freebsd'); +const _openbsd$5 = (_platform$6 === 'openbsd'); +const _netbsd$5 = (_platform$6 === 'netbsd'); +const _sunos$5 = (_platform$6 === 'sunos'); - result.push({ - ssid, - bssid: address, - mode, - channel: channel ? util$9.toInt(channel) : null, - frequency: frequency ? util$9.toInt(frequency.replace('.', '')) : null, - signalLevel: db, - quality, - security, - wpaFlags, - rsnFlags: [] +function parseUsersLinux(lines, phase) { + let result = []; + let result_who = []; + let result_w = {}; + let w_first = true; + let w_header = []; + let w_pos = []; + let who_line = {}; + + let is_whopart = true; + lines.forEach(function (line) { + if (line === '---') { + is_whopart = false; + } else { + let l = line.replace(/ +/g, ' ').split(' '); + + // who part + if (is_whopart) { + result_who.push({ + user: l[0], + tty: l[1], + date: l[2], + time: l[3], + ip: (l && l.length > 4) ? l[4].replace(/\(/g, '').replace(/\)/g, '') : '' }); - }); + } else { + // w part + if (w_first) { // header + w_header = l; + w_header.forEach(function (item) { + w_pos.push(line.indexOf(item)); + }); + w_first = false; + } else { + // split by w_pos + result_w.user = line.substring(w_pos[0], w_pos[1] - 1).trim(); + result_w.tty = line.substring(w_pos[1], w_pos[2] - 1).trim(); + result_w.ip = line.substring(w_pos[2], w_pos[3] - 1).replace(/\(/g, '').replace(/\)/g, '').trim(); + result_w.command = line.substring(w_pos[7], 1000).trim(); + // find corresponding 'who' line + who_line = result_who.filter(function (obj) { + return (obj.user.substring(0, 8).trim() === result_w.user && obj.tty === result_w.tty); + }); + if (who_line.length === 1) { + result.push({ + user: who_line[0].user, + tty: who_line[0].tty, + date: who_line[0].date, + time: who_line[0].time, + ip: who_line[0].ip, + command: result_w.command + }); + } + } + } } + }); + if (result.length === 0 && phase === 2) { + return result_who; + } else { return result; - } catch (e) { - return -1; } } -function parseWifiDarwin(wifiObj) { - const result = []; - if (wifiObj) { - wifiObj.forEach(function (wifiItem) { - const signalLevel = wifiItem.RSSI; - let security = []; - let wpaFlags = []; - let ssid = wifiItem.SSID_STR || ''; - if (wifiItem.WPA_IE) { - security.push('WPA'); - if (wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS) { - wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS.forEach(function (ciphers) { - if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); } - if (ciphers === 2 && wpaFlags.indexOf('PSK/TKIP') === -1) { wpaFlags.push('PSK/TKIP'); } - if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); } - }); - } - } - if (wifiItem.RSN_IE) { - security.push('WPA2'); - if (wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS) { - wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS.forEach(function (ciphers) { - if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); } - if (ciphers === 2 && wpaFlags.indexOf('TKIP/TKIP') === -1) { wpaFlags.push('TKIP/TKIP'); } - if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); } +function parseUsersDarwin(lines) { + let result = []; + let result_who = []; + let result_w = {}; + let who_line = {}; + + let is_whopart = true; + lines.forEach(function (line) { + if (line === '---') { + is_whopart = false; + } else { + let l = line.replace(/ +/g, ' ').split(' '); + + // who part + if (is_whopart) { + result_who.push({ + user: l[0], + tty: l[1], + date: ('' + new Date().getFullYear()) + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(l[2].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + l[3]).slice(-2), + time: l[4], + }); + } else { + // w part + // split by w_pos + result_w.user = l[0]; + result_w.tty = l[1]; + result_w.ip = (l[2] !== '-') ? l[2] : ''; + result_w.command = l.slice(5, 1000).join(' '); + // find corresponding 'who' line + who_line = result_who.filter(function (obj) { + return (obj.user === result_w.user && (obj.tty.substring(3, 1000) === result_w.tty || obj.tty === result_w.tty)); + }); + if (who_line.length === 1) { + result.push({ + user: who_line[0].user, + tty: who_line[0].tty, + date: who_line[0].date, + time: who_line[0].time, + ip: result_w.ip, + command: result_w.command }); } } - if (wifiItem.SSID && ssid === '') { - try { - ssid = Buffer.from(wifiItem.SSID, 'base64').toString('utf8'); - } catch (err) { - util$9.noop(); - } - } - result.push({ - ssid, - bssid: wifiItem.BSSID || '', - mode: '', - channel: wifiItem.CHANNEL, - frequency: wifiFrequencyFromChannel(wifiItem.CHANNEL), - signalLevel: signalLevel ? parseInt(signalLevel, 10) : null, - quality: wifiQualityFromDB(signalLevel), - security, - wpaFlags, - rsnFlags: [] - }); - }); - } + } + }); return result; } -function wifiNetworks(callback) { + +function users(callback) { + return new Promise((resolve) => { process.nextTick(() => { let result = []; - if (_linux$7) { - result = getWifiNetworkListNmi(); - if (result.length === 0) { - try { - const iwconfigParts = execSync$3('export LC_ALL=C; iwconfig 2>/dev/null; unset LC_ALL').toString().split('\n\n'); - let iface = ''; - iwconfigParts.forEach(element => { - if (element.indexOf('no wireless') === -1 && element.trim() !== '') { - iface = element.split(' ')[0]; - } - }); - if (iface) { - let ifaceSanitized = ''; - const s = util$9.isPrototypePolluted() ? '---' : util$9.sanitizeShellString(iface, true); - const l = util$9.mathMin(s.length, 2000); - for (let i = 0; i <= l; i++) { - if (s[i] !== undefined) { - ifaceSanitized = ifaceSanitized + s[i]; - } - } - - const res = getWifiNetworkListIw(ifaceSanitized); - if (res === -1) { - // try again after 4 secs - setTimeout(function (iface) { - const res = getWifiNetworkListIw(iface); - if (res != -1) { result = res; } - if (callback) { - callback(result); - } - resolve(result); - }, 4000); - } else { - result = res; - if (callback) { - callback(result); + // linux + if (_linux$5) { + exec$5('who --ips; echo "---"; w | tail -n +2', function (error, stdout) { + if (!error) { + // lines / split + let lines = stdout.toString().split('\n'); + result = parseUsersLinux(lines, 1); + if (result.length === 0) { + exec$5('who; echo "---"; w | tail -n +2', function (error, stdout) { + if (!error) { + // lines / split + lines = stdout.toString().split('\n'); + result = parseUsersLinux(lines, 2); } + if (callback) { callback(result); } resolve(result); - } + }); } else { - if (callback) { - callback(result); - } + if (callback) { callback(result); } resolve(result); } - } catch (e) { - if (callback) { - callback(result); - } + } else { + if (callback) { callback(result); } resolve(result); } - } else { - if (callback) { - callback(result); + }); + } + if (_freebsd$5 || _openbsd$5 || _netbsd$5) { + exec$5('who; echo "---"; w -ih', function (error, stdout) { + if (!error) { + // lines / split + let lines = stdout.toString().split('\n'); + result = parseUsersDarwin(lines); } + if (callback) { callback(result); } resolve(result); - } - } else if (_darwin$7) { - let cmd = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s -x'; - exec$7(cmd, { maxBuffer: 1024 * 40000 }, function (error, stdout) { - const output = stdout.toString(); - result = parseWifiDarwin(util$9.plistParser(output)); - if (callback) { - callback(result); + }); + } + if (_sunos$5) { + exec$5('who; echo "---"; w -h', function (error, stdout) { + if (!error) { + // lines / split + let lines = stdout.toString().split('\n'); + result = parseUsersDarwin(lines); } + if (callback) { callback(result); } resolve(result); }); - } else if (_windows$8) { - let cmd = 'netsh wlan show networks mode=Bssid'; - util$9.powerShell(cmd).then((stdout) => { - const ssidParts = stdout.toString('utf8').split(os$2.EOL + os$2.EOL + 'SSID '); - ssidParts.shift(); - - ssidParts.forEach(ssidPart => { - const ssidLines = ssidPart.split(os$2.EOL); - if (ssidLines && ssidLines.length >= 8 && ssidLines[0].indexOf(':') >= 0) { - const bssidsParts = ssidPart.split(' BSSID'); - bssidsParts.shift(); + } - bssidsParts.forEach((bssidPart) => { - const bssidLines = bssidPart.split(os$2.EOL); - const bssidLine = bssidLines[0].split(':'); - bssidLine.shift(); - const bssid = bssidLine.join(':').trim().toLowerCase(); - const channel = bssidLines[3].split(':').pop().trim(); - const quality = bssidLines[1].split(':').pop().trim(); + if (_darwin$5) { + exec$5('who; echo "---"; w -ih', function (error, stdout) { + if (!error) { + // lines / split + let lines = stdout.toString().split('\n'); + result = parseUsersDarwin(lines); + } + if (callback) { callback(result); } + resolve(result); + }); + } + if (_windows$6) { + try { + let cmd = 'Get-CimInstance Win32_LogonSession | select LogonId,@{n="StartTime";e={$_.StartTime.ToString("yyyy-MM-dd HH:mm:ss")}} | fl' + '; echo \'#-#-#-#\';'; + cmd += 'Get-CimInstance Win32_LoggedOnUser | select antecedent,dependent | fl ' + '; echo \'#-#-#-#\';'; + cmd += '$process = (Get-CimInstance Win32_Process -Filter "name = \'explorer.exe\'"); Invoke-CimMethod -InputObject $process[0] -MethodName GetOwner | select user, domain | fl; get-process -name explorer | select-object sessionid | fl; echo \'#-#-#-#\';'; + cmd += 'query user'; + util$7.powerShell(cmd).then((data) => { + if (data) { + data = data.split('#-#-#-#'); + let sessions = parseWinSessions((data[0] || '').split(/\n\s*\n/)); + let loggedons = parseWinLoggedOn((data[1] || '').split(/\n\s*\n/)); + let queryUser = parseWinUsersQuery((data[3] || '').split('\r\n')); + let users = parseWinUsers((data[2] || '').split(/\n\s*\n/), queryUser); + for (let id in loggedons) { + if ({}.hasOwnProperty.call(loggedons, id)) { + loggedons[id].dateTime = {}.hasOwnProperty.call(sessions, id) ? sessions[id] : ''; + } + } + users.forEach(user => { + let dateTime = ''; + for (let id in loggedons) { + if ({}.hasOwnProperty.call(loggedons, id)) { + if (loggedons[id].user === user.user && (!dateTime || dateTime < loggedons[id].dateTime)) { + dateTime = loggedons[id].dateTime; + } + } + } result.push({ - ssid: ssidLines[0].split(':').pop().trim(), - bssid, - mode: '', - channel: channel ? parseInt(channel, 10) : null, - frequency: wifiFrequencyFromChannel(channel), - signalLevel: wifiDBFromQuality(quality), - quality: quality ? parseInt(quality, 10) : null, - security: [ssidLines[2].split(':').pop().trim()], - wpaFlags: [ssidLines[3].split(':').pop().trim()], - rsnFlags: [] + user: user.user, + tty: user.tty, + date: `${dateTime.substring(0, 10)}`, + time: `${dateTime.substring(11, 19)}`, + ip: '', + command: '' }); }); } - }); + if (callback) { callback(result); } + resolve(result); - if (callback) { - callback(result); - } + }); + } catch (e) { + if (callback) { callback(result); } resolve(result); - }); - } else { - if (callback) { - callback(result); } - resolve(result); } }); }); } -wifi.wifiNetworks = wifiNetworks; +function parseWinSessions(sessionParts) { + const sessions = {}; + sessionParts.forEach(session => { + const lines = session.split('\r\n'); + const id = util$7.getValue(lines, 'LogonId'); + const starttime = util$7.getValue(lines, 'starttime'); + if (id) { + sessions[id] = starttime; + } + }); + return sessions; +} -function getVendor(model) { - model = model.toLowerCase(); - let result = ''; - if (model.indexOf('intel') >= 0) { result = 'Intel'; } - else if (model.indexOf('realtek') >= 0) { result = 'Realtek'; } - else if (model.indexOf('qualcom') >= 0) { result = 'Qualcom'; } - else if (model.indexOf('broadcom') >= 0) { result = 'Broadcom'; } - else if (model.indexOf('cavium') >= 0) { result = 'Cavium'; } - else if (model.indexOf('cisco') >= 0) { result = 'Cisco'; } - else if (model.indexOf('marvel') >= 0) { result = 'Marvel'; } - else if (model.indexOf('zyxel') >= 0) { result = 'Zyxel'; } - else if (model.indexOf('melanox') >= 0) { result = 'Melanox'; } - else if (model.indexOf('d-link') >= 0) { result = 'D-Link'; } - else if (model.indexOf('tp-link') >= 0) { result = 'TP-Link'; } - else if (model.indexOf('asus') >= 0) { result = 'Asus'; } - else if (model.indexOf('linksys') >= 0) { result = 'Linksys'; } +function fuzzyMatch(name1, name2) { + name1 = name1.toLowerCase(); + name2 = name2.toLowerCase(); + let eq = 0; + let len = name1.length; + if (name2.length > len) { len = name2.length; } + + for (let i = 0; i < len; i++) { + const c1 = name1[i] || ''; + const c2 = name2[i] || ''; + if (c1 === c2) { eq++; } + } + return (len > 10 ? eq / len > 0.9 : (len > 0 ? eq / len > 0.8 : false)); +} + +function parseWinUsers(userParts, userQuery) { + const users = []; + userParts.forEach(user => { + const lines = user.split('\r\n'); + + const domain = util$7.getValue(lines, 'domain', ':', true); + const username = util$7.getValue(lines, 'user', ':', true); + const sessionid = util$7.getValue(lines, 'sessionid', ':', true); + + if (username) { + const quser = userQuery.filter(item => fuzzyMatch(item.user, username)); + users.push({ + domain, + user: username, + tty: quser && quser[0] && quser[0].tty ? quser[0].tty : sessionid + }); + } + }); + return users; +} + +function parseWinLoggedOn(loggedonParts) { + const loggedons = {}; + loggedonParts.forEach(loggedon => { + const lines = loggedon.split('\r\n'); + + const antecendent = util$7.getValue(lines, 'antecedent', ':', true); + let parts = antecendent.split('='); + const name = parts.length > 2 ? parts[1].split(',')[0].replace(/"/g, '').trim() : ''; + const domain = parts.length > 2 ? parts[2].replace(/"/g, '').replace(/\)/g, '').trim() : ''; + const dependent = util$7.getValue(lines, 'dependent', ':', true); + parts = dependent.split('='); + const id = parts.length > 1 ? parts[1].replace(/"/g, '').replace(/\)/g, '').trim() : ''; + if (id) { + loggedons[id] = { + domain, + user: name + }; + } + }); + return loggedons; +} + +function parseWinUsersQuery(lines) { + lines = lines.filter(item => item); + let result = []; + const header = lines[0]; + const headerDelimiter = []; + if (header) { + const start = (header[0] === ' ') ? 1 : 0; + headerDelimiter.push(start - 1); + let nextSpace = 0; + for (let i = start + 1; i < header.length; i++) { + if (header[i] === ' ' && ((header[i - 1] === ' ') || (header[i - 1] === '.'))) { + nextSpace = i; + } else { + if (nextSpace) { + headerDelimiter.push(nextSpace); + nextSpace = 0; + } + } + } + for (let i = 1; i < lines.length; i++) { + if (lines[i].trim()) { + const user = lines[i].substring(headerDelimiter[0] + 1, headerDelimiter[1]).trim() || ''; + const tty = lines[i].substring(headerDelimiter[1] + 1, headerDelimiter[2] - 2).trim() || ''; + result.push({ + user: user, + tty: tty, + }); + } + } + } return result; } -function wifiConnections(callback) { +users$1.users = users; - return new Promise((resolve) => { - process.nextTick(() => { - const result = []; +var internet = {}; - if (_linux$7) { - const ifaces = ifaceListLinux(); - const networkList = getWifiNetworkListNmi(); - ifaces.forEach(ifaceDetail => { - let ifaceSanitized = ''; - const s = util$9.isPrototypePolluted() ? '---' : util$9.sanitizeShellString(ifaceDetail.iface, true); - const ll = util$9.mathMin(s.length, 2000); +// @ts-check +// ================================================================================== +// internet.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 12. Internet +// ---------------------------------------------------------------------------------- - for (let i = 0; i <= ll; i++) { - if (s[i] !== undefined) { - ifaceSanitized = ifaceSanitized + s[i]; - } - } +const util$6 = util$j; - const nmiDetails = nmiDeviceLinux(ifaceSanitized); - const wpaDetails = wpaConnectionLinux(ifaceSanitized); - const ssid = nmiDetails.ssid || wpaDetails.ssid; - const network = networkList.filter(nw => nw.ssid === ssid); - let ssidSanitized = ''; - const t = util$9.isPrototypePolluted() ? '---' : util$9.sanitizeShellString(ssid, true); - const l = util$9.mathMin(t.length, 2000); - for (let i = 0; i <= l; i++) { - if (t[i] !== undefined) { - ssidSanitized = ssidSanitized + t[i]; - } - } +let _platform$5 = process.platform; - const nmiConnection = nmiConnectionLinux(ssidSanitized); - const channel = network && network.length && network[0].channel ? network[0].channel : (wpaDetails.channel ? wpaDetails.channel : null); - const bssid = network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null); - if (ssid && bssid) { - result.push({ - id: ifaceDetail.id, - iface: ifaceDetail.iface, - model: nmiDetails.product, - ssid, - bssid: network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null), - channel, - frequency: channel ? wifiFrequencyFromChannel(channel) : null, - type: nmiConnection.type ? nmiConnection.type : '802.11', - security: nmiConnection.security ? nmiConnection.security : (wpaDetails.security ? wpaDetails.security : null), - signalLevel: network && network.length && network[0].signalLevel ? network[0].signalLevel : null, - txRate: null - }); +const _linux$4 = (_platform$5 === 'linux' || _platform$5 === 'android'); +const _darwin$4 = (_platform$5 === 'darwin'); +const _windows$5 = (_platform$5 === 'win32'); +const _freebsd$4 = (_platform$5 === 'freebsd'); +const _openbsd$4 = (_platform$5 === 'openbsd'); +const _netbsd$4 = (_platform$5 === 'netbsd'); +const _sunos$4 = (_platform$5 === 'sunos'); + +// -------------------------- +// check if external site is available + +function inetChecksite(url, callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + let result = { + url: url, + ok: false, + status: 404, + ms: null + }; + if (typeof url !== 'string') { + if (callback) { callback(result); } + return resolve(result); + } + let urlSanitized = ''; + const s = util$6.sanitizeShellString(url, true); + const l = util$6.mathMin(s.length, 2000); + for (let i = 0; i <= l; i++) { + if (s[i] !== undefined) { + s[i].__proto__.toLowerCase = util$6.stringToLower; + const sl = s[i].toLowerCase(); + if (sl && sl[0] && !sl[1] && sl[0].length === 1) { + urlSanitized = urlSanitized + sl[0]; } - }); - if (callback) { - callback(result); } - resolve(result); - } else if (_darwin$7) { - let cmd = 'system_profiler SPNetworkDataType'; - exec$7(cmd, function (error, stdout) { - const parts1 = stdout.toString().split('\n\n Wi-Fi:\n\n'); - if (parts1.length > 1) { - const lines = parts1[1].split('\n\n')[0].split('\n'); - const iface = util$9.getValue(lines, 'BSD Device Name', ':', true); - const model = util$9.getValue(lines, 'hardware', ':', true); - cmd = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I'; - exec$7(cmd, function (error, stdout) { - const lines2 = stdout.toString().split('\n'); - if (lines.length > 10) { - const ssid = util$9.getValue(lines2, 'ssid', ':', true); - const bssid = util$9.getValue(lines2, 'bssid', ':', true); - const security = util$9.getValue(lines2, 'link auth', ':', true); - const txRate = util$9.getValue(lines2, 'lastTxRate', ':', true); - const channel = util$9.getValue(lines2, 'channel', ':', true).split(',')[0]; - const type = '802.11'; - const rssi = util$9.toInt(util$9.getValue(lines2, 'agrCtlRSSI', ':', true)); - const noise = util$9.toInt(util$9.getValue(lines2, 'agrCtlNoise', ':', true)); - const signalLevel = rssi - noise; - if (ssid || bssid) { - result.push({ - id: 'Wi-Fi', - iface, - model, - ssid, - bssid, - channel: util$9.toInt(channel), - frequency: channel ? wifiFrequencyFromChannel(channel) : null, - type, - security, - signalLevel, - txRate - }); - } - } - if (callback) { - callback(result); - } + } + result.url = urlSanitized; + try { + if (urlSanitized && !util$6.isPrototypePolluted()) { + urlSanitized.__proto__.startsWith = util$6.stringStartWith; + if (urlSanitized.startsWith('file:') || urlSanitized.startsWith('gopher:') || urlSanitized.startsWith('telnet:') || urlSanitized.startsWith('mailto:') || urlSanitized.startsWith('news:') || urlSanitized.startsWith('nntp:')) { + if (callback) { callback(result); } + return resolve(result); + } + let t = Date.now(); + if (_linux$4 || _freebsd$4 || _openbsd$4 || _netbsd$4 || _darwin$4 || _sunos$4) { + let args = ['-I', '--connect-timeout', '5', '-m', '5']; + args.push(urlSanitized); + let cmd = 'curl'; + util$6.execSafe(cmd, args).then((stdout) => { + const lines = stdout.split('\n'); + let statusCode = lines[0] && lines[0].indexOf(' ') >= 0 ? parseInt(lines[0].split(' ')[1], 10) : 404; + result.status = statusCode || 404; + result.ok = (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304); + result.ms = (result.ok ? Date.now() - t : null); + if (callback) { callback(result); } resolve(result); }); - } else { - if (callback) { - callback(result); - } - resolve(result); - } - }); - } else if (_windows$8) { - let cmd = 'netsh wlan show interfaces'; - util$9.powerShell(cmd).then(function (stdout) { - const allLines = stdout.toString().split('\r\n'); - for (let i = 0; i < allLines.length; i++) { - allLines[i] = allLines[i].trim(); } - const parts = allLines.join('\r\n').split(':\r\n\r\n'); - parts.shift(); - parts.forEach(part => { - const lines = part.split('\r\n'); - if (lines.length >= 5) { - const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : ''; - const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : ''; - const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : ''; - const ssid = util$9.getValue(lines, 'SSID', ':', true); - const bssid = util$9.getValue(lines, 'BSSID', ':', true); - const signalLevel = util$9.getValue(lines, 'Signal', ':', true); - const type = util$9.getValue(lines, 'Radio type', ':', true) || util$9.getValue(lines, 'Type de radio', ':', true) || util$9.getValue(lines, 'Funktyp', ':', true) || null; - const security = util$9.getValue(lines, 'authentication', ':', true) || util$9.getValue(lines, 'Authentification', ':', true) || util$9.getValue(lines, 'Authentifizierung', ':', true) || null; - const channel = util$9.getValue(lines, 'Channel', ':', true) || util$9.getValue(lines, 'Canal', ':', true) || util$9.getValue(lines, 'Kanal', ':', true) || null; - const txRate = util$9.getValue(lines, 'Transmit rate (mbps)', ':', true) || util$9.getValue(lines, 'Transmission (mbit/s)', ':', true) || util$9.getValue(lines, 'Empfangsrate (MBit/s)', ':', true) || null; - if (model && id && ssid && bssid) { - result.push({ - id, - iface, - model, - ssid, - bssid, - channel: util$9.toInt(channel), - frequency: channel ? wifiFrequencyFromChannel(channel) : null, - type, - security, - signalLevel, - txRate: util$9.toInt(txRate) || null - }); - } + if (_windows$5) { // if this is stable, this can be used for all OS types + const http = (urlSanitized.startsWith('https:') ? require('https') : require('http')); + try { + http.get(urlSanitized, (res) => { + const statusCode = res.statusCode; + + result.status = statusCode || 404; + result.ok = (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304); + + if (statusCode !== 200) { + res.resume(); + result.ms = (result.ok ? Date.now() - t : null); + if (callback) { callback(result); } + resolve(result); + } else { + res.on('data', () => { }); + res.on('end', () => { + result.ms = (result.ok ? Date.now() - t : null); + if (callback) { callback(result); } + resolve(result); + }); + } + }).on('error', () => { + if (callback) { callback(result); } + resolve(result); + }); + } catch (err) { + if (callback) { callback(result); } + resolve(result); } - }); - if (callback) { - callback(result); } + } else { + if (callback) { callback(result); } resolve(result); - }); - } else { - if (callback) { - callback(result); } + } catch (err) { + if (callback) { callback(result); } resolve(result); } }); }); } -wifi.wifiConnections = wifiConnections; +internet.inetChecksite = inetChecksite; -function wifiInterfaces(callback) { +// -------------------------- +// check inet latency + +function inetLatency(host, callback) { + + // fallback - if only callback is given + if (util$6.isFunction(host) && !callback) { + callback = host; + host = ''; + } + + host = host || '8.8.8.8'; return new Promise((resolve) => { process.nextTick(() => { - const result = []; - - if (_linux$7) { - const ifaces = ifaceListLinux(); - ifaces.forEach(ifaceDetail => { - const nmiDetails = nmiDeviceLinux(ifaceDetail.iface); - result.push({ - id: ifaceDetail.id, - iface: ifaceDetail.iface, - model: nmiDetails.product ? nmiDetails.product : null, - vendor: nmiDetails.vendor ? nmiDetails.vendor : null, - mac: ifaceDetail.mac, - }); - }); - if (callback) { - callback(result); - } - resolve(result); - } else if (_darwin$7) { - let cmd = 'system_profiler SPNetworkDataType'; - exec$7(cmd, function (error, stdout) { - const parts1 = stdout.toString().split('\n\n Wi-Fi:\n\n'); - if (parts1.length > 1) { - const lines = parts1[1].split('\n\n')[0].split('\n'); - const iface = util$9.getValue(lines, 'BSD Device Name', ':', true); - const mac = util$9.getValue(lines, 'MAC Address', ':', true); - const model = util$9.getValue(lines, 'hardware', ':', true); - result.push({ - id: 'Wi-Fi', - iface, - model, - vendor: '', - mac - }); + if (typeof host !== 'string') { + if (callback) { callback(null); } + return resolve(null); + } + let hostSanitized = ''; + const s = (util$6.isPrototypePolluted() ? '8.8.8.8' : util$6.sanitizeShellString(host, true)).trim(); + const l = util$6.mathMin(s.length, 2000); + for (let i = 0; i <= l; i++) { + if (!(s[i] === undefined)) { + s[i].__proto__.toLowerCase = util$6.stringToLower; + const sl = s[i].toLowerCase(); + if (sl && sl[0] && !sl[1]) { + hostSanitized = hostSanitized + sl[0]; } - if (callback) { - callback(result); + } + } + hostSanitized.__proto__.startsWith = util$6.stringStartWith; + if (hostSanitized.startsWith('file:') || hostSanitized.startsWith('gopher:') || hostSanitized.startsWith('telnet:') || hostSanitized.startsWith('mailto:') || hostSanitized.startsWith('news:') || hostSanitized.startsWith('nntp:')) { + if (callback) { callback(null); } + return resolve(null); + } + let params; + if (_linux$4 || _freebsd$4 || _openbsd$4 || _netbsd$4 || _darwin$4) { + if (_linux$4) { + params = ['-c', '2', '-w', '3', hostSanitized]; + } + if (_freebsd$4 || _openbsd$4 || _netbsd$4) { + params = ['-c', '2', '-t', '3', hostSanitized]; + } + if (_darwin$4) { + params = ['-c2', '-t3', hostSanitized]; + } + util$6.execSafe('ping', params).then((stdout) => { + let result = null; + if (stdout) { + const lines = stdout.split('\n').filter((line) => (line.indexOf('rtt') >= 0 || line.indexOf('round-trip') >= 0 || line.indexOf('avg') >= 0)).join('\n'); + + const line = lines.split('='); + if (line.length > 1) { + const parts = line[1].split('/'); + if (parts.length > 1) { + result = parseFloat(parts[1]); + } + } } + if (callback) { callback(result); } resolve(result); }); - } else if (_windows$8) { - let cmd = 'netsh wlan show interfaces'; - util$9.powerShell(cmd).then(function (stdout) { - const allLines = stdout.toString().split('\r\n'); - for (let i = 0; i < allLines.length; i++) { - allLines[i] = allLines[i].trim(); - } - const parts = allLines.join('\r\n').split(':\r\n\r\n'); - parts.shift(); - parts.forEach(part => { - const lines = part.split('\r\n'); - if (lines.length >= 5) { - const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : ''; - const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : ''; - const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : ''; - const macParts = lines[3].indexOf(':') >= 0 ? lines[3].split(':') : []; - macParts.shift(); - const mac = macParts.join(':').trim(); - const vendor = getVendor(model); - if (iface && model && id && mac) { - result.push({ - id, - iface, - model, - vendor, - mac, - }); + } + if (_sunos$4) { + const params = ['-s', '-a', hostSanitized, '56', '2']; + const filt = 'avg'; + util$6.execSafe('ping', params, { timeout: 3000 }).then((stdout) => { + let result = null; + if (stdout) { + const lines = stdout.split('\n').filter(line => line.indexOf(filt) >= 0).join('\n'); + const line = lines.split('='); + if (line.length > 1) { + const parts = line[1].split('/'); + if (parts.length > 1) { + result = parseFloat(parts[1].replace(',', '.')); } } - }); - if (callback) { - callback(result); } + if (callback) { callback(result); } resolve(result); }); - } else { - if (callback) { - callback(result); + } + if (_windows$5) { + let result = null; + try { + const params = [hostSanitized, '-n', '1']; + util$6.execSafe('ping', params, util$6.execOptsWin).then((stdout) => { + if (stdout) { + let lines = stdout.split('\r\n'); + lines.shift(); + lines.forEach(function (line) { + if ((line.toLowerCase().match(/ms/g) || []).length === 3) { + let l = line.replace(/ +/g, ' ').split(' '); + if (l.length > 6) { + result = parseFloat(l[l.length - 1]); + } + } + }); + } + if (callback) { callback(result); } + resolve(result); + }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); } - resolve(result); } }); }); } -wifi.wifiInterfaces = wifiInterfaces; +internet.inetLatency = inetLatency; -var processes$1 = {}; +var docker = {}; // @ts-check // ================================================================================== -// processes.js +// dockerSockets.js // ---------------------------------------------------------------------------------- // Description: System Information - library // for Node.js @@ -67736,1292 +64331,1406 @@ var processes$1 = {}; // ---------------------------------------------------------------------------------- // License: MIT // ================================================================================== -// 10. Processes +// 13. DockerSockets // ---------------------------------------------------------------------------------- -const os$1 = require$$0$7; -const fs$1 = require$$0$5; -const path$1 = require$$1$1; -const exec$6 = require$$1$2.exec; -const execSync$2 = require$$1$2.execSync; - -const util$8 = util$j; +const net = require$$0$8; +const isWin = require$$0$7.type() === 'Windows_NT'; +const socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock'; -let _platform$7 = process.platform; +let DockerSocket$1 = class DockerSocket { -const _linux$6 = (_platform$7 === 'linux' || _platform$7 === 'android'); -const _darwin$6 = (_platform$7 === 'darwin'); -const _windows$7 = (_platform$7 === 'win32'); -const _freebsd$6 = (_platform$7 === 'freebsd'); -const _openbsd$6 = (_platform$7 === 'openbsd'); -const _netbsd$6 = (_platform$7 === 'netbsd'); -const _sunos$6 = (_platform$7 === 'sunos'); + getInfo(callback) { + try { -const _processes_cpu = { - all: 0, - all_utime: 0, - all_stime: 0, - list: {}, - ms: 0, - result: {} -}; -const _services_cpu = { - all: 0, - all_utime: 0, - all_stime: 0, - list: {}, - ms: 0, - result: {} -}; -const _process_cpu = { - all: 0, - all_utime: 0, - all_stime: 0, - list: {}, - ms: 0, - result: {} -}; + let socket = net.createConnection({ path: socketPath }); + let alldata = ''; + let data; -const _winStatusValues = { - '0': 'unknown', - '1': 'other', - '2': 'ready', - '3': 'running', - '4': 'blocked', - '5': 'suspended blocked', - '6': 'suspended ready', - '7': 'terminated', - '8': 'stopped', - '9': 'growing', -}; + socket.on('connect', () => { + socket.write('GET http:/info HTTP/1.0\r\n\r\n'); + }); -function parseTimeUnix(time) { - let result = time; - let parts = time.replace(/ +/g, ' ').split(' '); - if (parts.length === 5) { - result = parts[4] + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(parts[1].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + parts[2]).slice(-2) + ' ' + parts[3]; - } - return result; -} + socket.on('data', data => { + alldata = alldata + data.toString(); + }); -function parseElapsedTime(etime) { - let current = new Date(); - current = new Date(current.getTime() - current.getTimezoneOffset() * 60000); + socket.on('error', () => { + socket = false; + callback({}); + }); - const elapsed = etime.split('-'); + socket.on('end', () => { + let startbody = alldata.indexOf('\r\n\r\n'); + alldata = alldata.substring(startbody + 4); + socket = false; + try { + data = JSON.parse(alldata); + callback(data); + } catch (err) { + callback({}); + } + }); + } catch (err) { + callback({}); + } + } - const timeIndex = elapsed.length - 1; - const days = timeIndex > 0 ? parseInt(elapsed[timeIndex - 1]) : 0; + listImages(all, callback) { + try { - const timeStr = elapsed[timeIndex].split(':'); - const hours = timeStr.length === 3 ? parseInt(timeStr[0] || 0) : 0; - const mins = parseInt(timeStr[timeStr.length === 3 ? 1 : 0] || 0); - const secs = parseInt(timeStr[timeStr.length === 3 ? 2 : 1] || 0); - const ms = (((((days * 24 + hours) * 60) + mins) * 60 + secs) * 1000); + let socket = net.createConnection({ path: socketPath }); + let alldata = ''; + let data; - let res = new Date(current.getTime()); - let result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19); - try { - res = new Date(current.getTime() - ms); - result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19); - } catch (e) { - util$8.noop(); - } - return result; -} + socket.on('connect', () => { + socket.write('GET http:/images/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n'); + }); -// -------------------------- -// PS - services -// pass a comma separated string with services to check (mysql, apache, postgresql, ...) -// this function gives an array back, if the services are running. + socket.on('data', data => { + alldata = alldata + data.toString(); + }); -function services(srv, callback) { + socket.on('error', () => { + socket = false; + callback({}); + }); - // fallback - if only callback is given - if (util$8.isFunction(srv) && !callback) { - callback = srv; - srv = ''; + socket.on('end', () => { + let startbody = alldata.indexOf('\r\n\r\n'); + alldata = alldata.substring(startbody + 4); + socket = false; + try { + data = JSON.parse(alldata); + callback(data); + } catch (err) { + callback({}); + } + }); + } catch (err) { + callback({}); + } } - return new Promise((resolve) => { - process.nextTick(() => { - if (typeof srv !== 'string') { - if (callback) { callback([]); } - return resolve([]); - } + inspectImage(id, callback) { + id = id || ''; + if (id) { + try { + let socket = net.createConnection({ path: socketPath }); + let alldata = ''; + let data; - if (srv) { - let srvString = ''; - srvString.__proto__.toLowerCase = util$8.stringToLower; - srvString.__proto__.replace = util$8.stringReplace; - srvString.__proto__.trim = util$8.stringTrim; + socket.on('connect', () => { + socket.write('GET http:/images/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n'); + }); - const s = util$8.sanitizeShellString(srv); - const l = util$8.mathMin(s.length, 2000); - for (let i = 0; i <= l; i++) { - if (s[i] !== undefined) { - srvString = srvString + s[i]; - } - } + socket.on('data', data => { + alldata = alldata + data.toString(); + }); - srvString = srvString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|'); - if (srvString === '') { - srvString = '*'; - } - if (util$8.isPrototypePolluted() && srvString !== '*') { - srvString = '------'; - } - let srvs = srvString.split('|'); - let result = []; - let dataSrv = []; + socket.on('error', () => { + socket = false; + callback({}); + }); - if (_linux$6 || _freebsd$6 || _openbsd$6 || _netbsd$6 || _darwin$6) { - if ((_linux$6 || _freebsd$6 || _openbsd$6 || _netbsd$6) && srvString === '*') { - try { - const tmpsrv = execSync$2('systemctl --all --type=service --no-legend 2> /dev/null').toString().split('\n'); - srvs = []; - for (const s of tmpsrv) { - const name = s.split('.service')[0]; - if (name && s.indexOf(' not-found ') === -1) { - srvs.push(name.trim()); - } - } - srvString = srvs.join('|'); - } catch (d) { - try { - srvString = ''; - const tmpsrv = execSync$2('service --status-all 2> /dev/null').toString().split('\n'); - for (const s of tmpsrv) { - const parts = s.split(']'); - if (parts.length === 2) { - srvString += (srvString !== '' ? '|' : '') + parts[1].trim(); - } - } - srvs = srvString.split('|'); - } catch (e) { - try { - const srvStr = execSync$2('ls /etc/init.d/ -m 2> /dev/null').toString().split('\n').join(''); - srvString = ''; - if (srvStr) { - const tmpsrv = srvStr.split(','); - for (const s of tmpsrv) { - const name = s.trim(); - if (name) { - srvString += (srvString !== '' ? '|' : '') + name; - } - } - srvs = srvString.split('|'); - } - } catch (f) { - srvString = ''; - srvs = []; - } - } - } - } - if ((_darwin$6) && srvString === '*') { // service enumeration not yet suported on mac OS - if (callback) { callback(result); } - resolve(result); + socket.on('end', () => { + let startbody = alldata.indexOf('\r\n\r\n'); + alldata = alldata.substring(startbody + 4); + socket = false; + try { + data = JSON.parse(alldata); + callback(data); + } catch (err) { + callback({}); } - let args = (_darwin$6) ? ['-caxo', 'pcpu,pmem,pid,command'] : ['-axo', 'pcpu,pmem,pid,command']; - if (srvString !== '' && srvs.length > 0) { - util$8.execSafe('ps', args).then((stdout) => { - if (stdout) { - let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n'); - srvs.forEach(function (srv) { - let ps; - if (_darwin$6) { - ps = lines.filter(function (e) { - return (e.toLowerCase().indexOf(srv) !== -1); - }); + }); + } catch (err) { + callback({}); + } + } else { + callback({}); + } + } - } else { - ps = lines.filter(function (e) { - return (e.toLowerCase().indexOf(' ' + srv.toLowerCase() + ':') !== -1) || (e.toLowerCase().indexOf('/' + srv.toLowerCase()) !== -1); - }); - } - const pids = []; - for (const p of ps) { - const pid = p.trim().split(' ')[2]; - if (pid) { - pids.push(parseInt(pid, 10)); - } - } - result.push({ - name: srv, - running: ps.length > 0, - startmode: '', - pids: pids, - cpu: parseFloat((ps.reduce(function (pv, cv) { - return pv + parseFloat(cv.trim().split(' ')[0]); - }, 0)).toFixed(2)), - mem: parseFloat((ps.reduce(function (pv, cv) { - return pv + parseFloat(cv.trim().split(' ')[1]); - }, 0)).toFixed(2)) - }); - }); - if (_linux$6) { - // calc process_cpu - ps is not accurate in linux! - let cmd = 'cat /proc/stat | grep "cpu "'; - for (let i in result) { - for (let j in result[i].pids) { - cmd += (';cat /proc/' + result[i].pids[j] + '/stat'); - } - } - exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - let curr_processes = stdout.toString().split('\n'); + listContainers(all, callback) { + try { - // first line (all - /proc/stat) - let all = parseProcStat(curr_processes.shift()); + let socket = net.createConnection({ path: socketPath }); + let alldata = ''; + let data; - // process - let list_new = {}; - let resultProcess = {}; - curr_processes.forEach((element) => { - resultProcess = calcProcStatLinux(element, all, _services_cpu); + socket.on('connect', () => { + socket.write('GET http:/containers/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n'); + }); - if (resultProcess.pid) { - let listPos = -1; - for (let i in result) { - for (let j in result[i].pids) { - if (parseInt(result[i].pids[j]) === parseInt(resultProcess.pid)) { - listPos = i; - } - } - } - if (listPos >= 0) { - result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus; - } + socket.on('data', data => { + alldata = alldata + data.toString(); + }); - // save new values - list_new[resultProcess.pid] = { - cpuu: resultProcess.cpuu, - cpus: resultProcess.cpus, - utime: resultProcess.utime, - stime: resultProcess.stime, - cutime: resultProcess.cutime, - cstime: resultProcess.cstime - }; - } - }); + socket.on('error', () => { + socket = false; + callback({}); + }); - // store old values - _services_cpu.all = all; - _services_cpu.list = Object.assign({}, list_new); - _services_cpu.ms = Date.now() - _services_cpu.ms; - _services_cpu.result = Object.assign({}, result); - if (callback) { callback(result); } - resolve(result); - }); - } else { - if (callback) { callback(result); } - resolve(result); - } - } else { - args = ['-o', 'comm']; - util$8.execSafe('ps', args).then((stdout) => { - if (stdout) { - let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n'); - srvs.forEach(function (srv) { - let ps = lines.filter(function (e) { - return e.indexOf(srv) !== -1; - }); - result.push({ - name: srv, - running: ps.length > 0, - startmode: '', - cpu: 0, - mem: 0 - }); - }); - if (callback) { callback(result); } - resolve(result); - } else { - srvs.forEach(function (srv) { - result.push({ - name: srv, - running: false, - startmode: '', - cpu: 0, - mem: 0 - }); - }); - if (callback) { callback(result); } - resolve(result); - } - }); - } - }); - } else { - if (callback) { callback(result); } - resolve(result); - } + socket.on('end', () => { + let startbody = alldata.indexOf('\r\n\r\n'); + alldata = alldata.substring(startbody + 4); + socket = false; + try { + data = JSON.parse(alldata); + callback(data); + } catch (err) { + callback({}); } - if (_windows$7) { - try { - let wincommand = 'Get-CimInstance Win32_Service'; - if (srvs[0] !== '*') { - wincommand += ' -Filter "'; - srvs.forEach((srv) => { - wincommand += `Name='${srv}' or `; - }); - wincommand = `${wincommand.slice(0, -4)}"`; - } - wincommand += ' | select Name,Caption,Started,StartMode,ProcessId | fl'; - util$8.powerShell(wincommand).then((stdout, error) => { - if (!error) { - let serviceSections = stdout.split(/\n\s*\n/); - serviceSections.forEach((element) => { - if (element.trim() !== '') { - let lines = element.trim().split('\r\n'); - let srvName = util$8.getValue(lines, 'Name', ':', true).toLowerCase(); - let srvCaption = util$8.getValue(lines, 'Caption', ':', true).toLowerCase(); - let started = util$8.getValue(lines, 'Started', ':', true); - let startMode = util$8.getValue(lines, 'StartMode', ':', true); - let pid = util$8.getValue(lines, 'ProcessId', ':', true); - if (srvString === '*' || srvs.indexOf(srvName) >= 0 || srvs.indexOf(srvCaption) >= 0) { - result.push({ - name: srvName, - running: (started.toLowerCase() === 'true'), - startmode: startMode, - pids: [pid], - cpu: 0, - mem: 0 - }); - dataSrv.push(srvName); - dataSrv.push(srvCaption); - } - } + }); + } catch (err) { + callback({}); + } + } - }); + getStats(id, callback) { + id = id || ''; + if (id) { + try { + let socket = net.createConnection({ path: socketPath }); + let alldata = ''; + let data; + + socket.on('connect', () => { + socket.write('GET http:/containers/' + id + '/stats?stream=0 HTTP/1.0\r\n\r\n'); + }); + + socket.on('data', data => { + alldata = alldata + data.toString(); + }); + + socket.on('error', () => { + socket = false; + callback({}); + }); - if (srvString !== '*') { - let srvsMissing = srvs.filter(function (e) { - return dataSrv.indexOf(e) === -1; - }); - srvsMissing.forEach(function (srvName) { - result.push({ - name: srvName, - running: false, - startmode: '', - pids: [], - cpu: 0, - mem: 0 - }); - }); - } - if (callback) { callback(result); } - resolve(result); - } else { - srvs.forEach(function (srvName) { - result.push({ - name: srvName, - running: false, - startmode: '', - cpu: 0, - mem: 0 - }); - }); - if (callback) { callback(result); } - resolve(result); - } - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); + socket.on('end', () => { + let startbody = alldata.indexOf('\r\n\r\n'); + alldata = alldata.substring(startbody + 4); + socket = false; + try { + data = JSON.parse(alldata); + callback(data); + } catch (err) { + callback({}); } - } - } else { - if (callback) { callback([]); } - resolve([]); + }); + } catch (err) { + callback({}); } - }); - }); -} + } else { + callback({}); + } + } -processes$1.services = services; + getInspect(id, callback) { + id = id || ''; + if (id) { + try { + let socket = net.createConnection({ path: socketPath }); + let alldata = ''; + let data; -function parseProcStat(line) { - let parts = line.replace(/ +/g, ' ').split(' '); - let user = (parts.length >= 2 ? parseInt(parts[1]) : 0); - let nice = (parts.length >= 3 ? parseInt(parts[2]) : 0); - let system = (parts.length >= 4 ? parseInt(parts[3]) : 0); - let idle = (parts.length >= 5 ? parseInt(parts[4]) : 0); - let iowait = (parts.length >= 6 ? parseInt(parts[5]) : 0); - let irq = (parts.length >= 7 ? parseInt(parts[6]) : 0); - let softirq = (parts.length >= 8 ? parseInt(parts[7]) : 0); - let steal = (parts.length >= 9 ? parseInt(parts[8]) : 0); - let guest = (parts.length >= 10 ? parseInt(parts[9]) : 0); - let guest_nice = (parts.length >= 11 ? parseInt(parts[10]) : 0); - return user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice; -} + socket.on('connect', () => { + socket.write('GET http:/containers/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n'); + }); -function calcProcStatLinux(line, all, _cpu_old) { - let statparts = line.replace(/ +/g, ' ').split(')'); - if (statparts.length >= 2) { - let parts = statparts[1].split(' '); - if (parts.length >= 16) { - let pid = parseInt(statparts[0].split(' ')[0]); - let utime = parseInt(parts[12]); - let stime = parseInt(parts[13]); - let cutime = parseInt(parts[14]); - let cstime = parseInt(parts[15]); + socket.on('data', data => { + alldata = alldata + data.toString(); + }); - // calc - let cpuu = 0; - let cpus = 0; - if (_cpu_old.all > 0 && _cpu_old.list[pid]) { - cpuu = (utime + cutime - _cpu_old.list[pid].utime - _cpu_old.list[pid].cutime) / (all - _cpu_old.all) * 100; // user - cpus = (stime + cstime - _cpu_old.list[pid].stime - _cpu_old.list[pid].cstime) / (all - _cpu_old.all) * 100; // system - } else { - cpuu = (utime + cutime) / (all) * 100; // user - cpus = (stime + cstime) / (all) * 100; // system + socket.on('error', () => { + socket = false; + callback({}); + }); + + socket.on('end', () => { + let startbody = alldata.indexOf('\r\n\r\n'); + alldata = alldata.substring(startbody + 4); + socket = false; + try { + data = JSON.parse(alldata); + callback(data); + } catch (err) { + callback({}); + } + }); + } catch (err) { + callback({}); } - return { - pid: pid, - utime: utime, - stime: stime, - cutime: cutime, - cstime: cstime, - cpuu: cpuu, - cpus: cpus - }; } else { - return { - pid: 0, - utime: 0, - stime: 0, - cutime: 0, - cstime: 0, - cpuu: 0, - cpus: 0 - }; + callback({}); } - } else { - return { - pid: 0, - utime: 0, - stime: 0, - cutime: 0, - cstime: 0, - cpuu: 0, - cpus: 0 - }; } -} -function calcProcStatWin(procStat, all, _cpu_old) { - // calc - let cpuu = 0; - let cpus = 0; - if (_cpu_old.all > 0 && _cpu_old.list[procStat.pid]) { - cpuu = (procStat.utime - _cpu_old.list[procStat.pid].utime) / (all - _cpu_old.all) * 100; // user - cpus = (procStat.stime - _cpu_old.list[procStat.pid].stime) / (all - _cpu_old.all) * 100; // system - } else { - cpuu = (procStat.utime) / (all) * 100; // user - cpus = (procStat.stime) / (all) * 100; // system + getProcesses(id, callback) { + id = id || ''; + if (id) { + try { + let socket = net.createConnection({ path: socketPath }); + let alldata = ''; + let data; + + socket.on('connect', () => { + socket.write('GET http:/containers/' + id + '/top?ps_args=-opid,ppid,pgid,vsz,time,etime,nice,ruser,user,rgroup,group,stat,rss,args HTTP/1.0\r\n\r\n'); + }); + + socket.on('data', data => { + alldata = alldata + data.toString(); + }); + + socket.on('error', () => { + socket = false; + callback({}); + }); + + socket.on('end', () => { + let startbody = alldata.indexOf('\r\n\r\n'); + alldata = alldata.substring(startbody + 4); + socket = false; + try { + data = JSON.parse(alldata); + callback(data); + } catch (err) { + callback({}); + } + }); + } catch (err) { + callback({}); + } + } else { + callback({}); + } } - return { - pid: procStat.pid, - utime: procStat.utime, - stime: procStat.stime, - cpuu: cpuu > 0 ? cpuu : 0, - cpus: cpus > 0 ? cpus : 0 - }; -} + listVolumes(callback) { + try { + let socket = net.createConnection({ path: socketPath }); + let alldata = ''; + let data; -// -------------------------- -// running processes + socket.on('connect', () => { + socket.write('GET http:/volumes HTTP/1.0\r\n\r\n'); + }); -function processes(callback) { + socket.on('data', data => { + alldata = alldata + data.toString(); + }); - let parsedhead = []; + socket.on('error', () => { + socket = false; + callback({}); + }); - function getName(command) { - command = command || ''; - let result = command.split(' ')[0]; - if (result.substr(-1) === ':') { - result = result.substr(0, result.length - 1); - } - if (result.substr(0, 1) !== '[') { - let parts = result.split('/'); - if (isNaN(parseInt(parts[parts.length - 1]))) { - result = parts[parts.length - 1]; - } else { - result = parts[0]; - } + socket.on('end', () => { + let startbody = alldata.indexOf('\r\n\r\n'); + alldata = alldata.substring(startbody + 4); + socket = false; + try { + data = JSON.parse(alldata); + callback(data); + } catch (err) { + callback({}); + } + }); + } catch (err) { + callback({}); } - return result; } +}; - function parseLine(line) { +var dockerSocket = DockerSocket$1; - let offset = 0; - let offset2 = 0; +// @ts-check +// ================================================================================== +// docker.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 13. Docker +// ---------------------------------------------------------------------------------- - function checkColumn(i) { - offset = offset2; - if (parsedhead[i]) { - offset2 = line.substring(parsedhead[i].to + offset, 10000).indexOf(' '); - } else { - offset2 = 10000; +const util$5 = util$j; +const DockerSocket = dockerSocket; + +let _platform$4 = process.platform; +const _windows$4 = (_platform$4 === 'win32'); + +let _docker_container_stats = {}; +let _docker_socket; +let _docker_last_read = 0; + + +// -------------------------- +// get containers (parameter all: get also inactive/exited containers) + +function dockerInfo(callback) { + return new Promise((resolve) => { + process.nextTick(() => { + if (!_docker_socket) { + _docker_socket = new DockerSocket(); } - } + const result = {}; - checkColumn(0); - const pid = parseInt(line.substring(parsedhead[0].from + offset, parsedhead[0].to + offset2)); - checkColumn(1); - const ppid = parseInt(line.substring(parsedhead[1].from + offset, parsedhead[1].to + offset2)); - checkColumn(2); - const cpu = parseFloat(line.substring(parsedhead[2].from + offset, parsedhead[2].to + offset2).replace(/,/g, '.')); - checkColumn(3); - const mem = parseFloat(line.substring(parsedhead[3].from + offset, parsedhead[3].to + offset2).replace(/,/g, '.')); - checkColumn(4); - const priority = parseInt(line.substring(parsedhead[4].from + offset, parsedhead[4].to + offset2)); - checkColumn(5); - const vsz = parseInt(line.substring(parsedhead[5].from + offset, parsedhead[5].to + offset2)); - checkColumn(6); - const rss = parseInt(line.substring(parsedhead[6].from + offset, parsedhead[6].to + offset2)); - checkColumn(7); - const nice = parseInt(line.substring(parsedhead[7].from + offset, parsedhead[7].to + offset2)) || 0; - checkColumn(8); - const started = !_sunos$6 ? parseElapsedTime(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()) : parseTimeUnix(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()); - checkColumn(9); - let state = line.substring(parsedhead[9].from + offset, parsedhead[9].to + offset2).trim(); - state = (state[0] === 'R' ? 'running' : (state[0] === 'S' ? 'sleeping' : (state[0] === 'T' ? 'stopped' : (state[0] === 'W' ? 'paging' : (state[0] === 'X' ? 'dead' : (state[0] === 'Z' ? 'zombie' : ((state[0] === 'D' || state[0] === 'U') ? 'blocked' : 'unknown'))))))); - checkColumn(10); - let tty = line.substring(parsedhead[10].from + offset, parsedhead[10].to + offset2).trim(); - if (tty === '?' || tty === '??') { tty = ''; } - checkColumn(11); - const user = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim(); - checkColumn(12); - let cmdPath = ''; - let command = ''; - let params = ''; - let fullcommand = line.substring(parsedhead[12].from + offset, parsedhead[12].to + offset2).trim(); - if (fullcommand.substr(fullcommand.length - 1) === ']') { fullcommand = fullcommand.slice(0, -1); } - if (fullcommand.substr(0, 1) === '[') { command = fullcommand.substring(1); } - else { - const p1 = fullcommand.indexOf('('); - const p2 = fullcommand.indexOf(')'); - const p3 = fullcommand.indexOf('/'); - const p4 = fullcommand.indexOf(':'); - if (p1 < p2 && p1 < p3 && p3 < p2) { - command = fullcommand.split(' ')[0]; - command = command.replace(/:/g, ''); - } else { - if (p4 > 0 && (p3 === -1 || p3 > 3)) { - command = fullcommand.split(' ')[0]; - command = command.replace(/:/g, ''); - } else { - // try to figure out where parameter starts - let firstParamPos = fullcommand.indexOf(' -'); - let firstParamPathPos = fullcommand.indexOf(' /'); - firstParamPos = (firstParamPos >= 0 ? firstParamPos : 10000); - firstParamPathPos = (firstParamPathPos >= 0 ? firstParamPathPos : 10000); - const firstPos = Math.min(firstParamPos, firstParamPathPos); - let tmpCommand = fullcommand.substr(0, firstPos); - const tmpParams = fullcommand.substr(firstPos); - const lastSlashPos = tmpCommand.lastIndexOf('/'); - if (lastSlashPos >= 0) { - cmdPath = tmpCommand.substr(0, lastSlashPos); - tmpCommand = tmpCommand.substr(lastSlashPos + 1); - } + _docker_socket.getInfo((data) => { + result.id = data.ID; + result.containers = data.Containers; + result.containersRunning = data.ContainersRunning; + result.containersPaused = data.ContainersPaused; + result.containersStopped = data.ContainersStopped; + result.images = data.Images; + result.driver = data.Driver; + result.memoryLimit = data.MemoryLimit; + result.swapLimit = data.SwapLimit; + result.kernelMemory = data.KernelMemory; + result.cpuCfsPeriod = data.CpuCfsPeriod; + result.cpuCfsQuota = data.CpuCfsQuota; + result.cpuShares = data.CPUShares; + result.cpuSet = data.CPUSet; + result.ipv4Forwarding = data.IPv4Forwarding; + result.bridgeNfIptables = data.BridgeNfIptables; + result.bridgeNfIp6tables = data.BridgeNfIp6tables; + result.debug = data.Debug; + result.nfd = data.NFd; + result.oomKillDisable = data.OomKillDisable; + result.ngoroutines = data.NGoroutines; + result.systemTime = data.SystemTime; + result.loggingDriver = data.LoggingDriver; + result.cgroupDriver = data.CgroupDriver; + result.nEventsListener = data.NEventsListener; + result.kernelVersion = data.KernelVersion; + result.operatingSystem = data.OperatingSystem; + result.osType = data.OSType; + result.architecture = data.Architecture; + result.ncpu = data.NCPU; + result.memTotal = data.MemTotal; + result.dockerRootDir = data.DockerRootDir; + result.httpProxy = data.HttpProxy; + result.httpsProxy = data.HttpsProxy; + result.noProxy = data.NoProxy; + result.name = data.Name; + result.labels = data.Labels; + result.experimentalBuild = data.ExperimentalBuild; + result.serverVersion = data.ServerVersion; + result.clusterStore = data.ClusterStore; + result.clusterAdvertise = data.ClusterAdvertise; + result.defaultRuntime = data.DefaultRuntime; + result.liveRestoreEnabled = data.LiveRestoreEnabled; + result.isolation = data.Isolation; + result.initBinary = data.InitBinary; + result.productLicense = data.ProductLicense; + if (callback) { callback(result); } + resolve(result); + }); + }); + }); +} - if (firstPos === 10000 && tmpCommand.indexOf(' ') > -1) { - const parts = tmpCommand.split(' '); - if (fs$1.existsSync(path$1.join(cmdPath, parts[0]))) { - command = parts.shift(); - params = (parts.join(' ') + ' ' + tmpParams).trim(); +docker.dockerInfo = dockerInfo; + +function dockerImages(all, callback) { + + // fallback - if only callback is given + if (util$5.isFunction(all) && !callback) { + callback = all; + all = false; + } + if (typeof all === 'string' && all === 'true') { + all = true; + } + if (typeof all !== 'boolean' && all !== undefined) { + all = false; + } + + all = all || false; + let result = []; + return new Promise((resolve) => { + process.nextTick(() => { + if (!_docker_socket) { + _docker_socket = new DockerSocket(); + } + const workload = []; + + _docker_socket.listImages(all, data => { + let dockerImages = {}; + try { + dockerImages = data; + if (dockerImages && Object.prototype.toString.call(dockerImages) === '[object Array]' && dockerImages.length > 0) { + + dockerImages.forEach(function (element) { + + if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) { + element.Name = element.Names[0].replace(/^\/|\/$/g, ''); + } + workload.push(dockerImagesInspect(element.Id.trim(), element)); + }); + if (workload.length) { + Promise.all( + workload + ).then((data) => { + if (callback) { callback(data); } + resolve(data); + }); } else { - command = tmpCommand.trim(); - params = tmpParams.trim(); + if (callback) { callback(result); } + resolve(result); } } else { - command = tmpCommand.trim(); - params = tmpParams.trim(); + if (callback) { callback(result); } + resolve(result); + } + } catch (err) { + if (callback) { callback(result); } + resolve(result); + } + }); + }); + }); +} + +// -------------------------- +// container inspect (for one container) + +function dockerImagesInspect(imageID, payload) { + return new Promise((resolve) => { + process.nextTick(() => { + imageID = imageID || ''; + if (typeof imageID !== 'string') { + return resolve(); + } + const imageIDSanitized = (util$5.isPrototypePolluted() ? '' : util$5.sanitizeShellString(imageID, true)).trim(); + if (imageIDSanitized) { + + if (!_docker_socket) { + _docker_socket = new DockerSocket(); + } + + _docker_socket.inspectImage(imageIDSanitized.trim(), data => { + try { + resolve({ + id: payload.Id, + container: data.Container, + comment: data.Comment, + os: data.Os, + architecture: data.Architecture, + parent: data.Parent, + dockerVersion: data.DockerVersion, + size: data.Size, + sharedSize: payload.SharedSize, + virtualSize: data.VirtualSize, + author: data.Author, + created: data.Created ? Math.round(new Date(data.Created).getTime() / 1000) : 0, + containerConfig: data.ContainerConfig ? data.ContainerConfig : {}, + graphDriver: data.GraphDriver ? data.GraphDriver : {}, + repoDigests: data.RepoDigests ? data.RepoDigests : {}, + repoTags: data.RepoTags ? data.RepoTags : {}, + config: data.Config ? data.Config : {}, + rootFS: data.RootFS ? data.RootFS : {}, + }); + } catch (err) { + resolve(); } - } + }); + } else { + resolve(); } + }); + }); +} - } +docker.dockerImages = dockerImages; - return ({ - pid: pid, - parentPid: ppid, - name: _linux$6 ? getName(command) : command, - cpu: cpu, - cpuu: 0, - cpus: 0, - mem: mem, - priority: priority, - memVsz: vsz, - memRss: rss, - nice: nice, - started: started, - state: state, - tty: tty, - user: user, - command: command, - params: params, - path: cmdPath +function dockerContainers(all, callback) { + + function inContainers(containers, id) { + let filtered = containers.filter(obj => { + /** + * @namespace + * @property {string} Id + */ + return (obj.Id && (obj.Id === id)); }); + return (filtered.length > 0); } - function parseProcesses(lines) { - let result = []; - if (lines.length > 1) { - let head = lines[0]; - parsedhead = util$8.parseHead(head, 8); - lines.shift(); - lines.forEach(function (line) { - if (line.trim() !== '') { - result.push(parseLine(line)); - } - }); - } - return result; + // fallback - if only callback is given + if (util$5.isFunction(all) && !callback) { + callback = all; + all = false; + } + if (typeof all === 'string' && all === 'true') { + all = true; + } + if (typeof all !== 'boolean' && all !== undefined) { + all = false; } - function parseProcesses2(lines) { - function formatDateTime(time) { - const month = ('0' + (time.getMonth() + 1).toString()).slice(-2); - const year = time.getFullYear().toString(); - const day = ('0' + time.getDate().toString()).slice(-2); - const hours = ('0' + time.getHours().toString()).slice(-2); - const mins = ('0' + time.getMinutes().toString()).slice(-2); - const secs = ('0' + time.getSeconds().toString()).slice(-2); + all = all || false; + let result = []; + return new Promise((resolve) => { + process.nextTick(() => { + if (!_docker_socket) { + _docker_socket = new DockerSocket(); + } + const workload = []; - return (year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + secs); - } + _docker_socket.listContainers(all, data => { + let docker_containers = {}; + try { + docker_containers = data; + if (docker_containers && Object.prototype.toString.call(docker_containers) === '[object Array]' && docker_containers.length > 0) { + // GC in _docker_container_stats + for (let key in _docker_container_stats) { + if ({}.hasOwnProperty.call(_docker_container_stats, key)) { + if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; } + } + } - function parseElapsed(etime) { - let started = ''; - if (etime.indexOf('d') >= 0) { - const elapsed_parts = etime.split('d'); - started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 24 + elapsed_parts[1] * 1) * 60 * 60 * 1000)); - } else if (etime.indexOf('h') >= 0) { - const elapsed_parts = etime.split('h'); - started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 60 + elapsed_parts[1] * 1) * 60 * 1000)); - } else if (etime.indexOf(':') >= 0) { - const elapsed_parts = etime.split(':'); - started = formatDateTime(new Date(Date.now() - (elapsed_parts.length > 1 ? (elapsed_parts[0] * 60 + elapsed_parts[1]) * 1000 : elapsed_parts[0] * 1000))); + docker_containers.forEach(function (element) { + + if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) { + element.Name = element.Names[0].replace(/^\/|\/$/g, ''); + } + workload.push(dockerContainerInspect(element.Id.trim(), element)); + }); + if (workload.length) { + Promise.all( + workload + ).then((data) => { + if (callback) { callback(data); } + resolve(data); + }); + } else { + if (callback) { callback(result); } + resolve(result); + } + } else { + if (callback) { callback(result); } + resolve(result); + } + } catch (err) { + // GC in _docker_container_stats + for (let key in _docker_container_stats) { + if ({}.hasOwnProperty.call(_docker_container_stats, key)) { + if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; } + } + } + if (callback) { callback(result); } + resolve(result); + } + }); + }); + }); +} + +// -------------------------- +// container inspect (for one container) + +function dockerContainerInspect(containerID, payload) { + return new Promise((resolve) => { + process.nextTick(() => { + containerID = containerID || ''; + if (typeof containerID !== 'string') { + return resolve(); } - return started; - } + const containerIdSanitized = (util$5.isPrototypePolluted() ? '' : util$5.sanitizeShellString(containerID, true)).trim(); + if (containerIdSanitized) { - let result = []; - lines.forEach(function (line) { - if (line.trim() !== '') { - line = line.trim().replace(/ +/g, ' ').replace(/,+/g, '.'); - const parts = line.split(' '); - const command = parts.slice(9).join(' '); - const pmem = parseFloat((1.0 * parseInt(parts[3]) * 1024 / os$1.totalmem()).toFixed(1)); - const started = parseElapsed(parts[5]); + if (!_docker_socket) { + _docker_socket = new DockerSocket(); + } - result.push({ - pid: parseInt(parts[0]), - parentPid: parseInt(parts[1]), - name: getName(command), - cpu: 0, - cpuu: 0, - cpus: 0, - mem: pmem, - priority: 0, - memVsz: parseInt(parts[2]), - memRss: parseInt(parts[3]), - nice: parseInt(parts[4]), - started: started, - state: (parts[6] === 'R' ? 'running' : (parts[6] === 'S' ? 'sleeping' : (parts[6] === 'T' ? 'stopped' : (parts[6] === 'W' ? 'paging' : (parts[6] === 'X' ? 'dead' : (parts[6] === 'Z' ? 'zombie' : ((parts[6] === 'D' || parts[6] === 'U') ? 'blocked' : 'unknown'))))))), - tty: parts[7], - user: parts[8], - command: command + _docker_socket.getInspect(containerIdSanitized.trim(), data => { + try { + resolve({ + id: payload.Id, + name: payload.Name, + image: payload.Image, + imageID: payload.ImageID, + command: payload.Command, + created: payload.Created, + started: data.State && data.State.StartedAt ? Math.round(new Date(data.State.StartedAt).getTime() / 1000) : 0, + finished: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? Math.round(new Date(data.State.FinishedAt).getTime() / 1000) : 0, + createdAt: data.Created ? data.Created : '', + startedAt: data.State && data.State.StartedAt ? data.State.StartedAt : '', + finishedAt: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? data.State.FinishedAt : '', + state: payload.State, + restartCount: data.RestartCount || 0, + platform: data.Platform || '', + driver: data.Driver || '', + ports: payload.Ports, + mounts: payload.Mounts, + // hostconfig: payload.HostConfig, + // network: payload.NetworkSettings + }); + } catch (err) { + resolve(); + } }); + } else { + resolve(); } }); - return result; - } + }); +} - return new Promise((resolve) => { - process.nextTick(() => { - let result = { - all: 0, - running: 0, - blocked: 0, - sleeping: 0, - unknown: 0, - list: [] - }; +docker.dockerContainers = dockerContainers; - let cmd = ''; +// -------------------------- +// helper functions for calculation of docker stats - if ((_processes_cpu.ms && Date.now() - _processes_cpu.ms >= 500) || _processes_cpu.ms === 0) { - if (_linux$6 || _freebsd$6 || _openbsd$6 || _netbsd$6 || _darwin$6 || _sunos$6) { - if (_linux$6) { cmd = 'export LC_ALL=C; ps -axo pid:11,ppid:11,pcpu:6,pmem:6,pri:5,vsz:11,rss:11,ni:5,etime:30,state:5,tty:15,user:20,command; unset LC_ALL'; } - if (_freebsd$6 || _openbsd$6 || _netbsd$6) { cmd = 'export LC_ALL=C; ps -axo pid,ppid,pcpu,pmem,pri,vsz,rss,ni,etime,state,tty,user,command; unset LC_ALL'; } - if (_darwin$6) { cmd = 'ps -axo pid,ppid,pcpu,pmem,pri,vsz=temp_title_1,rss=temp_title_2,nice,etime=temp_title_3,state,tty,user,command -r'; } - if (_sunos$6) { cmd = 'ps -Ao pid,ppid,pcpu,pmem,pri,vsz,rss,nice,stime,s,tty,user,comm'; } - exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - if (!error && stdout.toString().trim()) { - result.list = (parseProcesses(stdout.toString().split('\n'))).slice(); - result.all = result.list.length; - result.running = result.list.filter(function (e) { - return e.state === 'running'; - }).length; - result.blocked = result.list.filter(function (e) { - return e.state === 'blocked'; - }).length; - result.sleeping = result.list.filter(function (e) { - return e.state === 'sleeping'; - }).length; +function docker_calcCPUPercent(cpu_stats, precpu_stats) { + /** + * @namespace + * @property {object} cpu_usage + * @property {number} cpu_usage.total_usage + * @property {number} system_cpu_usage + * @property {object} cpu_usage + * @property {Array} cpu_usage.percpu_usage + */ - if (_linux$6) { - // calc process_cpu - ps is not accurate in linux! - cmd = 'cat /proc/stat | grep "cpu "'; - result.list.forEach((element) => { - cmd += (';cat /proc/' + element.pid + '/stat'); - }); - exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - let curr_processes = stdout.toString().split('\n'); + if (!_windows$4) { + let cpuPercent = 0.0; + // calculate the change for the cpu usage of the container in between readings + let cpuDelta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage; + // calculate the change for the entire system between readings + let systemDelta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage; - // first line (all - /proc/stat) - let all = parseProcStat(curr_processes.shift()); + if (systemDelta > 0.0 && cpuDelta > 0.0) { + // calculate the change for the cpu usage of the container in between readings + if (precpu_stats.online_cpus) { + cpuPercent = (cpuDelta / systemDelta) * precpu_stats.online_cpus * 100.0; + } + else { + cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0; + } + } - // process - let list_new = {}; - let resultProcess = {}; - curr_processes.forEach((element) => { - resultProcess = calcProcStatLinux(element, all, _processes_cpu); + return cpuPercent; + } else { + let nanoSecNow = util$5.nanoSeconds(); + let cpuPercent = 0.0; + if (_docker_last_read > 0) { + let possIntervals = (nanoSecNow - _docker_last_read); // / 100 * os.cpus().length; + let intervalsUsed = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage; + if (possIntervals > 0) { + cpuPercent = 100.0 * intervalsUsed / possIntervals; + } + } + _docker_last_read = nanoSecNow; + return cpuPercent; + } +} - if (resultProcess.pid) { +function docker_calcNetworkIO(networks) { + let rx; + let wx; + for (let key in networks) { + // skip loop if the property is from prototype + if (!{}.hasOwnProperty.call(networks, key)) { continue; } - // store pcpu in outer array - let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid); - if (listPos >= 0) { - result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus; - result.list[listPos].cpuu = resultProcess.cpuu; - result.list[listPos].cpus = resultProcess.cpus; - } + /** + * @namespace + * @property {number} rx_bytes + * @property {number} tx_bytes + */ + let obj = networks[key]; + rx = +obj.rx_bytes; + wx = +obj.tx_bytes; + } + return { + rx, + wx + }; +} - // save new values - list_new[resultProcess.pid] = { - cpuu: resultProcess.cpuu, - cpus: resultProcess.cpus, - utime: resultProcess.utime, - stime: resultProcess.stime, - cutime: resultProcess.cutime, - cstime: resultProcess.cstime - }; - } - }); +function docker_calcBlockIO(blkio_stats) { + let result = { + r: 0, + w: 0 + }; - // store old values - _processes_cpu.all = all; - _processes_cpu.list = Object.assign({}, list_new); - _processes_cpu.ms = Date.now() - _processes_cpu.ms; - _processes_cpu.result = Object.assign({}, result); - if (callback) { callback(result); } - resolve(result); - }); - } else { - if (callback) { callback(result); } - resolve(result); - } - } else { - cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,stat,tty,user,comm'; - if (_sunos$6) { - cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,s,tty,user,comm'; - } - exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - lines.shift(); + /** + * @namespace + * @property {Array} io_service_bytes_recursive + */ + if (blkio_stats && blkio_stats.io_service_bytes_recursive && Object.prototype.toString.call(blkio_stats.io_service_bytes_recursive) === '[object Array]' && blkio_stats.io_service_bytes_recursive.length > 0) { + blkio_stats.io_service_bytes_recursive.forEach(function (element) { + /** + * @namespace + * @property {string} op + * @property {number} value + */ - result.list = parseProcesses2(lines).slice(); - result.all = result.list.length; - result.running = result.list.filter(function (e) { - return e.state === 'running'; - }).length; - result.blocked = result.list.filter(function (e) { - return e.state === 'blocked'; - }).length; - result.sleeping = result.list.filter(function (e) { - return e.state === 'sleeping'; - }).length; - if (callback) { callback(result); } - resolve(result); - } else { - if (callback) { callback(result); } - resolve(result); - } - }); - } - }); - } else if (_windows$7) { - try { - util$8.powerShell('Get-CimInstance Win32_Process | select-Object ProcessId,ParentProcessId,ExecutionState,Caption,CommandLine,ExecutablePath,UserModeTime,KernelModeTime,WorkingSetSize,Priority,PageFileUsage, @{n="CreationDate";e={$_.CreationDate.ToString("yyyy-MM-dd HH:mm:ss")}} | fl').then((stdout, error) => { - if (!error) { - let processSections = stdout.split(/\n\s*\n/); - let procs = []; - let procStats = []; - let list_new = {}; - let allcpuu = 0; - let allcpus = 0; - processSections.forEach((element) => { - if (element.trim() !== '') { - let lines = element.trim().split('\r\n'); - let pid = parseInt(util$8.getValue(lines, 'ProcessId', ':', true), 10); - let parentPid = parseInt(util$8.getValue(lines, 'ParentProcessId', ':', true), 10); - let statusValue = util$8.getValue(lines, 'ExecutionState', ':'); - let name = util$8.getValue(lines, 'Caption', ':', true); - let commandLine = util$8.getValue(lines, 'CommandLine', ':', true); - // get additional command line data - let additionalCommand = false; - lines.forEach((line) => { - if (additionalCommand && line.toLowerCase().startsWith(' ')) { - commandLine += ' ' + line.trim(); - } else { - additionalCommand = false; - } - if (line.toLowerCase().startsWith('commandline')) { - additionalCommand = true; - } - }); - let commandPath = util$8.getValue(lines, 'ExecutablePath', ':', true); - let utime = parseInt(util$8.getValue(lines, 'UserModeTime', ':', true), 10); - let stime = parseInt(util$8.getValue(lines, 'KernelModeTime', ':', true), 10); - let memw = parseInt(util$8.getValue(lines, 'WorkingSetSize', ':', true), 10); - allcpuu = allcpuu + utime; - allcpus = allcpus + stime; - result.all++; - if (!statusValue) { result.unknown++; } - if (statusValue === '3') { result.running++; } - if (statusValue === '4' || statusValue === '5') { result.blocked++; } + if (element.op && element.op.toLowerCase() === 'read' && element.value) { + result.r += element.value; + } + if (element.op && element.op.toLowerCase() === 'write' && element.value) { + result.w += element.value; + } + }); + } + return result; +} - procStats.push({ - pid: pid, - utime: utime, - stime: stime, - cpu: 0, - cpuu: 0, - cpus: 0, - }); - procs.push({ - pid: pid, - parentPid: parentPid, - name: name, - cpu: 0, - cpuu: 0, - cpus: 0, - mem: memw / os$1.totalmem() * 100, - priority: parseInt(util$8.getValue(lines, 'Priority', ':', true), 10), - memVsz: parseInt(util$8.getValue(lines, 'PageFileUsage', ':', true), 10), - memRss: Math.floor(parseInt(util$8.getValue(lines, 'WorkingSetSize', ':', true), 10) / 1024), - nice: 0, - started: util$8.getValue(lines, 'CreationDate', ':', true), - state: (!statusValue ? _winStatusValues[0] : _winStatusValues[statusValue]), - tty: '', - user: '', - command: commandLine || name, - path: commandPath, - params: '' - }); - } - }); +function dockerContainerStats(containerIDs, callback) { - result.sleeping = result.all - result.running - result.blocked - result.unknown; - result.list = procs; - procStats.forEach((element) => { - let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _processes_cpu); + let containerArray = []; + return new Promise((resolve) => { + process.nextTick(() => { + + // fallback - if only callback is given + if (util$5.isFunction(containerIDs) && !callback) { + callback = containerIDs; + containerArray = ['*']; + } else { + containerIDs = containerIDs || '*'; + if (typeof containerIDs !== 'string') { + if (callback) { callback([]); } + return resolve([]); + } + let containerIDsSanitized = ''; + containerIDsSanitized.__proto__.toLowerCase = util$5.stringToLower; + containerIDsSanitized.__proto__.replace = util$5.stringReplace; + containerIDsSanitized.__proto__.trim = util$5.stringTrim; + + containerIDsSanitized = containerIDs; + containerIDsSanitized = containerIDsSanitized.trim(); + if (containerIDsSanitized !== '*') { + containerIDsSanitized = ''; + const s = (util$5.isPrototypePolluted() ? '' : util$5.sanitizeShellString(containerIDs, true)).trim(); + const l = util$5.mathMin(s.length, 2000); + for (let i = 0; i <= l; i++) { + if (s[i] !== undefined) { + s[i].__proto__.toLowerCase = util$5.stringToLower; + const sl = s[i].toLowerCase(); + if (sl && sl[0] && !sl[1]) { + containerIDsSanitized = containerIDsSanitized + sl[0]; + } + } + } + } - // store pcpu in outer array - let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid); - if (listPos >= 0) { - result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus; - result.list[listPos].cpuu = resultProcess.cpuu; - result.list[listPos].cpus = resultProcess.cpus; - } + containerIDsSanitized = containerIDsSanitized.trim().toLowerCase().replace(/,+/g, '|'); + containerArray = containerIDsSanitized.split('|'); + } - // save new values - list_new[resultProcess.pid] = { - cpuu: resultProcess.cpuu, - cpus: resultProcess.cpus, - utime: resultProcess.utime, - stime: resultProcess.stime - }; - }); + const result = []; - // store old values - _processes_cpu.all = allcpuu + allcpus; - _processes_cpu.all_utime = allcpuu; - _processes_cpu.all_stime = allcpus; - _processes_cpu.list = Object.assign({}, list_new); - _processes_cpu.ms = Date.now() - _processes_cpu.ms; - _processes_cpu.result = Object.assign({}, result); - } - if (callback) { - callback(result); - } + const workload = []; + if (containerArray.length && containerArray[0].trim() === '*') { + containerArray = []; + dockerContainers().then(allContainers => { + for (let container of allContainers) { + containerArray.push(container.id.substring(0, 12)); + } + if (containerArray.length) { + dockerContainerStats(containerArray.join(',')).then(result => { + if (callback) { callback(result); } resolve(result); }); - } catch (e) { + } else { if (callback) { callback(result); } resolve(result); } + }); + } else { + for (let containerID of containerArray) { + workload.push(dockerContainerStatsSingle(containerID.trim())); + } + if (workload.length) { + Promise.all( + workload + ).then((data) => { + if (callback) { callback(data); } + resolve(data); + }); } else { if (callback) { callback(result); } resolve(result); } + } + }); + }); +} + +// -------------------------- +// container stats (for one container) + +function dockerContainerStatsSingle(containerID) { + containerID = containerID || ''; + let result = { + id: containerID, + memUsage: 0, + memLimit: 0, + memPercent: 0, + cpuPercent: 0, + pids: 0, + netIO: { + rx: 0, + wx: 0 + }, + blockIO: { + r: 0, + w: 0 + }, + restartCount: 0, + cpuStats: {}, + precpuStats: {}, + memoryStats: {}, + networks: {}, + }; + return new Promise((resolve) => { + process.nextTick(() => { + if (containerID) { + + if (!_docker_socket) { + _docker_socket = new DockerSocket(); + } + + _docker_socket.getInspect(containerID, dataInspect => { + try { + _docker_socket.getStats(containerID, data => { + try { + let stats = data; + if (!stats.message) { + if (data.id) { result.id = data.id; } + result.memUsage = (stats.memory_stats && stats.memory_stats.usage ? stats.memory_stats.usage : 0); + result.memLimit = (stats.memory_stats && stats.memory_stats.limit ? stats.memory_stats.limit : 0); + result.memPercent = (stats.memory_stats && stats.memory_stats.usage && stats.memory_stats.limit ? stats.memory_stats.usage / stats.memory_stats.limit * 100.0 : 0); + result.cpuPercent = (stats.cpu_stats && stats.precpu_stats ? docker_calcCPUPercent(stats.cpu_stats, stats.precpu_stats) : 0); + result.pids = (stats.pids_stats && stats.pids_stats.current ? stats.pids_stats.current : 0); + result.restartCount = (dataInspect.RestartCount ? dataInspect.RestartCount : 0); + if (stats.networks) { result.netIO = docker_calcNetworkIO(stats.networks); } + if (stats.blkio_stats) { result.blockIO = docker_calcBlockIO(stats.blkio_stats); } + result.cpuStats = (stats.cpu_stats ? stats.cpu_stats : {}); + result.precpuStats = (stats.precpu_stats ? stats.precpu_stats : {}); + result.memoryStats = (stats.memory_stats ? stats.memory_stats : {}); + result.networks = (stats.networks ? stats.networks : {}); + } + } catch (err) { + util$5.noop(); + } + // } + resolve(result); + }); + } catch (err) { + util$5.noop(); + } + }); } else { - if (callback) { callback(_processes_cpu.result); } - resolve(_processes_cpu.result); + resolve(result); } }); }); } -processes$1.processes = processes; +docker.dockerContainerStats = dockerContainerStats; // -------------------------- -// PS - process load -// get detailed information about a certain process -// (PID, CPU-Usage %, Mem-Usage %) +// container processes (for one container) -function processLoad(proc, callback) { +function dockerContainerProcesses(containerID, callback) { + let result = []; + return new Promise((resolve) => { + process.nextTick(() => { + containerID = containerID || ''; + if (typeof containerID !== 'string') { + return resolve(result); + } + const containerIdSanitized = (util$5.isPrototypePolluted() ? '' : util$5.sanitizeShellString(containerID, true)).trim(); - // fallback - if only callback is given - if (util$8.isFunction(proc) && !callback) { - callback = proc; - proc = ''; - } + if (containerIdSanitized) { + + if (!_docker_socket) { + _docker_socket = new DockerSocket(); + } + + _docker_socket.getProcesses(containerIdSanitized, data => { + /** + * @namespace + * @property {Array} Titles + * @property {Array} Processes + **/ + try { + if (data && data.Titles && data.Processes) { + let titles = data.Titles.map(function (value) { + return value.toUpperCase(); + }); + let pos_pid = titles.indexOf('PID'); + let pos_ppid = titles.indexOf('PPID'); + let pos_pgid = titles.indexOf('PGID'); + let pos_vsz = titles.indexOf('VSZ'); + let pos_time = titles.indexOf('TIME'); + let pos_elapsed = titles.indexOf('ELAPSED'); + let pos_ni = titles.indexOf('NI'); + let pos_ruser = titles.indexOf('RUSER'); + let pos_user = titles.indexOf('USER'); + let pos_rgroup = titles.indexOf('RGROUP'); + let pos_group = titles.indexOf('GROUP'); + let pos_stat = titles.indexOf('STAT'); + let pos_rss = titles.indexOf('RSS'); + let pos_command = titles.indexOf('COMMAND'); + data.Processes.forEach(process => { + result.push({ + pidHost: (pos_pid >= 0 ? process[pos_pid] : ''), + ppid: (pos_ppid >= 0 ? process[pos_ppid] : ''), + pgid: (pos_pgid >= 0 ? process[pos_pgid] : ''), + user: (pos_user >= 0 ? process[pos_user] : ''), + ruser: (pos_ruser >= 0 ? process[pos_ruser] : ''), + group: (pos_group >= 0 ? process[pos_group] : ''), + rgroup: (pos_rgroup >= 0 ? process[pos_rgroup] : ''), + stat: (pos_stat >= 0 ? process[pos_stat] : ''), + time: (pos_time >= 0 ? process[pos_time] : ''), + elapsed: (pos_elapsed >= 0 ? process[pos_elapsed] : ''), + nice: (pos_ni >= 0 ? process[pos_ni] : ''), + rss: (pos_rss >= 0 ? process[pos_rss] : ''), + vsz: (pos_vsz >= 0 ? process[pos_vsz] : ''), + command: (pos_command >= 0 ? process[pos_command] : '') + }); + }); + } + } catch (err) { + util$5.noop(); + } + if (callback) { callback(result); } + resolve(result); + }); + } else { + if (callback) { callback(result); } + resolve(result); + } + }); + }); +} + +docker.dockerContainerProcesses = dockerContainerProcesses; + +function dockerVolumes(callback) { + + let result = []; return new Promise((resolve) => { process.nextTick(() => { + if (!_docker_socket) { + _docker_socket = new DockerSocket(); + } + _docker_socket.listVolumes((data) => { + let dockerVolumes = {}; + try { + dockerVolumes = data; + if (dockerVolumes && dockerVolumes.Volumes && Object.prototype.toString.call(dockerVolumes.Volumes) === '[object Array]' && dockerVolumes.Volumes.length > 0) { - proc = proc || ''; + dockerVolumes.Volumes.forEach(function (element) { - if (typeof proc !== 'string') { - if (callback) { callback([]); } - return resolve([]); - } + result.push({ + name: element.Name, + driver: element.Driver, + labels: element.Labels, + mountpoint: element.Mountpoint, + options: element.Options, + scope: element.Scope, + created: element.CreatedAt ? Math.round(new Date(element.CreatedAt).getTime() / 1000) : 0, + }); + }); + if (callback) { callback(result); } + resolve(result); + } else { + if (callback) { callback(result); } + resolve(result); + } + } catch (err) { + if (callback) { callback(result); } + resolve(result); + } + }); + }); + }); +} - let processesString = ''; - processesString.__proto__.toLowerCase = util$8.stringToLower; - processesString.__proto__.replace = util$8.stringReplace; - processesString.__proto__.trim = util$8.stringTrim; +docker.dockerVolumes = dockerVolumes; - const s = util$8.sanitizeShellString(proc); - const l = util$8.mathMin(s.length, 2000); +function dockerAll(callback) { + return new Promise((resolve) => { + process.nextTick(() => { + dockerContainers(true).then(result => { + if (result && Object.prototype.toString.call(result) === '[object Array]' && result.length > 0) { + let l = result.length; + result.forEach(function (element) { + dockerContainerStats(element.id).then((res) => { + // include stats in array + element.memUsage = res[0].memUsage; + element.memLimit = res[0].memLimit; + element.memPercent = res[0].memPercent; + element.cpuPercent = res[0].cpuPercent; + element.pids = res[0].pids; + element.netIO = res[0].netIO; + element.blockIO = res[0].blockIO; + element.cpuStats = res[0].cpuStats; + element.precpuStats = res[0].precpuStats; + element.memoryStats = res[0].memoryStats; + element.networks = res[0].networks; - for (let i = 0; i <= l; i++) { - if (s[i] !== undefined) { - processesString = processesString + s[i]; + dockerContainerProcesses(element.id).then(processes => { + element.processes = processes; + + l -= 1; + if (l === 0) { + if (callback) { callback(result); } + resolve(result); + } + }); + // all done?? + }); + }); + } else { + if (callback) { callback(result); } + resolve(result); } - } + }); + }); + }); +} - processesString = processesString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|'); - if (processesString === '') { - processesString = '*'; - } - if (util$8.isPrototypePolluted() && processesString !== '*') { - processesString = '------'; - } - let processes = processesString.split('|'); - let result = []; +docker.dockerAll = dockerAll; - const procSanitized = util$8.isPrototypePolluted() ? '' : util$8.sanitizeShellString(proc); +var virtualbox = {}; - // from here new - // let result = { - // 'proc': procSanitized, - // 'pid': null, - // 'cpu': 0, - // 'mem': 0 - // }; - if (procSanitized && processes.length && processes[0] !== '------') { - if (_windows$7) { - try { - util$8.powerShell('Get-CimInstance Win32_Process | select ProcessId,Caption,UserModeTime,KernelModeTime,WorkingSetSize | fl').then((stdout, error) => { - if (!error) { - let processSections = stdout.split(/\n\s*\n/); - let procStats = []; - let list_new = {}; - let allcpuu = 0; - let allcpus = 0; +// @ts-check +// ================================================================================== +// virtualbox.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 14. Docker +// ---------------------------------------------------------------------------------- - // go through all processes - processSections.forEach((element) => { - if (element.trim() !== '') { - let lines = element.trim().split('\r\n'); - let pid = parseInt(util$8.getValue(lines, 'ProcessId', ':', true), 10); - let name = util$8.getValue(lines, 'Caption', ':', true); - let utime = parseInt(util$8.getValue(lines, 'UserModeTime', ':', true), 10); - let stime = parseInt(util$8.getValue(lines, 'KernelModeTime', ':', true), 10); - let mem = parseInt(util$8.getValue(lines, 'WorkingSetSize', ':', true), 10); - allcpuu = allcpuu + utime; - allcpus = allcpus + stime; +const os = require$$0$7; +const exec$4 = require$$1$2.exec; +const util$4 = util$j; - procStats.push({ - pid: pid, - name, - utime: utime, - stime: stime, - cpu: 0, - cpuu: 0, - cpus: 0, - mem - }); - let pname = ''; - let inList = false; - processes.forEach(function (proc) { - if (name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) { - inList = true; - pname = proc; - } - }); +function vboxInfo(callback) { - if (processesString === '*' || inList) { - let processFound = false; - result.forEach(function (item) { - if (item.proc.toLowerCase() === pname.toLowerCase()) { - item.pids.push(pid); - item.mem += mem / os$1.totalmem() * 100; - processFound = true; - } - }); - if (!processFound) { - result.push({ - proc: pname, - pid: pid, - pids: [pid], - cpu: 0, - mem: mem / os$1.totalmem() * 100 - }); - } - } - } - }); + // fallback - if only callback is given + let result = []; + return new Promise((resolve) => { + process.nextTick(() => { + try { + exec$4(util$4.getVboxmanage() + ' list vms --long', function (error, stdout) { + let parts = (os.EOL + stdout.toString()).split(os.EOL + 'Name:'); + parts.shift(); + parts.forEach(part => { + const lines = ('Name:' + part).split(os.EOL); + const state = util$4.getValue(lines, 'State'); + const running = state.startsWith('running'); + const runningSinceString = running ? state.replace('running (since ', '').replace(')', '').trim() : ''; + let runningSince = 0; + try { + if (running) { + const sinceDateObj = new Date(runningSinceString); + const offset = sinceDateObj.getTimezoneOffset(); + runningSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60; + } + } catch (e) { + util$4.noop(); + } + const stoppedSinceString = !running ? state.replace('powered off (since', '').replace(')', '').trim() : ''; + let stoppedSince = 0; + try { + if (!running) { + const sinceDateObj = new Date(stoppedSinceString); + const offset = sinceDateObj.getTimezoneOffset(); + stoppedSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60; + } + } catch (e) { + util$4.noop(); + } + result.push({ + id: util$4.getValue(lines, 'UUID'), + name: util$4.getValue(lines, 'Name'), + running, + started: runningSinceString, + runningSince, + stopped: stoppedSinceString, + stoppedSince, + guestOS: util$4.getValue(lines, 'Guest OS'), + hardwareUUID: util$4.getValue(lines, 'Hardware UUID'), + memory: parseInt(util$4.getValue(lines, 'Memory size', ' '), 10), + vram: parseInt(util$4.getValue(lines, 'VRAM size'), 10), + cpus: parseInt(util$4.getValue(lines, 'Number of CPUs'), 10), + cpuExepCap: util$4.getValue(lines, 'CPU exec cap'), + cpuProfile: util$4.getValue(lines, 'CPUProfile'), + chipset: util$4.getValue(lines, 'Chipset'), + firmware: util$4.getValue(lines, 'Firmware'), + pageFusion: util$4.getValue(lines, 'Page Fusion') === 'enabled', + configFile: util$4.getValue(lines, 'Config file'), + snapshotFolder: util$4.getValue(lines, 'Snapshot folder'), + logFolder: util$4.getValue(lines, 'Log folder'), + hpet: util$4.getValue(lines, 'HPET') === 'enabled', + pae: util$4.getValue(lines, 'PAE') === 'enabled', + longMode: util$4.getValue(lines, 'Long Mode') === 'enabled', + tripleFaultReset: util$4.getValue(lines, 'Triple Fault Reset') === 'enabled', + apic: util$4.getValue(lines, 'APIC') === 'enabled', + x2Apic: util$4.getValue(lines, 'X2APIC') === 'enabled', + acpi: util$4.getValue(lines, 'ACPI') === 'enabled', + ioApic: util$4.getValue(lines, 'IOAPIC') === 'enabled', + biosApicMode: util$4.getValue(lines, 'BIOS APIC mode'), + bootMenuMode: util$4.getValue(lines, 'Boot menu mode'), + bootDevice1: util$4.getValue(lines, 'Boot Device 1'), + bootDevice2: util$4.getValue(lines, 'Boot Device 2'), + bootDevice3: util$4.getValue(lines, 'Boot Device 3'), + bootDevice4: util$4.getValue(lines, 'Boot Device 4'), + timeOffset: util$4.getValue(lines, 'Time offset'), + rtc: util$4.getValue(lines, 'RTC'), + }); + }); - // add missing processes - if (processesString !== '*') { - let processesMissing = processes.filter(function (name) { - return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0; + if (callback) { callback(result); } + resolve(result); + }); + } catch (e) { + if (callback) { callback(result); } + resolve(result); + } + }); + }); +} - }); - processesMissing.forEach(function (procName) { - result.push({ - proc: procName, - pid: null, - pids: [], - cpu: 0, - mem: 0 - }); - }); - } +virtualbox.vboxInfo = vboxInfo; - // calculate proc stats for each proc - procStats.forEach((element) => { - let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _process_cpu); +var printer$1 = {}; - let listPos = -1; - for (let j = 0; j < result.length; j++) { - if (result[j].pid === resultProcess.pid || result[j].pids.indexOf(resultProcess.pid) >= 0) { listPos = j; } - } - if (listPos >= 0) { - result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus; - } +// @ts-check +// ================================================================================== +// printers.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 15. printers +// ---------------------------------------------------------------------------------- - // save new values - list_new[resultProcess.pid] = { - cpuu: resultProcess.cpuu, - cpus: resultProcess.cpus, - utime: resultProcess.utime, - stime: resultProcess.stime - }; - }); +const exec$3 = require$$1$2.exec; +const util$3 = util$j; - // store old values - _process_cpu.all = allcpuu + allcpus; - _process_cpu.all_utime = allcpuu; - _process_cpu.all_stime = allcpus; - _process_cpu.list = Object.assign({}, list_new); - _process_cpu.ms = Date.now() - _process_cpu.ms; - _process_cpu.result = JSON.parse(JSON.stringify(result)); - if (callback) { - callback(result); - } - resolve(result); - } - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } - } +let _platform$3 = process.platform; - if (_darwin$6 || _linux$6 || _freebsd$6 || _openbsd$6 || _netbsd$6) { - const params = ['-axo', 'pid,ppid,pcpu,pmem,comm']; - util$8.execSafe('ps', params).then((stdout) => { - if (stdout) { - let procStats = []; - let lines = stdout.toString().split('\n').filter(function (line) { - if (processesString === '*') { return true; } - if (line.toLowerCase().indexOf('grep') !== -1) { return false; } // remove this?? - let found = false; - processes.forEach(function (item) { - found = found || (line.toLowerCase().indexOf(item.toLowerCase()) >= 0); - }); - return found; - }); +const _linux$3 = (_platform$3 === 'linux' || _platform$3 === 'android'); +const _darwin$3 = (_platform$3 === 'darwin'); +const _windows$3 = (_platform$3 === 'win32'); +const _freebsd$3 = (_platform$3 === 'freebsd'); +const _openbsd$3 = (_platform$3 === 'openbsd'); +const _netbsd$3 = (_platform$3 === 'netbsd'); +const _sunos$3 = (_platform$3 === 'sunos'); - lines.forEach(function (line) { - let data = line.trim().replace(/ +/g, ' ').split(' '); - if (data.length > 4) { - procStats.push({ - name: data[4].substring(data[4].lastIndexOf('/') + 1), - pid: parseInt(data[0]) || 0, - ppid: parseInt(data[1]) || 0, - cpu: parseFloat(data[2].replace(',', '.')), - mem: parseFloat(data[3].replace(',', '.')) - }); - } - }); +const winPrinterStatus = { + 1: 'Other', + 2: 'Unknown', + 3: 'Idle', + 4: 'Printing', + 5: 'Warmup', + 6: 'Stopped Printing', + 7: 'Offline', +}; - procStats.forEach(function (item) { - let listPos = -1; - let inList = false; - let name = ''; - for (let j = 0; j < result.length; j++) { - if (item.name.toLowerCase().indexOf(result[j].proc.toLowerCase()) >= 0) { - listPos = j; - } - } - processes.forEach(function (proc) { +function parseLinuxCupsHeader(lines) { + const result = {}; + if (lines && lines.length) { + if (lines[0].indexOf(' CUPS v') > 0) { + const parts = lines[0].split(' CUPS v'); + result.cupsVersion = parts[1]; + } + } + return result; +} - if (item.name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) { - inList = true; - name = proc; - } - }); - if ((processesString === '*') || inList) { - if (listPos < 0) { - result.push({ - proc: name, - pid: item.pid, - pids: [item.pid], - cpu: item.cpu, - mem: item.mem - }); - } else { - if (item.ppid < 10) { - result[listPos].pid = item.pid; - } - result[listPos].pids.push(item.pid); - result[listPos].cpu += item.cpu; - result[listPos].mem += item.mem; - } - } - }); +function parseLinuxCupsPrinter(lines) { + const result = {}; + const printerId = util$3.getValue(lines, 'PrinterId', ' '); + result.id = printerId ? parseInt(printerId, 10) : null; + result.name = util$3.getValue(lines, 'Info', ' '); + result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : ''; + result.uri = util$3.getValue(lines, 'DeviceURI', ' '); + result.uuid = util$3.getValue(lines, 'UUID', ' '); + result.status = util$3.getValue(lines, 'State', ' '); + result.local = util$3.getValue(lines, 'Location', ' ').toLowerCase().startsWith('local'); + result.default = null; + result.shared = util$3.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes'); - if (processesString !== '*') { - // add missing processes - let processesMissing = processes.filter(function (name) { - return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0; - }); - processesMissing.forEach(function (procName) { - result.push({ - proc: procName, - pid: null, - pids: [], - cpu: 0, - mem: 0 - }); - }); - } - if (_linux$6) { - // calc process_cpu - ps is not accurate in linux! - result.forEach(function (item) { - item.cpu = 0; - }); - let cmd = 'cat /proc/stat | grep "cpu "'; - for (let i in result) { - for (let j in result[i].pids) { - cmd += (';cat /proc/' + result[i].pids[j] + '/stat'); - } - } - exec$6(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - let curr_processes = stdout.toString().split('\n'); + return result; +} - // first line (all - /proc/stat) - let all = parseProcStat(curr_processes.shift()); +function parseLinuxLpstatPrinter(lines, id) { + const result = {}; + result.id = id; + result.name = util$3.getValue(lines, 'Description', ':', true); + result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : ''; + result.uri = null; + result.uuid = null; + result.status = lines.length > 0 && lines[0] ? (lines[0].indexOf(' idle') > 0 ? 'idle' : (lines[0].indexOf(' printing') > 0 ? 'printing' : 'unknown')) : null; + result.local = util$3.getValue(lines, 'Location', ':', true).toLowerCase().startsWith('local'); + result.default = null; + result.shared = util$3.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes'); - // process - let list_new = {}; - let resultProcess = {}; - curr_processes.forEach((element) => { - resultProcess = calcProcStatLinux(element, all, _process_cpu); + return result; +} - if (resultProcess.pid) { +function parseDarwinPrinters(printerObject, id) { + const result = {}; + const uriParts = printerObject.uri.split('/'); + result.id = id; + result.name = printerObject._name; + result.model = uriParts.length ? uriParts[uriParts.length - 1] : ''; + result.uri = printerObject.uri; + result.uuid = null; + result.status = printerObject.status; + result.local = printerObject.printserver === 'local'; + result.default = printerObject.default === 'yes'; + result.shared = printerObject.shared === 'yes'; - // find result item - let resultItemId = -1; - for (let i in result) { - if (result[i].pids.indexOf(resultProcess.pid) >= 0) { - resultItemId = i; - } - } - // store pcpu in outer result - if (resultItemId >= 0) { - result[resultItemId].cpu += resultProcess.cpuu + resultProcess.cpus; - } + return result; +} - // save new values - list_new[resultProcess.pid] = { - cpuu: resultProcess.cpuu, - cpus: resultProcess.cpus, - utime: resultProcess.utime, - stime: resultProcess.stime, - cutime: resultProcess.cutime, - cstime: resultProcess.cstime - }; - } - }); +function parseWindowsPrinters(lines, id) { + const result = {}; + const status = parseInt(util$3.getValue(lines, 'PrinterStatus', ':'), 10); - result.forEach(function (item) { - item.cpu = Math.round(item.cpu * 100) / 100; - }); + result.id = id; + result.name = util$3.getValue(lines, 'name', ':'); + result.model = util$3.getValue(lines, 'DriverName', ':'); + result.uri = null; + result.uuid = null; + result.status = winPrinterStatus[status] ? winPrinterStatus[status] : null; + result.local = util$3.getValue(lines, 'Local', ':').toUpperCase() === 'TRUE'; + result.default = util$3.getValue(lines, 'Default', ':').toUpperCase() === 'TRUE'; + result.shared = util$3.getValue(lines, 'Shared', ':').toUpperCase() === 'TRUE'; - _process_cpu.all = all; - _process_cpu.list = Object.assign({}, list_new); - _process_cpu.ms = Date.now() - _process_cpu.ms; - _process_cpu.result = Object.assign({}, result); - if (callback) { callback(result); } - resolve(result); - }); - } else { - if (callback) { callback(result); } - resolve(result); + return result; +} + +function printer(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + let result = []; + if (_linux$3 || _freebsd$3 || _openbsd$3 || _netbsd$3) { + let cmd = 'cat /etc/cups/printers.conf 2>/dev/null'; + exec$3(cmd, function (error, stdout) { + // printers.conf + if (!error) { + const parts = stdout.toString().split(' { + if (!error) { + const parts = stdout.toString().split(/\n\s*\n/); + for (let i = 0; i < parts.length; i++) { + const printer = parseWindowsPrinters(parts[i].split('\n'), i); + if (printer.name || printer.model) { + result.push(printer); + } + } + } + if (callback) { + callback(result); + } + resolve(result); + }); + } + if (_sunos$3) { + resolve(null); } }); }); } -processes$1.processLoad = processLoad; +printer$1.printer = printer; -var users$1 = {}; +var usb$1 = {}; // @ts-check // ================================================================================== -// users.js +// usb.js // ---------------------------------------------------------------------------------- // Description: System Information - library // for Node.js @@ -69030,363 +65739,497 @@ var users$1 = {}; // ---------------------------------------------------------------------------------- // License: MIT // ================================================================================== -// 11. Users/Sessions +// 16. usb // ---------------------------------------------------------------------------------- -const exec$5 = require$$1$2.exec; -const util$7 = util$j; +const exec$2 = require$$1$2.exec; +const util$2 = util$j; -let _platform$6 = process.platform; +let _platform$2 = process.platform; -const _linux$5 = (_platform$6 === 'linux' || _platform$6 === 'android'); -const _darwin$5 = (_platform$6 === 'darwin'); -const _windows$6 = (_platform$6 === 'win32'); -const _freebsd$5 = (_platform$6 === 'freebsd'); -const _openbsd$5 = (_platform$6 === 'openbsd'); -const _netbsd$5 = (_platform$6 === 'netbsd'); -const _sunos$5 = (_platform$6 === 'sunos'); +const _linux$2 = (_platform$2 === 'linux' || _platform$2 === 'android'); +const _darwin$2 = (_platform$2 === 'darwin'); +const _windows$2 = (_platform$2 === 'win32'); +const _freebsd$2 = (_platform$2 === 'freebsd'); +const _openbsd$2 = (_platform$2 === 'openbsd'); +const _netbsd$2 = (_platform$2 === 'netbsd'); +const _sunos$2 = (_platform$2 === 'sunos'); + +function getLinuxUsbType(type, name) { + let result = type; + const str = (name + ' ' + type).toLowerCase(); + if (str.indexOf('camera') >= 0) { result = 'Camera'; } + else if (str.indexOf('hub') >= 0) { result = 'Hub'; } + else if (str.indexOf('keybrd') >= 0) { result = 'Keyboard'; } + else if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; } + else if (str.indexOf('mouse') >= 0) { result = 'Mouse'; } + else if (str.indexOf('stora') >= 0) { result = 'Storage'; } + else if (str.indexOf('mic') >= 0) { result = 'Microphone'; } + else if (str.indexOf('headset') >= 0) { result = 'Audio'; } + else if (str.indexOf('audio') >= 0) { result = 'Audio'; } + + return result; +} + +function parseLinuxUsb(usb) { + const result = {}; + const lines = usb.split('\n'); + if (lines && lines.length && lines[0].indexOf('Device') >= 0) { + const parts = lines[0].split(' '); + result.bus = parseInt(parts[0], 10); + if (parts[2]) { + result.deviceId = parseInt(parts[2], 10); + } else { + result.deviceId = null; + } + } else { + result.bus = null; + result.deviceId = null; + } + const idVendor = util$2.getValue(lines, 'idVendor', ' ', true).trim(); + let vendorParts = idVendor.split(' '); + vendorParts.shift(); + const vendor = vendorParts.join(' '); + + const idProduct = util$2.getValue(lines, 'idProduct', ' ', true).trim(); + let productParts = idProduct.split(' '); + productParts.shift(); + const product = productParts.join(' '); + + const interfaceClass = util$2.getValue(lines, 'bInterfaceClass', ' ', true).trim(); + let interfaceClassParts = interfaceClass.split(' '); + interfaceClassParts.shift(); + const usbType = interfaceClassParts.join(' '); + + const iManufacturer = util$2.getValue(lines, 'iManufacturer', ' ', true).trim(); + let iManufacturerParts = iManufacturer.split(' '); + iManufacturerParts.shift(); + const manufacturer = iManufacturerParts.join(' '); + + result.id = (idVendor.startsWith('0x') ? idVendor.split(' ')[0].substr(2, 10) : '') + ':' + (idProduct.startsWith('0x') ? idProduct.split(' ')[0].substr(2, 10) : ''); + result.name = product; + result.type = getLinuxUsbType(usbType, product); + result.removable = null; + result.vendor = vendor; + result.manufacturer = manufacturer; + result.maxPower = util$2.getValue(lines, 'MaxPower', ' ', true); + result.serialNumber = null; + + return result; +} + +function getDarwinUsbType(name) { + let result = ''; + if (name.indexOf('camera') >= 0) { result = 'Camera'; } + else if (name.indexOf('touch bar') >= 0) { result = 'Touch Bar'; } + else if (name.indexOf('controller') >= 0) { result = 'Controller'; } + else if (name.indexOf('headset') >= 0) { result = 'Audio'; } + else if (name.indexOf('keyboard') >= 0) { result = 'Keyboard'; } + else if (name.indexOf('trackpad') >= 0) { result = 'Trackpad'; } + else if (name.indexOf('sensor') >= 0) { result = 'Sensor'; } + else if (name.indexOf('bthusb') >= 0) { result = 'Bluetooth'; } + else if (name.indexOf('bth') >= 0) { result = 'Bluetooth'; } + else if (name.indexOf('rfcomm') >= 0) { result = 'Bluetooth'; } + else if (name.indexOf('usbhub') >= 0) { result = 'Hub'; } + else if (name.indexOf(' hub') >= 0) { result = 'Hub'; } + else if (name.indexOf('mouse') >= 0) { result = 'Mouse'; } + else if (name.indexOf('mic') >= 0) { result = 'Microphone'; } + else if (name.indexOf('removable') >= 0) { result = 'Storage'; } + return result; +} + + +function parseDarwinUsb(usb, id) { + const result = {}; + result.id = id; + + usb = usb.replace(/ \|/g, ''); + usb = usb.trim(); + let lines = usb.split('\n'); + lines.shift(); + try { + for (let i = 0; i < lines.length; i++) { + lines[i] = lines[i].trim(); + lines[i] = lines[i].replace(/=/g, ':'); + if (lines[i] !== '{' && lines[i] !== '}' && lines[i + 1] && lines[i + 1].trim() !== '}') { + lines[i] = lines[i] + ','; + } + + lines[i] = lines[i].replace(':Yes,', ':"Yes",'); + lines[i] = lines[i].replace(': Yes,', ': "Yes",'); + lines[i] = lines[i].replace(': Yes', ': "Yes"'); + lines[i] = lines[i].replace(':No,', ':"No",'); + lines[i] = lines[i].replace(': No,', ': "No",'); + lines[i] = lines[i].replace(': No', ': "No"'); + + // In this case (("com.apple.developer.driverkit.transport.usb")) + lines[i] = lines[i].replace('((', '').replace('))', ''); + + // In case we have <923c11> we need make it "<923c11>" for correct JSON parse + const match = /<(\w+)>/.exec(lines[i]); + if (match) { + const number = match[0]; + lines[i] = lines[i].replace(number, `"${number}"`); + } + } + const usbObj = JSON.parse(lines.join('\n')); + const removableDrive = (usbObj['Built-In'] ? usbObj['Built-In'].toLowerCase() !== 'yes' : true) && (usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() === 'no' : true); + + result.bus = null; + result.deviceId = null; + result.id = usbObj['USB Address'] || null; + result.name = usbObj['kUSBProductString'] || usbObj['USB Product Name'] || null; + result.type = getDarwinUsbType((usbObj['kUSBProductString'] || usbObj['USB Product Name'] || '').toLowerCase() + (removableDrive ? ' removable' : '')); + result.removable = usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() || '' === 'no' : true; + result.vendor = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null; + result.manufacturer = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null; -function parseUsersLinux(lines, phase) { - let result = []; - let result_who = []; - let result_w = {}; - let w_first = true; - let w_header = []; - let w_pos = []; - let who_line = {}; + result.maxPower = null; + result.serialNumber = usbObj['kUSBSerialNumberString'] || null; - let is_whopart = true; - lines.forEach(function (line) { - if (line === '---') { - is_whopart = false; + if (result.name) { + return result; } else { - let l = line.replace(/ +/g, ' ').split(' '); - - // who part - if (is_whopart) { - result_who.push({ - user: l[0], - tty: l[1], - date: l[2], - time: l[3], - ip: (l && l.length > 4) ? l[4].replace(/\(/g, '').replace(/\)/g, '') : '' - }); - } else { - // w part - if (w_first) { // header - w_header = l; - w_header.forEach(function (item) { - w_pos.push(line.indexOf(item)); - }); - w_first = false; - } else { - // split by w_pos - result_w.user = line.substring(w_pos[0], w_pos[1] - 1).trim(); - result_w.tty = line.substring(w_pos[1], w_pos[2] - 1).trim(); - result_w.ip = line.substring(w_pos[2], w_pos[3] - 1).replace(/\(/g, '').replace(/\)/g, '').trim(); - result_w.command = line.substring(w_pos[7], 1000).trim(); - // find corresponding 'who' line - who_line = result_who.filter(function (obj) { - return (obj.user.substring(0, 8).trim() === result_w.user && obj.tty === result_w.tty); - }); - if (who_line.length === 1) { - result.push({ - user: who_line[0].user, - tty: who_line[0].tty, - date: who_line[0].date, - time: who_line[0].time, - ip: who_line[0].ip, - command: result_w.command - }); - } - } - } + return null; } - }); - if (result.length === 0 && phase === 2) { - return result_who; - } else { - return result; + } catch (e) { + return null; } } -function parseUsersDarwin(lines) { - let result = []; - let result_who = []; - let result_w = {}; - let who_line = {}; +function getWindowsUsbTypeCreation(creationclass, name) { + let result = ''; + if (name.indexOf('storage') >= 0) { result = 'Storage'; } + else if (name.indexOf('speicher') >= 0) { result = 'Storage'; } + else if (creationclass.indexOf('usbhub') >= 0) { result = 'Hub'; } + else if (creationclass.indexOf('storage') >= 0) { result = 'Storage'; } + else if (creationclass.indexOf('usbcontroller') >= 0) { result = 'Controller'; } + else if (creationclass.indexOf('keyboard') >= 0) { result = 'Keyboard'; } + else if (creationclass.indexOf('pointing') >= 0) { result = 'Mouse'; } + else if (creationclass.indexOf('disk') >= 0) { result = 'Storage'; } + return result; +} - let is_whopart = true; - lines.forEach(function (line) { - if (line === '---') { - is_whopart = false; - } else { - let l = line.replace(/ +/g, ' ').split(' '); +function parseWindowsUsb(lines, id) { + const usbType = getWindowsUsbTypeCreation(util$2.getValue(lines, 'CreationClassName', ':').toLowerCase(), util$2.getValue(lines, 'name', ':').toLowerCase()); - // who part - if (is_whopart) { - result_who.push({ - user: l[0], - tty: l[1], - date: ('' + new Date().getFullYear()) + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(l[2].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + l[3]).slice(-2), - time: l[4], - }); - } else { - // w part - // split by w_pos - result_w.user = l[0]; - result_w.tty = l[1]; - result_w.ip = (l[2] !== '-') ? l[2] : ''; - result_w.command = l.slice(5, 1000).join(' '); - // find corresponding 'who' line - who_line = result_who.filter(function (obj) { - return (obj.user === result_w.user && (obj.tty.substring(3, 1000) === result_w.tty || obj.tty === result_w.tty)); - }); - if (who_line.length === 1) { - result.push({ - user: who_line[0].user, - tty: who_line[0].tty, - date: who_line[0].date, - time: who_line[0].time, - ip: result_w.ip, - command: result_w.command - }); - } - } - } - }); - return result; + if (usbType) { + const result = {}; + result.bus = null; + result.deviceId = util$2.getValue(lines, 'deviceid', ':'); + result.id = id; + result.name = util$2.getValue(lines, 'name', ':'); + result.type = usbType; + result.removable = null; + result.vendor = null; + result.manufacturer = util$2.getValue(lines, 'Manufacturer', ':'); + result.maxPower = null; + result.serialNumber = null; + + return result; + } else { + return null; + } } -function users(callback) { +function usb(callback) { return new Promise((resolve) => { process.nextTick(() => { let result = []; - - // linux - if (_linux$5) { - exec$5('who --ips; echo "---"; w | tail -n +2', function (error, stdout) { + if (_linux$2) { + const cmd = 'export LC_ALL=C; lsusb -v 2>/dev/null; unset LC_ALL'; + exec$2(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) { if (!error) { - // lines / split - let lines = stdout.toString().split('\n'); - result = parseUsersLinux(lines, 1); - if (result.length === 0) { - exec$5('who; echo "---"; w | tail -n +2', function (error, stdout) { - if (!error) { - // lines / split - lines = stdout.toString().split('\n'); - result = parseUsersLinux(lines, 2); - } - if (callback) { callback(result); } - resolve(result); - }); - } else { - if (callback) { callback(result); } - resolve(result); + const parts = ('\n\n' + stdout.toString()).split('\n\nBus '); + for (let i = 1; i < parts.length; i++) { + const usb = parseLinuxUsb(parts[i]); + result.push(usb); } - } else { - if (callback) { callback(result); } - resolve(result); } - }); - } - if (_freebsd$5 || _openbsd$5 || _netbsd$5) { - exec$5('who; echo "---"; w -ih', function (error, stdout) { - if (!error) { - // lines / split - let lines = stdout.toString().split('\n'); - result = parseUsersDarwin(lines); + if (callback) { + callback(result); } - if (callback) { callback(result); } resolve(result); }); } - if (_sunos$5) { - exec$5('who; echo "---"; w -h', function (error, stdout) { + if (_darwin$2) { + let cmd = 'ioreg -p IOUSB -c AppleUSBRootHubDevice -w0 -l'; + exec$2(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) { if (!error) { - // lines / split - let lines = stdout.toString().split('\n'); - result = parseUsersDarwin(lines); + const parts = (stdout.toString()).split(' +-o '); + for (let i = 1; i < parts.length; i++) { + const usb = parseDarwinUsb(parts[i]); + if (usb) { + result.push(usb); + } + } + if (callback) { + callback(result); + } + resolve(result); + } + if (callback) { + callback(result); } - if (callback) { callback(result); } resolve(result); }); } - - if (_darwin$5) { - exec$5('who; echo "---"; w -ih', function (error, stdout) { + if (_windows$2) { + util$2.powerShell('Get-CimInstance CIM_LogicalDevice | where { $_.Description -match "USB"} | select Name,CreationClassName,DeviceId,Manufacturer | fl').then((stdout, error) => { if (!error) { - // lines / split - let lines = stdout.toString().split('\n'); - result = parseUsersDarwin(lines); + const parts = stdout.toString().split(/\n\s*\n/); + for (let i = 0; i < parts.length; i++) { + const usb = parseWindowsUsb(parts[i].split('\n'), i); + if (usb) { + result.push(usb); + } + } + } + if (callback) { + callback(result); } - if (callback) { callback(result); } resolve(result); }); } - if (_windows$6) { - try { - let cmd = 'Get-CimInstance Win32_LogonSession | select LogonId,@{n="StartTime";e={$_.StartTime.ToString("yyyy-MM-dd HH:mm:ss")}} | fl' + '; echo \'#-#-#-#\';'; - cmd += 'Get-CimInstance Win32_LoggedOnUser | select antecedent,dependent | fl ' + '; echo \'#-#-#-#\';'; - cmd += '$process = (Get-CimInstance Win32_Process -Filter "name = \'explorer.exe\'"); Invoke-CimMethod -InputObject $process[0] -MethodName GetOwner | select user, domain | fl; get-process -name explorer | select-object sessionid | fl; echo \'#-#-#-#\';'; - cmd += 'query user'; - util$7.powerShell(cmd).then((data) => { - if (data) { - data = data.split('#-#-#-#'); - let sessions = parseWinSessions((data[0] || '').split(/\n\s*\n/)); - let loggedons = parseWinLoggedOn((data[1] || '').split(/\n\s*\n/)); - let queryUser = parseWinUsersQuery((data[3] || '').split('\r\n')); - let users = parseWinUsers((data[2] || '').split(/\n\s*\n/), queryUser); - for (let id in loggedons) { - if ({}.hasOwnProperty.call(loggedons, id)) { - loggedons[id].dateTime = {}.hasOwnProperty.call(sessions, id) ? sessions[id] : ''; - } - } - users.forEach(user => { - let dateTime = ''; - for (let id in loggedons) { - if ({}.hasOwnProperty.call(loggedons, id)) { - if (loggedons[id].user === user.user && (!dateTime || dateTime < loggedons[id].dateTime)) { - dateTime = loggedons[id].dateTime; - } - } - } - - result.push({ - user: user.user, - tty: user.tty, - date: `${dateTime.substring(0, 10)}`, - time: `${dateTime.substring(11, 19)}`, - ip: '', - command: '' - }); - }); - } - if (callback) { callback(result); } - resolve(result); - - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } + if (_sunos$2 || _freebsd$2 || _openbsd$2 || _netbsd$2) { + resolve(null); } }); }); } -function parseWinSessions(sessionParts) { - const sessions = {}; - sessionParts.forEach(session => { - const lines = session.split('\r\n'); - const id = util$7.getValue(lines, 'LogonId'); - const starttime = util$7.getValue(lines, 'starttime'); - if (id) { - sessions[id] = starttime; - } - }); - return sessions; +usb$1.usb = usb; + +var audio$1 = {}; + +// @ts-check +// ================================================================================== +// audio.js +// ---------------------------------------------------------------------------------- +// Description: System Information - library +// for Node.js +// Copyright: (c) 2014 - 2023 +// Author: Sebastian Hildebrandt +// ---------------------------------------------------------------------------------- +// License: MIT +// ================================================================================== +// 16. audio +// ---------------------------------------------------------------------------------- + +const exec$1 = require$$1$2.exec; +const execSync$1 = require$$1$2.execSync; +const util$1 = util$j; + +let _platform$1 = process.platform; + +const _linux$1 = (_platform$1 === 'linux' || _platform$1 === 'android'); +const _darwin$1 = (_platform$1 === 'darwin'); +const _windows$1 = (_platform$1 === 'win32'); +const _freebsd$1 = (_platform$1 === 'freebsd'); +const _openbsd$1 = (_platform$1 === 'openbsd'); +const _netbsd$1 = (_platform$1 === 'netbsd'); +const _sunos$1 = (_platform$1 === 'sunos'); + +function parseAudioType(str, input, output) { + str = str.toLowerCase(); + let result = ''; + + if (str.indexOf('input') >= 0) { result = 'Microphone'; } + if (str.indexOf('display audio') >= 0) { result = 'Speaker'; } + if (str.indexOf('speak') >= 0) { result = 'Speaker'; } + if (str.indexOf('laut') >= 0) { result = 'Speaker'; } + if (str.indexOf('loud') >= 0) { result = 'Speaker'; } + if (str.indexOf('head') >= 0) { result = 'Headset'; } + if (str.indexOf('mic') >= 0) { result = 'Microphone'; } + if (str.indexOf('mikr') >= 0) { result = 'Microphone'; } + if (str.indexOf('phone') >= 0) { result = 'Phone'; } + if (str.indexOf('controll') >= 0) { result = 'Controller'; } + if (str.indexOf('line o') >= 0) { result = 'Line Out'; } + if (str.indexOf('digital o') >= 0) { result = 'Digital Out'; } + if (str.indexOf('smart sound technology') >= 0) { result = 'Digital Signal Processor'; } + if (str.indexOf('high definition audio') >= 0) { result = 'Sound Driver'; } + + if (!result && output) { + result = 'Speaker'; + } else if (!result && input) { + result = 'Microphone'; + } + return result; } -function fuzzyMatch(name1, name2) { - name1 = name1.toLowerCase(); - name2 = name2.toLowerCase(); - let eq = 0; - let len = name1.length; - if (name2.length > len) { len = name2.length; } - for (let i = 0; i < len; i++) { - const c1 = name1[i] || ''; - const c2 = name2[i] || ''; - if (c1 === c2) { eq++; } +function getLinuxAudioPci() { + let cmd = 'lspci -v 2>/dev/null'; + let result = []; + try { + const parts = execSync$1(cmd).toString().split('\n\n'); + parts.forEach(element => { + const lines = element.split('\n'); + if (lines && lines.length && lines[0].toLowerCase().indexOf('audio') >= 0) { + const audio = {}; + audio.slotId = lines[0].split(' ')[0]; + audio.driver = util$1.getValue(lines, 'Kernel driver in use', ':', true) || util$1.getValue(lines, 'Kernel modules', ':', true); + result.push(audio); + } + }); + return result; + } catch (e) { + return result; } - return (len > 10 ? eq / len > 0.9 : (len > 0 ? eq / len > 0.8 : false)); } -function parseWinUsers(userParts, userQuery) { - const users = []; - userParts.forEach(user => { - const lines = user.split('\r\n'); +function parseLinuxAudioPciMM(lines, audioPCI) { + const result = {}; + const slotId = util$1.getValue(lines, 'Slot'); - const domain = util$7.getValue(lines, 'domain', ':', true); - const username = util$7.getValue(lines, 'user', ':', true); - const sessionid = util$7.getValue(lines, 'sessionid', ':', true); + const pciMatch = audioPCI.filter(function (item) { return item.slotId === slotId; }); - if (username) { - const quser = userQuery.filter(item => fuzzyMatch(item.user, username)); - users.push({ - domain, - user: username, - tty: quser && quser[0] && quser[0].tty ? quser[0].tty : sessionid - }); - } - }); - return users; + result.id = slotId; + result.name = util$1.getValue(lines, 'SDevice'); + result.manufacturer = util$1.getValue(lines, 'SVendor'); + result.revision = util$1.getValue(lines, 'Rev'); + result.driver = pciMatch && pciMatch.length === 1 && pciMatch[0].driver ? pciMatch[0].driver : ''; + result.default = null; + result.channel = 'PCIe'; + result.type = parseAudioType(result.name, null, null); + result.in = null; + result.out = null; + result.status = 'online'; + + return result; } -function parseWinLoggedOn(loggedonParts) { - const loggedons = {}; - loggedonParts.forEach(loggedon => { - const lines = loggedon.split('\r\n'); +function parseDarwinChannel(str) { + let result = ''; - const antecendent = util$7.getValue(lines, 'antecedent', ':', true); - let parts = antecendent.split('='); - const name = parts.length > 2 ? parts[1].split(',')[0].replace(/"/g, '').trim() : ''; - const domain = parts.length > 2 ? parts[2].replace(/"/g, '').replace(/\)/g, '').trim() : ''; - const dependent = util$7.getValue(lines, 'dependent', ':', true); - parts = dependent.split('='); - const id = parts.length > 1 ? parts[1].replace(/"/g, '').replace(/\)/g, '').trim() : ''; - if (id) { - loggedons[id] = { - domain, - user: name - }; - } - }); - return loggedons; + if (str.indexOf('builtin') >= 0) { result = 'Built-In'; } + if (str.indexOf('extern') >= 0) { result = 'Audio-Jack'; } + if (str.indexOf('hdmi') >= 0) { result = 'HDMI'; } + if (str.indexOf('displayport') >= 0) { result = 'Display-Port'; } + if (str.indexOf('usb') >= 0) { result = 'USB'; } + if (str.indexOf('pci') >= 0) { result = 'PCIe'; } + + return result; } -function parseWinUsersQuery(lines) { - lines = lines.filter(item => item); - let result = []; - const header = lines[0]; - const headerDelimiter = []; - if (header) { - const start = (header[0] === ' ') ? 1 : 0; - headerDelimiter.push(start - 1); - let nextSpace = 0; - for (let i = start + 1; i < header.length; i++) { - if (header[i] === ' ' && ((header[i - 1] === ' ') || (header[i - 1] === '.'))) { - nextSpace = i; - } else { - if (nextSpace) { - headerDelimiter.push(nextSpace); - nextSpace = 0; - } +function parseDarwinAudio(audioObject, id) { + const result = {}; + const channelStr = ((audioObject.coreaudio_device_transport || '') + ' ' + (audioObject._name || '')).toLowerCase(); + + result.id = id; + result.name = audioObject._name; + result.manufacturer = audioObject.coreaudio_device_manufacturer; + result.revision = null; + result.driver = null; + result.default = !!(audioObject.coreaudio_default_audio_input_device || '') || !!(audioObject.coreaudio_default_audio_output_device || ''); + result.channel = parseDarwinChannel(channelStr); + result.type = parseAudioType(result.name, !!(audioObject.coreaudio_device_input || ''), !!(audioObject.coreaudio_device_output || '')); + result.in = !!(audioObject.coreaudio_device_input || ''); + result.out = !!(audioObject.coreaudio_device_output || ''); + result.status = 'online'; + + return result; +} + +function parseWindowsAudio(lines) { + const result = {}; + const status = util$1.getValue(lines, 'StatusInfo', ':'); + + result.id = util$1.getValue(lines, 'DeviceID', ':'); // PNPDeviceID?? + result.name = util$1.getValue(lines, 'name', ':'); + result.manufacturer = util$1.getValue(lines, 'manufacturer', ':'); + result.revision = null; + result.driver = null; + result.default = null; + result.channel = null; + result.type = parseAudioType(result.name, null, null); + result.in = null; + result.out = null; + result.status = status; + + return result; +} + +function audio(callback) { + + return new Promise((resolve) => { + process.nextTick(() => { + let result = []; + if (_linux$1 || _freebsd$1 || _openbsd$1 || _netbsd$1) { + let cmd = 'lspci -vmm 2>/dev/null'; + exec$1(cmd, function (error, stdout) { + // PCI + if (!error) { + const audioPCI = getLinuxAudioPci(); + const parts = stdout.toString().split('\n\n'); + parts.forEach(element => { + const lines = element.split('\n'); + if (util$1.getValue(lines, 'class', ':', true).toLowerCase().indexOf('audio') >= 0) { + const audio = parseLinuxAudioPciMM(lines, audioPCI); + result.push(audio); + } + }); + } + if (callback) { + callback(result); + } + resolve(result); + }); } - } - for (let i = 1; i < lines.length; i++) { - if (lines[i].trim()) { - const user = lines[i].substring(headerDelimiter[0] + 1, headerDelimiter[1]).trim() || ''; - const tty = lines[i].substring(headerDelimiter[1] + 1, headerDelimiter[2] - 2).trim() || ''; - result.push({ - user: user, - tty: tty, + if (_darwin$1) { + let cmd = 'system_profiler SPAudioDataType -json'; + exec$1(cmd, function (error, stdout) { + if (!error) { + try { + const outObj = JSON.parse(stdout.toString()); + if (outObj.SPAudioDataType && outObj.SPAudioDataType.length && outObj.SPAudioDataType[0] && outObj.SPAudioDataType[0]['_items'] && outObj.SPAudioDataType[0]['_items'].length) { + for (let i = 0; i < outObj.SPAudioDataType[0]['_items'].length; i++) { + const audio = parseDarwinAudio(outObj.SPAudioDataType[0]['_items'][i], i); + result.push(audio); + } + } + } catch (e) { + util$1.noop(); + } + } + if (callback) { + callback(result); + } + resolve(result); }); } - } - } - return result; + if (_windows$1) { + util$1.powerShell('Get-CimInstance Win32_SoundDevice | select DeviceID,StatusInfo,Name,Manufacturer | fl').then((stdout, error) => { + if (!error) { + const parts = stdout.toString().split(/\n\s*\n/); + parts.forEach(element => { + const lines = element.split('\n'); + if (util$1.getValue(lines, 'name', ':')) { + result.push(parseWindowsAudio(lines)); + } + }); + } + if (callback) { + callback(result); + } + resolve(result); + }); + } + if (_sunos$1) { + resolve(null); + } + }); + }); } -users$1.users = users; +audio$1.audio = audio; -var internet = {}; +var bluetooth = {}; // @ts-check // ================================================================================== -// internet.js +// audio.js // ---------------------------------------------------------------------------------- // Description: System Information - library // for Node.js @@ -69395,2968 +66238,6145 @@ var internet = {}; // ---------------------------------------------------------------------------------- // License: MIT // ================================================================================== -// 12. Internet +// 17. bluetooth // ---------------------------------------------------------------------------------- -const util$6 = util$j; +const exec = require$$1$2.exec; +const execSync = require$$1$2.execSync; +const path = require$$1$1; +const util = util$j; +const fs = require$$0$5; -let _platform$5 = process.platform; +let _platform = process.platform; -const _linux$4 = (_platform$5 === 'linux' || _platform$5 === 'android'); -const _darwin$4 = (_platform$5 === 'darwin'); -const _windows$5 = (_platform$5 === 'win32'); -const _freebsd$4 = (_platform$5 === 'freebsd'); -const _openbsd$4 = (_platform$5 === 'openbsd'); -const _netbsd$4 = (_platform$5 === 'netbsd'); -const _sunos$4 = (_platform$5 === 'sunos'); +const _linux = (_platform === 'linux' || _platform === 'android'); +const _darwin = (_platform === 'darwin'); +const _windows = (_platform === 'win32'); +const _freebsd = (_platform === 'freebsd'); +const _openbsd = (_platform === 'openbsd'); +const _netbsd = (_platform === 'netbsd'); +const _sunos = (_platform === 'sunos'); -// -------------------------- -// check if external site is available +function parseBluetoothType(str) { + let result = ''; -function inetChecksite(url, callback) { + if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; } + if (str.indexOf('mouse') >= 0) { result = 'Mouse'; } + if (str.indexOf('trackpad') >= 0) { result = 'Trackpad'; } + if (str.indexOf('speaker') >= 0) { result = 'Speaker'; } + if (str.indexOf('headset') >= 0) { result = 'Headset'; } + if (str.indexOf('phone') >= 0) { result = 'Phone'; } + if (str.indexOf('macbook') >= 0) { result = 'Computer'; } + if (str.indexOf('imac') >= 0) { result = 'Computer'; } + if (str.indexOf('ipad') >= 0) { result = 'Tablet'; } + if (str.indexOf('watch') >= 0) { result = 'Watch'; } + if (str.indexOf('headphone') >= 0) { result = 'Headset'; } + // to be continued ... - return new Promise((resolve) => { - process.nextTick(() => { - let result = { - url: url, - ok: false, - status: 404, - ms: null - }; - if (typeof url !== 'string') { - if (callback) { callback(result); } - return resolve(result); - } - let urlSanitized = ''; - const s = util$6.sanitizeShellString(url, true); - const l = util$6.mathMin(s.length, 2000); - for (let i = 0; i <= l; i++) { - if (s[i] !== undefined) { - s[i].__proto__.toLowerCase = util$6.stringToLower; - const sl = s[i].toLowerCase(); - if (sl && sl[0] && !sl[1] && sl[0].length === 1) { - urlSanitized = urlSanitized + sl[0]; - } - } - } - result.url = urlSanitized; - try { - if (urlSanitized && !util$6.isPrototypePolluted()) { - urlSanitized.__proto__.startsWith = util$6.stringStartWith; - if (urlSanitized.startsWith('file:') || urlSanitized.startsWith('gopher:') || urlSanitized.startsWith('telnet:') || urlSanitized.startsWith('mailto:') || urlSanitized.startsWith('news:') || urlSanitized.startsWith('nntp:')) { - if (callback) { callback(result); } - return resolve(result); - } - let t = Date.now(); - if (_linux$4 || _freebsd$4 || _openbsd$4 || _netbsd$4 || _darwin$4 || _sunos$4) { - let args = ['-I', '--connect-timeout', '5', '-m', '5']; - args.push(urlSanitized); - let cmd = 'curl'; - util$6.execSafe(cmd, args).then((stdout) => { - const lines = stdout.split('\n'); - let statusCode = lines[0] && lines[0].indexOf(' ') >= 0 ? parseInt(lines[0].split(' ')[1], 10) : 404; - result.status = statusCode || 404; - result.ok = (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304); - result.ms = (result.ok ? Date.now() - t : null); - if (callback) { callback(result); } - resolve(result); - }); - } - if (_windows$5) { // if this is stable, this can be used for all OS types - const http = (urlSanitized.startsWith('https:') ? require('https') : require('http')); - try { - http.get(urlSanitized, (res) => { - const statusCode = res.statusCode; + return result; +} - result.status = statusCode || 404; - result.ok = (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304); +function parseBluetoothManufacturer(str) { + let result = str.split(' ')[0]; + str = str.toLowerCase(); + if (str.indexOf('apple') >= 0) { result = 'Apple'; } + if (str.indexOf('ipad') >= 0) { result = 'Apple'; } + if (str.indexOf('imac') >= 0) { result = 'Apple'; } + if (str.indexOf('iphone') >= 0) { result = 'Apple'; } + if (str.indexOf('magic mouse') >= 0) { result = 'Apple'; } + if (str.indexOf('magic track') >= 0) { result = 'Apple'; } + if (str.indexOf('macbook') >= 0) { result = 'Apple'; } + // to be continued ... - if (statusCode !== 200) { - res.resume(); - result.ms = (result.ok ? Date.now() - t : null); - if (callback) { callback(result); } - resolve(result); - } else { - res.on('data', () => { }); - res.on('end', () => { - result.ms = (result.ok ? Date.now() - t : null); - if (callback) { callback(result); } - resolve(result); - }); - } - }).on('error', () => { - if (callback) { callback(result); } - resolve(result); - }); - } catch (err) { - if (callback) { callback(result); } - resolve(result); - } - } - } else { - if (callback) { callback(result); } - resolve(result); - } - } catch (err) { - if (callback) { callback(result); } - resolve(result); - } - }); - }); + return result; } -internet.inetChecksite = inetChecksite; +function parseLinuxBluetoothInfo(lines, macAddr1, macAddr2) { + const result = {}; -// -------------------------- -// check inet latency + result.device = null; + result.name = util.getValue(lines, 'name', '='); + result.manufacturer = null; + result.macDevice = macAddr1; + result.macHost = macAddr2; + result.batteryPercent = null; + result.type = parseBluetoothType(result.name.toLowerCase()); + result.connected = false; -function inetLatency(host, callback) { + return result; +} - // fallback - if only callback is given - if (util$6.isFunction(host) && !callback) { - callback = host; - host = ''; - } +function parseDarwinBluetoothDevices(bluetoothObject, macAddr2) { + const result = {}; + const typeStr = ((bluetoothObject.device_minorClassOfDevice_string || bluetoothObject.device_majorClassOfDevice_string || bluetoothObject.device_minorType || '') + (bluetoothObject.device_name || '')).toLowerCase(); - host = host || '8.8.8.8'; + result.device = bluetoothObject.device_services || ''; + result.name = bluetoothObject.device_name || ''; + result.manufacturer = bluetoothObject.device_manufacturer || parseBluetoothManufacturer(bluetoothObject.device_name || '') || ''; + result.macDevice = (bluetoothObject.device_addr || bluetoothObject.device_address || '').toLowerCase().replace(/-/g, ':'); + result.macHost = macAddr2; + result.batteryPercent = bluetoothObject.device_batteryPercent || null; + result.type = parseBluetoothType(typeStr); + result.connected = bluetoothObject.device_isconnected === 'attrib_Yes' || false; + + return result; +} + +function parseWindowsBluetooth(lines) { + const result = {}; + + result.device = null; + result.name = util.getValue(lines, 'name', ':'); + result.manufacturer = util.getValue(lines, 'manufacturer', ':'); + result.macDevice = null; + result.macHost = null; + result.batteryPercent = null; + result.type = parseBluetoothType(result.name.toLowerCase()); + result.connected = null; + + return result; +} + +function bluetoothDevices(callback) { return new Promise((resolve) => { process.nextTick(() => { - if (typeof host !== 'string') { - if (callback) { callback(null); } - return resolve(null); - } - let hostSanitized = ''; - const s = (util$6.isPrototypePolluted() ? '8.8.8.8' : util$6.sanitizeShellString(host, true)).trim(); - const l = util$6.mathMin(s.length, 2000); - for (let i = 0; i <= l; i++) { - if (!(s[i] === undefined)) { - s[i].__proto__.toLowerCase = util$6.stringToLower; - const sl = s[i].toLowerCase(); - if (sl && sl[0] && !sl[1]) { - hostSanitized = hostSanitized + sl[0]; + let result = []; + if (_linux) { + // get files in /var/lib/bluetooth/ recursive + const btFiles = util.getFilesInPath('/var/lib/bluetooth/'); + btFiles.forEach((element) => { + const filename = path.basename(element); + const pathParts = element.split('/'); + const macAddr1 = pathParts.length >= 6 ? pathParts[pathParts.length - 2] : null; + const macAddr2 = pathParts.length >= 7 ? pathParts[pathParts.length - 3] : null; + if (filename === 'info') { + const infoFile = fs.readFileSync(element, { encoding: 'utf8' }).split('\n'); + result.push(parseLinuxBluetoothInfo(infoFile, macAddr1, macAddr2)); } + }); + // determine "connected" with hcitool con + try { + const hdicon = execSync('hcitool con').toString().toLowerCase(); + for (let i = 0; i < result.length; i++) { + if (result[i].macDevice && result[i].macDevice.length > 10 && hdicon.indexOf(result[i].macDevice.toLowerCase()) >= 0) { + result[i].connected = true; + } + } + } catch (e) { + util.noop(); } - } - hostSanitized.__proto__.startsWith = util$6.stringStartWith; - if (hostSanitized.startsWith('file:') || hostSanitized.startsWith('gopher:') || hostSanitized.startsWith('telnet:') || hostSanitized.startsWith('mailto:') || hostSanitized.startsWith('news:') || hostSanitized.startsWith('nntp:')) { - if (callback) { callback(null); } - return resolve(null); - } - let params; - if (_linux$4 || _freebsd$4 || _openbsd$4 || _netbsd$4 || _darwin$4) { - if (_linux$4) { - params = ['-c', '2', '-w', '3', hostSanitized]; - } - if (_freebsd$4 || _openbsd$4 || _netbsd$4) { - params = ['-c', '2', '-t', '3', hostSanitized]; - } - if (_darwin$4) { - params = ['-c2', '-t3', hostSanitized]; - } - util$6.execSafe('ping', params).then((stdout) => { - let result = null; - if (stdout) { - const lines = stdout.split('\n').filter((line) => (line.indexOf('rtt') >= 0 || line.indexOf('round-trip') >= 0 || line.indexOf('avg') >= 0)).join('\n'); - const line = lines.split('='); - if (line.length > 1) { - const parts = line[1].split('/'); - if (parts.length > 1) { - result = parseFloat(parts[1]); + if (callback) { + callback(result); + } + resolve(result); + } + if (_darwin) { + let cmd = 'system_profiler SPBluetoothDataType -json'; + exec(cmd, function (error, stdout) { + if (!error) { + try { + const outObj = JSON.parse(stdout.toString()); + if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_title'] && outObj.SPBluetoothDataType[0]['device_title'].length) { + // missing: host BT Adapter macAddr () + let macAddr2 = null; + if (outObj.SPBluetoothDataType[0]['local_device_title'] && outObj.SPBluetoothDataType[0].local_device_title.general_address) { + macAddr2 = outObj.SPBluetoothDataType[0].local_device_title.general_address.toLowerCase().replace(/-/g, ':'); + } + outObj.SPBluetoothDataType[0]['device_title'].forEach((element) => { + const obj = element; + const objKey = Object.keys(obj); + if (objKey && objKey.length === 1) { + const innerObject = obj[objKey[0]]; + innerObject.device_name = objKey[0]; + const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2); + result.push(bluetoothDevice); + } + }); + } + if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_connected'] && outObj.SPBluetoothDataType[0]['device_connected'].length) { + const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null; + outObj.SPBluetoothDataType[0]['device_connected'].forEach((element) => { + const obj = element; + const objKey = Object.keys(obj); + if (objKey && objKey.length === 1) { + const innerObject = obj[objKey[0]]; + innerObject.device_name = objKey[0]; + innerObject.device_isconnected = 'attrib_Yes'; + const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2); + result.push(bluetoothDevice); + } + }); + } + if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_not_connected'] && outObj.SPBluetoothDataType[0]['device_not_connected'].length) { + const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null; + outObj.SPBluetoothDataType[0]['device_not_connected'].forEach((element) => { + const obj = element; + const objKey = Object.keys(obj); + if (objKey && objKey.length === 1) { + const innerObject = obj[objKey[0]]; + innerObject.device_name = objKey[0]; + innerObject.device_isconnected = 'attrib_No'; + const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2); + result.push(bluetoothDevice); + } + }); } + } catch (e) { + util.noop(); } } - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); }); } - if (_sunos$4) { - const params = ['-s', '-a', hostSanitized, '56', '2']; - const filt = 'avg'; - util$6.execSafe('ping', params, { timeout: 3000 }).then((stdout) => { - let result = null; - if (stdout) { - const lines = stdout.split('\n').filter(line => line.indexOf(filt) >= 0).join('\n'); - const line = lines.split('='); - if (line.length > 1) { - const parts = line[1].split('/'); - if (parts.length > 1) { - result = parseFloat(parts[1].replace(',', '.')); + if (_windows) { + util.powerShell('Get-CimInstance Win32_PNPEntity | select PNPClass, Name, Manufacturer | fl').then((stdout, error) => { + if (!error) { + const parts = stdout.toString().split(/\n\s*\n/); + parts.forEach((part) => { + if (util.getValue(part.split('\n'), 'PNPClass', ':') === 'Bluetooth') { + result.push(parseWindowsBluetooth(part.split('\n'))); } - } + }); + } + if (callback) { + callback(result); } - if (callback) { callback(result); } resolve(result); }); } - if (_windows$5) { - let result = null; - try { - const params = [hostSanitized, '-n', '1']; - util$6.execSafe('ping', params, util$6.execOptsWin).then((stdout) => { - if (stdout) { - let lines = stdout.split('\r\n'); - lines.shift(); - lines.forEach(function (line) { - if ((line.toLowerCase().match(/ms/g) || []).length === 3) { - let l = line.replace(/ +/g, ' ').split(' '); - if (l.length > 6) { - result = parseFloat(l[l.length - 1]); - } - } - }); - } - if (callback) { callback(result); } - resolve(result); - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } + if (_freebsd || _netbsd || _openbsd || _sunos) { + resolve(null); } }); }); } -internet.inetLatency = inetLatency; +bluetooth.bluetoothDevices = bluetoothDevices; -var docker = {}; +(function (exports) { + // @ts-check + // ================================================================================== + // index.js + // ---------------------------------------------------------------------------------- + // Description: System Information - library + // for Node.js + // Copyright: (c) 2014 - 2023 + // Author: Sebastian Hildebrandt + // ---------------------------------------------------------------------------------- + // Contributors: Guillaume Legrain (https://github.com/glegrain) + // Riccardo Novaglia (https://github.com/richy24) + // Quentin Busuttil (https://github.com/Buzut) + // Lapsio (https://github.com/lapsio) + // csy (https://github.com/csy1983) + // ---------------------------------------------------------------------------------- + // License: MIT + // ================================================================================== -// @ts-check -// ================================================================================== -// dockerSockets.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 13. DockerSockets -// ---------------------------------------------------------------------------------- + // ---------------------------------------------------------------------------------- + // Dependencies + // ---------------------------------------------------------------------------------- + + const lib_version = require$$0.version; + const util = util$j; + const system = system$1; + const osInfo = osinfo; + const cpu = cpu$1; + const memory$1 = memory; + const battery$1 = battery; + const graphics = graphics$1; + const filesystem$1 = filesystem; + const network$1 = network; + const wifi$1 = wifi; + const processes = processes$1; + const users = users$1; + const internet$1 = internet; + const docker$1 = docker; + const vbox = virtualbox; + const printer = printer$1; + const usb = usb$1; + const audio = audio$1; + const bluetooth$1 = bluetooth; + + let _platform = process.platform; + const _windows = (_platform === 'win32'); + const _freebsd = (_platform === 'freebsd'); + const _openbsd = (_platform === 'openbsd'); + const _netbsd = (_platform === 'netbsd'); + const _sunos = (_platform === 'sunos'); + + // ---------------------------------------------------------------------------------- + // init + // ---------------------------------------------------------------------------------- + + if (_windows) { + util.getCodepage(); + } + + // ---------------------------------------------------------------------------------- + // General + // ---------------------------------------------------------------------------------- + + function version() { + return lib_version; + } + + // ---------------------------------------------------------------------------------- + // Get static and dynamic data (all) + // ---------------------------------------------------------------------------------- -const net = require$$0$8; -const isWin = require$$0$7.type() === 'Windows_NT'; -const socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock'; + // -------------------------- + // get static data - they should not change until restarted -let DockerSocket$1 = class DockerSocket { + function getStaticData(callback) { - getInfo(callback) { - try { + return new Promise((resolve) => { + process.nextTick(() => { - let socket = net.createConnection({ path: socketPath }); - let alldata = ''; - let data; + let data = {}; - socket.on('connect', () => { - socket.write('GET http:/info HTTP/1.0\r\n\r\n'); - }); + data.version = version(); - socket.on('data', data => { - alldata = alldata + data.toString(); - }); + Promise.all([ + system.system(), + system.bios(), + system.baseboard(), + system.chassis(), + osInfo.osInfo(), + osInfo.uuid(), + osInfo.versions(), + cpu.cpu(), + cpu.cpuFlags(), + graphics.graphics(), + network$1.networkInterfaces(), + memory$1.memLayout(), + filesystem$1.diskLayout() + ]).then((res) => { + data.system = res[0]; + data.bios = res[1]; + data.baseboard = res[2]; + data.chassis = res[3]; + data.os = res[4]; + data.uuid = res[5]; + data.versions = res[6]; + data.cpu = res[7]; + data.cpu.flags = res[8]; + data.graphics = res[9]; + data.net = res[10]; + data.memLayout = res[11]; + data.diskLayout = res[12]; + if (callback) { callback(data); } + resolve(data); + }); + }); + }); + } - socket.on('error', () => { - socket = false; - callback({}); - }); - socket.on('end', () => { - let startbody = alldata.indexOf('\r\n\r\n'); - alldata = alldata.substring(startbody + 4); - socket = false; - try { - data = JSON.parse(alldata); - callback(data); - } catch (err) { - callback({}); - } - }); - } catch (err) { - callback({}); - } - } + // -------------------------- + // get all dynamic data - e.g. for monitoring agents + // may take some seconds to get all data + // -------------------------- + // 2 additional parameters needed + // - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql" + // - iface: define network interface for which you like to monitor network speed e.g. "eth0" - listImages(all, callback) { - try { + function getDynamicData(srv, iface, callback) { - let socket = net.createConnection({ path: socketPath }); - let alldata = ''; - let data; + if (util.isFunction(iface)) { + callback = iface; + iface = ''; + } + if (util.isFunction(srv)) { + callback = srv; + srv = ''; + } - socket.on('connect', () => { - socket.write('GET http:/images/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n'); - }); + return new Promise((resolve) => { + process.nextTick(() => { - socket.on('data', data => { - alldata = alldata + data.toString(); - }); + iface = iface || network$1.getDefaultNetworkInterface(); + srv = srv || ''; - socket.on('error', () => { - socket = false; - callback({}); - }); + // use closure to track ƒ completion + let functionProcessed = (function () { + let totalFunctions = 15; + if (_windows) { totalFunctions = 13; } + if (_freebsd || _openbsd || _netbsd) { totalFunctions = 11; } + if (_sunos) { totalFunctions = 6; } - socket.on('end', () => { - let startbody = alldata.indexOf('\r\n\r\n'); - alldata = alldata.substring(startbody + 4); - socket = false; - try { - data = JSON.parse(alldata); - callback(data); - } catch (err) { - callback({}); - } - }); - } catch (err) { - callback({}); - } - } + return function () { + if (--totalFunctions === 0) { + if (callback) { + callback(data); + } + resolve(data); + } + }; + })(); - inspectImage(id, callback) { - id = id || ''; - if (id) { - try { - let socket = net.createConnection({ path: socketPath }); - let alldata = ''; - let data; + let data = {}; - socket.on('connect', () => { - socket.write('GET http:/images/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n'); - }); + // get time + data.time = osInfo.time(); - socket.on('data', data => { - alldata = alldata + data.toString(); - }); + /** + * @namespace + * @property {Object} versions + * @property {string} versions.node + * @property {string} versions.v8 + */ + data.node = process.versions.node; + data.v8 = process.versions.v8; - socket.on('error', () => { - socket = false; - callback({}); - }); + cpu.cpuCurrentSpeed().then((res) => { + data.cpuCurrentSpeed = res; + functionProcessed(); + }); - socket.on('end', () => { - let startbody = alldata.indexOf('\r\n\r\n'); - alldata = alldata.substring(startbody + 4); - socket = false; - try { - data = JSON.parse(alldata); - callback(data); - } catch (err) { - callback({}); - } - }); - } catch (err) { - callback({}); - } - } else { - callback({}); - } - } + users.users().then((res) => { + data.users = res; + functionProcessed(); + }); - listContainers(all, callback) { - try { + processes.processes().then((res) => { + data.processes = res; + functionProcessed(); + }); - let socket = net.createConnection({ path: socketPath }); - let alldata = ''; - let data; + cpu.currentLoad().then((res) => { + data.currentLoad = res; + functionProcessed(); + }); - socket.on('connect', () => { - socket.write('GET http:/containers/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n'); - }); + if (!_sunos) { + cpu.cpuTemperature().then((res) => { + data.temp = res; + functionProcessed(); + }); + } - socket.on('data', data => { - alldata = alldata + data.toString(); - }); + if (!_openbsd && !_freebsd && !_netbsd && !_sunos) { + network$1.networkStats(iface).then((res) => { + data.networkStats = res; + functionProcessed(); + }); + } - socket.on('error', () => { - socket = false; - callback({}); - }); + if (!_sunos) { + network$1.networkConnections().then((res) => { + data.networkConnections = res; + functionProcessed(); + }); + } - socket.on('end', () => { - let startbody = alldata.indexOf('\r\n\r\n'); - alldata = alldata.substring(startbody + 4); - socket = false; - try { - data = JSON.parse(alldata); - callback(data); - } catch (err) { - callback({}); - } - }); - } catch (err) { - callback({}); - } - } + memory$1.mem().then((res) => { + data.mem = res; + functionProcessed(); + }); - getStats(id, callback) { - id = id || ''; - if (id) { - try { - let socket = net.createConnection({ path: socketPath }); - let alldata = ''; - let data; + if (!_sunos) { + battery$1().then((res) => { + data.battery = res; + functionProcessed(); + }); + } - socket.on('connect', () => { - socket.write('GET http:/containers/' + id + '/stats?stream=0 HTTP/1.0\r\n\r\n'); - }); + if (!_sunos) { + processes.services(srv).then((res) => { + data.services = res; + functionProcessed(); + }); + } - socket.on('data', data => { - alldata = alldata + data.toString(); - }); + if (!_sunos) { + filesystem$1.fsSize().then((res) => { + data.fsSize = res; + functionProcessed(); + }); + } - socket.on('error', () => { - socket = false; - callback({}); - }); + if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) { + filesystem$1.fsStats().then((res) => { + data.fsStats = res; + functionProcessed(); + }); + } - socket.on('end', () => { - let startbody = alldata.indexOf('\r\n\r\n'); - alldata = alldata.substring(startbody + 4); - socket = false; - try { - data = JSON.parse(alldata); - callback(data); - } catch (err) { - callback({}); - } - }); - } catch (err) { - callback({}); - } - } else { - callback({}); - } - } + if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) { + filesystem$1.disksIO().then((res) => { + data.disksIO = res; + functionProcessed(); + }); + } - getInspect(id, callback) { - id = id || ''; - if (id) { - try { - let socket = net.createConnection({ path: socketPath }); - let alldata = ''; - let data; + if (!_openbsd && !_freebsd && !_netbsd && !_sunos) { + wifi$1.wifiNetworks().then((res) => { + data.wifiNetworks = res; + functionProcessed(); + }); + } - socket.on('connect', () => { - socket.write('GET http:/containers/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n'); - }); + internet$1.inetLatency().then((res) => { + data.inetLatency = res; + functionProcessed(); + }); + }); + }); + } - socket.on('data', data => { - alldata = alldata + data.toString(); - }); + // -------------------------- + // get all data at once + // -------------------------- + // 2 additional parameters needed + // - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql" + // - iface: define network interface for which you like to monitor network speed e.g. "eth0" - socket.on('error', () => { - socket = false; - callback({}); - }); + function getAllData(srv, iface, callback) { - socket.on('end', () => { - let startbody = alldata.indexOf('\r\n\r\n'); - alldata = alldata.substring(startbody + 4); - socket = false; - try { - data = JSON.parse(alldata); - callback(data); - } catch (err) { - callback({}); - } - }); - } catch (err) { - callback({}); - } - } else { - callback({}); - } - } + return new Promise((resolve) => { + process.nextTick(() => { + let data = {}; - getProcesses(id, callback) { - id = id || ''; - if (id) { - try { - let socket = net.createConnection({ path: socketPath }); - let alldata = ''; - let data; + if (iface && util.isFunction(iface) && !callback) { + callback = iface; + iface = ''; + } - socket.on('connect', () => { - socket.write('GET http:/containers/' + id + '/top?ps_args=-opid,ppid,pgid,vsz,time,etime,nice,ruser,user,rgroup,group,stat,rss,args HTTP/1.0\r\n\r\n'); - }); + if (srv && util.isFunction(srv) && !iface && !callback) { + callback = srv; + srv = ''; + iface = ''; + } - socket.on('data', data => { - alldata = alldata + data.toString(); - }); + getStaticData().then((res) => { + data = res; + getDynamicData(srv, iface).then((res) => { + for (let key in res) { + if ({}.hasOwnProperty.call(res, key)) { + data[key] = res[key]; + } + } + if (callback) { callback(data); } + resolve(data); + }); + }); + }); + }); + } + + function get(valueObject, callback) { + return new Promise((resolve) => { + process.nextTick(() => { + const allPromises = Object.keys(valueObject) + .filter(func => ({}.hasOwnProperty.call(exports, func))) + .map(func => { + const params = valueObject[func].substring(valueObject[func].lastIndexOf('(') + 1, valueObject[func].lastIndexOf(')')); + let funcWithoutParams = func.indexOf(')') >= 0 ? func.split(')')[1].trim() : func; + funcWithoutParams = func.indexOf('|') >= 0 ? func.split('|')[0].trim() : funcWithoutParams; + if (params) { + return exports[funcWithoutParams](params); + } else { + return exports[funcWithoutParams](''); + } + }); + + Promise.all(allPromises).then((data) => { + const result = {}; + let i = 0; + for (let key in valueObject) { + if ({}.hasOwnProperty.call(valueObject, key) && {}.hasOwnProperty.call(exports, key) && data.length > i) { + if (valueObject[key] === '*' || valueObject[key] === 'all') { + result[key] = data[i]; + } else { + let keys = valueObject[key]; + let filter = ''; + let filterParts = []; + // remove params + if (keys.indexOf(')') >= 0) { + keys = keys.split(')')[1].trim(); + } + // extract filter and remove it from keys + if (keys.indexOf('|') >= 0) { + filter = keys.split('|')[1].trim(); + filterParts = filter.split(':'); + + keys = keys.split('|')[0].trim(); + } + keys = keys.replace(/,/g, ' ').replace(/ +/g, ' ').split(' '); + if (data[i]) { + if (Array.isArray(data[i])) { + // result is in an array, go through all elements of array and pick only the right ones + const partialArray = []; + data[i].forEach(element => { + let partialRes = {}; + if (keys.length === 1 && (keys[0] === '*' || keys[0] === 'all')) { + partialRes = element; + } else { + keys.forEach(k => { + if ({}.hasOwnProperty.call(element, k)) { + partialRes[k] = element[k]; + } + }); + } + // if there is a filter, then just take those elements + if (filter && filterParts.length === 2) { + if ({}.hasOwnProperty.call(partialRes, filterParts[0].trim())) { + const val = partialRes[filterParts[0].trim()]; + if (typeof val == 'number') { + if (val === parseFloat(filterParts[1].trim())) { + partialArray.push(partialRes); + } + } else if (typeof val == 'string') { + if (val.toLowerCase() === filterParts[1].trim().toLowerCase()) { + partialArray.push(partialRes); + } + } + } + } else { + partialArray.push(partialRes); + } + + }); + result[key] = partialArray; + } else { + const partialRes = {}; + keys.forEach(k => { + if ({}.hasOwnProperty.call(data[i], k)) { + partialRes[k] = data[i][k]; + } + }); + result[key] = partialRes; + } + } else { + result[key] = {}; + } + } + i++; + } + } + if (callback) { callback(result); } + resolve(result); + }); + }); + }); + } - socket.on('error', () => { - socket = false; - callback({}); - }); + function observe(valueObject, interval, callback) { + let _data = null; - socket.on('end', () => { - let startbody = alldata.indexOf('\r\n\r\n'); - alldata = alldata.substring(startbody + 4); - socket = false; - try { - data = JSON.parse(alldata); - callback(data); - } catch (err) { - callback({}); - } - }); - } catch (err) { - callback({}); - } - } else { - callback({}); - } - } + const result = setInterval(() => { + get(valueObject).then((data) => { + if (JSON.stringify(_data) !== JSON.stringify(data)) { + _data = Object.assign({}, data); + callback(data); + } + }); + }, interval); + return result; + } - listVolumes(callback) { - try { + // ---------------------------------------------------------------------------------- + // export all libs + // ---------------------------------------------------------------------------------- - let socket = net.createConnection({ path: socketPath }); - let alldata = ''; - let data; + exports.version = version; + exports.system = system.system; + exports.bios = system.bios; + exports.baseboard = system.baseboard; + exports.chassis = system.chassis; - socket.on('connect', () => { - socket.write('GET http:/volumes HTTP/1.0\r\n\r\n'); - }); + exports.time = osInfo.time; + exports.osInfo = osInfo.osInfo; + exports.versions = osInfo.versions; + exports.shell = osInfo.shell; + exports.uuid = osInfo.uuid; - socket.on('data', data => { - alldata = alldata + data.toString(); - }); + exports.cpu = cpu.cpu; + exports.cpuFlags = cpu.cpuFlags; + exports.cpuCache = cpu.cpuCache; + exports.cpuCurrentSpeed = cpu.cpuCurrentSpeed; + exports.cpuTemperature = cpu.cpuTemperature; + exports.currentLoad = cpu.currentLoad; + exports.fullLoad = cpu.fullLoad; - socket.on('error', () => { - socket = false; - callback({}); - }); + exports.mem = memory$1.mem; + exports.memLayout = memory$1.memLayout; - socket.on('end', () => { - let startbody = alldata.indexOf('\r\n\r\n'); - alldata = alldata.substring(startbody + 4); - socket = false; - try { - data = JSON.parse(alldata); - callback(data); - } catch (err) { - callback({}); - } - }); - } catch (err) { - callback({}); - } - } -}; + exports.battery = battery$1; -var dockerSocket = DockerSocket$1; + exports.graphics = graphics.graphics; -// @ts-check -// ================================================================================== -// docker.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 13. Docker -// ---------------------------------------------------------------------------------- + exports.fsSize = filesystem$1.fsSize; + exports.fsOpenFiles = filesystem$1.fsOpenFiles; + exports.blockDevices = filesystem$1.blockDevices; + exports.fsStats = filesystem$1.fsStats; + exports.disksIO = filesystem$1.disksIO; + exports.diskLayout = filesystem$1.diskLayout; -const util$5 = util$j; -const DockerSocket = dockerSocket; + exports.networkInterfaceDefault = network$1.networkInterfaceDefault; + exports.networkGatewayDefault = network$1.networkGatewayDefault; + exports.networkInterfaces = network$1.networkInterfaces; + exports.networkStats = network$1.networkStats; + exports.networkConnections = network$1.networkConnections; -let _platform$4 = process.platform; -const _windows$4 = (_platform$4 === 'win32'); + exports.wifiNetworks = wifi$1.wifiNetworks; + exports.wifiInterfaces = wifi$1.wifiInterfaces; + exports.wifiConnections = wifi$1.wifiConnections; -let _docker_container_stats = {}; -let _docker_socket; -let _docker_last_read = 0; + exports.services = processes.services; + exports.processes = processes.processes; + exports.processLoad = processes.processLoad; + exports.users = users.users; -// -------------------------- -// get containers (parameter all: get also inactive/exited containers) + exports.inetChecksite = internet$1.inetChecksite; + exports.inetLatency = internet$1.inetLatency; -function dockerInfo(callback) { - return new Promise((resolve) => { - process.nextTick(() => { - if (!_docker_socket) { - _docker_socket = new DockerSocket(); - } - const result = {}; + exports.dockerInfo = docker$1.dockerInfo; + exports.dockerImages = docker$1.dockerImages; + exports.dockerContainers = docker$1.dockerContainers; + exports.dockerContainerStats = docker$1.dockerContainerStats; + exports.dockerContainerProcesses = docker$1.dockerContainerProcesses; + exports.dockerVolumes = docker$1.dockerVolumes; + exports.dockerAll = docker$1.dockerAll; - _docker_socket.getInfo((data) => { - result.id = data.ID; - result.containers = data.Containers; - result.containersRunning = data.ContainersRunning; - result.containersPaused = data.ContainersPaused; - result.containersStopped = data.ContainersStopped; - result.images = data.Images; - result.driver = data.Driver; - result.memoryLimit = data.MemoryLimit; - result.swapLimit = data.SwapLimit; - result.kernelMemory = data.KernelMemory; - result.cpuCfsPeriod = data.CpuCfsPeriod; - result.cpuCfsQuota = data.CpuCfsQuota; - result.cpuShares = data.CPUShares; - result.cpuSet = data.CPUSet; - result.ipv4Forwarding = data.IPv4Forwarding; - result.bridgeNfIptables = data.BridgeNfIptables; - result.bridgeNfIp6tables = data.BridgeNfIp6tables; - result.debug = data.Debug; - result.nfd = data.NFd; - result.oomKillDisable = data.OomKillDisable; - result.ngoroutines = data.NGoroutines; - result.systemTime = data.SystemTime; - result.loggingDriver = data.LoggingDriver; - result.cgroupDriver = data.CgroupDriver; - result.nEventsListener = data.NEventsListener; - result.kernelVersion = data.KernelVersion; - result.operatingSystem = data.OperatingSystem; - result.osType = data.OSType; - result.architecture = data.Architecture; - result.ncpu = data.NCPU; - result.memTotal = data.MemTotal; - result.dockerRootDir = data.DockerRootDir; - result.httpProxy = data.HttpProxy; - result.httpsProxy = data.HttpsProxy; - result.noProxy = data.NoProxy; - result.name = data.Name; - result.labels = data.Labels; - result.experimentalBuild = data.ExperimentalBuild; - result.serverVersion = data.ServerVersion; - result.clusterStore = data.ClusterStore; - result.clusterAdvertise = data.ClusterAdvertise; - result.defaultRuntime = data.DefaultRuntime; - result.liveRestoreEnabled = data.LiveRestoreEnabled; - result.isolation = data.Isolation; - result.initBinary = data.InitBinary; - result.productLicense = data.ProductLicense; - if (callback) { callback(result); } - resolve(result); - }); - }); - }); -} + exports.vboxInfo = vbox.vboxInfo; -docker.dockerInfo = dockerInfo; + exports.printer = printer.printer; -function dockerImages(all, callback) { + exports.usb = usb.usb; - // fallback - if only callback is given - if (util$5.isFunction(all) && !callback) { - callback = all; - all = false; - } - if (typeof all === 'string' && all === 'true') { - all = true; - } - if (typeof all !== 'boolean' && all !== undefined) { - all = false; - } + exports.audio = audio.audio; + exports.bluetoothDevices = bluetooth$1.bluetoothDevices; - all = all || false; - let result = []; - return new Promise((resolve) => { - process.nextTick(() => { - if (!_docker_socket) { - _docker_socket = new DockerSocket(); - } - const workload = []; + exports.getStaticData = getStaticData; + exports.getDynamicData = getDynamicData; + exports.getAllData = getAllData; + exports.get = get; + exports.observe = observe; - _docker_socket.listImages(all, data => { - let dockerImages = {}; - try { - dockerImages = data; - if (dockerImages && Object.prototype.toString.call(dockerImages) === '[object Array]' && dockerImages.length > 0) { + exports.powerShellStart = util.powerShellStart; + exports.powerShellRelease = util.powerShellRelease; +} (lib)); - dockerImages.forEach(function (element) { +var systemInfo = /*@__PURE__*/getDefaultExportFromCjs(lib); - if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) { - element.Name = element.Names[0].replace(/^\/|\/$/g, ''); - } - workload.push(dockerImagesInspect(element.Id.trim(), element)); - }); - if (workload.length) { - Promise.all( - workload - ).then((data) => { - if (callback) { callback(data); } - resolve(data); - }); - } else { - if (callback) { callback(result); } - resolve(result); - } - } else { - if (callback) { callback(result); } - resolve(result); - } - } catch (err) { - if (callback) { callback(result); } - resolve(result); +const CMD_HOLDER = '$folder'; +const executeOpenCMD = async (config, path) => { + const { openCMD } = config; + const command = openCMD ? openCMD.replaceAll(CMD_HOLDER, path) : `code ${path}`; + Log.info(`executing command: ${command}`); + await execa(command, { shell: true }); +}; +const handleFindResult = async (originSearchString, config, findFolders) => { + if (!findFolders?.length) { + Log.error(`${originSearchString} not found`); + return; + } + const targetFolder = findFolders.length === 1 + ? findFolders[0] + : (await select({ + message: 'Which folder do you wish to open?', + choices: findFolders.map(value => ({ value })), + })); + if (targetFolder) { + executeOpenCMD(config, targetFolder); + } +}; +const searchFolder = async (config, folder) => { + const { workspaceOnly, alias } = config; + const folderName = alias[folder] || folder; + Log.debug(folderName); + if (workspaceOnly) { + searchWorkspace(config, folderName); + } + else { + searchGlobally(config, folderName); + } +}; +const searchGlobally = async (config, folderName) => { + const { ignoreFolders } = config; + Log.debug(folderName); + const rootDirs = await getRootDirs(); + const results = []; + const folderMatcher = (folder) => { + if (minimatch(folder.currentFolder, folderName)) { + results.push(folder.fullPath); } - }); + }; + await bfsTravelFolder(rootDirs, folderMatcher, (folder) => ignoreFolders.some(e => minimatch(folder, e))); + handleFindResult(folderName, config, results); +}; +const searchWorkspace = async (config, folderName) => { + const { workspaces, ignoreFolders } = config; + const results = []; + const folderMatcher = (folder) => { + if (minimatch(folder.currentFolder, folderName)) { + results.push(folder.fullPath); + } + }; + await bfsTravelFolder(workspaces, folderMatcher, (folder) => ignoreFolders.some(e => minimatch(folder, e))); + handleFindResult(folderName, config, results); +}; +const bfsTravelFolder = async (folderPathList, callback, shouldIgnore) => { + const folders = _.flattenDeep(await Promise.all(folderPathList.map(async (folderPath) => { + try { + const underlayFolder = await fs$e.readdir(folderPath, { withFileTypes: true }); + return underlayFolder.filter(e => e.isDirectory() && !shouldIgnore(e.name)).map(e => ({ + fullPath: require$$1$1.resolve(e.path, e.name), + currentFolder: e.name, + })); + } + catch (error) { + Log.error(error); + return []; + } + }))); + folders.forEach(folder => { + callback(folder); }); - }); -} - -// -------------------------- -// container inspect (for one container) - -function dockerImagesInspect(imageID, payload) { - return new Promise((resolve) => { - process.nextTick(() => { - imageID = imageID || ''; - if (typeof imageID !== 'string') { - return resolve(); - } - const imageIDSanitized = (util$5.isPrototypePolluted() ? '' : util$5.sanitizeShellString(imageID, true)).trim(); - if (imageIDSanitized) { + if (folders.length > 0) { + await bfsTravelFolder(folders.map(e => e.fullPath), callback, shouldIgnore); + } +}; +const getRootDirs = async () => { + const isWin = require$$0$7.platform() === 'win32'; + const roots = isWin ? (await systemInfo.blockDevices()).slice(1).map(e => `${e.identifier}${require$$1$1.sep}`) : ['/']; + return roots; +}; - if (!_docker_socket) { - _docker_socket = new DockerSocket(); +const align = { + right: alignRight, + center: alignCenter +}; +const top = 0; +const right = 1; +const bottom = 2; +const left = 3; +class UI { + constructor(opts) { + var _a; + this.width = opts.width; + this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; + this.rows = []; + } + span(...args) { + const cols = this.div(...args); + cols.span = true; + } + resetOutput() { + this.rows = []; + } + div(...args) { + if (args.length === 0) { + this.div(''); } - - _docker_socket.inspectImage(imageIDSanitized.trim(), data => { - try { - resolve({ - id: payload.Id, - container: data.Container, - comment: data.Comment, - os: data.Os, - architecture: data.Architecture, - parent: data.Parent, - dockerVersion: data.DockerVersion, - size: data.Size, - sharedSize: payload.SharedSize, - virtualSize: data.VirtualSize, - author: data.Author, - created: data.Created ? Math.round(new Date(data.Created).getTime() / 1000) : 0, - containerConfig: data.ContainerConfig ? data.ContainerConfig : {}, - graphDriver: data.GraphDriver ? data.GraphDriver : {}, - repoDigests: data.RepoDigests ? data.RepoDigests : {}, - repoTags: data.RepoTags ? data.RepoTags : {}, - config: data.Config ? data.Config : {}, - rootFS: data.RootFS ? data.RootFS : {}, + if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { + return this.applyLayoutDSL(args[0]); + } + const cols = args.map(arg => { + if (typeof arg === 'string') { + return this.colFromString(arg); + } + return arg; + }); + this.rows.push(cols); + return cols; + } + shouldApplyLayoutDSL(...args) { + return args.length === 1 && typeof args[0] === 'string' && + /[\t\n]/.test(args[0]); + } + applyLayoutDSL(str) { + const rows = str.split('\n').map(row => row.split('\t')); + let leftColumnWidth = 0; + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(columns => { + if (columns.length > 1 && mixin$1.stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin$1.stringWidth(columns[0])); + } + }); + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(columns => { + this.div(...columns.map((r, i) => { + return { + text: r.trim(), + padding: this.measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + }; + })); + }); + return this.rows[this.rows.length - 1]; + } + colFromString(text) { + return { + text, + padding: this.measurePadding(text) + }; + } + measurePadding(str) { + // measure padding without ansi escape codes + const noAnsi = mixin$1.stripAnsi(str); + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; + } + toString() { + const lines = []; + this.rows.forEach(row => { + this.rowToString(row, lines); + }); + // don't display any lines with the + // hidden flag set. + return lines + .filter(line => !line.hidden) + .map(line => line.text) + .join('\n'); + } + rowToString(row, lines) { + this.rasterize(row).forEach((rrow, r) => { + let str = ''; + rrow.forEach((col, c) => { + const { width } = row[c]; // the width with padding. + const wrapWidth = this.negatePadding(row[c]); // the width without padding. + let ts = col; // temporary string used during alignment/padding. + if (wrapWidth > mixin$1.stringWidth(col)) { + ts += ' '.repeat(wrapWidth - mixin$1.stringWidth(col)); + } + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && this.wrap) { + const fn = align[row[c].align]; + ts = fn(ts, wrapWidth); + if (mixin$1.stringWidth(ts) < wrapWidth) { + ts += ' '.repeat((width || 0) - mixin$1.stringWidth(ts) - 1); + } + } + // apply border and padding to string. + const padding = row[c].padding || [0, 0, 0, 0]; + if (padding[left]) { + str += ' '.repeat(padding[left]); + } + str += addBorder(row[c], ts, '| '); + str += ts; + str += addBorder(row[c], ts, ' |'); + if (padding[right]) { + str += ' '.repeat(padding[right]); + } + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = this.renderInline(str, lines[lines.length - 1]); + } + }); + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span }); - } catch (err) { - resolve(); - } }); - } else { - resolve(); - } - }); - }); -} - -docker.dockerImages = dockerImages; - -function dockerContainers(all, callback) { - - function inContainers(containers, id) { - let filtered = containers.filter(obj => { - /** - * @namespace - * @property {string} Id - */ - return (obj.Id && (obj.Id === id)); - }); - return (filtered.length > 0); - } - - // fallback - if only callback is given - if (util$5.isFunction(all) && !callback) { - callback = all; - all = false; - } - if (typeof all === 'string' && all === 'true') { - all = true; - } - if (typeof all !== 'boolean' && all !== undefined) { - all = false; - } - - all = all || false; - let result = []; - return new Promise((resolve) => { - process.nextTick(() => { - if (!_docker_socket) { - _docker_socket = new DockerSocket(); - } - const workload = []; - - _docker_socket.listContainers(all, data => { - let docker_containers = {}; - try { - docker_containers = data; - if (docker_containers && Object.prototype.toString.call(docker_containers) === '[object Array]' && docker_containers.length > 0) { - // GC in _docker_container_stats - for (let key in _docker_container_stats) { - if ({}.hasOwnProperty.call(_docker_container_stats, key)) { - if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; } - } + return lines; + } + // if the full 'source' can render in + // the target line, do so. + renderInline(source, previousLine) { + const match = source.match(/^ */); + const leadingWhitespace = match ? match[0].length : 0; + const target = previousLine.text; + const targetTextWidth = mixin$1.stringWidth(target.trimRight()); + if (!previousLine.span) { + return source; + } + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true; + return target + source; + } + if (leadingWhitespace < targetTextWidth) { + return source; + } + previousLine.hidden = true; + return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft(); + } + rasterize(row) { + const rrows = []; + const widths = this.columnWidths(row); + let wrapped; + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach((col, c) => { + // leave room for left and right padding. + col.width = widths[c]; + if (this.wrap) { + wrapped = mixin$1.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); } - - docker_containers.forEach(function (element) { - - if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) { - element.Name = element.Names[0].replace(/^\/|\/$/g, ''); - } - workload.push(dockerContainerInspect(element.Id.trim(), element)); - }); - if (workload.length) { - Promise.all( - workload - ).then((data) => { - if (callback) { callback(data); } - resolve(data); - }); - } else { - if (callback) { callback(result); } - resolve(result); + else { + wrapped = col.text.split('\n'); } - } else { - if (callback) { callback(result); } - resolve(result); - } - } catch (err) { - // GC in _docker_container_stats - for (let key in _docker_container_stats) { - if ({}.hasOwnProperty.call(_docker_container_stats, key)) { - if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; } + if (col.border) { + wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); + wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); } - } - if (callback) { callback(result); } - resolve(result); + // add top and bottom padding. + if (col.padding) { + wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); + wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); + } + wrapped.forEach((str, r) => { + if (!rrows[r]) { + rrows.push([]); + } + const rrow = rrows[r]; + for (let i = 0; i < c; i++) { + if (rrow[i] === undefined) { + rrow.push(''); + } + } + rrow.push(str); + }); + }); + return rrows; + } + negatePadding(col) { + let wrapWidth = col.width || 0; + if (col.padding) { + wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); } - }); - }); - }); -} - -// -------------------------- -// container inspect (for one container) - -function dockerContainerInspect(containerID, payload) { - return new Promise((resolve) => { - process.nextTick(() => { - containerID = containerID || ''; - if (typeof containerID !== 'string') { - return resolve(); - } - const containerIdSanitized = (util$5.isPrototypePolluted() ? '' : util$5.sanitizeShellString(containerID, true)).trim(); - if (containerIdSanitized) { - - if (!_docker_socket) { - _docker_socket = new DockerSocket(); + if (col.border) { + wrapWidth -= 4; } - - _docker_socket.getInspect(containerIdSanitized.trim(), data => { - try { - resolve({ - id: payload.Id, - name: payload.Name, - image: payload.Image, - imageID: payload.ImageID, - command: payload.Command, - created: payload.Created, - started: data.State && data.State.StartedAt ? Math.round(new Date(data.State.StartedAt).getTime() / 1000) : 0, - finished: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? Math.round(new Date(data.State.FinishedAt).getTime() / 1000) : 0, - createdAt: data.Created ? data.Created : '', - startedAt: data.State && data.State.StartedAt ? data.State.StartedAt : '', - finishedAt: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? data.State.FinishedAt : '', - state: payload.State, - restartCount: data.RestartCount || 0, - platform: data.Platform || '', - driver: data.Driver || '', - ports: payload.Ports, - mounts: payload.Mounts, - // hostconfig: payload.HostConfig, - // network: payload.NetworkSettings + return wrapWidth; + } + columnWidths(row) { + if (!this.wrap) { + return row.map(col => { + return col.width || mixin$1.stringWidth(col.text); }); - } catch (err) { - resolve(); - } + } + let unset = row.length; + let remainingWidth = this.width; + // column widths can be set in config. + const widths = row.map(col => { + if (col.width) { + unset--; + remainingWidth -= col.width; + return col.width; + } + return undefined; }); - } else { - resolve(); - } + // any unset widths should be calculated. + const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; + return widths.map((w, i) => { + if (w === undefined) { + return Math.max(unsetWidth, _minWidth(row[i])); + } + return w; + }); + } +} +function addBorder(col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) { + return ''; + } + if (ts.trim().length !== 0) { + return style; + } + return ' '; + } + return ''; +} +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth(col) { + const padding = col.padding || []; + const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); + if (col.border) { + return minWidth + 4; + } + return minWidth; +} +function getWindowWidth() { + /* istanbul ignore next: depends on terminal */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return process.stdout.columns; + } + return 80; +} +function alignRight(str, width) { + str = str.trim(); + const strWidth = mixin$1.stringWidth(str); + if (strWidth < width) { + return ' '.repeat(width - strWidth) + str; + } + return str; +} +function alignCenter(str, width) { + str = str.trim(); + const strWidth = mixin$1.stringWidth(str); + /* istanbul ignore next */ + if (strWidth >= width) { + return str; + } + return ' '.repeat((width - strWidth) >> 1) + str; +} +let mixin$1; +function cliui(opts, _mixin) { + mixin$1 = _mixin; + return new UI({ + width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), + wrap: opts === null || opts === void 0 ? void 0 : opts.wrap }); - }); } -docker.dockerContainers = dockerContainers; - -// -------------------------- -// helper functions for calculation of docker stats - -function docker_calcCPUPercent(cpu_stats, precpu_stats) { - /** - * @namespace - * @property {object} cpu_usage - * @property {number} cpu_usage.total_usage - * @property {number} system_cpu_usage - * @property {object} cpu_usage - * @property {Array} cpu_usage.percpu_usage - */ - - if (!_windows$4) { - let cpuPercent = 0.0; - // calculate the change for the cpu usage of the container in between readings - let cpuDelta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage; - // calculate the change for the entire system between readings - let systemDelta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage; - - if (systemDelta > 0.0 && cpuDelta > 0.0) { - // calculate the change for the cpu usage of the container in between readings - if (precpu_stats.online_cpus) { - cpuPercent = (cpuDelta / systemDelta) * precpu_stats.online_cpus * 100.0; - } - else { - cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0; - } +// Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi". +// to facilitate ESM and Deno modules. +// TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM. +// The npm application +// Copyright (c) npm, Inc. and Contributors +// Licensed on the terms of The Artistic License 2.0 +// See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js +const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' + + '\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g'); +function stripAnsi(str) { + return str.replace(ansi, ''); +} +function wrap(str, width) { + const [start, end] = str.match(ansi) || ['', '']; + str = stripAnsi(str); + let wrapped = ''; + for (let i = 0; i < str.length; i++) { + if (i !== 0 && (i % width) === 0) { + wrapped += '\n'; + } + wrapped += str.charAt(i); } - - return cpuPercent; - } else { - let nanoSecNow = util$5.nanoSeconds(); - let cpuPercent = 0.0; - if (_docker_last_read > 0) { - let possIntervals = (nanoSecNow - _docker_last_read); // / 100 * os.cpus().length; - let intervalsUsed = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage; - if (possIntervals > 0) { - cpuPercent = 100.0 * intervalsUsed / possIntervals; - } + if (start && end) { + wrapped = `${start}${wrapped}${end}`; } - _docker_last_read = nanoSecNow; - return cpuPercent; - } + return wrapped; } -function docker_calcNetworkIO(networks) { - let rx; - let wx; - for (let key in networks) { - // skip loop if the property is from prototype - if (!{}.hasOwnProperty.call(networks, key)) { continue; } +// Bootstrap cliui with CommonJS dependencies: - /** - * @namespace - * @property {number} rx_bytes - * @property {number} tx_bytes - */ - let obj = networks[key]; - rx = +obj.rx_bytes; - wx = +obj.tx_bytes; - } - return { - rx, - wx - }; +function ui (opts) { + return cliui(opts, { + stringWidth: (str) => { + return [...str].length + }, + stripAnsi, + wrap + }) } -function docker_calcBlockIO(blkio_stats) { - let result = { - r: 0, - w: 0 - }; +function escalade (start, callback) { + let dir = resolve('.', start); + let tmp, stats = statSync(dir); - /** - * @namespace - * @property {Array} io_service_bytes_recursive - */ - if (blkio_stats && blkio_stats.io_service_bytes_recursive && Object.prototype.toString.call(blkio_stats.io_service_bytes_recursive) === '[object Array]' && blkio_stats.io_service_bytes_recursive.length > 0) { - blkio_stats.io_service_bytes_recursive.forEach(function (element) { - /** - * @namespace - * @property {string} op - * @property {number} value - */ + if (!stats.isDirectory()) { + dir = dirname(dir); + } - if (element.op && element.op.toLowerCase() === 'read' && element.value) { - result.r += element.value; - } - if (element.op && element.op.toLowerCase() === 'write' && element.value) { - result.w += element.value; - } - }); - } - return result; + while (true) { + tmp = callback(dir, readdirSync(dir)); + if (tmp) return resolve(dir, tmp); + dir = dirname(tmp = dir); + if (tmp === dir) break; + } } -function dockerContainerStats(containerIDs, callback) { - - let containerArray = []; - return new Promise((resolve) => { - process.nextTick(() => { - - // fallback - if only callback is given - if (util$5.isFunction(containerIDs) && !callback) { - callback = containerIDs; - containerArray = ['*']; - } else { - containerIDs = containerIDs || '*'; - if (typeof containerIDs !== 'string') { - if (callback) { callback([]); } - return resolve([]); +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +function camelCase(str) { + // Handle the case where an argument is provided as camel case, e.g., fooBar. + // by ensuring that the string isn't already mixed case: + const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); + if (!isCamelCase) { + str = str.toLowerCase(); + } + if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { + return str; + } + else { + let camelcase = ''; + let nextChrUpper = false; + const leadingHyphens = str.match(/^-+/); + for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { + let chr = str.charAt(i); + if (nextChrUpper) { + nextChrUpper = false; + chr = chr.toUpperCase(); + } + if (i !== 0 && (chr === '-' || chr === '_')) { + nextChrUpper = true; + } + else if (chr !== '-' && chr !== '_') { + camelcase += chr; + } } - let containerIDsSanitized = ''; - containerIDsSanitized.__proto__.toLowerCase = util$5.stringToLower; - containerIDsSanitized.__proto__.replace = util$5.stringReplace; - containerIDsSanitized.__proto__.trim = util$5.stringTrim; + return camelcase; + } +} +function decamelize(str, joinString) { + const lowercase = str.toLowerCase(); + joinString = joinString || '-'; + let notCamelcase = ''; + for (let i = 0; i < str.length; i++) { + const chrLower = lowercase.charAt(i); + const chrString = str.charAt(i); + if (chrLower !== chrString && i > 0) { + notCamelcase += `${joinString}${lowercase.charAt(i)}`; + } + else { + notCamelcase += chrString; + } + } + return notCamelcase; +} +function looksLikeNumber(x) { + if (x === null || x === undefined) + return false; + // if loaded from config, may already be a number. + if (typeof x === 'number') + return true; + // hexadecimal. + if (/^0x[0-9a-f]+$/i.test(x)) + return true; + // don't treat 0123 as a number; as it drops the leading '0'. + if (/^0[^.]/.test(x)) + return false; + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} - containerIDsSanitized = containerIDs; - containerIDsSanitized = containerIDsSanitized.trim(); - if (containerIDsSanitized !== '*') { - containerIDsSanitized = ''; - const s = (util$5.isPrototypePolluted() ? '' : util$5.sanitizeShellString(containerIDs, true)).trim(); - const l = util$5.mathMin(s.length, 2000); - for (let i = 0; i <= l; i++) { - if (s[i] !== undefined) { - s[i].__proto__.toLowerCase = util$5.stringToLower; - const sl = s[i].toLowerCase(); - if (sl && sl[0] && !sl[1]) { - containerIDsSanitized = containerIDsSanitized + sl[0]; - } +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +// take an un-split argv string and tokenize it. +function tokenizeArgString(argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e); + } + argString = argString.trim(); + let i = 0; + let prevC = null; + let c = null; + let opening = null; + const args = []; + for (let ii = 0; ii < argString.length; ii++) { + prevC = c; + c = argString.charAt(ii); + // split on spaces unless we're in quotes. + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++; } - } + continue; } - - containerIDsSanitized = containerIDsSanitized.trim().toLowerCase().replace(/,+/g, '|'); - containerArray = containerIDsSanitized.split('|'); - } - - const result = []; - - const workload = []; - if (containerArray.length && containerArray[0].trim() === '*') { - containerArray = []; - dockerContainers().then(allContainers => { - for (let container of allContainers) { - containerArray.push(container.id.substring(0, 12)); - } - if (containerArray.length) { - dockerContainerStats(containerArray.join(',')).then(result => { - if (callback) { callback(result); } - resolve(result); - }); - } else { - if (callback) { callback(result); } - resolve(result); - } - }); - } else { - for (let containerID of containerArray) { - workload.push(dockerContainerStatsSingle(containerID.trim())); + // don't split the string if we're in matching + // opening or closing single and double quotes. + if (c === opening) { + opening = null; } - if (workload.length) { - Promise.all( - workload - ).then((data) => { - if (callback) { callback(data); } - resolve(data); - }); - } else { - if (callback) { callback(result); } - resolve(result); + else if ((c === "'" || c === '"') && !opening) { + opening = c; } - } - }); - }); + if (!args[i]) + args[i] = ''; + args[i] += c; + } + return args; } -// -------------------------- -// container stats (for one container) - -function dockerContainerStatsSingle(containerID) { - containerID = containerID || ''; - let result = { - id: containerID, - memUsage: 0, - memLimit: 0, - memPercent: 0, - cpuPercent: 0, - pids: 0, - netIO: { - rx: 0, - wx: 0 - }, - blockIO: { - r: 0, - w: 0 - }, - restartCount: 0, - cpuStats: {}, - precpuStats: {}, - memoryStats: {}, - networks: {}, - }; - return new Promise((resolve) => { - process.nextTick(() => { - if (containerID) { +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +var DefaultValuesForTypeKey; +(function (DefaultValuesForTypeKey) { + DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; + DefaultValuesForTypeKey["STRING"] = "string"; + DefaultValuesForTypeKey["NUMBER"] = "number"; + DefaultValuesForTypeKey["ARRAY"] = "array"; +})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); - if (!_docker_socket) { - _docker_socket = new DockerSocket(); +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +let mixin; +class YargsParser { + constructor(_mixin) { + mixin = _mixin; + } + parse(argsInput, options) { + const opts = Object.assign({ + alias: undefined, + array: undefined, + boolean: undefined, + config: undefined, + configObjects: undefined, + configuration: undefined, + coerce: undefined, + count: undefined, + default: undefined, + envPrefix: undefined, + narg: undefined, + normalize: undefined, + string: undefined, + number: undefined, + __: undefined, + key: undefined + }, options); + // allow a string argument to be passed in rather + // than an argv array. + const args = tokenizeArgString(argsInput); + // tokenizeArgString adds extra quotes to args if argsInput is a string + // only strip those extra quotes in processValue if argsInput is a string + const inputIsString = typeof argsInput === 'string'; + // aliases might have transitive relationships, normalize this. + const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); + const configuration = Object.assign({ + 'boolean-negation': true, + 'camel-case-expansion': true, + 'combine-arrays': false, + 'dot-notation': true, + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'greedy-arrays': true, + 'halt-at-non-option': false, + 'nargs-eats-options': false, + 'negation-prefix': 'no-', + 'parse-numbers': true, + 'parse-positional-numbers': true, + 'populate--': false, + 'set-placeholder-key': false, + 'short-option-groups': true, + 'strip-aliased': false, + 'strip-dashed': false, + 'unknown-options-as-args': false + }, opts.configuration); + const defaults = Object.assign(Object.create(null), opts.default); + const configObjects = opts.configObjects || []; + const envPrefix = opts.envPrefix; + const notFlagsOption = configuration['populate--']; + const notFlagsArgv = notFlagsOption ? '--' : '_'; + const newAliases = Object.create(null); + const defaulted = Object.create(null); + // allow a i18n handler to be passed in, default to a fake one (util.format). + const __ = opts.__ || mixin.format; + const flags = { + aliases: Object.create(null), + arrays: Object.create(null), + bools: Object.create(null), + strings: Object.create(null), + numbers: Object.create(null), + counts: Object.create(null), + normalize: Object.create(null), + configs: Object.create(null), + nargs: Object.create(null), + coercions: Object.create(null), + keys: [] + }; + const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; + const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); + [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { + const key = typeof opt === 'object' ? opt.key : opt; + // assign to flags[bools|strings|numbers] + const assignment = Object.keys(opt).map(function (key) { + const arrayFlagKeys = { + boolean: 'bools', + string: 'strings', + number: 'numbers' + }; + return arrayFlagKeys[key]; + }).filter(Boolean).pop(); + // assign key to be coerced + if (assignment) { + flags[assignment][key] = true; + } + flags.arrays[key] = true; + flags.keys.push(key); + }); + [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + flags.keys.push(key); + }); + [].concat(opts.string || []).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + flags.keys.push(key); + }); + [].concat(opts.number || []).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true; + flags.keys.push(key); + }); + [].concat(opts.count || []).filter(Boolean).forEach(function (key) { + flags.counts[key] = true; + flags.keys.push(key); + }); + [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true; + flags.keys.push(key); + }); + if (typeof opts.narg === 'object') { + Object.entries(opts.narg).forEach(([key, value]) => { + if (typeof value === 'number') { + flags.nargs[key] = value; + flags.keys.push(key); + } + }); } - - _docker_socket.getInspect(containerID, dataInspect => { - try { - _docker_socket.getStats(containerID, data => { - try { - let stats = data; - if (!stats.message) { - if (data.id) { result.id = data.id; } - result.memUsage = (stats.memory_stats && stats.memory_stats.usage ? stats.memory_stats.usage : 0); - result.memLimit = (stats.memory_stats && stats.memory_stats.limit ? stats.memory_stats.limit : 0); - result.memPercent = (stats.memory_stats && stats.memory_stats.usage && stats.memory_stats.limit ? stats.memory_stats.usage / stats.memory_stats.limit * 100.0 : 0); - result.cpuPercent = (stats.cpu_stats && stats.precpu_stats ? docker_calcCPUPercent(stats.cpu_stats, stats.precpu_stats) : 0); - result.pids = (stats.pids_stats && stats.pids_stats.current ? stats.pids_stats.current : 0); - result.restartCount = (dataInspect.RestartCount ? dataInspect.RestartCount : 0); - if (stats.networks) { result.netIO = docker_calcNetworkIO(stats.networks); } - if (stats.blkio_stats) { result.blockIO = docker_calcBlockIO(stats.blkio_stats); } - result.cpuStats = (stats.cpu_stats ? stats.cpu_stats : {}); - result.precpuStats = (stats.precpu_stats ? stats.precpu_stats : {}); - result.memoryStats = (stats.memory_stats ? stats.memory_stats : {}); - result.networks = (stats.networks ? stats.networks : {}); + if (typeof opts.coerce === 'object') { + Object.entries(opts.coerce).forEach(([key, value]) => { + if (typeof value === 'function') { + flags.coercions[key] = value; + flags.keys.push(key); } - } catch (err) { - util$5.noop(); - } - // } - resolve(result); }); - } catch (err) { - util$5.noop(); - } - }); - } else { - resolve(result); - } - }); - }); -} - -docker.dockerContainerStats = dockerContainerStats; - -// -------------------------- -// container processes (for one container) - -function dockerContainerProcesses(containerID, callback) { - let result = []; - return new Promise((resolve) => { - process.nextTick(() => { - containerID = containerID || ''; - if (typeof containerID !== 'string') { - return resolve(result); - } - const containerIdSanitized = (util$5.isPrototypePolluted() ? '' : util$5.sanitizeShellString(containerID, true)).trim(); - - if (containerIdSanitized) { - - if (!_docker_socket) { - _docker_socket = new DockerSocket(); } - - _docker_socket.getProcesses(containerIdSanitized, data => { - /** - * @namespace - * @property {Array} Titles - * @property {Array} Processes - **/ - try { - if (data && data.Titles && data.Processes) { - let titles = data.Titles.map(function (value) { - return value.toUpperCase(); - }); - let pos_pid = titles.indexOf('PID'); - let pos_ppid = titles.indexOf('PPID'); - let pos_pgid = titles.indexOf('PGID'); - let pos_vsz = titles.indexOf('VSZ'); - let pos_time = titles.indexOf('TIME'); - let pos_elapsed = titles.indexOf('ELAPSED'); - let pos_ni = titles.indexOf('NI'); - let pos_ruser = titles.indexOf('RUSER'); - let pos_user = titles.indexOf('USER'); - let pos_rgroup = titles.indexOf('RGROUP'); - let pos_group = titles.indexOf('GROUP'); - let pos_stat = titles.indexOf('STAT'); - let pos_rss = titles.indexOf('RSS'); - let pos_command = titles.indexOf('COMMAND'); - - data.Processes.forEach(process => { - result.push({ - pidHost: (pos_pid >= 0 ? process[pos_pid] : ''), - ppid: (pos_ppid >= 0 ? process[pos_ppid] : ''), - pgid: (pos_pgid >= 0 ? process[pos_pgid] : ''), - user: (pos_user >= 0 ? process[pos_user] : ''), - ruser: (pos_ruser >= 0 ? process[pos_ruser] : ''), - group: (pos_group >= 0 ? process[pos_group] : ''), - rgroup: (pos_rgroup >= 0 ? process[pos_rgroup] : ''), - stat: (pos_stat >= 0 ? process[pos_stat] : ''), - time: (pos_time >= 0 ? process[pos_time] : ''), - elapsed: (pos_elapsed >= 0 ? process[pos_elapsed] : ''), - nice: (pos_ni >= 0 ? process[pos_ni] : ''), - rss: (pos_rss >= 0 ? process[pos_rss] : ''), - vsz: (pos_vsz >= 0 ? process[pos_vsz] : ''), - command: (pos_command >= 0 ? process[pos_command] : '') + if (typeof opts.config !== 'undefined') { + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + [].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true; }); - }); } - } catch (err) { - util$5.noop(); - } - if (callback) { callback(result); } - resolve(result); + else if (typeof opts.config === 'object') { + Object.entries(opts.config).forEach(([key, value]) => { + if (typeof value === 'boolean' || typeof value === 'function') { + flags.configs[key] = value; + } + }); + } + } + // create a lookup table that takes into account all + // combinations of aliases: {f: ['foo'], foo: ['f']} + extendAliases(opts.key, aliases, opts.default, flags.arrays); + // apply default values to all aliases. + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key]; + }); + }); + let error = null; + checkConfiguration(); + let notFlags = []; + const argv = Object.assign(Object.create(null), { _: [] }); + // TODO(bcoe): for the first pass at removing object prototype we didn't + // remove all prototypes from objects returned by this API, we might want + // to gradually move towards doing so. + const argvReturn = {}; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const truncatedArg = arg.replace(/^-{3,}/, '---'); + let broken; + let key; + let letters; + let m; + let next; + let value; + // any unknown option (except for end-of-options, "--") + if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { + pushPositional(arg); + // ---, ---=, ----, etc, + } + else if (truncatedArg.match(/^---+(=|$)/)) { + // options without key name are invalid. + pushPositional(arg); + continue; + // -- separated by = + } + else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + m = arg.match(/^--?([^=]+)=([\s\S]*)$/); + // arrays format = '--f=a b c' + if (m !== null && Array.isArray(m) && m.length >= 3) { + if (checkAllAliases(m[1], flags.arrays)) { + i = eatArray(i, m[1], args, m[2]); + } + else if (checkAllAliases(m[1], flags.nargs) !== false) { + // nargs format = '--f=monkey washing cat' + i = eatNargs(i, m[1], args, m[2]); + } + else { + setArg(m[1], m[2], true); + } + } + } + else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + m = arg.match(negatedBoolean); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); + } + // -- separated by space. + } + else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { + m = arg.match(/^--?(.+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '--foo a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '--foo a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + // dot-notation flag separated by '='. + } + else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + setArg(m[1], m[2]); + } + // dot-notation flag separated by space. + } + else if (arg.match(/^-.\..+/) && !arg.match(negative)) { + next = args[i + 1]; + m = arg.match(/^-(.\..+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split(''); + broken = false; + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3); + key = letters[j]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f=a b c' + i = eatArray(i, key, args, value); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f=monkey washing cat' + i = eatNargs(i, key, args, value); + } + else { + setArg(key, value); + } + broken = true; + break; + } + if (next === '-') { + setArg(letters[j], next); + continue; + } + // current letter is an alphabetic character and next value is a number + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && + checkAllAliases(next, flags.bools) === false) { + setArg(letters[j], next); + broken = true; + break; + } + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next); + broken = true; + break; + } + else { + setArg(letters[j], defaultValue(letters[j])); + } + } + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-[0-9]$/) && + arg.match(negative) && + checkAllAliases(arg.slice(1), flags.bools)) { + // single-digit boolean alias, e.g: xargs -0 + key = arg.slice(1); + setArg(key, defaultValue(key)); + } + else if (arg === '--') { + notFlags = args.slice(i + 1); + break; + } + else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i); + break; + } + else { + pushPositional(arg); + } + } + // order of precedence: + // 1. command line arg + // 2. value from env var + // 3. value from config file + // 4. value from config objects + // 5. configured default value + applyEnvVars(argv, true); // special case: check env vars that point to config file + applyEnvVars(argv, false); + setConfig(argv); + setConfigObjects(); + applyDefaultsAndAliases(argv, flags.aliases, defaults, true); + applyCoercions(argv); + if (configuration['set-placeholder-key']) + setPlaceholderKeys(argv); + // for any counts either not in args or without an explicit default, set to 0 + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) + setArg(key, 0); }); - } else { - if (callback) { callback(result); } - resolve(result); - } - }); - }); -} - -docker.dockerContainerProcesses = dockerContainerProcesses; - -function dockerVolumes(callback) { - - let result = []; - return new Promise((resolve) => { - process.nextTick(() => { - if (!_docker_socket) { - _docker_socket = new DockerSocket(); - } - _docker_socket.listVolumes((data) => { - let dockerVolumes = {}; - try { - dockerVolumes = data; - if (dockerVolumes && dockerVolumes.Volumes && Object.prototype.toString.call(dockerVolumes.Volumes) === '[object Array]' && dockerVolumes.Volumes.length > 0) { - - dockerVolumes.Volumes.forEach(function (element) { - - result.push({ - name: element.Name, - driver: element.Driver, - labels: element.Labels, - mountpoint: element.Mountpoint, - options: element.Options, - scope: element.Scope, - created: element.CreatedAt ? Math.round(new Date(element.CreatedAt).getTime() / 1000) : 0, - }); + // '--' defaults to undefined. + if (notFlagsOption && notFlags.length) + argv[notFlagsArgv] = []; + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key); + }); + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key]; }); - if (callback) { callback(result); } - resolve(result); - } else { - if (callback) { callback(result); } - resolve(result); - } - } catch (err) { - if (callback) { callback(result); } - resolve(result); } - }); - }); - }); -} - -docker.dockerVolumes = dockerVolumes; - -function dockerAll(callback) { - return new Promise((resolve) => { - process.nextTick(() => { - dockerContainers(true).then(result => { - if (result && Object.prototype.toString.call(result) === '[object Array]' && result.length > 0) { - let l = result.length; - result.forEach(function (element) { - dockerContainerStats(element.id).then((res) => { - // include stats in array - element.memUsage = res[0].memUsage; - element.memLimit = res[0].memLimit; - element.memPercent = res[0].memPercent; - element.cpuPercent = res[0].cpuPercent; - element.pids = res[0].pids; - element.netIO = res[0].netIO; - element.blockIO = res[0].blockIO; - element.cpuStats = res[0].cpuStats; - element.precpuStats = res[0].precpuStats; - element.memoryStats = res[0].memoryStats; - element.networks = res[0].networks; - - dockerContainerProcesses(element.id).then(processes => { - element.processes = processes; - - l -= 1; - if (l === 0) { - if (callback) { callback(result); } - resolve(result); + if (configuration['strip-aliased']) { + [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion'] && alias.includes('-')) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; } - }); - // all done?? + delete argv[alias]; }); - }); - } else { - if (callback) { callback(result); } - resolve(result); } - }); - }); - }); -} - -docker.dockerAll = dockerAll; - -var virtualbox = {}; - -// @ts-check -// ================================================================================== -// virtualbox.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 14. Docker -// ---------------------------------------------------------------------------------- - -const os = require$$0$7; -const exec$4 = require$$1$2.exec; -const util$4 = util$j; - -function vboxInfo(callback) { - - // fallback - if only callback is given - let result = []; - return new Promise((resolve) => { - process.nextTick(() => { - try { - exec$4(util$4.getVboxmanage() + ' list vms --long', function (error, stdout) { - let parts = (os.EOL + stdout.toString()).split(os.EOL + 'Name:'); - parts.shift(); - parts.forEach(part => { - const lines = ('Name:' + part).split(os.EOL); - const state = util$4.getValue(lines, 'State'); - const running = state.startsWith('running'); - const runningSinceString = running ? state.replace('running (since ', '').replace(')', '').trim() : ''; - let runningSince = 0; - try { - if (running) { - const sinceDateObj = new Date(runningSinceString); - const offset = sinceDateObj.getTimezoneOffset(); - runningSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60; - } - } catch (e) { - util$4.noop(); + // Push argument into positional array, applying numeric coercion: + function pushPositional(arg) { + const maybeCoercedNumber = maybeCoerceNumber('_', arg); + if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { + argv._.push(maybeCoercedNumber); } - const stoppedSinceString = !running ? state.replace('powered off (since', '').replace(')', '').trim() : ''; - let stoppedSince = 0; - try { - if (!running) { - const sinceDateObj = new Date(stoppedSinceString); - const offset = sinceDateObj.getTimezoneOffset(); - stoppedSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60; - } - } catch (e) { - util$4.noop(); + } + // how many arguments should we consume, based + // on the nargs option? + function eatNargs(i, key, args, argAfterEqualSign) { + let ii; + let toEat = checkAllAliases(key, flags.nargs); + // NaN has a special meaning for the array type, indicating that one or + // more values are expected. + toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; + if (toEat === 0) { + if (!isUndefined(argAfterEqualSign)) { + error = Error(__('Argument unexpected for: %s', key)); + } + setArg(key, defaultValue(key)); + return i; } - result.push({ - id: util$4.getValue(lines, 'UUID'), - name: util$4.getValue(lines, 'Name'), - running, - started: runningSinceString, - runningSince, - stopped: stoppedSinceString, - stoppedSince, - guestOS: util$4.getValue(lines, 'Guest OS'), - hardwareUUID: util$4.getValue(lines, 'Hardware UUID'), - memory: parseInt(util$4.getValue(lines, 'Memory size', ' '), 10), - vram: parseInt(util$4.getValue(lines, 'VRAM size'), 10), - cpus: parseInt(util$4.getValue(lines, 'Number of CPUs'), 10), - cpuExepCap: util$4.getValue(lines, 'CPU exec cap'), - cpuProfile: util$4.getValue(lines, 'CPUProfile'), - chipset: util$4.getValue(lines, 'Chipset'), - firmware: util$4.getValue(lines, 'Firmware'), - pageFusion: util$4.getValue(lines, 'Page Fusion') === 'enabled', - configFile: util$4.getValue(lines, 'Config file'), - snapshotFolder: util$4.getValue(lines, 'Snapshot folder'), - logFolder: util$4.getValue(lines, 'Log folder'), - hpet: util$4.getValue(lines, 'HPET') === 'enabled', - pae: util$4.getValue(lines, 'PAE') === 'enabled', - longMode: util$4.getValue(lines, 'Long Mode') === 'enabled', - tripleFaultReset: util$4.getValue(lines, 'Triple Fault Reset') === 'enabled', - apic: util$4.getValue(lines, 'APIC') === 'enabled', - x2Apic: util$4.getValue(lines, 'X2APIC') === 'enabled', - acpi: util$4.getValue(lines, 'ACPI') === 'enabled', - ioApic: util$4.getValue(lines, 'IOAPIC') === 'enabled', - biosApicMode: util$4.getValue(lines, 'BIOS APIC mode'), - bootMenuMode: util$4.getValue(lines, 'Boot menu mode'), - bootDevice1: util$4.getValue(lines, 'Boot Device 1'), - bootDevice2: util$4.getValue(lines, 'Boot Device 2'), - bootDevice3: util$4.getValue(lines, 'Boot Device 3'), - bootDevice4: util$4.getValue(lines, 'Boot Device 4'), - timeOffset: util$4.getValue(lines, 'Time offset'), - rtc: util$4.getValue(lines, 'RTC'), - }); - }); - - if (callback) { callback(result); } - resolve(result); - }); - } catch (e) { - if (callback) { callback(result); } - resolve(result); - } - }); - }); -} - -virtualbox.vboxInfo = vboxInfo; - -var printer$1 = {}; - -// @ts-check -// ================================================================================== -// printers.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 15. printers -// ---------------------------------------------------------------------------------- - -const exec$3 = require$$1$2.exec; -const util$3 = util$j; - -let _platform$3 = process.platform; - -const _linux$3 = (_platform$3 === 'linux' || _platform$3 === 'android'); -const _darwin$3 = (_platform$3 === 'darwin'); -const _windows$3 = (_platform$3 === 'win32'); -const _freebsd$3 = (_platform$3 === 'freebsd'); -const _openbsd$3 = (_platform$3 === 'openbsd'); -const _netbsd$3 = (_platform$3 === 'netbsd'); -const _sunos$3 = (_platform$3 === 'sunos'); - -const winPrinterStatus = { - 1: 'Other', - 2: 'Unknown', - 3: 'Idle', - 4: 'Printing', - 5: 'Warmup', - 6: 'Stopped Printing', - 7: 'Offline', -}; - -function parseLinuxCupsHeader(lines) { - const result = {}; - if (lines && lines.length) { - if (lines[0].indexOf(' CUPS v') > 0) { - const parts = lines[0].split(' CUPS v'); - result.cupsVersion = parts[1]; - } - } - return result; -} - -function parseLinuxCupsPrinter(lines) { - const result = {}; - const printerId = util$3.getValue(lines, 'PrinterId', ' '); - result.id = printerId ? parseInt(printerId, 10) : null; - result.name = util$3.getValue(lines, 'Info', ' '); - result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : ''; - result.uri = util$3.getValue(lines, 'DeviceURI', ' '); - result.uuid = util$3.getValue(lines, 'UUID', ' '); - result.status = util$3.getValue(lines, 'State', ' '); - result.local = util$3.getValue(lines, 'Location', ' ').toLowerCase().startsWith('local'); - result.default = null; - result.shared = util$3.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes'); - - return result; -} - -function parseLinuxLpstatPrinter(lines, id) { - const result = {}; - result.id = id; - result.name = util$3.getValue(lines, 'Description', ':', true); - result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : ''; - result.uri = null; - result.uuid = null; - result.status = lines.length > 0 && lines[0] ? (lines[0].indexOf(' idle') > 0 ? 'idle' : (lines[0].indexOf(' printing') > 0 ? 'printing' : 'unknown')) : null; - result.local = util$3.getValue(lines, 'Location', ':', true).toLowerCase().startsWith('local'); - result.default = null; - result.shared = util$3.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes'); - - return result; -} - -function parseDarwinPrinters(printerObject, id) { - const result = {}; - const uriParts = printerObject.uri.split('/'); - result.id = id; - result.name = printerObject._name; - result.model = uriParts.length ? uriParts[uriParts.length - 1] : ''; - result.uri = printerObject.uri; - result.uuid = null; - result.status = printerObject.status; - result.local = printerObject.printserver === 'local'; - result.default = printerObject.default === 'yes'; - result.shared = printerObject.shared === 'yes'; - - return result; -} - -function parseWindowsPrinters(lines, id) { - const result = {}; - const status = parseInt(util$3.getValue(lines, 'PrinterStatus', ':'), 10); - - result.id = id; - result.name = util$3.getValue(lines, 'name', ':'); - result.model = util$3.getValue(lines, 'DriverName', ':'); - result.uri = null; - result.uuid = null; - result.status = winPrinterStatus[status] ? winPrinterStatus[status] : null; - result.local = util$3.getValue(lines, 'Local', ':').toUpperCase() === 'TRUE'; - result.default = util$3.getValue(lines, 'Default', ':').toUpperCase() === 'TRUE'; - result.shared = util$3.getValue(lines, 'Shared', ':').toUpperCase() === 'TRUE'; - - return result; -} - -function printer(callback) { - - return new Promise((resolve) => { - process.nextTick(() => { - let result = []; - if (_linux$3 || _freebsd$3 || _openbsd$3 || _netbsd$3) { - let cmd = 'cat /etc/cups/printers.conf 2>/dev/null'; - exec$3(cmd, function (error, stdout) { - // printers.conf - if (!error) { - const parts = stdout.toString().split(' 0) { + setArg(key, argAfterEqualSign); + consumed--; + } + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]); + } + return (i + consumed); + } + // if an option is an array, eat all non-hyphenated arguments + // following it... YUM! + // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] + function eatArray(i, key, args, argAfterEqualSign) { + let argsToSet = []; + let next = argAfterEqualSign || args[i + 1]; + // If both array and nargs are configured, enforce the nargs count: + const nargsCount = checkAllAliases(key, flags.nargs); + if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { + argsToSet.push(true); + } + else if (isUndefined(next) || + (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { + // for keys without value ==> argsToSet remains an empty [] + // set user default value, if available + if (defaults[key] !== undefined) { + const defVal = defaults[key]; + argsToSet = Array.isArray(defVal) ? defVal : [defVal]; + } + } + else { + // value in --option=value is eaten as is + if (!isUndefined(argAfterEqualSign)) { + argsToSet.push(processValue(key, argAfterEqualSign, true)); + } + for (let ii = i + 1; ii < args.length; ii++) { + if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || + (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) + break; + next = args[ii]; + if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) + break; + i = ii; + argsToSet.push(processValue(key, next, inputIsString)); } - }); - if (callback) { - callback(result); - } - resolve(result); - } else { - if (callback) { - callback(result); - } - resolve(result); } - } else { - if (callback) { - callback(result); + // If both array and nargs are configured, create an error if less than + // nargs positionals were found. NaN has special meaning, indicating + // that at least one value is required (more are okay). + if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || + (isNaN(nargsCount) && argsToSet.length === 0))) { + error = Error(__('Not enough arguments following: %s', key)); } - resolve(result); - } - }); - } - if (_darwin$3) { - let cmd = 'system_profiler SPPrintersDataType -json'; - exec$3(cmd, function (error, stdout) { - if (!error) { - try { - const outObj = JSON.parse(stdout.toString()); - if (outObj.SPPrintersDataType && outObj.SPPrintersDataType.length) { - for (let i = 0; i < outObj.SPPrintersDataType.length; i++) { - const printer = parseDarwinPrinters(outObj.SPPrintersDataType[i], i); - result.push(printer); + setArg(key, argsToSet); + return i; + } + function setArg(key, val, shouldStripQuotes = inputIsString) { + if (/-/.test(key) && configuration['camel-case-expansion']) { + const alias = key.split('.').map(function (prop) { + return camelCase(prop); + }).join('.'); + addNewAlias(key, alias); + } + const value = processValue(key, val, shouldStripQuotes); + const splitKey = key.split('.'); + setKey(argv, splitKey, value); + // handle populating aliases of the full key + if (flags.aliases[key]) { + flags.aliases[key].forEach(function (x) { + const keyProperties = x.split('.'); + setKey(argv, keyProperties, value); + }); + } + // handle populating aliases of the first element of the dot-notation key + if (splitKey.length > 1 && configuration['dot-notation']) { + (flags.aliases[splitKey[0]] || []).forEach(function (x) { + let keyProperties = x.split('.'); + // expand alias with nested objects in key + const a = [].concat(splitKey); + a.shift(); // nuke the old key. + keyProperties = keyProperties.concat(a); + // populate alias only if is not already an alias of the full key + // (already populated above) + if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { + setKey(argv, keyProperties, value); + } + }); + } + // Set normalize getter and setter when key is in 'normalize' but isn't an array + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + const keys = [key].concat(flags.aliases[key] || []); + keys.forEach(function (key) { + Object.defineProperty(argvReturn, key, { + enumerable: true, + get() { + return val; + }, + set(value) { + val = typeof value === 'string' ? mixin.normalize(value) : value; + } + }); + }); + } + } + function addNewAlias(key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias]; + newAliases[alias] = true; + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key); + } + } + function processValue(key, val, shouldStripQuotes) { + // strings may be quoted, clean this up as we assign values. + if (shouldStripQuotes) { + val = stripQuotes(val); + } + // handle parsing boolean arguments --foo=true --bar false. + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') + val = val === 'true'; + } + let value = Array.isArray(val) + ? val.map(function (v) { return maybeCoerceNumber(key, v); }) + : maybeCoerceNumber(key, val); + // increment a count given as arg (either no value or value parsed as boolean) + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment(); + } + // Set normalized value when key is in 'normalize' and in 'arrays' + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) + value = val.map((val) => { return mixin.normalize(val); }); + else + value = mixin.normalize(val); + } + return value; + } + function maybeCoerceNumber(key, value) { + if (!configuration['parse-positional-numbers'] && key === '_') + return value; + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { + const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { + value = Number(value); } - } - } catch (e) { - util$3.noop(); } - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_windows$3) { - util$3.powerShell('Get-CimInstance Win32_Printer | select PrinterStatus,Name,DriverName,Local,Default,Shared | fl').then((stdout, error) => { - if (!error) { - const parts = stdout.toString().split(/\n\s*\n/); - for (let i = 0; i < parts.length; i++) { - const printer = parseWindowsPrinters(parts[i].split('\n'), i); - if (printer.name || printer.model) { - result.push(printer); - } + return value; + } + // set args from config.json file, this should be + // applied last so that defaults can be applied. + function setConfig(argv) { + const configLookup = Object.create(null); + // expand defaults/aliases, in-case any happen to reference + // the config.json file. + applyDefaultsAndAliases(configLookup, flags.aliases, defaults); + Object.keys(flags.configs).forEach(function (configKey) { + const configPath = argv[configKey] || configLookup[configKey]; + if (configPath) { + try { + let config = null; + const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); + const resolveConfig = flags.configs[configKey]; + if (typeof resolveConfig === 'function') { + try { + config = resolveConfig(resolvedConfigPath); + } + catch (e) { + config = e; + } + if (config instanceof Error) { + error = config; + return; + } + } + else { + config = mixin.require(resolvedConfigPath); + } + setConfigObject(config); + } + catch (ex) { + // Deno will receive a PermissionDenied error if an attempt is + // made to load config without the --allow-read flag: + if (ex.name === 'PermissionDenied') + error = ex; + else if (argv[configKey]) + error = Error(__('Invalid JSON config file: %s', configPath)); + } + } + }); + } + // set args from config object. + // it recursively checks nested objects. + function setConfigObject(config, prev) { + Object.keys(config).forEach(function (key) { + const value = config[key]; + const fullKey = prev ? prev + '.' + key : key; + // if the value is an inner object and we have dot-notation + // enabled, treat inner objects in config the same as + // heavily nested dot notations (foo.bar.apple). + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + // if the value is an object but not an array, check nested object + setConfigObject(value, fullKey); + } + else { + // setting arguments via CLI takes precedence over + // values within the config file. + if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { + setArg(fullKey, value); + } + } + }); + } + // set all config objects passed in opts + function setConfigObjects() { + if (typeof configObjects !== 'undefined') { + configObjects.forEach(function (configObject) { + setConfigObject(configObject); + }); } - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_sunos$3) { - resolve(null); - } - }); - }); -} - -printer$1.printer = printer; - -var usb$1 = {}; - -// @ts-check -// ================================================================================== -// usb.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 16. usb -// ---------------------------------------------------------------------------------- - -const exec$2 = require$$1$2.exec; -const util$2 = util$j; - -let _platform$2 = process.platform; - -const _linux$2 = (_platform$2 === 'linux' || _platform$2 === 'android'); -const _darwin$2 = (_platform$2 === 'darwin'); -const _windows$2 = (_platform$2 === 'win32'); -const _freebsd$2 = (_platform$2 === 'freebsd'); -const _openbsd$2 = (_platform$2 === 'openbsd'); -const _netbsd$2 = (_platform$2 === 'netbsd'); -const _sunos$2 = (_platform$2 === 'sunos'); - -function getLinuxUsbType(type, name) { - let result = type; - const str = (name + ' ' + type).toLowerCase(); - if (str.indexOf('camera') >= 0) { result = 'Camera'; } - else if (str.indexOf('hub') >= 0) { result = 'Hub'; } - else if (str.indexOf('keybrd') >= 0) { result = 'Keyboard'; } - else if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; } - else if (str.indexOf('mouse') >= 0) { result = 'Mouse'; } - else if (str.indexOf('stora') >= 0) { result = 'Storage'; } - else if (str.indexOf('mic') >= 0) { result = 'Microphone'; } - else if (str.indexOf('headset') >= 0) { result = 'Audio'; } - else if (str.indexOf('audio') >= 0) { result = 'Audio'; } - - return result; -} - -function parseLinuxUsb(usb) { - const result = {}; - const lines = usb.split('\n'); - if (lines && lines.length && lines[0].indexOf('Device') >= 0) { - const parts = lines[0].split(' '); - result.bus = parseInt(parts[0], 10); - if (parts[2]) { - result.deviceId = parseInt(parts[2], 10); - } else { - result.deviceId = null; - } - } else { - result.bus = null; - result.deviceId = null; - } - const idVendor = util$2.getValue(lines, 'idVendor', ' ', true).trim(); - let vendorParts = idVendor.split(' '); - vendorParts.shift(); - const vendor = vendorParts.join(' '); - - const idProduct = util$2.getValue(lines, 'idProduct', ' ', true).trim(); - let productParts = idProduct.split(' '); - productParts.shift(); - const product = productParts.join(' '); - - const interfaceClass = util$2.getValue(lines, 'bInterfaceClass', ' ', true).trim(); - let interfaceClassParts = interfaceClass.split(' '); - interfaceClassParts.shift(); - const usbType = interfaceClassParts.join(' '); - - const iManufacturer = util$2.getValue(lines, 'iManufacturer', ' ', true).trim(); - let iManufacturerParts = iManufacturer.split(' '); - iManufacturerParts.shift(); - const manufacturer = iManufacturerParts.join(' '); - - result.id = (idVendor.startsWith('0x') ? idVendor.split(' ')[0].substr(2, 10) : '') + ':' + (idProduct.startsWith('0x') ? idProduct.split(' ')[0].substr(2, 10) : ''); - result.name = product; - result.type = getLinuxUsbType(usbType, product); - result.removable = null; - result.vendor = vendor; - result.manufacturer = manufacturer; - result.maxPower = util$2.getValue(lines, 'MaxPower', ' ', true); - result.serialNumber = null; - - return result; -} - -function getDarwinUsbType(name) { - let result = ''; - if (name.indexOf('camera') >= 0) { result = 'Camera'; } - else if (name.indexOf('touch bar') >= 0) { result = 'Touch Bar'; } - else if (name.indexOf('controller') >= 0) { result = 'Controller'; } - else if (name.indexOf('headset') >= 0) { result = 'Audio'; } - else if (name.indexOf('keyboard') >= 0) { result = 'Keyboard'; } - else if (name.indexOf('trackpad') >= 0) { result = 'Trackpad'; } - else if (name.indexOf('sensor') >= 0) { result = 'Sensor'; } - else if (name.indexOf('bthusb') >= 0) { result = 'Bluetooth'; } - else if (name.indexOf('bth') >= 0) { result = 'Bluetooth'; } - else if (name.indexOf('rfcomm') >= 0) { result = 'Bluetooth'; } - else if (name.indexOf('usbhub') >= 0) { result = 'Hub'; } - else if (name.indexOf(' hub') >= 0) { result = 'Hub'; } - else if (name.indexOf('mouse') >= 0) { result = 'Mouse'; } - else if (name.indexOf('mic') >= 0) { result = 'Microphone'; } - else if (name.indexOf('removable') >= 0) { result = 'Storage'; } - return result; -} - - -function parseDarwinUsb(usb, id) { - const result = {}; - result.id = id; - - usb = usb.replace(/ \|/g, ''); - usb = usb.trim(); - let lines = usb.split('\n'); - lines.shift(); - try { - for (let i = 0; i < lines.length; i++) { - lines[i] = lines[i].trim(); - lines[i] = lines[i].replace(/=/g, ':'); - if (lines[i] !== '{' && lines[i] !== '}' && lines[i + 1] && lines[i + 1].trim() !== '}') { - lines[i] = lines[i] + ','; - } - - lines[i] = lines[i].replace(':Yes,', ':"Yes",'); - lines[i] = lines[i].replace(': Yes,', ': "Yes",'); - lines[i] = lines[i].replace(': Yes', ': "Yes"'); - lines[i] = lines[i].replace(':No,', ':"No",'); - lines[i] = lines[i].replace(': No,', ': "No",'); - lines[i] = lines[i].replace(': No', ': "No"'); - - // In this case (("com.apple.developer.driverkit.transport.usb")) - lines[i] = lines[i].replace('((', '').replace('))', ''); - - // In case we have <923c11> we need make it "<923c11>" for correct JSON parse - const match = /<(\w+)>/.exec(lines[i]); - if (match) { - const number = match[0]; - lines[i] = lines[i].replace(number, `"${number}"`); - } - } - const usbObj = JSON.parse(lines.join('\n')); - const removableDrive = (usbObj['Built-In'] ? usbObj['Built-In'].toLowerCase() !== 'yes' : true) && (usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() === 'no' : true); - - result.bus = null; - result.deviceId = null; - result.id = usbObj['USB Address'] || null; - result.name = usbObj['kUSBProductString'] || usbObj['USB Product Name'] || null; - result.type = getDarwinUsbType((usbObj['kUSBProductString'] || usbObj['USB Product Name'] || '').toLowerCase() + (removableDrive ? ' removable' : '')); - result.removable = usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() || '' === 'no' : true; - result.vendor = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null; - result.manufacturer = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null; - - result.maxPower = null; - result.serialNumber = usbObj['kUSBSerialNumberString'] || null; - - if (result.name) { - return result; - } else { - return null; - } - } catch (e) { - return null; - } -} - -function getWindowsUsbTypeCreation(creationclass, name) { - let result = ''; - if (name.indexOf('storage') >= 0) { result = 'Storage'; } - else if (name.indexOf('speicher') >= 0) { result = 'Storage'; } - else if (creationclass.indexOf('usbhub') >= 0) { result = 'Hub'; } - else if (creationclass.indexOf('storage') >= 0) { result = 'Storage'; } - else if (creationclass.indexOf('usbcontroller') >= 0) { result = 'Controller'; } - else if (creationclass.indexOf('keyboard') >= 0) { result = 'Keyboard'; } - else if (creationclass.indexOf('pointing') >= 0) { result = 'Mouse'; } - else if (creationclass.indexOf('disk') >= 0) { result = 'Storage'; } - return result; -} - -function parseWindowsUsb(lines, id) { - const usbType = getWindowsUsbTypeCreation(util$2.getValue(lines, 'CreationClassName', ':').toLowerCase(), util$2.getValue(lines, 'name', ':').toLowerCase()); - - if (usbType) { - const result = {}; - result.bus = null; - result.deviceId = util$2.getValue(lines, 'deviceid', ':'); - result.id = id; - result.name = util$2.getValue(lines, 'name', ':'); - result.type = usbType; - result.removable = null; - result.vendor = null; - result.manufacturer = util$2.getValue(lines, 'Manufacturer', ':'); - result.maxPower = null; - result.serialNumber = null; - - return result; - } else { - return null; - } -} - -function usb(callback) { - - return new Promise((resolve) => { - process.nextTick(() => { - let result = []; - if (_linux$2) { - const cmd = 'export LC_ALL=C; lsusb -v 2>/dev/null; unset LC_ALL'; - exec$2(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) { - if (!error) { - const parts = ('\n\n' + stdout.toString()).split('\n\nBus '); - for (let i = 1; i < parts.length; i++) { - const usb = parseLinuxUsb(parts[i]); - result.push(usb); + } + function applyEnvVars(argv, configOnly) { + if (typeof envPrefix === 'undefined') + return; + const prefix = typeof envPrefix === 'string' ? envPrefix : ''; + const env = mixin.env(); + Object.keys(env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + // get array of nested keys and convert them to camel case + const keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length); + } + return camelCase(key); + }); + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { + setArg(keys.join('.'), env[envVar]); + } + } + }); + } + function applyCoercions(argv) { + let coerce; + const applied = new Set(); + Object.keys(argv).forEach(function (key) { + if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases + coerce = checkAllAliases(key, flags.coercions); + if (typeof coerce === 'function') { + try { + const value = maybeCoerceNumber(key, coerce(argv[key])); + ([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied.add(ali); + argv[ali] = value; + }); + } + catch (err) { + error = err; + } + } + } + }); + } + function setPlaceholderKeys(argv) { + flags.keys.forEach((key) => { + // don't set placeholder keys for dot notation options 'foo.bar'. + if (~key.indexOf('.')) + return; + if (typeof argv[key] === 'undefined') + argv[key] = undefined; + }); + return argv; + } + function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]); + if (canLog) + defaulted[key] = true; + (aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) + return; + setKey(obj, x.split('.'), defaults[key]); + }); + } + }); + } + function hasKey(obj, keys) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}); + }); + const key = keys[keys.length - 1]; + if (typeof o !== 'object') + return false; + else + return key in o; + } + function setKey(obj, keys, value) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + key = sanitizeKey(key); + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {}; + } + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + // ensure that o[key] is an array, and that the last item is an empty object. + if (Array.isArray(o[key])) { + o[key].push({}); + } + else { + o[key] = [o[key], {}]; + } + // we want to update the empty object at the end of the o[key] array, so set o to that object + o = o[key][o[key].length - 1]; + } + else { + o = o[key]; + } + }); + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + const key = sanitizeKey(keys[keys.length - 1]); + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); + const isValueArray = Array.isArray(value); + let duplicate = configuration['duplicate-arguments-array']; + // nargs has higher priority than duplicate + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true; + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined; + } } - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_darwin$2) { - let cmd = 'ioreg -p IOUSB -c AppleUSBRootHubDevice -w0 -l'; - exec$2(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) { - if (!error) { - const parts = (stdout.toString()).split(' +-o '); - for (let i = 1; i < parts.length; i++) { - const usb = parseDarwinUsb(parts[i]); - if (usb) { - result.push(usb); - } + if (value === increment()) { + o[key] = increment(o[key]); } - if (callback) { - callback(result); + else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); + } + else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value; + } + else { + o[key] = o[key].concat([value]); + } } - resolve(result); - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_windows$2) { - util$2.powerShell('Get-CimInstance CIM_LogicalDevice | where { $_.Description -match "USB"} | select Name,CreationClassName,DeviceId,Manufacturer | fl').then((stdout, error) => { - if (!error) { - const parts = stdout.toString().split(/\n\s*\n/); - for (let i = 0; i < parts.length; i++) { - const usb = parseWindowsUsb(parts[i].split('\n'), i); - if (usb) { - result.push(usb); - } + else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value]; } - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_sunos$2 || _freebsd$2 || _openbsd$2 || _netbsd$2) { - resolve(null); - } - }); - }); -} - -usb$1.usb = usb; - -var audio$1 = {}; - -// @ts-check -// ================================================================================== -// audio.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 16. audio -// ---------------------------------------------------------------------------------- - -const exec$1 = require$$1$2.exec; -const execSync$1 = require$$1$2.execSync; -const util$1 = util$j; - -let _platform$1 = process.platform; - -const _linux$1 = (_platform$1 === 'linux' || _platform$1 === 'android'); -const _darwin$1 = (_platform$1 === 'darwin'); -const _windows$1 = (_platform$1 === 'win32'); -const _freebsd$1 = (_platform$1 === 'freebsd'); -const _openbsd$1 = (_platform$1 === 'openbsd'); -const _netbsd$1 = (_platform$1 === 'netbsd'); -const _sunos$1 = (_platform$1 === 'sunos'); - -function parseAudioType(str, input, output) { - str = str.toLowerCase(); - let result = ''; - - if (str.indexOf('input') >= 0) { result = 'Microphone'; } - if (str.indexOf('display audio') >= 0) { result = 'Speaker'; } - if (str.indexOf('speak') >= 0) { result = 'Speaker'; } - if (str.indexOf('laut') >= 0) { result = 'Speaker'; } - if (str.indexOf('loud') >= 0) { result = 'Speaker'; } - if (str.indexOf('head') >= 0) { result = 'Headset'; } - if (str.indexOf('mic') >= 0) { result = 'Microphone'; } - if (str.indexOf('mikr') >= 0) { result = 'Microphone'; } - if (str.indexOf('phone') >= 0) { result = 'Phone'; } - if (str.indexOf('controll') >= 0) { result = 'Controller'; } - if (str.indexOf('line o') >= 0) { result = 'Line Out'; } - if (str.indexOf('digital o') >= 0) { result = 'Digital Out'; } - if (str.indexOf('smart sound technology') >= 0) { result = 'Digital Signal Processor'; } - if (str.indexOf('high definition audio') >= 0) { result = 'Sound Driver'; } - - if (!result && output) { - result = 'Speaker'; - } else if (!result && input) { - result = 'Microphone'; - } - return result; -} - - -function getLinuxAudioPci() { - let cmd = 'lspci -v 2>/dev/null'; - let result = []; - try { - const parts = execSync$1(cmd).toString().split('\n\n'); - parts.forEach(element => { - const lines = element.split('\n'); - if (lines && lines.length && lines[0].toLowerCase().indexOf('audio') >= 0) { - const audio = {}; - audio.slotId = lines[0].split(' ')[0]; - audio.driver = util$1.getValue(lines, 'Kernel driver in use', ':', true) || util$1.getValue(lines, 'Kernel modules', ':', true); - result.push(audio); - } - }); - return result; - } catch (e) { - return result; - } -} - -function parseLinuxAudioPciMM(lines, audioPCI) { - const result = {}; - const slotId = util$1.getValue(lines, 'Slot'); - - const pciMatch = audioPCI.filter(function (item) { return item.slotId === slotId; }); - - result.id = slotId; - result.name = util$1.getValue(lines, 'SDevice'); - result.manufacturer = util$1.getValue(lines, 'SVendor'); - result.revision = util$1.getValue(lines, 'Rev'); - result.driver = pciMatch && pciMatch.length === 1 && pciMatch[0].driver ? pciMatch[0].driver : ''; - result.default = null; - result.channel = 'PCIe'; - result.type = parseAudioType(result.name, null, null); - result.in = null; - result.out = null; - result.status = 'online'; - - return result; -} - -function parseDarwinChannel(str) { - let result = ''; - - if (str.indexOf('builtin') >= 0) { result = 'Built-In'; } - if (str.indexOf('extern') >= 0) { result = 'Audio-Jack'; } - if (str.indexOf('hdmi') >= 0) { result = 'HDMI'; } - if (str.indexOf('displayport') >= 0) { result = 'Display-Port'; } - if (str.indexOf('usb') >= 0) { result = 'USB'; } - if (str.indexOf('pci') >= 0) { result = 'PCIe'; } - - return result; -} - -function parseDarwinAudio(audioObject, id) { - const result = {}; - const channelStr = ((audioObject.coreaudio_device_transport || '') + ' ' + (audioObject._name || '')).toLowerCase(); - - result.id = id; - result.name = audioObject._name; - result.manufacturer = audioObject.coreaudio_device_manufacturer; - result.revision = null; - result.driver = null; - result.default = !!(audioObject.coreaudio_default_audio_input_device || '') || !!(audioObject.coreaudio_default_audio_output_device || ''); - result.channel = parseDarwinChannel(channelStr); - result.type = parseAudioType(result.name, !!(audioObject.coreaudio_device_input || ''), !!(audioObject.coreaudio_device_output || '')); - result.in = !!(audioObject.coreaudio_device_input || ''); - result.out = !!(audioObject.coreaudio_device_output || ''); - result.status = 'online'; - - return result; -} - -function parseWindowsAudio(lines) { - const result = {}; - const status = util$1.getValue(lines, 'StatusInfo', ':'); - - result.id = util$1.getValue(lines, 'DeviceID', ':'); // PNPDeviceID?? - result.name = util$1.getValue(lines, 'name', ':'); - result.manufacturer = util$1.getValue(lines, 'manufacturer', ':'); - result.revision = null; - result.driver = null; - result.default = null; - result.channel = null; - result.type = parseAudioType(result.name, null, null); - result.in = null; - result.out = null; - result.status = status; - - return result; -} - -function audio(callback) { - - return new Promise((resolve) => { - process.nextTick(() => { - let result = []; - if (_linux$1 || _freebsd$1 || _openbsd$1 || _netbsd$1) { - let cmd = 'lspci -vmm 2>/dev/null'; - exec$1(cmd, function (error, stdout) { - // PCI - if (!error) { - const audioPCI = getLinuxAudioPci(); - const parts = stdout.toString().split('\n\n'); - parts.forEach(element => { - const lines = element.split('\n'); - if (util$1.getValue(lines, 'class', ':', true).toLowerCase().indexOf('audio') >= 0) { - const audio = parseLinuxAudioPciMM(lines, audioPCI); - result.push(audio); - } - }); - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_darwin$1) { - let cmd = 'system_profiler SPAudioDataType -json'; - exec$1(cmd, function (error, stdout) { - if (!error) { - try { - const outObj = JSON.parse(stdout.toString()); - if (outObj.SPAudioDataType && outObj.SPAudioDataType.length && outObj.SPAudioDataType[0] && outObj.SPAudioDataType[0]['_items'] && outObj.SPAudioDataType[0]['_items'].length) { - for (let i = 0; i < outObj.SPAudioDataType[0]['_items'].length; i++) { - const audio = parseDarwinAudio(outObj.SPAudioDataType[0]['_items'][i], i); - result.push(audio); - } - } - } catch (e) { - util$1.noop(); + else if (duplicate && !(o[key] === undefined || + checkAllAliases(key, flags.counts) || + checkAllAliases(key, flags.bools))) { + o[key] = [o[key], value]; } - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_windows$1) { - util$1.powerShell('Get-CimInstance Win32_SoundDevice | select DeviceID,StatusInfo,Name,Manufacturer | fl').then((stdout, error) => { - if (!error) { - const parts = stdout.toString().split(/\n\s*\n/); - parts.forEach(element => { - const lines = element.split('\n'); - if (util$1.getValue(lines, 'name', ':')) { - result.push(parseWindowsAudio(lines)); - } - }); - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_sunos$1) { - resolve(null); - } - }); - }); -} - -audio$1.audio = audio; - -var bluetooth = {}; - -// @ts-check -// ================================================================================== -// audio.js -// ---------------------------------------------------------------------------------- -// Description: System Information - library -// for Node.js -// Copyright: (c) 2014 - 2023 -// Author: Sebastian Hildebrandt -// ---------------------------------------------------------------------------------- -// License: MIT -// ================================================================================== -// 17. bluetooth -// ---------------------------------------------------------------------------------- - -const exec = require$$1$2.exec; -const execSync = require$$1$2.execSync; -const path = require$$1$1; -const util = util$j; -const fs = require$$0$5; - -let _platform = process.platform; - -const _linux = (_platform === 'linux' || _platform === 'android'); -const _darwin = (_platform === 'darwin'); -const _windows = (_platform === 'win32'); -const _freebsd = (_platform === 'freebsd'); -const _openbsd = (_platform === 'openbsd'); -const _netbsd = (_platform === 'netbsd'); -const _sunos = (_platform === 'sunos'); - -function parseBluetoothType(str) { - let result = ''; - - if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; } - if (str.indexOf('mouse') >= 0) { result = 'Mouse'; } - if (str.indexOf('trackpad') >= 0) { result = 'Trackpad'; } - if (str.indexOf('speaker') >= 0) { result = 'Speaker'; } - if (str.indexOf('headset') >= 0) { result = 'Headset'; } - if (str.indexOf('phone') >= 0) { result = 'Phone'; } - if (str.indexOf('macbook') >= 0) { result = 'Computer'; } - if (str.indexOf('imac') >= 0) { result = 'Computer'; } - if (str.indexOf('ipad') >= 0) { result = 'Tablet'; } - if (str.indexOf('watch') >= 0) { result = 'Watch'; } - if (str.indexOf('headphone') >= 0) { result = 'Headset'; } - // to be continued ... - - return result; -} - -function parseBluetoothManufacturer(str) { - let result = str.split(' ')[0]; - str = str.toLowerCase(); - if (str.indexOf('apple') >= 0) { result = 'Apple'; } - if (str.indexOf('ipad') >= 0) { result = 'Apple'; } - if (str.indexOf('imac') >= 0) { result = 'Apple'; } - if (str.indexOf('iphone') >= 0) { result = 'Apple'; } - if (str.indexOf('magic mouse') >= 0) { result = 'Apple'; } - if (str.indexOf('magic track') >= 0) { result = 'Apple'; } - if (str.indexOf('macbook') >= 0) { result = 'Apple'; } - // to be continued ... - - return result; -} - -function parseLinuxBluetoothInfo(lines, macAddr1, macAddr2) { - const result = {}; - - result.device = null; - result.name = util.getValue(lines, 'name', '='); - result.manufacturer = null; - result.macDevice = macAddr1; - result.macHost = macAddr2; - result.batteryPercent = null; - result.type = parseBluetoothType(result.name.toLowerCase()); - result.connected = false; - - return result; -} - -function parseDarwinBluetoothDevices(bluetoothObject, macAddr2) { - const result = {}; - const typeStr = ((bluetoothObject.device_minorClassOfDevice_string || bluetoothObject.device_majorClassOfDevice_string || bluetoothObject.device_minorType || '') + (bluetoothObject.device_name || '')).toLowerCase(); - - result.device = bluetoothObject.device_services || ''; - result.name = bluetoothObject.device_name || ''; - result.manufacturer = bluetoothObject.device_manufacturer || parseBluetoothManufacturer(bluetoothObject.device_name || '') || ''; - result.macDevice = (bluetoothObject.device_addr || bluetoothObject.device_address || '').toLowerCase().replace(/-/g, ':'); - result.macHost = macAddr2; - result.batteryPercent = bluetoothObject.device_batteryPercent || null; - result.type = parseBluetoothType(typeStr); - result.connected = bluetoothObject.device_isconnected === 'attrib_Yes' || false; - - return result; -} - -function parseWindowsBluetooth(lines) { - const result = {}; - - result.device = null; - result.name = util.getValue(lines, 'name', ':'); - result.manufacturer = util.getValue(lines, 'manufacturer', ':'); - result.macDevice = null; - result.macHost = null; - result.batteryPercent = null; - result.type = parseBluetoothType(result.name.toLowerCase()); - result.connected = null; - - return result; -} - -function bluetoothDevices(callback) { - - return new Promise((resolve) => { - process.nextTick(() => { - let result = []; - if (_linux) { - // get files in /var/lib/bluetooth/ recursive - const btFiles = util.getFilesInPath('/var/lib/bluetooth/'); - btFiles.forEach((element) => { - const filename = path.basename(element); - const pathParts = element.split('/'); - const macAddr1 = pathParts.length >= 6 ? pathParts[pathParts.length - 2] : null; - const macAddr2 = pathParts.length >= 7 ? pathParts[pathParts.length - 3] : null; - if (filename === 'info') { - const infoFile = fs.readFileSync(element, { encoding: 'utf8' }).split('\n'); - result.push(parseLinuxBluetoothInfo(infoFile, macAddr1, macAddr2)); - } - }); - // determine "connected" with hcitool con - try { - const hdicon = execSync('hcitool con').toString().toLowerCase(); - for (let i = 0; i < result.length; i++) { - if (result[i].macDevice && result[i].macDevice.length > 10 && hdicon.indexOf(result[i].macDevice.toLowerCase()) >= 0) { - result[i].connected = true; + else { + o[key] = value; } - } - } catch (e) { - util.noop(); } - - if (callback) { - callback(result); + // extend the aliases list with inferred aliases. + function extendAliases(...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + // short-circuit if we've already added a key + // to the aliases array, for example it might + // exist in both 'opts.default' and 'opts.key'. + if (flags.aliases[key]) + return; + flags.aliases[key] = [].concat(aliases[key] || []); + // For "--option-name", also set argv.optionName + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + const c = camelCase(x); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + // For "--optionName", also set argv['option-name'] + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + const c = decamelize(x, '-'); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + }); + } + function checkAllAliases(key, flag) { + const toCheck = [].concat(flags.aliases[key] || [], key); + const keys = Object.keys(flag); + const setAlias = toCheck.find(key => keys.includes(key)); + return setAlias ? flag[setAlias] : false; } - resolve(result); - } - if (_darwin) { - let cmd = 'system_profiler SPBluetoothDataType -json'; - exec(cmd, function (error, stdout) { - if (!error) { - try { - const outObj = JSON.parse(stdout.toString()); - if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_title'] && outObj.SPBluetoothDataType[0]['device_title'].length) { - // missing: host BT Adapter macAddr () - let macAddr2 = null; - if (outObj.SPBluetoothDataType[0]['local_device_title'] && outObj.SPBluetoothDataType[0].local_device_title.general_address) { - macAddr2 = outObj.SPBluetoothDataType[0].local_device_title.general_address.toLowerCase().replace(/-/g, ':'); + function hasAnyFlag(key) { + const flagsKeys = Object.keys(flags); + const toCheck = [].concat(flagsKeys.map(k => flags[k])); + return toCheck.some(function (flag) { + return Array.isArray(flag) ? flag.includes(key) : flag[key]; + }); + } + function hasFlagsMatching(arg, ...patterns) { + const toCheck = [].concat(...patterns); + return toCheck.some(function (pattern) { + const match = arg.match(pattern); + return match && hasAnyFlag(match[1]); + }); + } + // based on a simplified version of the short flag group parsing logic + function hasAllShortFlags(arg) { + // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group + if (arg.match(negative) || !arg.match(/^-[^-]+/)) { + return false; + } + let hasAllFlags = true; + let next; + const letters = arg.slice(1).split(''); + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (!hasAnyFlag(letters[j])) { + hasAllFlags = false; + break; + } + if ((letters[j + 1] && letters[j + 1] === '=') || + next === '-' || + (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || + (letters[j + 1] && letters[j + 1].match(/\W/))) { + break; } - outObj.SPBluetoothDataType[0]['device_title'].forEach((element) => { - const obj = element; - const objKey = Object.keys(obj); - if (objKey && objKey.length === 1) { - const innerObject = obj[objKey[0]]; - innerObject.device_name = objKey[0]; - const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2); - result.push(bluetoothDevice); - } - }); - } - if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_connected'] && outObj.SPBluetoothDataType[0]['device_connected'].length) { - const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null; - outObj.SPBluetoothDataType[0]['device_connected'].forEach((element) => { - const obj = element; - const objKey = Object.keys(obj); - if (objKey && objKey.length === 1) { - const innerObject = obj[objKey[0]]; - innerObject.device_name = objKey[0]; - innerObject.device_isconnected = 'attrib_Yes'; - const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2); - result.push(bluetoothDevice); - } - }); - } - if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_not_connected'] && outObj.SPBluetoothDataType[0]['device_not_connected'].length) { - const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null; - outObj.SPBluetoothDataType[0]['device_not_connected'].forEach((element) => { - const obj = element; - const objKey = Object.keys(obj); - if (objKey && objKey.length === 1) { - const innerObject = obj[objKey[0]]; - innerObject.device_name = objKey[0]; - innerObject.device_isconnected = 'attrib_No'; - const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2); - result.push(bluetoothDevice); - } - }); - } - } catch (e) { - util.noop(); } - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_windows) { - util.powerShell('Get-CimInstance Win32_PNPEntity | select PNPClass, Name, Manufacturer | fl').then((stdout, error) => { - if (!error) { - const parts = stdout.toString().split(/\n\s*\n/); - parts.forEach((part) => { - if (util.getValue(part.split('\n'), 'PNPClass', ':') === 'Bluetooth') { - result.push(parseWindowsBluetooth(part.split('\n'))); - } - }); - } - if (callback) { - callback(result); - } - resolve(result); - }); - } - if (_freebsd || _netbsd || _openbsd || _sunos) { - resolve(null); - } - }); - }); -} - -bluetooth.bluetoothDevices = bluetoothDevices; - -(function (exports) { - // @ts-check - // ================================================================================== - // index.js - // ---------------------------------------------------------------------------------- - // Description: System Information - library - // for Node.js - // Copyright: (c) 2014 - 2023 - // Author: Sebastian Hildebrandt - // ---------------------------------------------------------------------------------- - // Contributors: Guillaume Legrain (https://github.com/glegrain) - // Riccardo Novaglia (https://github.com/richy24) - // Quentin Busuttil (https://github.com/Buzut) - // Lapsio (https://github.com/lapsio) - // csy (https://github.com/csy1983) - // ---------------------------------------------------------------------------------- - // License: MIT - // ================================================================================== - - // ---------------------------------------------------------------------------------- - // Dependencies - // ---------------------------------------------------------------------------------- - - const lib_version = require$$0.version; - const util = util$j; - const system = system$1; - const osInfo = osinfo; - const cpu = cpu$1; - const memory$1 = memory; - const battery$1 = battery; - const graphics = graphics$1; - const filesystem$1 = filesystem; - const network$1 = network; - const wifi$1 = wifi; - const processes = processes$1; - const users = users$1; - const internet$1 = internet; - const docker$1 = docker; - const vbox = virtualbox; - const printer = printer$1; - const usb = usb$1; - const audio = audio$1; - const bluetooth$1 = bluetooth; - - let _platform = process.platform; - const _windows = (_platform === 'win32'); - const _freebsd = (_platform === 'freebsd'); - const _openbsd = (_platform === 'openbsd'); - const _netbsd = (_platform === 'netbsd'); - const _sunos = (_platform === 'sunos'); - - // ---------------------------------------------------------------------------------- - // init - // ---------------------------------------------------------------------------------- - - if (_windows) { - util.getCodepage(); - } - - // ---------------------------------------------------------------------------------- - // General - // ---------------------------------------------------------------------------------- - - function version() { - return lib_version; - } - - // ---------------------------------------------------------------------------------- - // Get static and dynamic data (all) - // ---------------------------------------------------------------------------------- - - // -------------------------- - // get static data - they should not change until restarted - - function getStaticData(callback) { - - return new Promise((resolve) => { - process.nextTick(() => { - - let data = {}; - - data.version = version(); - - Promise.all([ - system.system(), - system.bios(), - system.baseboard(), - system.chassis(), - osInfo.osInfo(), - osInfo.uuid(), - osInfo.versions(), - cpu.cpu(), - cpu.cpuFlags(), - graphics.graphics(), - network$1.networkInterfaces(), - memory$1.memLayout(), - filesystem$1.diskLayout() - ]).then((res) => { - data.system = res[0]; - data.bios = res[1]; - data.baseboard = res[2]; - data.chassis = res[3]; - data.os = res[4]; - data.uuid = res[5]; - data.versions = res[6]; - data.cpu = res[7]; - data.cpu.flags = res[8]; - data.graphics = res[9]; - data.net = res[10]; - data.memLayout = res[11]; - data.diskLayout = res[12]; - if (callback) { callback(data); } - resolve(data); - }); - }); - }); - } - - - // -------------------------- - // get all dynamic data - e.g. for monitoring agents - // may take some seconds to get all data - // -------------------------- - // 2 additional parameters needed - // - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql" - // - iface: define network interface for which you like to monitor network speed e.g. "eth0" - - function getDynamicData(srv, iface, callback) { - - if (util.isFunction(iface)) { - callback = iface; - iface = ''; - } - if (util.isFunction(srv)) { - callback = srv; - srv = ''; - } - - return new Promise((resolve) => { - process.nextTick(() => { - - iface = iface || network$1.getDefaultNetworkInterface(); - srv = srv || ''; - - // use closure to track Æ’ completion - let functionProcessed = (function () { - let totalFunctions = 15; - if (_windows) { totalFunctions = 13; } - if (_freebsd || _openbsd || _netbsd) { totalFunctions = 11; } - if (_sunos) { totalFunctions = 6; } - - return function () { - if (--totalFunctions === 0) { - if (callback) { - callback(data); - } - resolve(data); - } - }; - })(); - - let data = {}; - - // get time - data.time = osInfo.time(); - - /** - * @namespace - * @property {Object} versions - * @property {string} versions.node - * @property {string} versions.v8 - */ - data.node = process.versions.node; - data.v8 = process.versions.v8; - - cpu.cpuCurrentSpeed().then((res) => { - data.cpuCurrentSpeed = res; - functionProcessed(); - }); - - users.users().then((res) => { - data.users = res; - functionProcessed(); - }); - - processes.processes().then((res) => { - data.processes = res; - functionProcessed(); - }); - - cpu.currentLoad().then((res) => { - data.currentLoad = res; - functionProcessed(); - }); - - if (!_sunos) { - cpu.cpuTemperature().then((res) => { - data.temp = res; - functionProcessed(); - }); - } - - if (!_openbsd && !_freebsd && !_netbsd && !_sunos) { - network$1.networkStats(iface).then((res) => { - data.networkStats = res; - functionProcessed(); - }); - } - - if (!_sunos) { - network$1.networkConnections().then((res) => { - data.networkConnections = res; - functionProcessed(); - }); - } - - memory$1.mem().then((res) => { - data.mem = res; - functionProcessed(); - }); - - if (!_sunos) { - battery$1().then((res) => { - data.battery = res; - functionProcessed(); - }); - } - - if (!_sunos) { - processes.services(srv).then((res) => { - data.services = res; - functionProcessed(); - }); - } - - if (!_sunos) { - filesystem$1.fsSize().then((res) => { - data.fsSize = res; - functionProcessed(); - }); - } - - if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) { - filesystem$1.fsStats().then((res) => { - data.fsStats = res; - functionProcessed(); - }); - } - - if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) { - filesystem$1.disksIO().then((res) => { - data.disksIO = res; - functionProcessed(); - }); - } - - if (!_openbsd && !_freebsd && !_netbsd && !_sunos) { - wifi$1.wifiNetworks().then((res) => { - data.wifiNetworks = res; - functionProcessed(); - }); - } - - internet$1.inetLatency().then((res) => { - data.inetLatency = res; - functionProcessed(); - }); - }); - }); - } - - // -------------------------- - // get all data at once - // -------------------------- - // 2 additional parameters needed - // - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql" - // - iface: define network interface for which you like to monitor network speed e.g. "eth0" - - function getAllData(srv, iface, callback) { - - return new Promise((resolve) => { - process.nextTick(() => { - let data = {}; + return hasAllFlags; + } + function isUnknownOptionAsArg(arg) { + return configuration['unknown-options-as-args'] && isUnknownOption(arg); + } + function isUnknownOption(arg) { + arg = arg.replace(/^-{3,}/, '--'); + // ignore negative numbers + if (arg.match(negative)) { + return false; + } + // if this is a short option group and all of them are configured, it isn't unknown + if (hasAllShortFlags(arg)) { + return false; + } + // e.g. '--count=2' + const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; + // e.g. '-a' or '--arg' + const normalFlag = /^-+([^=]+?)$/; + // e.g. '-a-' + const flagEndingInHyphen = /^-+([^=]+?)-$/; + // e.g. '-abc123' + const flagEndingInDigits = /^-+([^=]+?\d+)$/; + // e.g. '-a/usr/local' + const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; + // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method + return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); + } + // make a best effort to pick a default value + // for an option based on name and type. + function defaultValue(key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key]; + } + else { + return defaultForType(guessType(key)); + } + } + // return a default value, given the type of a flag., + function defaultForType(type) { + const def = { + [DefaultValuesForTypeKey.BOOLEAN]: true, + [DefaultValuesForTypeKey.STRING]: '', + [DefaultValuesForTypeKey.NUMBER]: undefined, + [DefaultValuesForTypeKey.ARRAY]: [] + }; + return def[type]; + } + // given a flag, enforce a default type. + function guessType(key) { + let type = DefaultValuesForTypeKey.BOOLEAN; + if (checkAllAliases(key, flags.strings)) + type = DefaultValuesForTypeKey.STRING; + else if (checkAllAliases(key, flags.numbers)) + type = DefaultValuesForTypeKey.NUMBER; + else if (checkAllAliases(key, flags.bools)) + type = DefaultValuesForTypeKey.BOOLEAN; + else if (checkAllAliases(key, flags.arrays)) + type = DefaultValuesForTypeKey.ARRAY; + return type; + } + function isUndefined(num) { + return num === undefined; + } + // check user configuration settings for inconsistencies + function checkConfiguration() { + // count keys should not be set as array/narg + Object.keys(flags.counts).find(key => { + if (checkAllAliases(key, flags.arrays)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); + return true; + } + else if (checkAllAliases(key, flags.nargs)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); + return true; + } + return false; + }); + } + return { + aliases: Object.assign({}, flags.aliases), + argv: Object.assign(argvReturn, argv), + configuration: configuration, + defaulted: Object.assign({}, defaulted), + error: error, + newAliases: Object.assign({}, newAliases) + }; + } +} +// if any aliases reference each other, we should +// merge them together. +function combineAliases(aliases) { + const aliasArrays = []; + const combined = Object.create(null); + let change = true; + // turn alias lookup hash {key: ['alias1', 'alias2']} into + // a simple array ['key', 'alias1', 'alias2'] + Object.keys(aliases).forEach(function (key) { + aliasArrays.push([].concat(aliases[key], key)); + }); + // combine arrays until zero changes are + // made in an iteration. + while (change) { + change = false; + for (let i = 0; i < aliasArrays.length; i++) { + for (let ii = i + 1; ii < aliasArrays.length; ii++) { + const intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1; + }); + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); + aliasArrays.splice(ii, 1); + change = true; + break; + } + } + } + } + // map arrays back to the hash-lookup (de-dupe while + // we're at it). + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i; + }); + const lastAlias = aliasArray.pop(); + if (lastAlias !== undefined && typeof lastAlias === 'string') { + combined[lastAlias] = aliasArray; + } + }); + return combined; +} +// this function should only be called when a count is given as an arg +// it is NOT called to set a default value +// thus we can start the count at 1 instead of 0 +function increment(orig) { + return orig !== undefined ? orig + 1 : 1; +} +// TODO(bcoe): in the next major version of yargs, switch to +// Object.create(null) for dot notation: +function sanitizeKey(key) { + if (key === '__proto__') + return '___proto___'; + return key; +} +function stripQuotes(val) { + return (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0]) + ? val.substring(1, val.length - 1) + : val; +} - if (iface && util.isFunction(iface) && !callback) { - callback = iface; - iface = ''; - } +/** + * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js + * CJS and ESM environments. + * + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +var _a, _b, _c; +// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our +// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only. +const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) + ? Number(process.env.YARGS_MIN_NODE_VERSION) + : 12; +const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); +if (nodeVersion) { + const major = Number(nodeVersion.match(/^([^.]+)/)[1]); + if (major < minNodeVersion) { + throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); + } +} +// Creates a yargs-parser instance using Node.js standard libraries: +const env = process ? process.env : {}; +const parser = new YargsParser({ + cwd: process.cwd, + env: () => { + return env; + }, + format, + normalize, + resolve, + // TODO: figure out a way to combine ESM and CJS coverage, such that + // we can exercise all the lines below: + require: (path) => { + if (typeof require !== 'undefined') { + return require(path); + } + else if (path.match(/\.json$/)) { + // Addresses: https://github.com/yargs/yargs/issues/2040 + return JSON.parse(readFileSync$1(path, 'utf8')); + } + else { + throw Error('only .json config files are supported in ESM'); + } + } +}); +const yargsParser = function Parser(args, opts) { + const result = parser.parse(args.slice(), opts); + return result.argv; +}; +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts); +}; +yargsParser.camelCase = camelCase; +yargsParser.decamelize = decamelize; +yargsParser.looksLikeNumber = looksLikeNumber; - if (srv && util.isFunction(srv) && !iface && !callback) { - callback = srv; - srv = ''; - iface = ''; - } +function getProcessArgvBinIndex() { + if (isBundledElectronApp()) + return 0; + return 1; +} +function isBundledElectronApp() { + return isElectronApp() && !process.defaultApp; +} +function isElectronApp() { + return !!process.versions.electron; +} +function hideBin(argv) { + return argv.slice(getProcessArgvBinIndex() + 1); +} +function getProcessArgvBin() { + return process.argv[getProcessArgvBinIndex()]; +} - getStaticData().then((res) => { - data = res; - getDynamicData(srv, iface).then((res) => { - for (let key in res) { - if ({}.hasOwnProperty.call(res, key)) { - data[key] = res[key]; - } - } - if (callback) { callback(data); } - resolve(data); - }); - }); - }); - }); - } +class YError extends Error { + constructor(msg) { + super(msg || 'yargs error'); + this.name = 'YError'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, YError); + } + } +} - function get(valueObject, callback) { - return new Promise((resolve) => { - process.nextTick(() => { - const allPromises = Object.keys(valueObject) - .filter(func => ({}.hasOwnProperty.call(exports, func))) - .map(func => { - const params = valueObject[func].substring(valueObject[func].lastIndexOf('(') + 1, valueObject[func].lastIndexOf(')')); - let funcWithoutParams = func.indexOf(')') >= 0 ? func.split(')')[1].trim() : func; - funcWithoutParams = func.indexOf('|') >= 0 ? func.split('|')[0].trim() : funcWithoutParams; - if (params) { - return exports[funcWithoutParams](params); - } else { - return exports[funcWithoutParams](''); - } - }); +var shim$3 = { + fs: { + readFileSync: readFileSync$1, + writeFile: writeFile$1 + }, + format, + resolve, + exists: (file) => { + try { + return statSync(file).isFile(); + } + catch (err) { + return false; + } + } +}; - Promise.all(allPromises).then((data) => { - const result = {}; - let i = 0; - for (let key in valueObject) { - if ({}.hasOwnProperty.call(valueObject, key) && {}.hasOwnProperty.call(exports, key) && data.length > i) { - if (valueObject[key] === '*' || valueObject[key] === 'all') { - result[key] = data[i]; - } else { - let keys = valueObject[key]; - let filter = ''; - let filterParts = []; - // remove params - if (keys.indexOf(')') >= 0) { - keys = keys.split(')')[1].trim(); - } - // extract filter and remove it from keys - if (keys.indexOf('|') >= 0) { - filter = keys.split('|')[1].trim(); - filterParts = filter.split(':'); +let shim$2; +class Y18N { + constructor(opts) { + // configurable options. + opts = opts || {}; + this.directory = opts.directory || './locales'; + this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true; + this.locale = opts.locale || 'en'; + this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true; + // internal stuff. + this.cache = Object.create(null); + this.writeQueue = []; + } + __(...args) { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral(arguments[0], ...arguments); + } + const str = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + cb = cb || function () { }; // noop. + if (!this.cache[this.locale]) + this._readLocaleFile(); + // we've observed a new string, update the language file. + if (!this.cache[this.locale][str] && this.updateFiles) { + this.cache[this.locale][str] = str; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + return shim$2.format.apply(shim$2.format, [this.cache[this.locale][str] || str].concat(args)); + } + __n() { + const args = Array.prototype.slice.call(arguments); + const singular = args.shift(); + const plural = args.shift(); + const quantity = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + if (!this.cache[this.locale]) + this._readLocaleFile(); + let str = quantity === 1 ? singular : plural; + if (this.cache[this.locale][singular]) { + const entry = this.cache[this.locale][singular]; + str = entry[quantity === 1 ? 'one' : 'other']; + } + // we've observed a new string, update the language file. + if (!this.cache[this.locale][singular] && this.updateFiles) { + this.cache[this.locale][singular] = { + one: singular, + other: plural + }; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + // if a %d placeholder is provided, add quantity + // to the arguments expanded by util.format. + const values = [str]; + if (~str.indexOf('%d')) + values.push(quantity); + return shim$2.format.apply(shim$2.format, values.concat(args)); + } + setLocale(locale) { + this.locale = locale; + } + getLocale() { + return this.locale; + } + updateLocale(obj) { + if (!this.cache[this.locale]) + this._readLocaleFile(); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + this.cache[this.locale][key] = obj[key]; + } + } + } + _taggedLiteral(parts, ...args) { + let str = ''; + parts.forEach(function (part, i) { + const arg = args[i + 1]; + str += part; + if (typeof arg !== 'undefined') { + str += '%s'; + } + }); + return this.__.apply(this, [str].concat([].slice.call(args, 1))); + } + _enqueueWrite(work) { + this.writeQueue.push(work); + if (this.writeQueue.length === 1) + this._processWriteQueue(); + } + _processWriteQueue() { + const _this = this; + const work = this.writeQueue[0]; + // destructure the enqueued work. + const directory = work.directory; + const locale = work.locale; + const cb = work.cb; + const languageFile = this._resolveLocaleFile(directory, locale); + const serializedLocale = JSON.stringify(this.cache[locale], null, 2); + shim$2.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { + _this.writeQueue.shift(); + if (_this.writeQueue.length > 0) + _this._processWriteQueue(); + cb(err); + }); + } + _readLocaleFile() { + let localeLookup = {}; + const languageFile = this._resolveLocaleFile(this.directory, this.locale); + try { + // When using a bundler such as webpack, readFileSync may not be defined: + if (shim$2.fs.readFileSync) { + localeLookup = JSON.parse(shim$2.fs.readFileSync(languageFile, 'utf-8')); + } + } + catch (err) { + if (err instanceof SyntaxError) { + err.message = 'syntax error in ' + languageFile; + } + if (err.code === 'ENOENT') + localeLookup = {}; + else + throw err; + } + this.cache[this.locale] = localeLookup; + } + _resolveLocaleFile(directory, locale) { + let file = shim$2.resolve(directory, './', locale + '.json'); + if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { + // attempt fallback to language only + const languageFile = shim$2.resolve(directory, './', locale.split('_')[0] + '.json'); + if (this._fileExistsSync(languageFile)) + file = languageFile; + } + return file; + } + _fileExistsSync(file) { + return shim$2.exists(file); + } +} +function y18n$1(opts, _shim) { + shim$2 = _shim; + const y18n = new Y18N(opts); + return { + __: y18n.__.bind(y18n), + __n: y18n.__n.bind(y18n), + setLocale: y18n.setLocale.bind(y18n), + getLocale: y18n.getLocale.bind(y18n), + updateLocale: y18n.updateLocale.bind(y18n), + locale: y18n.locale + }; +} - keys = keys.split('|')[0].trim(); - } - keys = keys.replace(/,/g, ' ').replace(/ +/g, ' ').split(' '); - if (data[i]) { - if (Array.isArray(data[i])) { - // result is in an array, go through all elements of array and pick only the right ones - const partialArray = []; - data[i].forEach(element => { - let partialRes = {}; - if (keys.length === 1 && (keys[0] === '*' || keys[0] === 'all')) { - partialRes = element; - } else { - keys.forEach(k => { - if ({}.hasOwnProperty.call(element, k)) { - partialRes[k] = element[k]; - } - }); - } - // if there is a filter, then just take those elements - if (filter && filterParts.length === 2) { - if ({}.hasOwnProperty.call(partialRes, filterParts[0].trim())) { - const val = partialRes[filterParts[0].trim()]; - if (typeof val == 'number') { - if (val === parseFloat(filterParts[1].trim())) { - partialArray.push(partialRes); - } - } else if (typeof val == 'string') { - if (val.toLowerCase() === filterParts[1].trim().toLowerCase()) { - partialArray.push(partialRes); - } - } - } - } else { - partialArray.push(partialRes); - } +const y18n = (opts) => { + return y18n$1(opts, shim$3) +}; - }); - result[key] = partialArray; - } else { - const partialRes = {}; - keys.forEach(k => { - if ({}.hasOwnProperty.call(data[i], k)) { - partialRes[k] = data[i][k]; - } - }); - result[key] = partialRes; - } - } else { - result[key] = {}; - } - } - i++; - } - } - if (callback) { callback(result); } - resolve(result); - }); - }); - }); - } +const REQUIRE_ERROR = 'require is not supported by ESM'; +const REQUIRE_DIRECTORY_ERROR = 'loading a directory of commands is not supported yet for ESM'; - function observe(valueObject, interval, callback) { - let _data = null; +let __dirname; +try { + __dirname = fileURLToPath(import.meta.url); +} catch (e) { + __dirname = process.cwd(); +} +const mainFilename = __dirname.substring(0, __dirname.lastIndexOf('node_modules')); - const result = setInterval(() => { - get(valueObject).then((data) => { - if (JSON.stringify(_data) !== JSON.stringify(data)) { - _data = Object.assign({}, data); - callback(data); - } - }); - }, interval); - return result; - } +var shim$1 = { + assert: { + notStrictEqual, + strictEqual + }, + cliui: ui, + findUp: escalade, + getEnv: (key) => { + return process.env[key] + }, + inspect, + getCallerFile: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR) + }, + getProcessArgvBin, + mainFilename: mainFilename || process.cwd(), + Parser: yargsParser, + path: { + basename, + dirname, + extname, + relative, + resolve + }, + process: { + argv: () => process.argv, + cwd: process.cwd, + emitWarning: (warning, type) => process.emitWarning(warning, type), + execPath: () => process.execPath, + exit: process.exit, + nextTick: process.nextTick, + stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null + }, + readFileSync: readFileSync$1, + require: () => { + throw new YError(REQUIRE_ERROR) + }, + requireDirectory: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR) + }, + stringWidth: (str) => { + return [...str].length + }, + y18n: y18n({ + directory: resolve(__dirname, '../../../locales'), + updateFiles: false + }) +}; - // ---------------------------------------------------------------------------------- - // export all libs - // ---------------------------------------------------------------------------------- +function assertNotStrictEqual(actual, expected, shim, message) { + shim.assert.notStrictEqual(actual, expected, message); +} +function assertSingleKey(actual, shim) { + shim.assert.strictEqual(typeof actual, 'string'); +} +function objectKeys(object) { + return Object.keys(object); +} - exports.version = version; - exports.system = system.system; - exports.bios = system.bios; - exports.baseboard = system.baseboard; - exports.chassis = system.chassis; +function isPromise(maybePromise) { + return (!!maybePromise && + !!maybePromise.then && + typeof maybePromise.then === 'function'); +} - exports.time = osInfo.time; - exports.osInfo = osInfo.osInfo; - exports.versions = osInfo.versions; - exports.shell = osInfo.shell; - exports.uuid = osInfo.uuid; +function parseCommand(cmd) { + const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' '); + const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/); + const bregex = /\.*[\][<>]/g; + const firstCommand = splitCommand.shift(); + if (!firstCommand) + throw new Error(`No command found in: ${cmd}`); + const parsedCommand = { + cmd: firstCommand.replace(bregex, ''), + demanded: [], + optional: [], + }; + splitCommand.forEach((cmd, i) => { + let variadic = false; + cmd = cmd.replace(/\s/g, ''); + if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) + variadic = true; + if (/^\[/.test(cmd)) { + parsedCommand.optional.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + else { + parsedCommand.demanded.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + }); + return parsedCommand; +} - exports.cpu = cpu.cpu; - exports.cpuFlags = cpu.cpuFlags; - exports.cpuCache = cpu.cpuCache; - exports.cpuCurrentSpeed = cpu.cpuCurrentSpeed; - exports.cpuTemperature = cpu.cpuTemperature; - exports.currentLoad = cpu.currentLoad; - exports.fullLoad = cpu.fullLoad; +const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']; +function argsert(arg1, arg2, arg3) { + function parseArgs() { + return typeof arg1 === 'object' + ? [{ demanded: [], optional: [] }, arg1, arg2] + : [ + parseCommand(`cmd ${arg1}`), + arg2, + arg3, + ]; + } + try { + let position = 0; + const [parsed, callerArguments, _length] = parseArgs(); + const args = [].slice.call(callerArguments); + while (args.length && args[args.length - 1] === undefined) + args.pop(); + const length = _length || args.length; + if (length < parsed.demanded.length) { + throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`); + } + const totalCommands = parsed.demanded.length + parsed.optional.length; + if (length > totalCommands) { + throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`); + } + parsed.demanded.forEach(demanded => { + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, demanded.cmd, position); + position += 1; + }); + parsed.optional.forEach(optional => { + if (args.length === 0) + return; + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, optional.cmd, position); + position += 1; + }); + } + catch (err) { + console.warn(err.stack); + } +} +function guessType(arg) { + if (Array.isArray(arg)) { + return 'array'; + } + else if (arg === null) { + return 'null'; + } + return typeof arg; +} +function argumentTypeError(observedType, allowedTypes, position) { + throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`); +} - exports.mem = memory$1.mem; - exports.memLayout = memory$1.memLayout; +class GlobalMiddleware { + constructor(yargs) { + this.globalMiddleware = []; + this.frozens = []; + this.yargs = yargs; + } + addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) { + argsert(' [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length); + if (Array.isArray(callback)) { + for (let i = 0; i < callback.length; i++) { + if (typeof callback[i] !== 'function') { + throw Error('middleware must be a function'); + } + const m = callback[i]; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + } + Array.prototype.push.apply(this.globalMiddleware, callback); + } + else if (typeof callback === 'function') { + const m = callback; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + m.mutates = mutates; + this.globalMiddleware.push(callback); + } + return this.yargs; + } + addCoerceMiddleware(callback, option) { + const aliases = this.yargs.getAliases(); + this.globalMiddleware = this.globalMiddleware.filter(m => { + const toCheck = [...(aliases[option] || []), option]; + if (!m.option) + return true; + else + return !toCheck.includes(m.option); + }); + callback.option = option; + return this.addMiddleware(callback, true, true, true); + } + getMiddleware() { + return this.globalMiddleware; + } + freeze() { + this.frozens.push([...this.globalMiddleware]); + } + unfreeze() { + const frozen = this.frozens.pop(); + if (frozen !== undefined) + this.globalMiddleware = frozen; + } + reset() { + this.globalMiddleware = this.globalMiddleware.filter(m => m.global); + } +} +function commandMiddlewareFactory(commandMiddleware) { + if (!commandMiddleware) + return []; + return commandMiddleware.map(middleware => { + middleware.applyBeforeValidation = false; + return middleware; + }); +} +function applyMiddleware(argv, yargs, middlewares, beforeValidation) { + return middlewares.reduce((acc, middleware) => { + if (middleware.applyBeforeValidation !== beforeValidation) { + return acc; + } + if (middleware.mutates) { + if (middleware.applied) + return acc; + middleware.applied = true; + } + if (isPromise(acc)) { + return acc + .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)])) + .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj)); + } + else { + const result = middleware(acc, yargs); + return isPromise(result) + ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) + : Object.assign(acc, result); + } + }, argv); +} - exports.battery = battery$1; +function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => { + throw err; +}) { + try { + const result = isFunction(getResult) ? getResult() : getResult; + return isPromise(result) + ? result.then((result) => resultHandler(result)) + : resultHandler(result); + } + catch (err) { + return errorHandler(err); + } +} +function isFunction(arg) { + return typeof arg === 'function'; +} - exports.graphics = graphics.graphics; +function whichModule(exported) { + if (typeof require === 'undefined') + return null; + for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) { + mod = require.cache[files[i]]; + if (mod.exports === exported) + return mod; + } + return null; +} - exports.fsSize = filesystem$1.fsSize; - exports.fsOpenFiles = filesystem$1.fsOpenFiles; - exports.blockDevices = filesystem$1.blockDevices; - exports.fsStats = filesystem$1.fsStats; - exports.disksIO = filesystem$1.disksIO; - exports.diskLayout = filesystem$1.diskLayout; +const DEFAULT_MARKER = /(^\*)|(^\$0)/; +class CommandInstance { + constructor(usage, validation, globalMiddleware, shim) { + this.requireCache = new Set(); + this.handlers = {}; + this.aliasMap = {}; + this.frozens = []; + this.shim = shim; + this.usage = usage; + this.globalMiddleware = globalMiddleware; + this.validation = validation; + } + addDirectory(dir, req, callerFile, opts) { + opts = opts || {}; + if (typeof opts.recurse !== 'boolean') + opts.recurse = false; + if (!Array.isArray(opts.extensions)) + opts.extensions = ['js']; + const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o; + opts.visit = (obj, joined, filename) => { + const visited = parentVisit(obj, joined, filename); + if (visited) { + if (this.requireCache.has(joined)) + return visited; + else + this.requireCache.add(joined); + this.addHandler(visited); + } + return visited; + }; + this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts); + } + addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) { + let aliases = []; + const middlewares = commandMiddlewareFactory(commandMiddleware); + handler = handler || (() => { }); + if (Array.isArray(cmd)) { + if (isCommandAndAliases(cmd)) { + [cmd, ...aliases] = cmd; + } + else { + for (const command of cmd) { + this.addHandler(command); + } + } + } + else if (isCommandHandlerDefinition(cmd)) { + let command = Array.isArray(cmd.command) || typeof cmd.command === 'string' + ? cmd.command + : this.moduleName(cmd); + if (cmd.aliases) + command = [].concat(command).concat(cmd.aliases); + this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated); + return; + } + else if (isCommandBuilderDefinition(builder)) { + this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated); + return; + } + if (typeof cmd === 'string') { + const parsedCommand = parseCommand(cmd); + aliases = aliases.map(alias => parseCommand(alias).cmd); + let isDefault = false; + const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => { + if (DEFAULT_MARKER.test(c)) { + isDefault = true; + return false; + } + return true; + }); + if (parsedAliases.length === 0 && isDefault) + parsedAliases.push('$0'); + if (isDefault) { + parsedCommand.cmd = parsedAliases[0]; + aliases = parsedAliases.slice(1); + cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd); + } + aliases.forEach(alias => { + this.aliasMap[alias] = parsedCommand.cmd; + }); + if (description !== false) { + this.usage.command(cmd, description, isDefault, aliases, deprecated); + } + this.handlers[parsedCommand.cmd] = { + original: cmd, + description, + handler, + builder: builder || {}, + middlewares, + deprecated, + demanded: parsedCommand.demanded, + optional: parsedCommand.optional, + }; + if (isDefault) + this.defaultCommand = this.handlers[parsedCommand.cmd]; + } + } + getCommandHandlers() { + return this.handlers; + } + getCommands() { + return Object.keys(this.handlers).concat(Object.keys(this.aliasMap)); + } + hasDefaultCommand() { + return !!this.defaultCommand; + } + runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) { + const commandHandler = this.handlers[command] || + this.handlers[this.aliasMap[command]] || + this.defaultCommand; + const currentContext = yargs.getInternalMethods().getContext(); + const parentCommands = currentContext.commands.slice(); + const isDefaultCommand = !command; + if (command) { + currentContext.commands.push(command); + currentContext.fullCommands.push(commandHandler.original); + } + const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet); + return isPromise(builderResult) + ? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) + : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs); + } + applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) { + const builder = commandHandler.builder; + let innerYargs = yargs; + if (isCommandBuilderCallback(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet); + if (isPromise(builderOutput)) { + return builderOutput.then(output => { + innerYargs = isYargsInstance(output) ? output : yargs; + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + }); + } + } + else if (isCommandBuilderOptionDefinitions(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + innerYargs = yargs.getInternalMethods().reset(aliases); + Object.keys(commandHandler.builder).forEach(key => { + innerYargs.option(key, builder[key]); + }); + } + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + } + parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) { + if (isDefaultCommand) + innerYargs.getInternalMethods().getUsageInstance().unfreeze(true); + if (this.shouldUpdateUsage(innerYargs)) { + innerYargs + .getInternalMethods() + .getUsageInstance() + .usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); + } + const innerArgv = innerYargs + .getInternalMethods() + .runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly); + return isPromise(innerArgv) + ? innerArgv.then(argv => ({ + aliases: innerYargs.parsed.aliases, + innerArgv: argv, + })) + : { + aliases: innerYargs.parsed.aliases, + innerArgv: innerArgv, + }; + } + shouldUpdateUsage(yargs) { + return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && + yargs.getInternalMethods().getUsageInstance().getUsage().length === 0); + } + usageFromParentCommandsCommandHandler(parentCommands, commandHandler) { + const c = DEFAULT_MARKER.test(commandHandler.original) + ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() + : commandHandler.original; + const pc = parentCommands.filter(c => { + return !DEFAULT_MARKER.test(c); + }); + pc.push(c); + return `$0 ${pc.join(' ')}`; + } + handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) { + if (!yargs.getInternalMethods().getHasOutput()) { + const validation = yargs + .getInternalMethods() + .runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand); + innerArgv = maybeAsyncResult(innerArgv, result => { + validation(result); + return result; + }); + } + if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) { + yargs.getInternalMethods().setHasOutput(); + const populateDoubleDash = !!yargs.getOptions().configuration['populate--']; + yargs + .getInternalMethods() + .postProcess(innerArgv, populateDoubleDash, false, false); + innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false); + innerArgv = maybeAsyncResult(innerArgv, result => { + const handlerResult = commandHandler.handler(result); + return isPromise(handlerResult) + ? handlerResult.then(() => result) + : result; + }); + if (!isDefaultCommand) { + yargs.getInternalMethods().getUsageInstance().cacheHelpMessage(); + } + if (isPromise(innerArgv) && + !yargs.getInternalMethods().hasParseCallback()) { + innerArgv.catch(error => { + try { + yargs.getInternalMethods().getUsageInstance().fail(null, error); + } + catch (_err) { + } + }); + } + } + if (!isDefaultCommand) { + currentContext.commands.pop(); + currentContext.fullCommands.pop(); + } + return innerArgv; + } + applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) { + let positionalMap = {}; + if (helpOnly) + return innerArgv; + if (!yargs.getInternalMethods().getHasOutput()) { + positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs); + } + const middlewares = this.globalMiddleware + .getMiddleware() + .slice(0) + .concat(commandHandler.middlewares); + const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true); + return isPromise(maybePromiseArgv) + ? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) + : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap); + } + populatePositionals(commandHandler, argv, context, yargs) { + argv._ = argv._.slice(context.commands.length); + const demanded = commandHandler.demanded.slice(0); + const optional = commandHandler.optional.slice(0); + const positionalMap = {}; + this.validation.positionalCount(demanded.length, argv._.length); + while (demanded.length) { + const demand = demanded.shift(); + this.populatePositional(demand, argv, positionalMap); + } + while (optional.length) { + const maybe = optional.shift(); + this.populatePositional(maybe, argv, positionalMap); + } + argv._ = context.commands.concat(argv._.map(a => '' + a)); + this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs); + return positionalMap; + } + populatePositional(positional, argv, positionalMap) { + const cmd = positional.cmd[0]; + if (positional.variadic) { + positionalMap[cmd] = argv._.splice(0).map(String); + } + else { + if (argv._.length) + positionalMap[cmd] = [String(argv._.shift())]; + } + } + cmdToParseOptions(cmdString) { + const parseOptions = { + array: [], + default: {}, + alias: {}, + demand: {}, + }; + const parsed = parseCommand(cmdString); + parsed.demanded.forEach(d => { + const [cmd, ...aliases] = d.cmd; + if (d.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + parseOptions.demand[cmd] = true; + }); + parsed.optional.forEach(o => { + const [cmd, ...aliases] = o.cmd; + if (o.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + }); + return parseOptions; + } + postProcessPositionals(argv, positionalMap, parseOptions, yargs) { + const options = Object.assign({}, yargs.getOptions()); + options.default = Object.assign(parseOptions.default, options.default); + for (const key of Object.keys(parseOptions.alias)) { + options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]); + } + options.array = options.array.concat(parseOptions.array); + options.config = {}; + const unparsed = []; + Object.keys(positionalMap).forEach(key => { + positionalMap[key].map(value => { + if (options.configuration['unknown-options-as-args']) + options.key[key] = true; + unparsed.push(`--${key}`); + unparsed.push(value); + }); + }); + if (!unparsed.length) + return; + const config = Object.assign({}, options.configuration, { + 'populate--': false, + }); + const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, { + configuration: config, + })); + if (parsed.error) { + yargs + .getInternalMethods() + .getUsageInstance() + .fail(parsed.error.message, parsed.error); + } + else { + const positionalKeys = Object.keys(positionalMap); + Object.keys(positionalMap).forEach(key => { + positionalKeys.push(...parsed.aliases[key]); + }); + Object.keys(parsed.argv).forEach(key => { + if (positionalKeys.includes(key)) { + if (!positionalMap[key]) + positionalMap[key] = parsed.argv[key]; + if (!this.isInConfigs(yargs, key) && + !this.isDefaulted(yargs, key) && + Object.prototype.hasOwnProperty.call(argv, key) && + Object.prototype.hasOwnProperty.call(parsed.argv, key) && + (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) { + argv[key] = [].concat(argv[key], parsed.argv[key]); + } + else { + argv[key] = parsed.argv[key]; + } + } + }); + } + } + isDefaulted(yargs, key) { + const { default: defaults } = yargs.getOptions(); + return (Object.prototype.hasOwnProperty.call(defaults, key) || + Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key))); + } + isInConfigs(yargs, key) { + const { configObjects } = yargs.getOptions(); + return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) || + configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)))); + } + runDefaultBuilderOn(yargs) { + if (!this.defaultCommand) + return; + if (this.shouldUpdateUsage(yargs)) { + const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) + ? this.defaultCommand.original + : this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 '); + yargs + .getInternalMethods() + .getUsageInstance() + .usage(commandString, this.defaultCommand.description); + } + const builder = this.defaultCommand.builder; + if (isCommandBuilderCallback(builder)) { + return builder(yargs, true); + } + else if (!isCommandBuilderDefinition(builder)) { + Object.keys(builder).forEach(key => { + yargs.option(key, builder[key]); + }); + } + return undefined; + } + moduleName(obj) { + const mod = whichModule(obj); + if (!mod) + throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`); + return this.commandFromFilename(mod.filename); + } + commandFromFilename(filename) { + return this.shim.path.basename(filename, this.shim.path.extname(filename)); + } + extractDesc({ describe, description, desc }) { + for (const test of [describe, description, desc]) { + if (typeof test === 'string' || test === false) + return test; + assertNotStrictEqual(test, true, this.shim); + } + return false; + } + freeze() { + this.frozens.push({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + }); + } + unfreeze() { + const frozen = this.frozens.pop(); + assertNotStrictEqual(frozen, undefined, this.shim); + ({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + } = frozen); + } + reset() { + this.handlers = {}; + this.aliasMap = {}; + this.defaultCommand = undefined; + this.requireCache = new Set(); + return this; + } +} +function command$1(usage, validation, globalMiddleware, shim) { + return new CommandInstance(usage, validation, globalMiddleware, shim); +} +function isCommandBuilderDefinition(builder) { + return (typeof builder === 'object' && + !!builder.builder && + typeof builder.handler === 'function'); +} +function isCommandAndAliases(cmd) { + return cmd.every(c => typeof c === 'string'); +} +function isCommandBuilderCallback(builder) { + return typeof builder === 'function'; +} +function isCommandBuilderOptionDefinitions(builder) { + return typeof builder === 'object'; +} +function isCommandHandlerDefinition(cmd) { + return typeof cmd === 'object' && !Array.isArray(cmd); +} - exports.networkInterfaceDefault = network$1.networkInterfaceDefault; - exports.networkGatewayDefault = network$1.networkGatewayDefault; - exports.networkInterfaces = network$1.networkInterfaces; - exports.networkStats = network$1.networkStats; - exports.networkConnections = network$1.networkConnections; +function objFilter(original = {}, filter = () => true) { + const obj = {}; + objectKeys(original).forEach(key => { + if (filter(key, original[key])) { + obj[key] = original[key]; + } + }); + return obj; +} - exports.wifiNetworks = wifi$1.wifiNetworks; - exports.wifiInterfaces = wifi$1.wifiInterfaces; - exports.wifiConnections = wifi$1.wifiConnections; +function setBlocking(blocking) { + if (typeof process === 'undefined') + return; + [process.stdout, process.stderr].forEach(_stream => { + const stream = _stream; + if (stream._handle && + stream.isTTY && + typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking); + } + }); +} - exports.services = processes.services; - exports.processes = processes.processes; - exports.processLoad = processes.processLoad; +function isBoolean(fail) { + return typeof fail === 'boolean'; +} +function usage(yargs, shim) { + const __ = shim.y18n.__; + const self = {}; + const fails = []; + self.failFn = function failFn(f) { + fails.push(f); + }; + let failMessage = null; + let globalFailMessage = null; + let showHelpOnFail = true; + self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) { + const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2]; + if (yargs.getInternalMethods().isGlobalContext()) { + globalFailMessage = message; + } + failMessage = message; + showHelpOnFail = enabled; + return self; + }; + let failureOutput = false; + self.fail = function fail(msg, err) { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (fails.length) { + for (let i = fails.length - 1; i >= 0; --i) { + const fail = fails[i]; + if (isBoolean(fail)) { + if (err) + throw err; + else if (msg) + throw Error(msg); + } + else { + fail(msg, err, self); + } + } + } + else { + if (yargs.getExitProcess()) + setBlocking(true); + if (!failureOutput) { + failureOutput = true; + if (showHelpOnFail) { + yargs.showHelp('error'); + logger.error(); + } + if (msg || err) + logger.error(msg || err); + const globalOrCommandFailMessage = failMessage || globalFailMessage; + if (globalOrCommandFailMessage) { + if (msg || err) + logger.error(''); + logger.error(globalOrCommandFailMessage); + } + } + err = err || new YError(msg); + if (yargs.getExitProcess()) { + return yargs.exit(1); + } + else if (yargs.getInternalMethods().hasParseCallback()) { + return yargs.exit(1, err); + } + else { + throw err; + } + } + }; + let usages = []; + let usageDisabled = false; + self.usage = (msg, description) => { + if (msg === null) { + usageDisabled = true; + usages = []; + return self; + } + usageDisabled = false; + usages.push([msg, description || '']); + return self; + }; + self.getUsage = () => { + return usages; + }; + self.getUsageDisabled = () => { + return usageDisabled; + }; + self.getPositionalGroupName = () => { + return __('Positionals:'); + }; + let examples = []; + self.example = (cmd, description) => { + examples.push([cmd, description || '']); + }; + let commands = []; + self.command = function command(cmd, description, isDefault, aliases, deprecated = false) { + if (isDefault) { + commands = commands.map(cmdArray => { + cmdArray[2] = false; + return cmdArray; + }); + } + commands.push([cmd, description || '', isDefault, aliases, deprecated]); + }; + self.getCommands = () => commands; + let descriptions = {}; + self.describe = function describe(keyOrKeys, desc) { + if (Array.isArray(keyOrKeys)) { + keyOrKeys.forEach(k => { + self.describe(k, desc); + }); + } + else if (typeof keyOrKeys === 'object') { + Object.keys(keyOrKeys).forEach(k => { + self.describe(k, keyOrKeys[k]); + }); + } + else { + descriptions[keyOrKeys] = desc; + } + }; + self.getDescriptions = () => descriptions; + let epilogs = []; + self.epilog = msg => { + epilogs.push(msg); + }; + let wrapSet = false; + let wrap; + self.wrap = cols => { + wrapSet = true; + wrap = cols; + }; + self.getWrap = () => { + if (shim.getEnv('YARGS_DISABLE_WRAP')) { + return null; + } + if (!wrapSet) { + wrap = windowWidth(); + wrapSet = true; + } + return wrap; + }; + const deferY18nLookupPrefix = '__yargsString__:'; + self.deferY18nLookup = str => deferY18nLookupPrefix + str; + self.help = function help() { + if (cachedHelpMessage) + return cachedHelpMessage; + normalizeAliases(); + const base$0 = yargs.customScriptName + ? yargs.$0 + : shim.path.basename(yargs.$0); + const demandedOptions = yargs.getDemandedOptions(); + const demandedCommands = yargs.getDemandedCommands(); + const deprecatedOptions = yargs.getDeprecatedOptions(); + const groups = yargs.getGroups(); + const options = yargs.getOptions(); + let keys = []; + keys = keys.concat(Object.keys(descriptions)); + keys = keys.concat(Object.keys(demandedOptions)); + keys = keys.concat(Object.keys(demandedCommands)); + keys = keys.concat(Object.keys(options.default)); + keys = keys.filter(filterHiddenOptions); + keys = Object.keys(keys.reduce((acc, key) => { + if (key !== '_') + acc[key] = true; + return acc; + }, {})); + const theWrap = self.getWrap(); + const ui = shim.cliui({ + width: theWrap, + wrap: !!theWrap, + }); + if (!usageDisabled) { + if (usages.length) { + usages.forEach(usage => { + ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` }); + if (usage[1]) { + ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }); + } + }); + ui.div(); + } + else if (commands.length) { + let u = null; + if (demandedCommands._) { + u = `${base$0} <${__('command')}>\n`; + } + else { + u = `${base$0} [${__('command')}]\n`; + } + ui.div(`${u}`); + } + } + if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) { + ui.div(__('Commands:')); + const context = yargs.getInternalMethods().getContext(); + const parentCommands = context.commands.length + ? `${context.commands.join(' ')} ` + : ''; + if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] === + true) { + commands = commands.sort((a, b) => a[0].localeCompare(b[0])); + } + const prefix = base$0 ? `${base$0} ` : ''; + commands.forEach(command => { + const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; + ui.span({ + text: commandString, + padding: [0, 2, 0, 2], + width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4, + }, { text: command[1] }); + const hints = []; + if (command[2]) + hints.push(`[${__('default')}]`); + if (command[3] && command[3].length) { + hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`); + } + if (command[4]) { + if (typeof command[4] === 'string') { + hints.push(`[${__('deprecated: %s', command[4])}]`); + } + else { + hints.push(`[${__('deprecated')}]`); + } + } + if (hints.length) { + ui.div({ + text: hints.join(' '), + padding: [0, 0, 0, 2], + align: 'right', + }); + } + else { + ui.div(); + } + }); + ui.div(); + } + const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []); + keys = keys.filter(key => !yargs.parsed.newAliases[key] && + aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)); + const defaultGroup = __('Options:'); + if (!groups[defaultGroup]) + groups[defaultGroup] = []; + addUngroupedKeys(keys, options.alias, groups, defaultGroup); + const isLongSwitch = (sw) => /^--/.test(getText(sw)); + const displayedGroups = Object.keys(groups) + .filter(groupName => groups[groupName].length > 0) + .map(groupName => { + const normalizedKeys = groups[groupName] + .filter(filterHiddenOptions) + .map(key => { + if (aliasKeys.includes(key)) + return key; + for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { + if ((options.alias[aliasKey] || []).includes(key)) + return aliasKey; + } + return key; + }); + return { groupName, normalizedKeys }; + }) + .filter(({ normalizedKeys }) => normalizedKeys.length > 0) + .map(({ groupName, normalizedKeys }) => { + const switches = normalizedKeys.reduce((acc, key) => { + acc[key] = [key] + .concat(options.alias[key] || []) + .map(sw => { + if (groupName === self.getPositionalGroupName()) + return sw; + else { + return ((/^[0-9]$/.test(sw) + ? options.boolean.includes(key) + ? '-' + : '--' + : sw.length > 1 + ? '--' + : '-') + sw); + } + }) + .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) + ? 0 + : isLongSwitch(sw1) + ? 1 + : -1) + .join(', '); + return acc; + }, {}); + return { groupName, normalizedKeys, switches }; + }); + const shortSwitchesUsed = displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key]))); + if (shortSwitchesUsed) { + displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .forEach(({ normalizedKeys, switches }) => { + normalizedKeys.forEach(key => { + if (isLongSwitch(switches[key])) { + switches[key] = addIndentation(switches[key], '-x, '.length); + } + }); + }); + } + displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => { + ui.div(groupName); + normalizedKeys.forEach(key => { + const kswitch = switches[key]; + let desc = descriptions[key] || ''; + let type = null; + if (desc.includes(deferY18nLookupPrefix)) + desc = __(desc.substring(deferY18nLookupPrefix.length)); + if (options.boolean.includes(key)) + type = `[${__('boolean')}]`; + if (options.count.includes(key)) + type = `[${__('count')}]`; + if (options.string.includes(key)) + type = `[${__('string')}]`; + if (options.normalize.includes(key)) + type = `[${__('string')}]`; + if (options.array.includes(key)) + type = `[${__('array')}]`; + if (options.number.includes(key)) + type = `[${__('number')}]`; + const deprecatedExtra = (deprecated) => typeof deprecated === 'string' + ? `[${__('deprecated: %s', deprecated)}]` + : `[${__('deprecated')}]`; + const extra = [ + key in deprecatedOptions + ? deprecatedExtra(deprecatedOptions[key]) + : null, + type, + key in demandedOptions ? `[${__('required')}]` : null, + options.choices && options.choices[key] + ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` + : null, + defaultString(options.default[key], options.defaultDescription[key]), + ] + .filter(Boolean) + .join(' '); + ui.span({ + text: getText(kswitch), + padding: [0, 2, 0, 2 + getIndentation(kswitch)], + width: maxWidth(switches, theWrap) + 4, + }, desc); + const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] === + true; + if (extra && !shouldHideOptionExtras) + ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }); + else + ui.div(); + }); + ui.div(); + }); + if (examples.length) { + ui.div(__('Examples:')); + examples.forEach(example => { + example[0] = example[0].replace(/\$0/g, base$0); + }); + examples.forEach(example => { + if (example[1] === '') { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + }); + } + else { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + width: maxWidth(examples, theWrap) + 4, + }, { + text: example[1], + }); + } + }); + ui.div(); + } + if (epilogs.length > 0) { + const e = epilogs + .map(epilog => epilog.replace(/\$0/g, base$0)) + .join('\n'); + ui.div(`${e}\n`); + } + return ui.toString().replace(/\s*$/, ''); + }; + function maxWidth(table, theWrap, modifier) { + let width = 0; + if (!Array.isArray(table)) { + table = Object.values(table).map(v => [v]); + } + table.forEach(v => { + width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width); + }); + if (theWrap) + width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10)); + return width; + } + function normalizeAliases() { + const demandedOptions = yargs.getDemandedOptions(); + const options = yargs.getOptions(); + (Object.keys(options.alias) || []).forEach(key => { + options.alias[key].forEach(alias => { + if (descriptions[alias]) + self.describe(key, descriptions[alias]); + if (alias in demandedOptions) + yargs.demandOption(key, demandedOptions[alias]); + if (options.boolean.includes(alias)) + yargs.boolean(key); + if (options.count.includes(alias)) + yargs.count(key); + if (options.string.includes(alias)) + yargs.string(key); + if (options.normalize.includes(alias)) + yargs.normalize(key); + if (options.array.includes(alias)) + yargs.array(key); + if (options.number.includes(alias)) + yargs.number(key); + }); + }); + } + let cachedHelpMessage; + self.cacheHelpMessage = function () { + cachedHelpMessage = this.help(); + }; + self.clearCachedHelpMessage = function () { + cachedHelpMessage = undefined; + }; + self.hasCachedHelpMessage = function () { + return !!cachedHelpMessage; + }; + function addUngroupedKeys(keys, aliases, groups, defaultGroup) { + let groupedKeys = []; + let toCheck = null; + Object.keys(groups).forEach(group => { + groupedKeys = groupedKeys.concat(groups[group]); + }); + keys.forEach(key => { + toCheck = [key].concat(aliases[key]); + if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { + groups[defaultGroup].push(key); + } + }); + return groupedKeys; + } + function filterHiddenOptions(key) { + return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 || + yargs.parsed.argv[yargs.getOptions().showHiddenOpt]); + } + self.showHelp = (level) => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(self.help()); + }; + self.functionDescription = fn => { + const description = fn.name + ? shim.Parser.decamelize(fn.name, '-') + : __('generated-value'); + return ['(', description, ')'].join(''); + }; + self.stringifiedValues = function stringifiedValues(values, separator) { + let string = ''; + const sep = separator || ', '; + const array = [].concat(values); + if (!values || !array.length) + return string; + array.forEach(value => { + if (string.length) + string += sep; + string += JSON.stringify(value); + }); + return string; + }; + function defaultString(value, defaultDescription) { + let string = `[${__('default:')} `; + if (value === undefined && !defaultDescription) + return null; + if (defaultDescription) { + string += defaultDescription; + } + else { + switch (typeof value) { + case 'string': + string += `"${value}"`; + break; + case 'object': + string += JSON.stringify(value); + break; + default: + string += value; + } + } + return `${string}]`; + } + function windowWidth() { + const maxWidth = 80; + if (shim.process.stdColumns) { + return Math.min(maxWidth, shim.process.stdColumns); + } + else { + return maxWidth; + } + } + let version = null; + self.version = ver => { + version = ver; + }; + self.showVersion = level => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(version); + }; + self.reset = function reset(localLookup) { + failMessage = null; + failureOutput = false; + usages = []; + usageDisabled = false; + epilogs = []; + examples = []; + commands = []; + descriptions = objFilter(descriptions, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + }); + }; + self.unfreeze = function unfreeze(defaultCommand = false) { + const frozen = frozens.pop(); + if (!frozen) + return; + if (defaultCommand) { + descriptions = { ...frozen.descriptions, ...descriptions }; + commands = [...frozen.commands, ...commands]; + usages = [...frozen.usages, ...usages]; + examples = [...frozen.examples, ...examples]; + epilogs = [...frozen.epilogs, ...epilogs]; + } + else { + ({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + } = frozen); + } + }; + return self; +} +function isIndentedText(text) { + return typeof text === 'object'; +} +function addIndentation(text, indent) { + return isIndentedText(text) + ? { text: text.text, indentation: text.indentation + indent } + : { text, indentation: indent }; +} +function getIndentation(text) { + return isIndentedText(text) ? text.indentation : 0; +} +function getText(text) { + return isIndentedText(text) ? text.text : text; +} - exports.users = users.users; +const completionShTemplate = `###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc +# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local cur_word args type_list - exports.inetChecksite = internet$1.inetChecksite; - exports.inetLatency = internet$1.inetLatency; + cur_word="\${COMP_WORDS[COMP_CWORD]}" + args=("\${COMP_WORDS[@]}") - exports.dockerInfo = docker$1.dockerInfo; - exports.dockerImages = docker$1.dockerImages; - exports.dockerContainers = docker$1.dockerContainers; - exports.dockerContainerStats = docker$1.dockerContainerStats; - exports.dockerContainerProcesses = docker$1.dockerContainerProcesses; - exports.dockerVolumes = docker$1.dockerVolumes; - exports.dockerAll = docker$1.dockerAll; + # ask yargs to generate completions. + type_list=$({{app_path}} --get-yargs-completions "\${args[@]}") - exports.vboxInfo = vbox.vboxInfo; + COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) ) - exports.printer = printer.printer; + # if no match was found, fall back to filename completion + if [ \${#COMPREPLY[@]} -eq 0 ]; then + COMPREPLY=() + fi - exports.usb = usb.usb; + return 0 +} +complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; +const completionZshTemplate = `#compdef {{app_name}} +###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc +# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local reply + local si=$IFS + IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) + IFS=$si + _describe 'values' reply +} +compdef _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; - exports.audio = audio.audio; - exports.bluetoothDevices = bluetooth$1.bluetoothDevices; +class Completion { + constructor(yargs, usage, command, shim) { + var _a, _b, _c; + this.yargs = yargs; + this.usage = usage; + this.command = command; + this.shim = shim; + this.completionKey = 'get-yargs-completions'; + this.aliases = null; + this.customCompletionFunction = null; + this.indexAfterLastReset = 0; + this.zshShell = + (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) || + ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false; + } + defaultCompletion(args, argv, current, done) { + const handlers = this.command.getCommandHandlers(); + for (let i = 0, ii = args.length; i < ii; ++i) { + if (handlers[args[i]] && handlers[args[i]].builder) { + const builder = handlers[args[i]].builder; + if (isCommandBuilderCallback(builder)) { + this.indexAfterLastReset = i + 1; + const y = this.yargs.getInternalMethods().reset(); + builder(y, true); + return y.argv; + } + } + } + const completions = []; + this.commandCompletions(completions, args, current); + this.optionCompletions(completions, args, argv, current); + this.choicesFromOptionsCompletions(completions, args, argv, current); + this.choicesFromPositionalsCompletions(completions, args, argv, current); + done(null, completions); + } + commandCompletions(completions, args, current) { + const parentCommands = this.yargs + .getInternalMethods() + .getContext().commands; + if (!current.match(/^-/) && + parentCommands[parentCommands.length - 1] !== current && + !this.previousArgHasChoices(args)) { + this.usage.getCommands().forEach(usageCommand => { + const commandName = parseCommand(usageCommand[0]).cmd; + if (args.indexOf(commandName) === -1) { + if (!this.zshShell) { + completions.push(commandName); + } + else { + const desc = usageCommand[1] || ''; + completions.push(commandName.replace(/:/g, '\\:') + ':' + desc); + } + } + }); + } + } + optionCompletions(completions, args, argv, current) { + if ((current.match(/^-/) || (current === '' && completions.length === 0)) && + !this.previousArgHasChoices(args)) { + const options = this.yargs.getOptions(); + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + Object.keys(options.key).forEach(key => { + const negable = !!options.configuration['boolean-negation'] && + options.boolean.includes(key); + const isPositionalKey = positionalKeys.includes(key); + if (!isPositionalKey && + !options.hiddenOptions.includes(key) && + !this.argsContainKey(args, key, negable)) { + this.completeOptionKey(key, completions, current, negable && !!options.default[key]); + } + }); + } + } + choicesFromOptionsCompletions(completions, args, argv, current) { + if (this.previousArgHasChoices(args)) { + const choices = this.getPreviousArgChoices(args); + if (choices && choices.length > 0) { + completions.push(...choices.map(c => c.replace(/:/g, '\\:'))); + } + } + } + choicesFromPositionalsCompletions(completions, args, argv, current) { + if (current === '' && + completions.length > 0 && + this.previousArgHasChoices(args)) { + return; + } + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + + 1); + const positionalKey = positionalKeys[argv._.length - offset - 1]; + if (!positionalKey) { + return; + } + const choices = this.yargs.getOptions().choices[positionalKey] || []; + for (const choice of choices) { + if (choice.startsWith(current)) { + completions.push(choice.replace(/:/g, '\\:')); + } + } + } + getPreviousArgChoices(args) { + if (args.length < 1) + return; + let previousArg = args[args.length - 1]; + let filter = ''; + if (!previousArg.startsWith('-') && args.length > 1) { + filter = previousArg; + previousArg = args[args.length - 2]; + } + if (!previousArg.startsWith('-')) + return; + const previousArgKey = previousArg.replace(/^-+/, ''); + const options = this.yargs.getOptions(); + const possibleAliases = [ + previousArgKey, + ...(this.yargs.getAliases()[previousArgKey] || []), + ]; + let choices; + for (const possibleAlias of possibleAliases) { + if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && + Array.isArray(options.choices[possibleAlias])) { + choices = options.choices[possibleAlias]; + break; + } + } + if (choices) { + return choices.filter(choice => !filter || choice.startsWith(filter)); + } + } + previousArgHasChoices(args) { + const choices = this.getPreviousArgChoices(args); + return choices !== undefined && choices.length > 0; + } + argsContainKey(args, key, negable) { + const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1; + if (argsContains(key)) + return true; + if (negable && argsContains(`no-${key}`)) + return true; + if (this.aliases) { + for (const alias of this.aliases[key]) { + if (argsContains(alias)) + return true; + } + } + return false; + } + completeOptionKey(key, completions, current, negable) { + var _a, _b, _c, _d; + let keyWithDesc = key; + if (this.zshShell) { + const descs = this.usage.getDescriptions(); + const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => { + const desc = descs[alias]; + return typeof desc === 'string' && desc.length > 0; + }); + const descFromAlias = aliasKey ? descs[aliasKey] : undefined; + const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : ''; + keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc + .replace('__yargsString__:', '') + .replace(/(\r\n|\n|\r)/gm, ' ')}`; + } + const startsByTwoDashes = (s) => /^--/.test(s); + const isShortOption = (s) => /^[^0-9]$/.test(s); + const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'; + completions.push(dashes + keyWithDesc); + if (negable) { + completions.push(dashes + 'no-' + keyWithDesc); + } + } + customCompletion(args, argv, current, done) { + assertNotStrictEqual(this.customCompletionFunction, null, this.shim); + if (isSyncCompletionFunction(this.customCompletionFunction)) { + const result = this.customCompletionFunction(current, argv); + if (isPromise(result)) { + return result + .then(list => { + this.shim.process.nextTick(() => { + done(null, list); + }); + }) + .catch(err => { + this.shim.process.nextTick(() => { + done(err, undefined); + }); + }); + } + return done(null, result); + } + else if (isFallbackCompletionFunction(this.customCompletionFunction)) { + return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => { + done(null, completions); + }); + } + else { + return this.customCompletionFunction(current, argv, completions => { + done(null, completions); + }); + } + } + getCompletion(args, done) { + const current = args.length ? args[args.length - 1] : ''; + const argv = this.yargs.parse(args, true); + const completionFunction = this.customCompletionFunction + ? (argv) => this.customCompletion(args, argv, current, done) + : (argv) => this.defaultCompletion(args, argv, current, done); + return isPromise(argv) + ? argv.then(completionFunction) + : completionFunction(argv); + } + generateCompletionScript($0, cmd) { + let script = this.zshShell + ? completionZshTemplate + : completionShTemplate; + const name = this.shim.path.basename($0); + if ($0.match(/\.js$/)) + $0 = `./${$0}`; + script = script.replace(/{{app_name}}/g, name); + script = script.replace(/{{completion_command}}/g, cmd); + return script.replace(/{{app_path}}/g, $0); + } + registerFunction(fn) { + this.customCompletionFunction = fn; + } + setParsed(parsed) { + this.aliases = parsed.aliases; + } +} +function completion(yargs, usage, command, shim) { + return new Completion(yargs, usage, command, shim); +} +function isSyncCompletionFunction(completionFunction) { + return completionFunction.length < 3; +} +function isFallbackCompletionFunction(completionFunction) { + return completionFunction.length > 3; +} - exports.getStaticData = getStaticData; - exports.getDynamicData = getDynamicData; - exports.getAllData = getAllData; - exports.get = get; - exports.observe = observe; +function levenshtein(a, b) { + if (a.length === 0) + return b.length; + if (b.length === 0) + return a.length; + const matrix = []; + let i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; + } + let j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; + } + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i - 1) === a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } + else { + if (i > 1 && + j > 1 && + b.charAt(i - 2) === a.charAt(j - 1) && + b.charAt(i - 1) === a.charAt(j - 2)) { + matrix[i][j] = matrix[i - 2][j - 2] + 1; + } + else { + matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)); + } + } + } + } + return matrix[b.length][a.length]; +} - exports.powerShellStart = util.powerShellStart; - exports.powerShellRelease = util.powerShellRelease; -} (lib)); +const specialKeys = ['$0', '--', '_']; +function validation(yargs, usage, shim) { + const __ = shim.y18n.__; + const __n = shim.y18n.__n; + const self = {}; + self.nonOptionCount = function nonOptionCount(argv) { + const demandedCommands = yargs.getDemandedCommands(); + const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0); + const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length; + if (demandedCommands._ && + (_s < demandedCommands._.min || _s > demandedCommands._.max)) { + if (_s < demandedCommands._.min) { + if (demandedCommands._.minMsg !== undefined) { + usage.fail(demandedCommands._.minMsg + ? demandedCommands._.minMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.min.toString()) + : null); + } + else { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString())); + } + } + else if (_s > demandedCommands._.max) { + if (demandedCommands._.maxMsg !== undefined) { + usage.fail(demandedCommands._.maxMsg + ? demandedCommands._.maxMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.max.toString()) + : null); + } + else { + usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString())); + } + } + } + }; + self.positionalCount = function positionalCount(required, observed) { + if (observed < required) { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + '')); + } + }; + self.requiredArguments = function requiredArguments(argv, demandedOptions) { + let missing = null; + for (const key of Object.keys(demandedOptions)) { + if (!Object.prototype.hasOwnProperty.call(argv, key) || + typeof argv[key] === 'undefined') { + missing = missing || {}; + missing[key] = demandedOptions[key]; + } + } + if (missing) { + const customMsgs = []; + for (const key of Object.keys(missing)) { + const msg = missing[key]; + if (msg && customMsgs.indexOf(msg) < 0) { + customMsgs.push(msg); + } + } + const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''; + usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg)); + } + }; + self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) { + var _a; + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + Object.keys(argv).forEach(key => { + if (!specialKeys.includes(key) && + !Object.prototype.hasOwnProperty.call(positionalMap, key) && + !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && + !self.isValidAndSomeAliasIsNotNew(key, aliases)) { + unknown.push(key); + } + }); + if (checkPositionals && + (currentContext.commands.length > 0 || + commandKeys.length > 0 || + isDefaultCommand)) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (checkPositionals) { + const demandedCommands = yargs.getDemandedCommands(); + const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0; + const expected = currentContext.commands.length + maxNonOptDemanded; + if (expected < argv._.length) { + argv._.slice(expected).forEach(key => { + key = String(key); + if (!currentContext.commands.includes(key) && + !unknown.includes(key)) { + unknown.push(key); + } + }); + } + } + if (unknown.length) { + usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', '))); + } + }; + self.unknownCommands = function unknownCommands(argv) { + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + if (currentContext.commands.length > 0 || commandKeys.length > 0) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (unknown.length > 0) { + usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', '))); + return true; + } + else { + return false; + } + }; + self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) { + if (!Object.prototype.hasOwnProperty.call(aliases, key)) { + return false; + } + const newAliases = yargs.parsed.newAliases; + return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]); + }; + self.limitedChoices = function limitedChoices(argv) { + const options = yargs.getOptions(); + const invalid = {}; + if (!Object.keys(options.choices).length) + return; + Object.keys(argv).forEach(key => { + if (specialKeys.indexOf(key) === -1 && + Object.prototype.hasOwnProperty.call(options.choices, key)) { + [].concat(argv[key]).forEach(value => { + if (options.choices[key].indexOf(value) === -1 && + value !== undefined) { + invalid[key] = (invalid[key] || []).concat(value); + } + }); + } + }); + const invalidKeys = Object.keys(invalid); + if (!invalidKeys.length) + return; + let msg = __('Invalid values:'); + invalidKeys.forEach(key => { + msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`; + }); + usage.fail(msg); + }; + let implied = {}; + self.implies = function implies(key, value) { + argsert(' [array|number|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.implies(k, key[k]); + }); + } + else { + yargs.global(key); + if (!implied[key]) { + implied[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.implies(key, i)); + } + else { + assertNotStrictEqual(value, undefined, shim); + implied[key].push(value); + } + } + }; + self.getImplied = function getImplied() { + return implied; + }; + function keyExists(argv, val) { + const num = Number(val); + val = isNaN(num) ? val : num; + if (typeof val === 'number') { + val = argv._.length >= val; + } + else if (val.match(/^--no-.+/)) { + val = val.match(/^--no-(.+)/)[1]; + val = !Object.prototype.hasOwnProperty.call(argv, val); + } + else { + val = Object.prototype.hasOwnProperty.call(argv, val); + } + return val; + } + self.implications = function implications(argv) { + const implyFail = []; + Object.keys(implied).forEach(key => { + const origKey = key; + (implied[key] || []).forEach(value => { + let key = origKey; + const origValue = value; + key = keyExists(argv, key); + value = keyExists(argv, value); + if (key && !value) { + implyFail.push(` ${origKey} -> ${origValue}`); + } + }); + }); + if (implyFail.length) { + let msg = `${__('Implications failed:')}\n`; + implyFail.forEach(value => { + msg += value; + }); + usage.fail(msg); + } + }; + let conflicting = {}; + self.conflicts = function conflicts(key, value) { + argsert(' [array|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.conflicts(k, key[k]); + }); + } + else { + yargs.global(key); + if (!conflicting[key]) { + conflicting[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.conflicts(key, i)); + } + else { + conflicting[key].push(value); + } + } + }; + self.getConflicting = () => conflicting; + self.conflicting = function conflictingFn(argv) { + Object.keys(argv).forEach(key => { + if (conflicting[key]) { + conflicting[key].forEach(value => { + if (value && argv[key] !== undefined && argv[value] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + } + }); + if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) { + Object.keys(conflicting).forEach(key => { + conflicting[key].forEach(value => { + if (value && + argv[shim.Parser.camelCase(key)] !== undefined && + argv[shim.Parser.camelCase(value)] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + }); + } + }; + self.recommendCommands = function recommendCommands(cmd, potentialCommands) { + const threshold = 3; + potentialCommands = potentialCommands.sort((a, b) => b.length - a.length); + let recommended = null; + let bestDistance = Infinity; + for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { + const d = levenshtein(cmd, candidate); + if (d <= threshold && d < bestDistance) { + bestDistance = d; + recommended = candidate; + } + } + if (recommended) + usage.fail(__('Did you mean %s?', recommended)); + }; + self.reset = function reset(localLookup) { + implied = objFilter(implied, k => !localLookup[k]); + conflicting = objFilter(conflicting, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + implied, + conflicting, + }); + }; + self.unfreeze = function unfreeze() { + const frozen = frozens.pop(); + assertNotStrictEqual(frozen, undefined, shim); + ({ implied, conflicting } = frozen); + }; + return self; +} -var systemInfo = /*@__PURE__*/getDefaultExportFromCjs(lib); +let previouslyVisitedConfigs = []; +let shim; +function applyExtends(config, cwd, mergeExtends, _shim) { + shim = _shim; + let defaultConfig = {}; + if (Object.prototype.hasOwnProperty.call(config, 'extends')) { + if (typeof config.extends !== 'string') + return defaultConfig; + const isPath = /\.json|\..*rc$/.test(config.extends); + let pathToDefault = null; + if (!isPath) { + try { + pathToDefault = require.resolve(config.extends); + } + catch (_err) { + return config; + } + } + else { + pathToDefault = getPathToDefaultConfig(cwd, config.extends); + } + checkForCircularExtends(pathToDefault); + previouslyVisitedConfigs.push(pathToDefault); + defaultConfig = isPath + ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) + : require(config.extends); + delete config.extends; + defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim); + } + previouslyVisitedConfigs = []; + return mergeExtends + ? mergeDeep(defaultConfig, config) + : Object.assign({}, defaultConfig, config); +} +function checkForCircularExtends(cfgPath) { + if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { + throw new YError(`Circular extended configurations: '${cfgPath}'.`); + } +} +function getPathToDefaultConfig(cwd, pathToExtend) { + return shim.path.resolve(cwd, pathToExtend); +} +function mergeDeep(config1, config2) { + const target = {}; + function isObject(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); + } + Object.assign(target, config1); + for (const key of Object.keys(config2)) { + if (isObject(config2[key]) && isObject(target[key])) { + target[key] = mergeDeep(config1[key], config2[key]); + } + else { + target[key] = config2[key]; + } + } + return target; +} -const CMD_HOLDER = '$folder'; -const executeOpenCMD = async (config, path) => { - const { openCMD } = config; - const command = openCMD ? openCMD.replaceAll(CMD_HOLDER, path) : `code ${path}`; - Log.info(`executing command: ${command}`); - await execa(command, { shell: true }); +var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; -const handleFindResult = async (originSearchString, config, findFolders) => { - if (!findFolders?.length) { - Log.error(`${originSearchString} not found`); - return; +var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation; +function YargsFactory(_shim) { + return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => { + const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim); + Object.defineProperty(yargs, 'argv', { + get: () => { + return yargs.parse(); + }, + enumerable: true, + }); + yargs.help(); + yargs.version(); + return yargs; + }; +} +const kCopyDoubleDash = Symbol('copyDoubleDash'); +const kCreateLogger = Symbol('copyDoubleDash'); +const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject'); +const kEmitWarning = Symbol('emitWarning'); +const kFreeze = Symbol('freeze'); +const kGetDollarZero = Symbol('getDollarZero'); +const kGetParserConfiguration = Symbol('getParserConfiguration'); +const kGetUsageConfiguration = Symbol('getUsageConfiguration'); +const kGuessLocale = Symbol('guessLocale'); +const kGuessVersion = Symbol('guessVersion'); +const kParsePositionalNumbers = Symbol('parsePositionalNumbers'); +const kPkgUp = Symbol('pkgUp'); +const kPopulateParserHintArray = Symbol('populateParserHintArray'); +const kPopulateParserHintSingleValueDictionary = Symbol('populateParserHintSingleValueDictionary'); +const kPopulateParserHintArrayDictionary = Symbol('populateParserHintArrayDictionary'); +const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary'); +const kSanitizeKey = Symbol('sanitizeKey'); +const kSetKey = Symbol('setKey'); +const kUnfreeze = Symbol('unfreeze'); +const kValidateAsync = Symbol('validateAsync'); +const kGetCommandInstance = Symbol('getCommandInstance'); +const kGetContext = Symbol('getContext'); +const kGetHasOutput = Symbol('getHasOutput'); +const kGetLoggerInstance = Symbol('getLoggerInstance'); +const kGetParseContext = Symbol('getParseContext'); +const kGetUsageInstance = Symbol('getUsageInstance'); +const kGetValidationInstance = Symbol('getValidationInstance'); +const kHasParseCallback = Symbol('hasParseCallback'); +const kIsGlobalContext = Symbol('isGlobalContext'); +const kPostProcess = Symbol('postProcess'); +const kRebase = Symbol('rebase'); +const kReset = Symbol('reset'); +const kRunYargsParserAndExecuteCommands = Symbol('runYargsParserAndExecuteCommands'); +const kRunValidation = Symbol('runValidation'); +const kSetHasOutput = Symbol('setHasOutput'); +const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys'); +class YargsInstance { + constructor(processArgs = [], cwd, parentRequire, shim) { + this.customScriptName = false; + this.parsed = false; + _YargsInstance_command.set(this, void 0); + _YargsInstance_cwd.set(this, void 0); + _YargsInstance_context.set(this, { commands: [], fullCommands: [] }); + _YargsInstance_completion.set(this, null); + _YargsInstance_completionCommand.set(this, null); + _YargsInstance_defaultShowHiddenOpt.set(this, 'show-hidden'); + _YargsInstance_exitError.set(this, null); + _YargsInstance_detectLocale.set(this, true); + _YargsInstance_emittedWarnings.set(this, {}); + _YargsInstance_exitProcess.set(this, true); + _YargsInstance_frozens.set(this, []); + _YargsInstance_globalMiddleware.set(this, void 0); + _YargsInstance_groups.set(this, {}); + _YargsInstance_hasOutput.set(this, false); + _YargsInstance_helpOpt.set(this, null); + _YargsInstance_isGlobalContext.set(this, true); + _YargsInstance_logger.set(this, void 0); + _YargsInstance_output.set(this, ''); + _YargsInstance_options.set(this, void 0); + _YargsInstance_parentRequire.set(this, void 0); + _YargsInstance_parserConfig.set(this, {}); + _YargsInstance_parseFn.set(this, null); + _YargsInstance_parseContext.set(this, null); + _YargsInstance_pkgs.set(this, {}); + _YargsInstance_preservedGroups.set(this, {}); + _YargsInstance_processArgs.set(this, void 0); + _YargsInstance_recommendCommands.set(this, false); + _YargsInstance_shim.set(this, void 0); + _YargsInstance_strict.set(this, false); + _YargsInstance_strictCommands.set(this, false); + _YargsInstance_strictOptions.set(this, false); + _YargsInstance_usage.set(this, void 0); + _YargsInstance_usageConfig.set(this, {}); + _YargsInstance_versionOpt.set(this, null); + _YargsInstance_validation.set(this, void 0); + __classPrivateFieldSet(this, _YargsInstance_shim, shim, "f"); + __classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f"); + __classPrivateFieldSet(this, _YargsInstance_cwd, cwd, "f"); + __classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f"); + __classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f"); + this.$0 = this[kGetDollarZero](); + this[kReset](); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + __classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f"); + } + addHelpOpt(opt, msg) { + const defaultHelpOpt = 'help'; + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + __classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f"); + } + if (opt === false && msg === undefined) + return this; + __classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === 'string' ? opt : defaultHelpOpt, "f"); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show help')); + return this; + } + help(opt, msg) { + return this.addHelpOpt(opt, msg); + } + addShowHiddenOpt(opt, msg) { + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (opt === false && msg === undefined) + return this; + const showHiddenOpt = typeof opt === 'string' ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + this.boolean(showHiddenOpt); + this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show hidden options')); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt; + return this; + } + showHidden(opt, msg) { + return this.addShowHiddenOpt(opt, msg); + } + alias(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.alias.bind(this), 'alias', key, value); + return this; + } + array(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('array', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + boolean(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('boolean', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + check(f, global) { + argsert(' [boolean]', [f, global], arguments.length); + this.middleware((argv, _yargs) => { + return maybeAsyncResult(() => { + return f(argv, _yargs.getOptions()); + }, (result) => { + if (!result) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__('Argument check failed: %s', f.toString())); + } + else if (typeof result === 'string' || result instanceof Error) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(result.toString(), result); + } + return argv; + }, (err) => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err); + return argv; + }); + }, false, global); + return this; + } + choices(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.choices.bind(this), 'choices', key, value); + return this; + } + coerce(keys, value) { + argsert(' [function]', [keys, value], arguments.length); + if (Array.isArray(keys)) { + if (!value) { + throw new YError('coerce callback must be provided'); + } + for (const key of keys) { + this.coerce(key, value); + } + return this; + } + else if (typeof keys === 'object') { + for (const key of Object.keys(keys)) { + this.coerce(key, keys[key]); + } + return this; + } + if (!value) { + throw new YError('coerce callback must be provided'); + } + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => { + let aliases; + const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); + if (!shouldCoerce) { + return argv; + } + return maybeAsyncResult(() => { + aliases = yargs.getAliases(); + return value(argv[keys]); + }, (result) => { + argv[keys] = result; + const stripAliased = yargs + .getInternalMethods() + .getParserConfiguration()['strip-aliased']; + if (aliases[keys] && stripAliased !== true) { + for (const alias of aliases[keys]) { + argv[alias] = result; + } + } + return argv; + }, (err) => { + throw new YError(err.message); + }); + }, keys); + return this; + } + conflicts(key1, key2) { + argsert(' [string|array]', [key1, key2], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicts(key1, key2); + return this; + } + config(key = 'config', msg, parseFn) { + argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length); + if (typeof key === 'object' && !Array.isArray(key)) { + key = applyExtends(key, __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(key); + return this; + } + if (typeof msg === 'function') { + parseFn = msg; + msg = undefined; + } + this.describe(key, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Path to JSON config file')); + (Array.isArray(key) ? key : [key]).forEach(k => { + __classPrivateFieldGet(this, _YargsInstance_options, "f").config[k] = parseFn || true; + }); + return this; + } + completion(cmd, desc, fn) { + argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length); + if (typeof desc === 'function') { + fn = desc; + desc = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion', "f"); + if (!desc && desc !== false) { + desc = 'generate completion script'; + } + this.command(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), desc); + if (fn) + __classPrivateFieldGet(this, _YargsInstance_completion, "f").registerFunction(fn); + return this; + } + command(cmd, description, builder, handler, middlewares, deprecated) { + argsert(' [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated); + return this; + } + commands(cmd, description, builder, handler, middlewares, deprecated) { + return this.command(cmd, description, builder, handler, middlewares, deprecated); + } + commandDir(dir, opts) { + argsert(' [object]', [dir, opts], arguments.length); + const req = __classPrivateFieldGet(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").require; + __classPrivateFieldGet(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet(this, _YargsInstance_shim, "f").getCallerFile(), opts); + return this; + } + count(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('count', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + default(key, value, defaultDescription) { + argsert(' [*] [string]', [key, value, defaultDescription], arguments.length); + if (defaultDescription) { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription; + } + if (typeof value === 'function') { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key]) + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = + __classPrivateFieldGet(this, _YargsInstance_usage, "f").functionDescription(value); + value = value.call(); + } + this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), 'default', key, value); + return this; + } + defaults(key, value, defaultDescription) { + return this.default(key, value, defaultDescription); + } + demandCommand(min = 1, max, minMsg, maxMsg) { + argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length); + if (typeof max !== 'number') { + minMsg = max; + max = Infinity; + } + this.global('_', false); + __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands._ = { + min, + max, + minMsg, + maxMsg, + }; + return this; + } + demand(keys, max, msg) { + if (Array.isArray(max)) { + max.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + max = Infinity; + } + else if (typeof max !== 'number') { + msg = max; + max = Infinity; + } + if (typeof keys === 'number') { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandCommand(keys, max, msg, msg); + } + else if (Array.isArray(keys)) { + keys.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + } + else { + if (typeof msg === 'string') { + this.demandOption(keys, msg); + } + else if (msg === true || typeof msg === 'undefined') { + this.demandOption(keys); + } + } + return this; + } + demandOption(keys, msg) { + argsert(' [string]', [keys, msg], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), 'demandedOptions', keys, msg); + return this; + } + deprecateOption(option, message) { + argsert(' [string|boolean]', [option, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions[option] = message; + return this; + } + describe(keys, description) { + argsert(' [string]', [keys, description], arguments.length); + this[kSetKey](keys, true); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").describe(keys, description); + return this; + } + detectLocale(detect) { + argsert('', [detect], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, detect, "f"); + return this; + } + env(prefix) { + argsert('[string|boolean]', [prefix], arguments.length); + if (prefix === false) + delete __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + else + __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix = prefix || ''; + return this; + } + epilogue(msg) { + argsert('', [msg], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").epilog(msg); + return this; + } + epilog(msg) { + return this.epilogue(msg); + } + example(cmd, description) { + argsert(' [string]', [cmd, description], arguments.length); + if (Array.isArray(cmd)) { + cmd.forEach(exampleParams => this.example(...exampleParams)); + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").example(cmd, description); + } + return this; + } + exit(code, err) { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, err, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.exit(code); + } + exitProcess(enabled = true) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_exitProcess, enabled, "f"); + return this; + } + fail(f) { + argsert('', [f], arguments.length); + if (typeof f === 'boolean' && f !== false) { + throw new YError("Invalid first argument. Expected function or boolean 'false'"); + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").failFn(f); + return this; + } + getAliases() { + return this.parsed ? this.parsed.aliases : {}; + } + async getCompletion(args, done) { + argsert(' [function]', [args, done], arguments.length); + if (!done) { + return new Promise((resolve, reject) => { + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => { + if (err) + reject(err); + else + resolve(completions); + }); + }); + } + else { + return __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, done); + } + } + getDemandedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedOptions; + } + getDemandedCommands() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands; + } + getDeprecatedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions; + } + getDetectLocale() { + return __classPrivateFieldGet(this, _YargsInstance_detectLocale, "f"); + } + getExitProcess() { + return __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"); + } + getGroups() { + return Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_groups, "f"), __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")); + } + getHelp() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + return parse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + return builderResponse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + return Promise.resolve(__classPrivateFieldGet(this, _YargsInstance_usage, "f").help()); + } + getOptions() { + return __classPrivateFieldGet(this, _YargsInstance_options, "f"); + } + getStrict() { + return __classPrivateFieldGet(this, _YargsInstance_strict, "f"); + } + getStrictCommands() { + return __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"); + } + getStrictOptions() { + return __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"); + } + global(globals, global) { + argsert(' [boolean]', [globals, global], arguments.length); + globals = [].concat(globals); + if (global !== false) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local.filter(l => globals.indexOf(l) === -1); + } + else { + globals.forEach(g => { + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").local.includes(g)) + __classPrivateFieldGet(this, _YargsInstance_options, "f").local.push(g); + }); + } + return this; + } + group(opts, groupName) { + argsert(' ', [opts, groupName], arguments.length); + const existing = __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName]; + if (__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]) { + delete __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]; + } + const seen = {}; + __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter(key => { + if (seen[key]) + return false; + return (seen[key] = true); + }); + return this; + } + hide(key) { + argsert('', [key], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").hiddenOptions.push(key); + return this; + } + implies(key, value) { + argsert(' [number|string|array]', [key, value], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implies(key, value); + return this; + } + locale(locale) { + argsert('[string]', [locale], arguments.length); + if (locale === undefined) { + this[kGuessLocale](); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.getLocale(); + } + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(locale); + return this; + } + middleware(callback, applyBeforeValidation, global) { + return __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global); + } + nargs(key, value) { + argsert(' [number]', [key, value], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), 'narg', key, value); + return this; + } + normalize(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('normalize', keys); + return this; + } + number(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('number', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + option(key, opt) { + argsert(' [object]', [key, opt], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + this.options(k, key[k]); + }); + } + else { + if (typeof opt !== 'object') { + opt = {}; + } + this[kTrackManuallySetKeys](key); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && (key === 'version' || (opt === null || opt === void 0 ? void 0 : opt.alias) === 'version')) { + this[kEmitWarning]([ + '"version" is a reserved word.', + 'Please do one of the following:', + '- Disable version with `yargs.version(false)` if using "version" as an option', + '- Use the built-in `yargs.version` method instead (if applicable)', + '- Use a different option key', + 'https://yargs.js.org/docs/#api-reference-version', + ].join('\n'), undefined, 'versionWarning'); + } + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[key] = true; + if (opt.alias) + this.alias(key, opt.alias); + const deprecate = opt.deprecate || opt.deprecated; + if (deprecate) { + this.deprecateOption(key, deprecate); + } + const demand = opt.demand || opt.required || opt.require; + if (demand) { + this.demand(key, demand); + } + if (opt.demandOption) { + this.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined); + } + if (opt.conflicts) { + this.conflicts(key, opt.conflicts); + } + if ('default' in opt) { + this.default(key, opt.default); + } + if (opt.implies !== undefined) { + this.implies(key, opt.implies); + } + if (opt.nargs !== undefined) { + this.nargs(key, opt.nargs); + } + if (opt.config) { + this.config(key, opt.configParser); + } + if (opt.normalize) { + this.normalize(key); + } + if (opt.choices) { + this.choices(key, opt.choices); + } + if (opt.coerce) { + this.coerce(key, opt.coerce); + } + if (opt.group) { + this.group(key, opt.group); + } + if (opt.boolean || opt.type === 'boolean') { + this.boolean(key); + if (opt.alias) + this.boolean(opt.alias); + } + if (opt.array || opt.type === 'array') { + this.array(key); + if (opt.alias) + this.array(opt.alias); + } + if (opt.number || opt.type === 'number') { + this.number(key); + if (opt.alias) + this.number(opt.alias); + } + if (opt.string || opt.type === 'string') { + this.string(key); + if (opt.alias) + this.string(opt.alias); + } + if (opt.count || opt.type === 'count') { + this.count(key); + } + if (typeof opt.global === 'boolean') { + this.global(key, opt.global); + } + if (opt.defaultDescription) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription; + } + if (opt.skipValidation) { + this.skipValidation(key); + } + const desc = opt.describe || opt.description || opt.desc; + const descriptions = __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions(); + if (!Object.prototype.hasOwnProperty.call(descriptions, key) || + typeof desc === 'string') { + this.describe(key, desc); + } + if (opt.hidden) { + this.hide(key); + } + if (opt.requiresArg) { + this.requiresArg(key); + } + } + return this; + } + options(key, opt) { + return this.option(key, opt); + } + parse(args, shortCircuit, _parseFn) { + argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length); + this[kFreeze](); + if (typeof args === 'undefined') { + args = __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + } + if (typeof shortCircuit === 'object') { + __classPrivateFieldSet(this, _YargsInstance_parseContext, shortCircuit, "f"); + shortCircuit = _parseFn; + } + if (typeof shortCircuit === 'function') { + __classPrivateFieldSet(this, _YargsInstance_parseFn, shortCircuit, "f"); + shortCircuit = false; + } + if (!shortCircuit) + __classPrivateFieldSet(this, _YargsInstance_processArgs, args, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldSet(this, _YargsInstance_exitProcess, false, "f"); + const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit); + const tmpParsed = this.parsed; + __classPrivateFieldGet(this, _YargsInstance_completion, "f").setParsed(this.parsed); + if (isPromise(parsed)) { + return parsed + .then(argv => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + return argv; + }) + .catch(err => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) { + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + } + throw err; + }) + .finally(() => { + this[kUnfreeze](); + this.parsed = tmpParsed; + }); + } + else { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + this[kUnfreeze](); + this.parsed = tmpParsed; + } + return parsed; + } + parseAsync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + return !isPromise(maybePromise) + ? Promise.resolve(maybePromise) + : maybePromise; + } + parseSync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + if (isPromise(maybePromise)) { + throw new YError('.parseSync() must not be used with asynchronous builders, handlers, or middleware'); + } + return maybePromise; + } + parserConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_parserConfig, config, "f"); + return this; + } + pkgConf(key, rootPath) { + argsert(' [string]', [key, rootPath], arguments.length); + let conf = null; + const obj = this[kPkgUp](rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f")); + if (obj[key] && typeof obj[key] === 'object') { + conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(conf); + } + return this; + } + positional(key, opts) { + argsert(' ', [key, opts], arguments.length); + const supportedOpts = [ + 'default', + 'defaultDescription', + 'implies', + 'normalize', + 'choices', + 'conflicts', + 'coerce', + 'type', + 'describe', + 'desc', + 'description', + 'alias', + ]; + opts = objFilter(opts, (k, v) => { + if (k === 'type' && !['string', 'number', 'boolean'].includes(v)) + return false; + return supportedOpts.includes(k); + }); + const fullCommand = __classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands.length - 1]; + const parseOptions = fullCommand + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) + : { + array: [], + alias: {}, + default: {}, + demand: {}, + }; + objectKeys(parseOptions).forEach(pk => { + const parseOption = parseOptions[pk]; + if (Array.isArray(parseOption)) { + if (parseOption.indexOf(key) !== -1) + opts[pk] = true; + } + else { + if (parseOption[key] && !(pk in opts)) + opts[pk] = parseOption[key]; + } + }); + this.group(key, __classPrivateFieldGet(this, _YargsInstance_usage, "f").getPositionalGroupName()); + return this.option(key, opts); + } + recommendCommands(recommend = true) { + argsert('[boolean]', [recommend], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_recommendCommands, recommend, "f"); + return this; + } + required(keys, max, msg) { + return this.demand(keys, max, msg); + } + require(keys, max, msg) { + return this.demand(keys, max, msg); + } + requiresArg(keys) { + argsert(' [number]', [keys], arguments.length); + if (typeof keys === 'string' && __classPrivateFieldGet(this, _YargsInstance_options, "f").narg[keys]) { + return this; + } + else { + this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), 'narg', keys, NaN); + } + return this; + } + showCompletionScript($0, cmd) { + argsert('[string] [string]', [$0, cmd], arguments.length); + $0 = $0 || this.$0; + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion')); + return this; + } + showHelp(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + parse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + builderResponse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + return this; + } + scriptName(scriptName) { + this.customScriptName = true; + this.$0 = scriptName; + return this; + } + showHelpOnFail(enabled, message) { + argsert('[boolean|string] [string]', [enabled, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message); + return this; + } + showVersion(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion(level); + return this; + } + skipValidation(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('skipValidation', keys); + return this; + } + strict(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strict, enabled !== false, "f"); + return this; + } + strictCommands(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictCommands, enabled !== false, "f"); + return this; + } + strictOptions(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictOptions, enabled !== false, "f"); + return this; + } + string(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('string', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + terminalWidth() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.stdColumns; + } + updateLocale(obj) { + return this.updateStrings(obj); + } + updateStrings(obj) { + argsert('', [obj], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.updateLocale(obj); + return this; + } + usage(msg, description, builder, handler) { + argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length); + if (description !== undefined) { + assertNotStrictEqual(msg, null, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if ((msg || '').match(/^\$0( |$)/)) { + return this.command(msg, description, builder, handler); + } + else { + throw new YError('.usage() description must start with $0 if being used as alias for .command()'); + } + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").usage(msg); + return this; + } + } + usageConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_usageConfig, config, "f"); + return this; + } + version(opt, msg, ver) { + const defaultVersionOpt = 'version'; + argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(undefined); + __classPrivateFieldSet(this, _YargsInstance_versionOpt, null, "f"); + } + if (arguments.length === 0) { + ver = this[kGuessVersion](); + opt = defaultVersionOpt; + } + else if (arguments.length === 1) { + if (opt === false) { + return this; + } + ver = opt; + opt = defaultVersionOpt; + } + else if (arguments.length === 2) { + ver = msg; + msg = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_versionOpt, typeof opt === 'string' ? opt : defaultVersionOpt, "f"); + msg = msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show version number'); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(ver || undefined); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"), msg); + return this; + } + wrap(cols) { + argsert('', [cols], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").wrap(cols); + return this; + } + [(_YargsInstance_command = new WeakMap(), _YargsInstance_cwd = new WeakMap(), _YargsInstance_context = new WeakMap(), _YargsInstance_completion = new WeakMap(), _YargsInstance_completionCommand = new WeakMap(), _YargsInstance_defaultShowHiddenOpt = new WeakMap(), _YargsInstance_exitError = new WeakMap(), _YargsInstance_detectLocale = new WeakMap(), _YargsInstance_emittedWarnings = new WeakMap(), _YargsInstance_exitProcess = new WeakMap(), _YargsInstance_frozens = new WeakMap(), _YargsInstance_globalMiddleware = new WeakMap(), _YargsInstance_groups = new WeakMap(), _YargsInstance_hasOutput = new WeakMap(), _YargsInstance_helpOpt = new WeakMap(), _YargsInstance_isGlobalContext = new WeakMap(), _YargsInstance_logger = new WeakMap(), _YargsInstance_output = new WeakMap(), _YargsInstance_options = new WeakMap(), _YargsInstance_parentRequire = new WeakMap(), _YargsInstance_parserConfig = new WeakMap(), _YargsInstance_parseFn = new WeakMap(), _YargsInstance_parseContext = new WeakMap(), _YargsInstance_pkgs = new WeakMap(), _YargsInstance_preservedGroups = new WeakMap(), _YargsInstance_processArgs = new WeakMap(), _YargsInstance_recommendCommands = new WeakMap(), _YargsInstance_shim = new WeakMap(), _YargsInstance_strict = new WeakMap(), _YargsInstance_strictCommands = new WeakMap(), _YargsInstance_strictOptions = new WeakMap(), _YargsInstance_usage = new WeakMap(), _YargsInstance_usageConfig = new WeakMap(), _YargsInstance_versionOpt = new WeakMap(), _YargsInstance_validation = new WeakMap(), kCopyDoubleDash)](argv) { + if (!argv._ || !argv['--']) + return argv; + argv._.push.apply(argv._, argv['--']); + try { + delete argv['--']; + } + catch (_err) { } + return argv; + } + [kCreateLogger]() { + return { + log: (...args) => { + if (!this[kHasParseCallback]()) + console.log(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + error: (...args) => { + if (!this[kHasParseCallback]()) + console.error(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + }; + } + [kDeleteFromParserHintObject](optionKey) { + objectKeys(__classPrivateFieldGet(this, _YargsInstance_options, "f")).forEach((hintKey) => { + if (((key) => key === 'configObjects')(hintKey)) + return; + const hint = __classPrivateFieldGet(this, _YargsInstance_options, "f")[hintKey]; + if (Array.isArray(hint)) { + if (hint.includes(optionKey)) + hint.splice(hint.indexOf(optionKey), 1); + } + else if (typeof hint === 'object') { + delete hint[optionKey]; + } + }); + delete __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions()[optionKey]; + } + [kEmitWarning](warning, type, deduplicationId) { + if (!__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) { + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.emitWarning(warning, type); + __classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true; + } + } + [kFreeze]() { + __classPrivateFieldGet(this, _YargsInstance_frozens, "f").push({ + options: __classPrivateFieldGet(this, _YargsInstance_options, "f"), + configObjects: __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects.slice(0), + exitProcess: __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"), + groups: __classPrivateFieldGet(this, _YargsInstance_groups, "f"), + strict: __classPrivateFieldGet(this, _YargsInstance_strict, "f"), + strictCommands: __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"), + strictOptions: __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"), + completionCommand: __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), + output: __classPrivateFieldGet(this, _YargsInstance_output, "f"), + exitError: __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), + hasOutput: __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"), + parsed: this.parsed, + parseFn: __classPrivateFieldGet(this, _YargsInstance_parseFn, "f"), + parseContext: __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"), + }); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").freeze(); + } + [kGetDollarZero]() { + let $0 = ''; + let default$0; + if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv()[0])) { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(1, 2); + } + else { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(0, 1); + } + $0 = default$0 + .map(x => { + const b = this[kRebase](__classPrivateFieldGet(this, _YargsInstance_cwd, "f"), x); + return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; + }) + .join(' ') + .trim(); + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_') && + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_')) { + $0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f") + .getEnv('_') + .replace(`${__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.execPath())}/`, ''); + } + return $0; } - const targetFolder = findFolders.length === 1 - ? findFolders[0] - : (await select({ - message: 'Which folder do you wish to open?', - choices: findFolders.map(value => ({ value })), - })); - if (targetFolder) { - executeOpenCMD(config, targetFolder); + [kGetParserConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_parserConfig, "f"); } -}; -const searchFolder = async (config, folder) => { - const { workspaceOnly, alias } = config; - const folderName = alias[folder] || folder; - Log.debug(folderName); - if (workspaceOnly) { - searchWorkspace(config, folderName); + [kGetUsageConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_usageConfig, "f"); } - else { - searchGlobally(config, folderName); + [kGuessLocale]() { + if (!__classPrivateFieldGet(this, _YargsInstance_detectLocale, "f")) + return; + const locale = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_ALL') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_MESSAGES') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANG') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANGUAGE') || + 'en_US'; + this.locale(locale.replace(/[.:].*/, '')); } -}; -const searchGlobally = async (config, folderName) => { - const { ignoreFolders } = config; - Log.debug(folderName); - const rootDirs = await getRootDirs(); - const results = []; - const folderMatcher = (folder) => { - if (minimatch(folder.currentFolder, folderName)) { - results.push(folder.fullPath); + [kGuessVersion]() { + const obj = this[kPkgUp](); + return obj.version || 'unknown'; + } + [kParsePositionalNumbers](argv) { + const args = argv['--'] ? argv['--'] : argv._; + for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && + Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) { + args[i] = Number(arg); + } } - }; - await bfsTravelFolder(rootDirs, folderMatcher, (folder) => ignoreFolders.some(e => minimatch(folder, e))); - handleFindResult(folderName, config, results); -}; -const searchWorkspace = async (config, folderName) => { - const { workspaces, ignoreFolders } = config; - const results = []; - const folderMatcher = (folder) => { - if (minimatch(folder.currentFolder, folderName)) { - results.push(folder.fullPath); + return argv; + } + [kPkgUp](rootPath) { + const npath = rootPath || '*'; + if (__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]) + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + let obj = {}; + try { + let startDir = rootPath || __classPrivateFieldGet(this, _YargsInstance_shim, "f").mainFilename; + if (!rootPath && __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.extname(startDir)) { + startDir = __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(startDir); + } + const pkgJsonPath = __classPrivateFieldGet(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => { + if (names.includes('package.json')) { + return 'package.json'; + } + else { + return undefined; + } + }); + assertNotStrictEqual(pkgJsonPath, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + obj = JSON.parse(__classPrivateFieldGet(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, 'utf8')); + } + catch (_noop) { } + __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath] = obj || {}; + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + } + [kPopulateParserHintArray](type, keys) { + keys = [].concat(keys); + keys.forEach(key => { + key = this[kSanitizeKey](key); + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type].push(key); + }); + } + [kPopulateParserHintSingleValueDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = value; + }); + } + [kPopulateParserHintArrayDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] || []).concat(value); + }); + } + [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) { + if (Array.isArray(key)) { + key.forEach(k => { + builder(k, value); + }); + } + else if (((key) => typeof key === 'object')(key)) { + for (const k of objectKeys(key)) { + builder(k, key[k]); + } + } + else { + singleKeyHandler(type, this[kSanitizeKey](key), value); + } + } + [kSanitizeKey](key) { + if (key === '__proto__') + return '___proto___'; + return key; + } + [kSetKey](key, set) { + this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), 'key', key, set); + return this; + } + [kUnfreeze]() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + const frozen = __classPrivateFieldGet(this, _YargsInstance_frozens, "f").pop(); + assertNotStrictEqual(frozen, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + let configObjects; + (_a = this, _b = this, _c = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, { + options: ({ set value(_o) { __classPrivateFieldSet(_a, _YargsInstance_options, _o, "f"); } }).value, + configObjects, + exitProcess: ({ set value(_o) { __classPrivateFieldSet(_b, _YargsInstance_exitProcess, _o, "f"); } }).value, + groups: ({ set value(_o) { __classPrivateFieldSet(_c, _YargsInstance_groups, _o, "f"); } }).value, + output: ({ set value(_o) { __classPrivateFieldSet(_d, _YargsInstance_output, _o, "f"); } }).value, + exitError: ({ set value(_o) { __classPrivateFieldSet(_e, _YargsInstance_exitError, _o, "f"); } }).value, + hasOutput: ({ set value(_o) { __classPrivateFieldSet(_f, _YargsInstance_hasOutput, _o, "f"); } }).value, + parsed: this.parsed, + strict: ({ set value(_o) { __classPrivateFieldSet(_g, _YargsInstance_strict, _o, "f"); } }).value, + strictCommands: ({ set value(_o) { __classPrivateFieldSet(_h, _YargsInstance_strictCommands, _o, "f"); } }).value, + strictOptions: ({ set value(_o) { __classPrivateFieldSet(_j, _YargsInstance_strictOptions, _o, "f"); } }).value, + completionCommand: ({ set value(_o) { __classPrivateFieldSet(_k, _YargsInstance_completionCommand, _o, "f"); } }).value, + parseFn: ({ set value(_o) { __classPrivateFieldSet(_l, _YargsInstance_parseFn, _o, "f"); } }).value, + parseContext: ({ set value(_o) { __classPrivateFieldSet(_m, _YargsInstance_parseContext, _o, "f"); } }).value, + } = frozen); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = configObjects; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").unfreeze(); + } + [kValidateAsync](validation, argv) { + return maybeAsyncResult(argv, result => { + validation(result); + return result; + }); + } + getInternalMethods() { + return { + getCommandInstance: this[kGetCommandInstance].bind(this), + getContext: this[kGetContext].bind(this), + getHasOutput: this[kGetHasOutput].bind(this), + getLoggerInstance: this[kGetLoggerInstance].bind(this), + getParseContext: this[kGetParseContext].bind(this), + getParserConfiguration: this[kGetParserConfiguration].bind(this), + getUsageConfiguration: this[kGetUsageConfiguration].bind(this), + getUsageInstance: this[kGetUsageInstance].bind(this), + getValidationInstance: this[kGetValidationInstance].bind(this), + hasParseCallback: this[kHasParseCallback].bind(this), + isGlobalContext: this[kIsGlobalContext].bind(this), + postProcess: this[kPostProcess].bind(this), + reset: this[kReset].bind(this), + runValidation: this[kRunValidation].bind(this), + runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this), + setHasOutput: this[kSetHasOutput].bind(this), + }; + } + [kGetCommandInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_command, "f"); + } + [kGetContext]() { + return __classPrivateFieldGet(this, _YargsInstance_context, "f"); + } + [kGetHasOutput]() { + return __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"); + } + [kGetLoggerInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_logger, "f"); + } + [kGetParseContext]() { + return __classPrivateFieldGet(this, _YargsInstance_parseContext, "f") || {}; + } + [kGetUsageInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f"); + } + [kGetValidationInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_validation, "f"); + } + [kHasParseCallback]() { + return !!__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"); + } + [kIsGlobalContext]() { + return __classPrivateFieldGet(this, _YargsInstance_isGlobalContext, "f"); + } + [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) { + if (calledFromCommand) + return argv; + if (isPromise(argv)) + return argv; + if (!populateDoubleDash) { + argv = this[kCopyDoubleDash](argv); + } + const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] || + this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined; + if (parsePositionalNumbers) { + argv = this[kParsePositionalNumbers](argv); + } + if (runGlobalMiddleware) { + argv = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + } + return argv; + } + [kReset](aliases = {}) { + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f") || {}, "f"); + const tmpOptions = {}; + tmpOptions.local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local || []; + tmpOptions.configObjects = __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []; + const localLookup = {}; + tmpOptions.local.forEach(l => { + localLookup[l] = true; + (aliases[l] || []).forEach(a => { + localLookup[a] = true; + }); + }); + Object.assign(__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => { + const keys = __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName].filter(key => !(key in localLookup)); + if (keys.length > 0) { + acc[groupName] = keys; + } + return acc; + }, {})); + __classPrivateFieldSet(this, _YargsInstance_groups, {}, "f"); + const arrayOptions = [ + 'array', + 'boolean', + 'string', + 'skipValidation', + 'count', + 'normalize', + 'number', + 'hiddenOptions', + ]; + const objectOptions = [ + 'narg', + 'key', + 'alias', + 'default', + 'defaultDescription', + 'config', + 'choices', + 'demandedOptions', + 'demandedCommands', + 'deprecatedOptions', + ]; + arrayOptions.forEach(k => { + tmpOptions[k] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[k] || []).filter((k) => !localLookup[k]); + }); + objectOptions.forEach((k) => { + tmpOptions[k] = objFilter(__classPrivateFieldGet(this, _YargsInstance_options, "f")[k], k => !localLookup[k]); + }); + tmpOptions.envPrefix = __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + __classPrivateFieldSet(this, _YargsInstance_options, tmpOptions, "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f") + ? __classPrivateFieldGet(this, _YargsInstance_usage, "f").reset(localLookup) + : usage(this, __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f") + ? __classPrivateFieldGet(this, _YargsInstance_validation, "f").reset(localLookup) + : validation(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f") + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").reset() + : command$1(__classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_validation, "f"), __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_completion, "f")) + __classPrivateFieldSet(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_command, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").reset(); + __classPrivateFieldSet(this, _YargsInstance_completionCommand, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_output, '', "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, false, "f"); + this.parsed = false; + return this; + } + [kRebase](base, dir) { + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.relative(base, dir); + } + [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) { + let skipValidation = !!calledFromCommand || helpOnly; + args = args || __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__; + __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration](); + const populateDoubleDash = !!__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration['populate--']; + const config = Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration, { + 'populate--': true, + }); + const parsed = __classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f"), { + configuration: { 'parse-positional-numbers': false, ...config }, + })); + const argv = Object.assign(parsed.argv, __classPrivateFieldGet(this, _YargsInstance_parseContext, "f")); + let argvPromise = undefined; + const aliases = parsed.aliases; + let helpOptSet = false; + let versionOptSet = false; + Object.keys(argv).forEach(key => { + if (key === __classPrivateFieldGet(this, _YargsInstance_helpOpt, "f") && argv[key]) { + helpOptSet = true; + } + else if (key === __classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && argv[key]) { + versionOptSet = true; + } + }); + argv.$0 = this.$0; + this.parsed = parsed; + if (commandIndex === 0) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").clearCachedHelpMessage(); } - }; - await bfsTravelFolder(workspaces, folderMatcher, (folder) => ignoreFolders.some(e => minimatch(folder, e))); - handleFindResult(folderName, config, results); -}; -const bfsTravelFolder = async (folderPathList, callback, shouldIgnore) => { - const folders = _.flattenDeep(await Promise.all(folderPathList.map(async (folderPath) => { try { - const underlayFolder = await fs$e.readdir(folderPath, { withFileTypes: true }); - return underlayFolder.filter(e => e.isDirectory() && !shouldIgnore(e.name)).map(e => ({ - fullPath: require$$1$1.resolve(e.path, e.name), - currentFolder: e.name, - })); + this[kGuessLocale](); + if (shortCircuit) { + return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false); + } + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + const helpCmds = [__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] + .concat(aliases[__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] || []) + .filter(k => k.length > 1); + if (helpCmds.includes('' + argv._[argv._.length - 1])) { + argv._.pop(); + helpOptSet = true; + } + } + __classPrivateFieldSet(this, _YargsInstance_isGlobalContext, false, "f"); + const handlerKeys = __classPrivateFieldGet(this, _YargsInstance_command, "f").getCommands(); + const requestCompletions = __classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey in argv; + const skipRecommendation = helpOptSet || requestCompletions || helpOnly; + if (argv._.length) { + if (handlerKeys.length) { + let firstUnknownCommand; + for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) { + cmd = String(argv._[i]); + if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + else if (!firstUnknownCommand && + cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + firstUnknownCommand = cmd; + break; + } + } + if (!__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && + __classPrivateFieldGet(this, _YargsInstance_recommendCommands, "f") && + firstUnknownCommand && + !skipRecommendation) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") && + argv._.includes(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) && + !requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + this.showCompletionScript(); + this.exit(0); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + if (requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + args = [].concat(args); + const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey}`) + 1); + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => { + if (err) + throw new YError(err.message); + (completions || []).forEach(completion => { + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(completion); + }); + this.exit(0); + }); + return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false); + } + if (!__classPrivateFieldGet(this, _YargsInstance_hasOutput, "f")) { + if (helpOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + this.showHelp('log'); + this.exit(0); + } + else if (versionOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion('log'); + this.exit(0); + } + } + if (!skipValidation && __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.length > 0) { + skipValidation = Object.keys(argv).some(key => __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true); + } + if (!skipValidation) { + if (parsed.error) + throw new YError(parsed.error.message); + if (!requestCompletions) { + const validation = this[kRunValidation](aliases, {}, parsed.error); + if (!calledFromCommand) { + argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true); + } + argvPromise = this[kValidateAsync](validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv); + if (isPromise(argvPromise) && !calledFromCommand) { + argvPromise = argvPromise.then(() => { + return applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + }); + } + } + } } - catch (error) { - Log.error(error); - return []; + catch (err) { + if (err instanceof YError) + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message, err); + else + throw err; } - }))); - folders.forEach(folder => { - callback(folder); - }); - if (folders.length > 0) { - await bfsTravelFolder(folders.map(e => e.fullPath), callback, shouldIgnore); + return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true); } -}; -const getRootDirs = async () => { - const isWin = require$$0$7.platform() === 'win32'; - const roots = isWin ? (await systemInfo.blockDevices()).slice(1).map(e => `${e.identifier}${require$$1$1.sep}`) : ['/']; - return roots; -}; + [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) { + const demandedOptions = { ...this.getDemandedOptions() }; + return (argv) => { + if (parseErrors) + throw new YError(parseErrors.message); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").nonOptionCount(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions); + let failedStrictCommands = false; + if (__classPrivateFieldGet(this, _YargsInstance_strictCommands, "f")) { + failedStrictCommands = __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownCommands(argv); + } + if (__classPrivateFieldGet(this, _YargsInstance_strict, "f") && !failedStrictCommands) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand); + } + else if (__classPrivateFieldGet(this, _YargsInstance_strictOptions, "f")) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false); + } + __classPrivateFieldGet(this, _YargsInstance_validation, "f").limitedChoices(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implications(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicting(argv); + }; + } + [kSetHasOutput]() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + } + [kTrackManuallySetKeys](keys) { + if (typeof keys === 'string') { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; + } + else { + for (const k of keys) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[k] = true; + } + } + } +} +function isYargsInstance(y) { + return !!y && typeof y.getInternalMethods === 'function'; +} + +const Yargs = YargsFactory(shim$1); + +const argv = Yargs(hideBin(process.argv)) + .scriptName("openc") + .command('', `Open the project using the preset commands, Similarly ** matching is possible for , like project**`) + .command('config', 'print config') + .command('openCMD', 'Setting up the open command when a folder is found, default is \'code $folder\' for vscode. \'idea $folder\' is example for IntelliJ IDEA (Make sure the command \'idea\' is available)') + .command('workspaces add ', `Adding a list of folders to find for the \'openc\' command`) + .command('workspaces rm ', `Remove workspace from config`) + .command('workspaces ls', `List config workspaces`) + .command('workspaces clear', `Clear workspaces`) + .command('alias ', `Set an alias for a frequently used folder, so you can open it with the alias next time.`) + .command('alias ', `Remove alias`) + .command('alias clear', `Clear alias`) + .command('alias print', `Print alias`) + .command('ignoreFolders add ', `Set the name of the folder to ignore, default is ["node_modules", ". **"], these folders will be ignored when searching for files.Matching functionality via \'minimatch\'`) + .command('ignoreFolders rm ', `Remove folderName from ignoreList`) + .command('ignoreFolders ls', `List ignoreFolders`) + .command('ignoreFolders clear', `Clear ignoreFolders`) + .command('workspaceOnly ', `Default is true, setting it to false will cause the \'openc\' command to globally find the folder.`) + .demandCommand() + .parse(); -const argv = Yargs(hideBin(process.argv)).argv; const [command, ...args] = argv._; if (!command) { - Log.error('required command'); + Log.error('required args'); process.exit(1); } (async () => { diff --git a/package.json b/package.json index 8ffaaed..fb5ccab 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "code-opener-cli", - "version": "0.0.8", + "version": "0.1.0", "description": "command line interface code opener", "repository": { "type": "git", diff --git a/src/cliDoc.ts b/src/cliDoc.ts new file mode 100644 index 0000000..4835421 --- /dev/null +++ b/src/cliDoc.ts @@ -0,0 +1,75 @@ +import yargs from 'yargs'; +import { hideBin } from 'yargs/helpers'; + +export const argv = <{ _: string[], [k: string]: unknown }> yargs(hideBin(process.argv)) + .scriptName("openc") + .command( + '', + `Open the project using the preset commands, Similarly ** matching is possible for , like project**` + ) + .command( + 'config', + 'print config' + ) + .command( + 'openCMD', + 'Setting up the open command when a folder is found, default is \'code $folder\' for vscode. \'idea $folder\' is example for IntelliJ IDEA (Make sure the command \'idea\' is available)' + ) + + .command( + 'workspaces add ', + `Adding a list of folders to find for the \'openc\' command` + ) + .command( + 'workspaces rm ', + `Remove workspace from config` + ) + .command( + 'workspaces ls', + `List config workspaces` + ) + .command( + 'workspaces clear', + `Clear workspaces` + ) + + .command( + 'alias ', + `Set an alias for a frequently used folder, so you can open it with the alias next time.` + ) + .command( + 'alias ', + `Remove alias` + ) + .command( + 'alias clear', + `Clear alias` + ) + .command( + 'alias print', + `Print alias` + ) + + .command( + 'ignoreFolders add ', + `Set the name of the folder to ignore, default is ["node_modules", ". **"], these folders will be ignored when searching for files.Matching functionality via \'minimatch\'` + ) + .command( + 'ignoreFolders rm ', + `Remove folderName from ignoreList` + ) + .command( + 'ignoreFolders ls', + `List ignoreFolders` + ) + .command( + 'ignoreFolders clear', + `Clear ignoreFolders` + ) + + .command( + 'workspaceOnly ', + `Default is true, setting it to false will cause the \'openc\' command to globally find the folder.` + ) + .demandCommand() + .parse() diff --git a/src/index.ts b/src/index.ts index b4cf46e..4ca5073 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,25 +1,17 @@ -import yargs from 'yargs'; -import { hideBin } from 'yargs/helpers'; import { SETTING_COMMANDS, changeConfig, readConfig, writeConfig } from './configFile'; import { Log, formatObjectJson } from './utils'; import { searchFolder } from './folderSearch'; - -const argv = <{ _: string[] }> yargs(hideBin(process.argv)).argv; +import { argv } from './cliDoc'; const [command, ...args] = argv._; -if (!command) { - Log.error('required command') - process.exit(1); -} - ;(async () => { const config = await readConfig(); Log.debug('config:', formatObjectJson(config)); if (SETTING_COMMANDS.includes(command)) { Log.debug(command, ...args); - changeConfig(command, ...args) + changeConfig(command, ...args); return; }