lib/validation.ts
520 LOC · 520 covered · 0 uncovered · 125 ranges · 1119 concepts · 59 introducers · 788 tests
File neighbourhood
The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.
Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file
In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.
Graph controls are ready.
Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.
import {
Dictionary,
assertNotStrictEqual,
PlatformShim,
} from './typings/common-types.js';
import {levenshtein as distance} from './utils/levenshtein.js';
import {objFilter} from './utils/obj-filter.js';
import {UsageInstance} from './usage.js';
import {YargsInstance, Arguments} from './yargs-factory.js';
import {DetailedArguments} from './typings/yargs-parser-types.js';
const specialKeys = ['$0', '--', '_'];
// validation-type-stuff, missing params,
// bad implications:
export function validation(
usage: UsageInstance,
shim: PlatformShim
) {
const __ = shim.y18n.__;
const __n = shim.y18n.__n;
const self = {} as ValidationInstance;
// validate appropriate # of non-option
// arguments were provided, i.e., '_'.
self.nonOptionCount = function nonOptionCount(argv) {
// don't count currently executing commands
const positionalCount =
argv._.length + (argv['--'] ? argv['--'].length : 0);
const _s =
positionalCount - yargs.getInternalMethods().getContext().commands.length;
if (
demandedCommands._ &&
// replace $0 with observed, $1 with expected.
demandedCommands._.minMsg
? demandedCommands._.minMsg
.replace(/\$1/, demandedCommands._.min.toString())
);
__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()
)
);
}
// replace $0 with observed, $1 with expected.
demandedCommands._.maxMsg
? demandedCommands._.maxMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.max.toString())
: null
);
__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()
)
);
}
// validate the appropriate # of <required>
// positional arguments were provided:
self.positionalCount = function positionalCount(required, observed) {
__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 + ''
)
);
}
// make sure all the required arguments are present.
self.requiredArguments = function requiredArguments(
demandedOptions: Dictionary<string | undefined>
) {
let missing: Dictionary<string | undefined> | null = null;
for (const key of Object.keys(demandedOptions)) {
!Object.prototype.hasOwnProperty.call(argv, key) ||
missing[key] = demandedOptions[key];
}
if (missing) {
for (const key of Object.keys(missing)) {
const msg = missing[key];
if (msg && customMsgs.indexOf(msg) < 0) {
}
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
)
);
}
// check for unknown arguments (strict-mode).
self.unknownArguments = function unknownArguments(
aliases,
positionalMap,
isDefaultCommand,
checkPositionals = true
) {
const commandKeys = yargs
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
Object.keys(argv).forEach(key => {
if (
!specialKeys.includes(key) &&
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
yargs.getInternalMethods().getParseContext(),
key
}
if (
checkPositionals &&
commandKeys.length > 0 ||
isDefaultCommand)
unknown.push('' + key);
}
}
// https://github.com/yargs/yargs/issues/1861
if (checkPositionals) {
// Take into account expected args from commands and yargs.demand(number)
const demandedCommands = yargs.getDemandedCommands();
const maxNonOptDemanded = demandedCommands._?.max || 0;
const expected = currentContext.commands.length + maxNonOptDemanded;
if (expected < argv._.length) {
key = String(key);
if (
!currentContext.commands.includes(key) &&
!unknown.includes(key)
) {
}
}
if (unknown.length) {
__n(
'Unknown argument: %s',
'Unknown arguments: %s',
unknown.length,
unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', ')
)
);
}
self.unknownCommands = function unknownCommands(argv) {
.getInternalMethods()
.getCommandInstance()
.getCommands();
const unknown: string[] = [];
const currentContext = yargs.getInternalMethods().getContext();
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach(key => {
unknown.push('' + key);
}
}
if (unknown.length > 0) {
__n(
'Unknown command: %s',
'Unknown commands: %s',
unknown.length,
unknown.join(', ')
)
);
return true;
}
// check for a key that is not an alias, or for which every alias is new,
// implying that it was invented by the parser, e.g., during camelization
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(
aliases
) {
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
}
return [key, ...aliases[key]].some(
a =>
!Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]
);
// validate arguments limited to enumerated choices
self.limitedChoices = function limitedChoices(argv) {
const invalid: Dictionary<any[]> = {};
if (!Object.keys(options.choices).length) return;
Object.keys(argv).forEach(key => {
if (
specialKeys.indexOf(key) === -1 &&
// TODO case-insensitive configurability
if (
options.choices[key].indexOf(value) === -1 &&
}
}
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);
// check implications, argument foo implies => argument bar.
let implied: Dictionary<KeyOrPos[]> = {};
self.implies = function implies(key, value) {
'<string|object> [array|number|string]',
[key, value],
arguments.length
);
if (typeof key === 'object') {
self.implies(k, key[k]);
});
yargs.global(key);
if (!implied[key]) {
implied[key] = [];
}
if (Array.isArray(value)) {
assertNotStrictEqual(value, undefined, shim);
implied[key].push(value);
}
}
self.getImplied = function getImplied() {
function keyExists(argv: Arguments, val: any): any {
const num = Number(val);
val = isNaN(num) ? val : num;
if (typeof val === 'number') {
val = argv._.length >= val;
val = val.match(/^--no-(.+)/)[1];
val = !Object.prototype.hasOwnProperty.call(argv, val);
// check if key/value exists
val = Object.prototype.hasOwnProperty.call(argv, val);
}
return val;
}
self.implications = function implications(argv) {
Object.keys(implied).forEach(key => {
(implied[key] || []).forEach(value => {
let key = origKey;
const origValue = value;
key = keyExists(argv, key);
value = keyExists(argv, value);
if (key && !value) {
}
if (implyFail.length) {
implyFail.forEach(value => {
msg += value;
});
usage.fail(msg);
}
let conflicting: Dictionary<(string | undefined)[]> = {};
self.conflicts = function conflicts(key, value) {
if (typeof key === 'object') {
self.conflicts(k, key[k]);
});
yargs.global(key);
if (!conflicting[key]) {
conflicting[key] = [];
}
if (Array.isArray(value)) {
conflicting[key].push(value);
}
}
self.getConflicting = () => conflicting;
self.conflicting = function conflictingFn(argv) {
if (conflicting[key]) {
// we default keys to 'undefined' that have been configured, we should not
// apply conflicting check unless they are a value other than 'undefined'.
if (value && argv[key] !== undefined && argv[value] !== undefined) {
__('Arguments %s and %s are mutually exclusive', key, value)
);
}
}
// When strip-dashed is true, match conflicts (kebab) with argv (camel)
// Addresses: https://github.com/yargs/yargs/issues/1952
if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) {
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) {
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 = distance(cmd, candidate);
if (d <= threshold && d < bestDistance) {
recommended = candidate;
}
if (recommended) usage.fail(__('Did you mean %s?', recommended));
self.reset = function reset(localLookup) {
conflicting = objFilter(conflicting, k => !localLookup[k]);
return self;
const frozens: FrozenValidationInstance[] = [];
self.freeze = function freeze() {
implied,
conflicting,
});
self.unfreeze = function unfreeze() {
assertNotStrictEqual(frozen, undefined, shim);
({implied, conflicting} = frozen);
return self;
}
/** Instance of the validation module. */
export interface ValidationInstance {
conflicting(argv: Arguments): void;
conflicts(
key: string | Dictionary<string | string[]>,
value?: string | string[]
): void;
freeze(): void;
getConflicting(): Dictionary<(string | undefined)[]>;
getImplied(): Dictionary<KeyOrPos[]>;
implications(argv: Arguments): void;
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): void;
isValidAndSomeAliasIsNotNew(
key: string,
aliases: DetailedArguments['aliases']
): boolean;
limitedChoices(argv: Arguments): void;
nonOptionCount(argv: Arguments): void;
positionalCount(required: number, observed: number): void;
recommendCommands(cmd: string, potentialCommands: string[]): void;
requiredArguments(
argv: Arguments,
demandedOptions: Dictionary<string | undefined>
): void;
reset(localLookup: Dictionary): ValidationInstance;
unfreeze(): void;
unknownArguments(
argv: Arguments,
aliases: DetailedArguments['aliases'],
positionalMap: Dictionary,
isDefaultCommand: boolean,
checkPositionals?: boolean
): void;
unknownCommands(argv: Arguments): boolean;
}
interface FrozenValidationInstance {
implied: Dictionary<KeyOrPos[]>;
conflicting: Dictionary<(string | undefined)[]>;
}
export type KeyOrPos = string | number;