id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
2,700 | optimizeNames(names: UsedNames, constants: Constants): this | undefined {
if (!super.optimizeNames(names, constants)) return
this.iterable = optimizeExpr(this.iterable, names, constants)
return this
} | type Constants = Record<string, SafeExpr | undefined> |
2,701 | optimizeNames(names: UsedNames, constants: Constants): this | undefined {
if (!super.optimizeNames(names, constants)) return
this.iterable = optimizeExpr(this.iterable, names, constants)
return this
} | type UsedNames = Record<string, number | undefined> |
2,702 | constructor(public name: Name, public args: Code, public async?: boolean) {
super()
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,703 | constructor(public name: Name, public args: Code, public async?: boolean) {
super()
} | type Code = _Code | Name |
2,704 | render(opts: CGOptions): string {
const _async = this.async ? "async " : ""
return `${_async}function ${this.name}(${this.args})` + super.render(opts)
} | interface CGOptions extends CodeGenOptions {
_n: "\n" | ""
} |
2,705 | render(opts: CGOptions): string {
return "return " + super.render(opts)
} | interface CGOptions extends CodeGenOptions {
_n: "\n" | ""
} |
2,706 | render(opts: CGOptions): string {
let code = "try" + super.render(opts)
if (this.catch) code += this.catch.render(opts)
if (this.finally) code += this.finally.render(opts)
return code
} | interface CGOptions extends CodeGenOptions {
_n: "\n" | ""
} |
2,707 | optimizeNames(names: UsedNames, constants: Constants): this {
super.optimizeNames(names, constants)
this.catch?.optimizeNames(names, constants)
this.finally?.optimizeNames(names, constants)
return this
} | type Constants = Record<string, SafeExpr | undefined> |
2,708 | optimizeNames(names: UsedNames, constants: Constants): this {
super.optimizeNames(names, constants)
this.catch?.optimizeNames(names, constants)
this.finally?.optimizeNames(names, constants)
return this
} | type UsedNames = Record<string, number | undefined> |
2,709 | constructor(readonly error: Name) {
super()
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,710 | render(opts: CGOptions): string {
return `catch(${this.error})` + super.render(opts)
} | interface CGOptions extends CodeGenOptions {
_n: "\n" | ""
} |
2,711 | render(opts: CGOptions): string {
return "finally" + super.render(opts)
} | interface CGOptions extends CodeGenOptions {
_n: "\n" | ""
} |
2,712 | constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
this.opts = {...opts, _n: opts.lines ? "\n" : ""}
this._extScope = extScope
this._scope = new Scope({parent: extScope})
this._nodes = [new Root()]
} | class ValueScope extends Scope {
protected readonly _values: ScopeValues = {}
protected readonly _scope: ScopeStore
readonly opts: VSOptions
constructor(opts: ValueScopeOptions) {
super(opts)
this._scope = opts.scope
this.opts = {...opts, _n: opts.lines ? line : nil}
}
get(): ScopeStore {
return this._scope
}
name(prefix: string): ValueScopeName {
return new ValueScopeName(prefix, this._newName(prefix))
}
value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {
if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value")
const name = this.toName(nameOrPrefix) as ValueScopeName
const {prefix} = name
const valueKey = value.key ?? value.ref
let vs = this._values[prefix]
if (vs) {
const _name = vs.get(valueKey)
if (_name) return _name
} else {
vs = this._values[prefix] = new Map()
}
vs.set(valueKey, name)
const s = this._scope[prefix] || (this._scope[prefix] = [])
const itemIndex = s.length
s[itemIndex] = value.ref
name.setValue(value, {property: prefix, itemIndex})
return name
}
getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
const vs = this._values[prefix]
if (!vs) return
return vs.get(keyOrRef)
}
scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {
return this._reduceValues(values, (name: ValueScopeName) => {
if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
return _`${scopeName}${name.scopePath}`
})
}
scopeCode(
values: ScopeValues | ScopeValueSets = this._values,
usedValues?: UsedScopeValues,
getCode?: (n: ValueScopeName) => Code | undefined
): Code {
return this._reduceValues(
values,
(name: ValueScopeName) => {
if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
return name.value.code
},
usedValues,
getCode
)
}
private _reduceValues(
values: ScopeValues | ScopeValueSets,
valueCode: (n: ValueScopeName) => Code | undefined,
usedValues: UsedScopeValues = {},
getCode?: (n: ValueScopeName) => Code | undefined
): Code {
let code: Code = nil
for (const prefix in values) {
const vs = values[prefix]
if (!vs) continue
const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())
vs.forEach((name: ValueScopeName) => {
if (nameSet.has(name)) return
nameSet.set(name, UsedValueState.Started)
let c = valueCode(name)
if (c) {
const def = this.opts.es5 ? varKinds.var : varKinds.const
code = _`${code}${def} ${name} = ${c};${this.opts._n}`
} else if ((c = getCode?.(name))) {
code = _`${code}${c}${this.opts._n}`
} else {
throw new ValueError(name)
}
nameSet.set(name, UsedValueState.Completed)
})
}
return code
}
} |
2,713 | constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
this.opts = {...opts, _n: opts.lines ? "\n" : ""}
this._extScope = extScope
this._scope = new Scope({parent: extScope})
this._nodes = [new Root()]
} | interface CodeGenOptions {
es5?: boolean
lines?: boolean
ownProperties?: boolean
} |
2,714 | scopeRefs(scopeName: Name): Code {
return this._extScope.scopeRefs(scopeName, this._values)
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,715 | private _def(
varKind: Name,
nameOrPrefix: Name | string,
rhs?: SafeExpr,
constant?: boolean
): Name {
const name = this._scope.toName(nameOrPrefix)
if (rhs !== undefined && constant) this._constants[name.str] = rhs
this._leafNode(new Def(varKind, name, rhs))
return name
} | type SafeExpr = Code | number | boolean | null |
2,716 | private _def(
varKind: Name,
nameOrPrefix: Name | string,
rhs?: SafeExpr,
constant?: boolean
): Name {
const name = this._scope.toName(nameOrPrefix)
if (rhs !== undefined && constant) this._constants[name.str] = rhs
this._leafNode(new Def(varKind, name, rhs))
return name
} | type SafeExpr = Code | number | boolean | null |
2,717 | private _def(
varKind: Name,
nameOrPrefix: Name | string,
rhs?: SafeExpr,
constant?: boolean
): Name {
const name = this._scope.toName(nameOrPrefix)
if (rhs !== undefined && constant) this._constants[name.str] = rhs
this._leafNode(new Def(varKind, name, rhs))
return name
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,718 | assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
return this._leafNode(new Assign(lhs, rhs, sideEffects))
} | type SafeExpr = Code | number | boolean | null |
2,719 | assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
return this._leafNode(new Assign(lhs, rhs, sideEffects))
} | type SafeExpr = Code | number | boolean | null |
2,720 | assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
return this._leafNode(new Assign(lhs, rhs, sideEffects))
} | type Code = _Code | Name |
2,721 | add(lhs: Code, rhs: SafeExpr): CodeGen {
return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
} | type SafeExpr = Code | number | boolean | null |
2,722 | add(lhs: Code, rhs: SafeExpr): CodeGen {
return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
} | type SafeExpr = Code | number | boolean | null |
2,723 | add(lhs: Code, rhs: SafeExpr): CodeGen {
return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
} | type Code = _Code | Name |
2,724 | private _for(node: For, forBody?: Block): CodeGen {
this._blockNode(node)
if (forBody) this.code(forBody).endFor()
return this
} | type Block = Code | (() => void) |
2,725 | for(iteration: Code, forBody?: Block): CodeGen {
return this._for(new ForLoop(iteration), forBody)
} | type Block = Code | (() => void) |
2,726 | for(iteration: Code, forBody?: Block): CodeGen {
return this._for(new ForLoop(iteration), forBody)
} | type Code = _Code | Name |
2,727 | (index: Name) => void | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,728 | (item: Name) => void | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,729 | label(label: Name): CodeGen {
return this._leafNode(new Label(label))
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,730 | break(label?: Code): CodeGen {
return this._leafNode(new Break(label))
} | type Code = _Code | Name |
2,731 | try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
const node = new Try()
this._blockNode(node)
this.code(tryBody)
if (catchCode) {
const error = this.name("e")
this._currNode = node.catch = new Catch(error)
catchCode(error)
}
if (finallyCode) {
this._currNode = node.finally = new Finally()
this.code(finallyCode)
}
return this._endBlockNode(Catch, Finally)
} | type Block = Code | (() => void) |
2,732 | try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
const node = new Try()
this._blockNode(node)
this.code(tryBody)
if (catchCode) {
const error = this.name("e")
this._currNode = node.catch = new Catch(error)
catchCode(error)
}
if (finallyCode) {
this._currNode = node.finally = new Finally()
this.code(finallyCode)
}
return this._endBlockNode(Catch, Finally)
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,733 | (e: Name) => void | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,734 | throw(error: Code): CodeGen {
return this._leafNode(new Throw(error))
} | type Code = _Code | Name |
2,735 | block(body?: Block, nodeCount?: number): CodeGen {
this._blockStarts.push(this._nodes.length)
if (body) this.code(body).endBlock(nodeCount)
return this
} | type Block = Code | (() => void) |
2,736 | func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
this._blockNode(new Func(name, args, async))
if (funcBody) this.code(funcBody).endFunc()
return this
} | type Block = Code | (() => void) |
2,737 | func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
this._blockNode(new Func(name, args, async))
if (funcBody) this.code(funcBody).endFunc()
return this
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,738 | func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
this._blockNode(new Func(name, args, async))
if (funcBody) this.code(funcBody).endFunc()
return this
} | type Code = _Code | Name |
2,739 | private _leafNode(node: LeafNode): CodeGen {
this._currNode.nodes.push(node)
return this
} | type LeafNode = Def | Assign | Label | Break | Throw | AnyCode |
2,740 | private _blockNode(node: StartBlockNode): void {
this._currNode.nodes.push(node)
this._nodes.push(node)
} | type StartBlockNode = If | For | Func | Return | Try |
2,741 | private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
const n = this._currNode
if (n instanceof N1 || (N2 && n instanceof N2)) {
this._nodes.pop()
return this
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
} | type EndBlockNodeType =
| typeof If
| typeof Else
| typeof For
| typeof Func
| typeof Return
| typeof Catch
| typeof Finally |
2,742 | function addNames(names: UsedNames, from: UsedNames): UsedNames {
for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)
return names
} | type UsedNames = Record<string, number | undefined> |
2,743 | function addExprNames(names: UsedNames, from: SafeExpr): UsedNames {
return from instanceof _CodeOrName ? addNames(names, from.names) : names
} | type SafeExpr = Code | number | boolean | null |
2,744 | function addExprNames(names: UsedNames, from: SafeExpr): UsedNames {
return from instanceof _CodeOrName ? addNames(names, from.names) : names
} | type SafeExpr = Code | number | boolean | null |
2,745 | function addExprNames(names: UsedNames, from: SafeExpr): UsedNames {
return from instanceof _CodeOrName ? addNames(names, from.names) : names
} | type UsedNames = Record<string, number | undefined> |
2,746 | function optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T | type Constants = Record<string, SafeExpr | undefined> |
2,747 | function optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T | type UsedNames = Record<string, number | undefined> |
2,748 | function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {
if (expr instanceof Name) return replaceName(expr)
if (!canOptimize(expr)) return expr
return new _Code(
expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {
if (c instanceof Name) c = replaceName(c)
if (c instanceof _Code) items.push(...c._items)
else items.push(c)
return items
}, [])
)
function replaceName(n: Name): SafeExpr {
const c = constants[n.str]
if (c === undefined || names[n.str] !== 1) return n
delete names[n.str]
return c
}
function canOptimize(e: SafeExpr): e is _Code {
return (
e instanceof _Code &&
e._items.some(
(c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
)
)
}
} | type SafeExpr = Code | number | boolean | null |
2,749 | function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {
if (expr instanceof Name) return replaceName(expr)
if (!canOptimize(expr)) return expr
return new _Code(
expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {
if (c instanceof Name) c = replaceName(c)
if (c instanceof _Code) items.push(...c._items)
else items.push(c)
return items
}, [])
)
function replaceName(n: Name): SafeExpr {
const c = constants[n.str]
if (c === undefined || names[n.str] !== 1) return n
delete names[n.str]
return c
}
function canOptimize(e: SafeExpr): e is _Code {
return (
e instanceof _Code &&
e._items.some(
(c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
)
)
}
} | type SafeExpr = Code | number | boolean | null |
2,750 | function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {
if (expr instanceof Name) return replaceName(expr)
if (!canOptimize(expr)) return expr
return new _Code(
expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {
if (c instanceof Name) c = replaceName(c)
if (c instanceof _Code) items.push(...c._items)
else items.push(c)
return items
}, [])
)
function replaceName(n: Name): SafeExpr {
const c = constants[n.str]
if (c === undefined || names[n.str] !== 1) return n
delete names[n.str]
return c
}
function canOptimize(e: SafeExpr): e is _Code {
return (
e instanceof _Code &&
e._items.some(
(c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
)
)
}
} | type UsedNames = Record<string, number | undefined> |
2,751 | function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {
if (expr instanceof Name) return replaceName(expr)
if (!canOptimize(expr)) return expr
return new _Code(
expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {
if (c instanceof Name) c = replaceName(c)
if (c instanceof _Code) items.push(...c._items)
else items.push(c)
return items
}, [])
)
function replaceName(n: Name): SafeExpr {
const c = constants[n.str]
if (c === undefined || names[n.str] !== 1) return n
delete names[n.str]
return c
}
function canOptimize(e: SafeExpr): e is _Code {
return (
e instanceof _Code &&
e._items.some(
(c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
)
)
}
} | type Constants = Record<string, SafeExpr | undefined> |
2,752 | function replaceName(n: Name): SafeExpr {
const c = constants[n.str]
if (c === undefined || names[n.str] !== 1) return n
delete names[n.str]
return c
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,753 | function canOptimize(e: SafeExpr): e is _Code {
return (
e instanceof _Code &&
e._items.some(
(c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
)
)
} | type SafeExpr = Code | number | boolean | null |
2,754 | function canOptimize(e: SafeExpr): e is _Code {
return (
e instanceof _Code &&
e._items.some(
(c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
)
)
} | type SafeExpr = Code | number | boolean | null |
2,755 | function subtractNames(names: UsedNames, from: UsedNames): void {
for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)
} | type UsedNames = Record<string, number | undefined> |
2,756 | (x: Code, y: Code) => Code | type Code = _Code | Name |
2,757 | function mappend(op: Code): MAppend {
return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)
} | type Code = _Code | Name |
2,758 | function par(x: Code): Code {
return x instanceof Name ? x : _`(${x})`
} | type Code = _Code | Name |
2,759 | constructor(name: ValueScopeName) {
super(`CodeGen: "code" for ${name} not defined`)
this.value = name.value
} | class ValueScopeName extends Name {
readonly prefix: string
value?: NameValue
scopePath?: Code
constructor(prefix: string, nameStr: string) {
super(nameStr)
this.prefix = prefix
}
setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
}
} |
2,760 | constructor({prefixes, parent}: ScopeOptions = {}) {
this._prefixes = prefixes
this._parent = parent
} | interface ScopeOptions {
prefixes?: Set<string>
parent?: Scope
} |
2,761 | setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
} | interface NameValue {
ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure
key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used
code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)
} |
2,762 | setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
} | interface ScopePath {
property: string
itemIndex: number
} |
2,763 | constructor(opts: ValueScopeOptions) {
super(opts)
this._scope = opts.scope
this.opts = {...opts, _n: opts.lines ? line : nil}
} | interface ValueScopeOptions extends ScopeOptions {
scope: ScopeStore
es5?: boolean
lines?: boolean
} |
2,764 | scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {
return this._reduceValues(values, (name: ValueScopeName) => {
if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
return _`${scopeName}${name.scopePath}`
})
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,765 | (name: ValueScopeName) => {
if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
return _`${scopeName}${name.scopePath}`
} | class ValueScopeName extends Name {
readonly prefix: string
value?: NameValue
scopePath?: Code
constructor(prefix: string, nameStr: string) {
super(nameStr)
this.prefix = prefix
}
setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
}
} |
2,766 | (n: ValueScopeName) => Code | undefined | class ValueScopeName extends Name {
readonly prefix: string
value?: NameValue
scopePath?: Code
constructor(prefix: string, nameStr: string) {
super(nameStr)
this.prefix = prefix
}
setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
}
} |
2,767 | (name: ValueScopeName) => {
if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
return name.value.code
} | class ValueScopeName extends Name {
readonly prefix: string
value?: NameValue
scopePath?: Code
constructor(prefix: string, nameStr: string) {
super(nameStr)
this.prefix = prefix
}
setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
}
} |
2,768 | (name: ValueScopeName) => {
if (nameSet.has(name)) return
nameSet.set(name, UsedValueState.Started)
let c = valueCode(name)
if (c) {
const def = this.opts.es5 ? varKinds.var : varKinds.const
code = _`${code}${def} ${name} = ${c};${this.opts._n}`
} else if ((c = getCode?.(name))) {
code = _`${code}${c}${this.opts._n}`
} else {
throw new ValueError(name)
}
nameSet.set(name, UsedValueState.Completed)
} | class ValueScopeName extends Name {
readonly prefix: string
value?: NameValue
scopePath?: Code
constructor(prefix: string, nameStr: string) {
super(nameStr)
this.prefix = prefix
}
setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
}
} |
2,769 | function Parser (args: ArgsInput, opts?: Partial<Options>): Arguments {
const result = parser.parse(args.slice(), opts)
return result.argv
} | type ArgsInput = string | any[]; |
2,770 | function (args: ArgsInput, opts?: Partial<Options>): DetailedArguments {
return parser.parse(args.slice(), opts)
} | type ArgsInput = string | any[]; |
2,771 | (args: ArgsInput, opts?: Partial<Options>): Arguments | type ArgsInput = string | any[]; |
2,772 | detailed(args: ArgsInput, opts?: Partial<Options>): DetailedArguments | type ArgsInput = string | any[]; |
2,773 | constructor (_mixin: YargsParserMixin) {
mixin = _mixin
} | interface YargsParserMixin {
cwd: Function;
format: Function;
normalize: Function;
require: Function;
resolve: Function;
env: Function;
} |
2,774 | parse (argsInput: ArgsInput, options?: Partial<Options>): DetailedArguments {
const opts: Partial<Options> = 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: 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: OptionsDefault = Object.assign(Object.create(null), opts.default)
const configObjects = opts.configObjects || []
const envPrefix = opts.envPrefix
const notFlagsOption = configuration['populate--']
const notFlagsArgv: string = notFlagsOption ? '--' : '_'
const newAliases: Dictionary<boolean> = Object.create(null)
const defaulted: Dictionary<boolean> = Object.create(null)
// allow a i18n handler to be passed in, default to a fake one (util.format).
const __ = opts.__ || mixin.format
const flags: 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'] + '(.+)')
;([] as ArrayOption[]).concat(opts.array || []).filter(Boolean).forEach(function (opt) {
const key = typeof opt === 'object' ? opt.key : opt
// assign to flags[bools|strings|numbers]
const assignment: ArrayFlagsKey | undefined = Object.keys(opt).map(function (key) {
const arrayFlagKeys: Record<string, ArrayFlagsKey> = {
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)
})
;([] as string[]).concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
flags.bools[key] = true
flags.keys.push(key)
})
;([] as string[]).concat(opts.string || []).filter(Boolean).forEach(function (key) {
flags.strings[key] = true
flags.keys.push(key)
})
;([] as string[]).concat(opts.number || []).filter(Boolean).forEach(function (key) {
flags.numbers[key] = true
flags.keys.push(key)
})
;([] as string[]).concat(opts.count || []).filter(Boolean).forEach(function (key) {
flags.counts[key] = true
flags.keys.push(key)
})
;([] as string[]).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)
}
})
}
if (typeof opts.coerce === 'object') {
Object.entries(opts.coerce).forEach(([key, value]) => {
if (typeof value === 'function') {
flags.coercions[key] = value
flags.keys.push(key)
}
})
}
if (typeof opts.config !== 'undefined') {
if (Array.isArray(opts.config) || typeof opts.config === 'string') {
;([] as 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
}
})
}
}
// 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: Error | null = null
checkConfiguration()
let notFlags: string[] = []
const argv: Arguments = 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: { [argName: string]: any } = {}
for (let i = 0; i < args.length; i++) {
const arg = args[i]
const truncatedArg = arg.replace(/^-{3,}/, '---')
let broken: boolean
let key: string | undefined
let letters: string[]
let m: RegExpMatchArray | null
let next: string
let value: string
// 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]
})
}
if (configuration['strip-aliased']) {
;([] as string[]).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]
})
}
// Push argument into positional array, applying numeric coercion:
function pushPositional (arg: string) {
const maybeCoercedNumber = maybeCoerceNumber('_', arg)
if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
argv._.push(maybeCoercedNumber)
}
}
// how many arguments should we consume, based
// on the nargs option?
function eatNargs (i: number, key: string, args: string[], argAfterEqualSign?: string): number {
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 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: number, key: string, args: string[], argAfterEqualSign?: string): number {
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: string, val: any, shouldStripQuotes: boolean = inputIsString): void {
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 = ([] as string[]).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: string, alias: string): void {
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: string, val: any, shouldStripQuotes: boolean) {
// 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: string, value: string | number | null | undefined) {
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: Arguments): void {
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: any) {
// 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: { [key: string]: any }, prev?: string): void {
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 (): void {
if (typeof configObjects !== 'undefined') {
configObjects.forEach(function (configObject) {
setConfigObject(configObject)
})
}
}
function applyEnvVars (argv: Arguments, configOnly: boolean): void {
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: Arguments): void {
let coerce: false | CoerceCallback
const applied: Set<string> = 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]))
;(([] as string[]).concat(flags.aliases[key] || [], key)).forEach(ali => {
applied.add(ali)
argv[ali] = value
})
} catch (err) {
error = err as Error
}
}
}
})
}
function setPlaceholderKeys (argv: Arguments): Arguments {
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: { [key: string]: any }, aliases: { [key: string]: string[] }, defaults: { [key: string]: any }, canLog: boolean = false): void {
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: { [key: string]: any }, keys: string[]): boolean {
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: { [key: string]: any }, keys: string[], value: any): void {
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: Array<{ [key: string]: any } | undefined>) {
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] = ([] as string[]).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
}))
})
})
})
}
// return the 1st set flag for any of a key's aliases (or false if no flag set)
function checkAllAliases (key: string, flag: StringFlag): ValueOf<StringFlag> | false
function checkAllAliases (key: string, flag: BooleanFlag): ValueOf<BooleanFlag> | false
function checkAllAliases (key: string, flag: NumberFlag): ValueOf<NumberFlag> | false
function checkAllAliases (key: string, flag: ConfigsFlag): ValueOf<ConfigsFlag> | false
function checkAllAliases (key: string, flag: CoercionsFlag): ValueOf<CoercionsFlag> | false
function checkAllAliases (key: string, flag: Flag): ValueOf<Flag> | false {
const toCheck = ([] as string[]).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: string): boolean {
const flagsKeys = Object.keys(flags) as FlagsKey[]
const toCheck = ([] as Array<{ [key: string]: any } | string[]>).concat(flagsKeys.map(k => flags[k]))
return toCheck.some(function (flag) {
return Array.isArray(flag) ? flag.includes(key) : flag[key]
})
}
function hasFlagsMatching (arg: string, ...patterns: RegExp[]): boolean {
const toCheck = ([] as RegExp[]).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: string): boolean {
// 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: string
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: string): boolean {
return configuration['unknown-options-as-args'] && isUnknownOption(arg)
}
function isUnknownOption (arg: string): boolean {
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: string) {
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<K extends DefaultValuesForTypeKey> (type: K): DefaultValuesForType[K] {
const def: DefaultValuesForType = {
[DefaultValuesForTypeKey.BOOLEAN]: true,
[DefaultValuesForTypeKey.STRING]: '',
[DefaultValuesForTypeKey.NUMBER]: undefined,
[DefaultValuesForTypeKey.ARRAY]: []
}
return def[type]
}
// given a flag, enforce a default type.
function guessType (key: string): DefaultValuesForTypeKey {
let type: DefaultValuesForTypeKey = 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: any): num is undefined {
return num === undefined
}
// check user configuration settings for inconsistencies
function checkConfiguration (): void {
// 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)
}
} | type ArgsInput = string | any[]; |
2,775 | function setConfig (argv: Arguments): void {
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: any) {
// 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))
}
}
})
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,776 | function applyEnvVars (argv: Arguments, configOnly: boolean): void {
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])
}
}
})
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,777 | function applyCoercions (argv: Arguments): void {
let coerce: false | CoerceCallback
const applied: Set<string> = 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]))
;(([] as string[]).concat(flags.aliases[key] || [], key)).forEach(ali => {
applied.add(ali)
argv[ali] = value
})
} catch (err) {
error = err as Error
}
}
}
})
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,778 | function setPlaceholderKeys (argv: Arguments): Arguments {
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
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,779 | (_err: Error, argv: Arguments, _output: string) => {
output = _output;
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,780 | (_err: Error, argv: Arguments, _output: string) => {
output = _output;
} | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,781 | (_err: Error, argv: Arguments, _output: string) => {
output = _output;
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,782 | async (argv: Arguments) => {
await new Promise(resolve => {
setTimeout(resolve, 10);
});
argv.foo *= 2;
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,783 | async (argv: Arguments) => {
await new Promise(resolve => {
setTimeout(resolve, 10);
});
argv.foo *= 2;
} | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,784 | async (argv: Arguments) => {
await new Promise(resolve => {
setTimeout(resolve, 10);
});
argv.foo *= 2;
} | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,785 | registerFunction(fn: CompletionFunction): void | type CompletionFunction =
| SyncCompletionFunction
| AsyncCompletionFunction
| FallbackCompletionFunction; |
2,786 | setParsed(parsed: DetailedArguments): void | interface DetailedArguments extends ParserDetailedArguments {
argv: Arguments;
aliases: Dictionary<string[]>;
} |
2,787 | setParsed(parsed: DetailedArguments): void | interface DetailedArguments {
/** An object representing the parsed value of `args` */
argv: Arguments;
/** Populated with an error object if an exception occurred during parsing. */
error: Error | null;
/** The inferred list of aliases built by combining lists in opts.alias. */
aliases: Dictionary<string[]>;
/** Any new aliases added via camel-case expansion. */
newAliases: Dictionary<boolean>;
/** Any new argument created by opts.default, no aliases included. */
defaulted: Dictionary<boolean>;
/** The configuration loaded from the yargs stanza in package.json. */
configuration: Configuration;
} |
2,788 | constructor(
private readonly yargs: YargsInstance,
private readonly usage: UsageInstance,
private readonly command: CommandInstance,
private readonly shim: PlatformShim
) {
this.zshShell =
(this.shim.getEnv('SHELL')?.includes('zsh') ||
this.shim.getEnv('ZSH_NAME')?.includes('zsh')) ??
false;
} | class CommandInstance {
shim: PlatformShim;
requireCache: Set<string> = new Set();
handlers: Dictionary<CommandHandler> = {};
aliasMap: Dictionary<string> = {};
defaultCommand?: CommandHandler;
usage: UsageInstance;
globalMiddleware: GlobalMiddleware;
validation: ValidationInstance;
// Used to cache state from prior invocations of commands.
// This allows the parser to push and pop state when running
// a nested command:
frozens: FrozenCommandInstance[] = [];
constructor(
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: GlobalMiddleware,
shim: PlatformShim
) {
this.shim = shim;
this.usage = usage;
this.globalMiddleware = globalMiddleware;
this.validation = validation;
}
addDirectory(
dir: string,
req: Function,
callerFile: string,
opts?: RequireDirectoryOptions
): void {
opts = opts || {};
// disable recursion to support nested directories of subcommands
if (typeof opts.recurse !== 'boolean') opts.recurse = false;
// exclude 'json', 'coffee' from require-directory defaults
if (!Array.isArray(opts.extensions)) opts.extensions = ['js'];
// allow consumer to define their own visitor function
const parentVisit =
typeof opts.visit === 'function' ? opts.visit : (o: any) => o;
// call addHandler via visitor function
opts.visit = (obj, joined, filename) => {
const visited = parentVisit(obj, joined, filename);
// allow consumer to skip modules with their own visitor
if (visited) {
// check for cyclic reference:
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: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
commandMiddleware?: Middleware[],
deprecated?: boolean
): void {
let aliases: string[] = [];
const middlewares = commandMiddlewareFactory(commandMiddleware);
handler = handler || (() => {});
// If an array is provided that is all CommandHandlerDefinitions, add
// each handler individually:
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 = ([] as string[]).concat(command).concat(cmd.aliases);
this.addHandler(
command,
this.extractDesc(cmd),
cmd.builder,
cmd.handler,
cmd.middlewares,
cmd.deprecated
);
return;
} else if (isCommandBuilderDefinition(builder)) {
// Allow a module to be provided as builder, rather than function:
this.addHandler(
[cmd].concat(aliases),
description,
builder.builder,
builder.handler,
builder.middlewares,
builder.deprecated
);
return;
}
// The 'cmd' provided was a string, we apply the command DSL:
// https://github.com/yargs/yargs/blob/main/docs/advanced.md#advanced-topics
if (typeof cmd === 'string') {
// parse positionals out of cmd string
const parsedCommand = parseCommand(cmd);
// remove positional args from aliases only
aliases = aliases.map(alias => parseCommand(alias).cmd);
// check for default and filter out '*'
let isDefault = false;
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
if (DEFAULT_MARKER.test(c)) {
isDefault = true;
return false;
}
return true;
});
// standardize on $0 for default command.
if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0');
// shift cmd and aliases after filtering out '*'
if (isDefault) {
parsedCommand.cmd = parsedAliases[0];
aliases = parsedAliases.slice(1);
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
}
// populate aliasMap
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 as CommandBuilder) || {},
middlewares,
deprecated,
demanded: parsedCommand.demanded,
optional: parsedCommand.optional,
};
if (isDefault) this.defaultCommand = this.handlers[parsedCommand.cmd];
}
}
getCommandHandlers(): Dictionary<CommandHandler> {
return this.handlers;
}
getCommands(): string[] {
return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
}
hasDefaultCommand(): boolean {
return !!this.defaultCommand;
}
runCommand(
command: string | null,
yargs: YargsInstance,
parsed: DetailedArguments,
commandIndex: number,
helpOnly: boolean,
helpOrVersionSet: boolean
): Arguments | Promise<Arguments> {
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
);
}
private applyBuilderUpdateUsageAndParse(
isDefaultCommand: boolean,
commandHandler: CommandHandler,
yargs: YargsInstance,
aliases: Dictionary<string[]>,
parentCommands: string[],
commandIndex: number,
helpOnly: boolean,
helpOrVersionSet: boolean
):
| {aliases: Dictionary<string[]>; innerArgv: Arguments}
| Promise<{aliases: Dictionary<string[]>; innerArgv: Arguments}> {
const builder = commandHandler.builder;
let innerYargs: YargsInstance = yargs;
if (isCommandBuilderCallback(builder)) {
// A function can be provided, which builds
// up a yargs chain and possibly returns it.
const builderOutput = builder(
yargs.getInternalMethods().reset(aliases),
helpOrVersionSet
);
// Support the use-case of async builders:
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)) {
// as a short hand, an object can instead be provided, specifying
// the options that a command takes.
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
);
}
private parseAndUpdateUsage(
isDefaultCommand: boolean,
commandHandler: CommandHandler,
innerYargs: YargsInstance,
parentCommands: string[],
commandIndex: number,
helpOnly: boolean
):
| {aliases: Dictionary<string[]>; innerArgv: Arguments}
| Promise<{aliases: Dictionary<string[]>; innerArgv: Arguments}> {
// A null command indicates we are running the default command,
// if this is the case, we should show the root usage instructions
// rather than the usage instructions for the nested default command:
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 as DetailedArguments).aliases,
innerArgv: argv,
}))
: {
aliases: (innerYargs.parsed as DetailedArguments).aliases,
innerArgv: innerArgv,
};
}
private shouldUpdateUsage(yargs: YargsInstance) {
return (
!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() &&
yargs.getInternalMethods().getUsageInstance().getUsage().length === 0
);
}
private usageFromParentCommandsCommandHandler(
parentCommands: string[],
commandHandler: 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(' ')}`;
}
private handleValidationAndGetResult(
isDefaultCommand: boolean,
commandHandler: CommandHandler,
innerArgv: Arguments | Promise<Arguments>,
currentContext: Context,
aliases: Dictionary<string[]>,
yargs: YargsInstance,
middlewares: Middleware[],
positionalMap: Dictionary<string[]>
) {
// we apply validation post-hoc, so that custom
// checks get passed populated positional arguments.
if (!yargs.getInternalMethods().getHasOutput()) {
const validation = yargs
.getInternalMethods()
.runValidation(
aliases,
positionalMap,
(yargs.parsed as DetailedArguments).error,
isDefaultCommand
);
innerArgv = maybeAsyncResult<Arguments>(innerArgv, result => {
validation(result);
return result;
});
}
if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
yargs.getInternalMethods().setHasOutput();
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
const populateDoubleDash =
!!yargs.getOptions().configuration['populate--'];
yargs
.getInternalMethods()
.postProcess(innerArgv, populateDoubleDash, false, false);
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
innerArgv = maybeAsyncResult<Arguments>(innerArgv, result => {
const handlerResult = commandHandler.handler(result as Arguments);
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 .fail(false) is not set, and no parse cb() has been
// registered, run usage's default fail method.
}
});
}
}
if (!isDefaultCommand) {
currentContext.commands.pop();
currentContext.fullCommands.pop();
}
return innerArgv;
}
private applyMiddlewareAndGetResult(
isDefaultCommand: boolean,
commandHandler: CommandHandler,
innerArgv: Arguments,
currentContext: Context,
helpOnly: boolean,
aliases: Dictionary<string[]>,
yargs: YargsInstance
): Arguments | Promise<Arguments> {
let positionalMap: Dictionary<string[]> = {};
// If showHelp() or getHelp() is being run, we should not
// execute middleware or handlers (these may perform expensive operations
// like creating a DB connection).
if (helpOnly) return innerArgv;
if (!yargs.getInternalMethods().getHasOutput()) {
positionalMap = this.populatePositionals(
commandHandler,
innerArgv as Arguments,
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
);
}
// transcribe all positional arguments "command <foo> <bar> [apple]"
// onto argv.
private populatePositionals(
commandHandler: CommandHandler,
argv: Arguments,
context: Context,
yargs: YargsInstance
) {
argv._ = argv._.slice(context.commands.length); // nuke the current commands
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap: Dictionary<string[]> = {};
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;
}
private populatePositional(
positional: Positional,
argv: Arguments,
positionalMap: Dictionary<string[]>
) {
const cmd = positional.cmd[0];
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String);
} else {
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())];
}
}
// Based on parsing variadic markers '...', demand syntax '<foo>', etc.,
// populate parser hints:
public cmdToParseOptions(cmdString: string): Positionals {
const parseOptions: Positionals = {
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;
}
// we run yargs-parser against the positional arguments
// applying the same parsing logic used for flags.
private postProcessPositionals(
argv: Arguments,
positionalMap: Dictionary<string[]>,
parseOptions: Positionals,
yargs: YargsInstance
) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
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 = {}; // don't load config when processing positionals.
const unparsed: string[] = [];
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);
});
});
// short-circuit parse.
if (!unparsed.length) return;
const config: Configuration = 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 {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
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)) {
// any new aliases need to be placed in positionalMap, which
// is used for validation.
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key];
// Addresses: https://github.com/yargs/yargs/issues/1637
// If both positionals/options provided,
// and no default or config values were set for that key,
// and if at least one is an array: don't overwrite, combine.
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] = ([] as string[]).concat(argv[key], parsed.argv[key]);
} else {
argv[key] = parsed.argv[key];
}
}
});
}
}
// Check defaults for key (and camel case version of key)
isDefaulted(yargs: YargsInstance, key: string): boolean {
const {default: defaults} = yargs.getOptions();
return (
Object.prototype.hasOwnProperty.call(defaults, key) ||
Object.prototype.hasOwnProperty.call(
defaults,
this.shim.Parser.camelCase(key)
)
);
}
// Check each config for key (and camel case version of key)
isInConfigs(yargs: YargsInstance, key: string): boolean {
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: YargsInstance): unknown | Promise<unknown> {
if (!this.defaultCommand) return;
if (this.shouldUpdateUsage(yargs)) {
// build the root-level command string from the default string.
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;
}
// lookup module object from require()d command and derive name
// if module was not require()d and no name given, throw error
private moduleName(obj: CommandHandlerDefinition) {
const mod = whichModule(obj);
if (!mod)
throw new Error(
`No command name given for module: ${this.shim.inspect(obj)}`
);
return this.commandFromFilename(mod.filename);
}
private commandFromFilename(filename: string) {
return this.shim.path.basename(filename, this.shim.path.extname(filename));
}
private extractDesc({describe, description, desc}: CommandHandlerDefinition) {
for (const test of [describe, description, desc]) {
if (typeof test === 'string' || test === false) return test;
assertNotStrictEqual(test, true as const, this.shim);
}
return false;
}
// Push/pop the current command configuration:
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);
}
// Revert to initial state:
reset(): CommandInstance {
this.handlers = {};
this.aliasMap = {};
this.defaultCommand = undefined;
this.requireCache = new Set();
return this;
}
} |
2,789 | constructor(
private readonly yargs: YargsInstance,
private readonly usage: UsageInstance,
private readonly command: CommandInstance,
private readonly shim: PlatformShim
) {
this.zshShell =
(this.shim.getEnv('SHELL')?.includes('zsh') ||
this.shim.getEnv('ZSH_NAME')?.includes('zsh')) ??
false;
} | interface UsageInstance {
cacheHelpMessage(): void;
clearCachedHelpMessage(): void;
hasCachedHelpMessage(): boolean;
command(
cmd: string,
description: string | undefined,
isDefault: boolean,
aliases: string[],
deprecated?: boolean
): void;
deferY18nLookup(str: string): string;
describe(keys: string | string[] | Dictionary<string>, desc?: string): void;
epilog(msg: string): void;
example(cmd: string, description?: string): void;
fail(msg?: string | null, err?: YError | string): void;
failFn(f: FailureFunction | boolean): void;
freeze(): void;
functionDescription(fn: {name?: string}): string;
getCommands(): [string, string, boolean, string[], boolean][];
getDescriptions(): Dictionary<string | undefined>;
getPositionalGroupName(): string;
getUsage(): [string, string][];
getUsageDisabled(): boolean;
getWrap(): number | nil;
help(): string;
reset(localLookup: Dictionary<boolean>): UsageInstance;
showHelp(level?: 'error' | 'log' | ((message: string) => void)): void;
showHelpOnFail(enabled?: boolean | string, message?: string): UsageInstance;
showVersion(level?: 'error' | 'log' | ((message: string) => void)): void;
stringifiedValues(values?: any[], separator?: string): string;
unfreeze(defaultCommand?: boolean): void;
usage(msg: string | null, description?: string | false): UsageInstance;
version(ver: any): void;
wrap(cols: number | nil): void;
} |
2,790 | constructor(
private readonly yargs: YargsInstance,
private readonly usage: UsageInstance,
private readonly command: CommandInstance,
private readonly shim: PlatformShim
) {
this.zshShell =
(this.shim.getEnv('SHELL')?.includes('zsh') ||
this.shim.getEnv('ZSH_NAME')?.includes('zsh')) ??
false;
} | interface PlatformShim {
cwd: Function;
format: Function;
normalize: Function;
require: Function;
resolve: Function;
env: Function;
} |
2,791 | constructor(
private readonly yargs: YargsInstance,
private readonly usage: UsageInstance,
private readonly command: CommandInstance,
private readonly shim: PlatformShim
) {
this.zshShell =
(this.shim.getEnv('SHELL')?.includes('zsh') ||
this.shim.getEnv('ZSH_NAME')?.includes('zsh')) ??
false;
} | interface PlatformShim {
assert: {
notStrictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
strictEqual: (
expected: any,
observed: any,
message?: string | Error
) => void;
};
findUp: (
startDir: string,
fn: (dir: string[], names: string[]) => string | undefined
) => string;
getCallerFile: () => string;
getEnv: (key: string) => string | undefined;
getProcessArgvBin: () => string;
inspect: (obj: object) => string;
mainFilename: string;
requireDirectory: Function;
stringWidth: (str: string) => number;
cliui: Function;
Parser: Parser;
path: {
basename: (p1: string, p2?: string) => string;
extname: (path: string) => string;
dirname: (path: string) => string;
relative: (p1: string, p2: string) => string;
resolve: (p1: string, p2: string) => string;
};
process: {
argv: () => string[];
cwd: () => string;
emitWarning: (warning: string | Error, type?: string) => void;
execPath: () => string;
exit: (code: number) => void;
nextTick: (cb: Function) => void;
stdColumns: number | null;
};
readFileSync: (path: string, encoding: string) => string;
require: RequireType;
y18n: Y18N;
} |
2,792 | constructor(
private readonly yargs: YargsInstance,
private readonly usage: UsageInstance,
private readonly command: CommandInstance,
private readonly shim: PlatformShim
) {
this.zshShell =
(this.shim.getEnv('SHELL')?.includes('zsh') ||
this.shim.getEnv('ZSH_NAME')?.includes('zsh')) ??
false;
} | class YargsInstance {
$0: string;
argv?: Arguments;
customScriptName = false;
parsed: DetailedArguments | false = false;
#command: CommandInstance;
#cwd: string;
// use context object to keep track of resets, subcommand execution, etc.,
// submodules should modify and check the state of context as necessary:
#context: Context = {commands: [], fullCommands: []};
#completion: CompletionInstance | null = null;
#completionCommand: string | null = null;
#defaultShowHiddenOpt = 'show-hidden';
#exitError: YError | string | nil = null;
#detectLocale = true;
#emittedWarnings: Dictionary<boolean> = {};
#exitProcess = true;
#frozens: FrozenYargsInstance[] = [];
#globalMiddleware: GlobalMiddleware;
#groups: Dictionary<string[]> = {};
#hasOutput = false;
#helpOpt: string | null = null;
#isGlobalContext = true;
#logger: LoggerInstance;
#output = '';
#options: Options;
#parentRequire?: RequireType;
#parserConfig: Configuration = {};
#parseFn: ParseCallback | null = null;
#parseContext: object | null = null;
#pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
#preservedGroups: Dictionary<string[]> = {};
#processArgs: string | string[];
#recommendCommands = false;
#shim: PlatformShim;
#strict = false;
#strictCommands = false;
#strictOptions = false;
#usage: UsageInstance;
#usageConfig: UsageConfiguration = {};
#versionOpt: string | null = null;
#validation: ValidationInstance;
constructor(
processArgs: string | string[] = [],
cwd: string,
parentRequire: RequireType | undefined,
shim: PlatformShim
) {
this.#shim = shim;
this.#processArgs = processArgs;
this.#cwd = cwd;
this.#parentRequire = parentRequire;
this.#globalMiddleware = new GlobalMiddleware(this);
this.$0 = this[kGetDollarZero]();
// #command, #validation, and #usage are initialized on first reset:
this[kReset]();
this.#command = this!.#command;
this.#usage = this!.#usage;
this.#validation = this!.#validation;
this.#options = this!.#options;
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
this.#logger = this[kCreateLogger]();
}
addHelpOpt(opt?: string | false, msg?: string): YargsInstance {
const defaultHelpOpt = 'help';
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
// nuke the key previously configured
// to return help.
if (this.#helpOpt) {
this[kDeleteFromParserHintObject](this.#helpOpt);
this.#helpOpt = null;
}
if (opt === false && msg === undefined) return this;
// use arguments, fallback to defaults for opt and msg
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
this.boolean(this.#helpOpt);
this.describe(
this.#helpOpt,
msg || this.#usage.deferY18nLookup('Show help')
);
return this;
}
help(opt?: string, msg?: string): YargsInstance {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
if (opt === false && msg === undefined) return this;
const showHiddenOpt =
typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt;
this.boolean(showHiddenOpt);
this.describe(
showHiddenOpt,
msg || this.#usage.deferY18nLookup('Show hidden options')
);
this.#options.showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt?: string | false, msg?: string): YargsInstance {
return this.addShowHiddenOpt(opt, msg);
}
alias(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.alias.bind(this),
'alias',
key,
value
);
return this;
}
array(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('array', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('boolean', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
argv: Arguments,
_yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
this.#usage.fail(
this.#shim.y18n.__('Argument check failed: %s', f.toString())
);
} else if (typeof result === 'string' || result instanceof Error) {
this.#usage.fail(result.toString(), result);
}
return argv;
},
(err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
this.#usage.fail(err.message ? err.message : err.toString(), err);
return argv;
}
);
},
false,
global
);
return this;
}
choices(
key: string | string[] | Dictionary<string | string[]>,
value?: string | string[]
): YargsInstance {
argsert(
'<object|string|array> [string|array]',
[key, value],
arguments.length
);
this[kPopulateParserHintArrayDictionary](
this.choices.bind(this),
'choices',
key,
value
);
return this;
}
coerce(
keys: string | string[] | Dictionary<CoerceCallback>,
value?: CoerceCallback
): YargsInstance {
argsert(
'<object|string|array> [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');
}
// This noop tells yargs-parser about the existence of the option
// represented by "keys", so that it can apply camel case expansion
// if needed:
this.#options.key[keys] = true;
this.#globalMiddleware.addCoerceMiddleware(
(
argv: Arguments,
yargs: YargsInstance
): Partial<Arguments> | Promise<Partial<Arguments>> => {
let aliases: Dictionary<string[]>;
// Skip coerce logic if related arg was not provided
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult<
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
aliases = yargs.getAliases();
return value(argv[keys]);
},
(result: any): Partial<Arguments> => {
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: Error): Partial<Arguments> | Promise<Partial<Arguments>> => {
throw new YError(err.message);
}
);
},
keys
);
return this;
}
conflicts(
key1: string | Dictionary<string | string[]>,
key2?: string | string[]
): YargsInstance {
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
this.#validation.conflicts(key1, key2);
return this;
}
config(
key: string | string[] | Dictionary = 'config',
msg?: string | ConfigCallback,
parseFn?: ConfigCallback
): YargsInstance {
argsert(
'[object|string] [string|function] [function]',
[key, msg, parseFn],
arguments.length
);
// allow a config object to be provided directly.
if (typeof key === 'object' && !Array.isArray(key)) {
key = applyExtends(
key,
this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
key
);
return this;
}
// allow for a custom parsing function.
if (typeof msg === 'function') {
parseFn = msg;
msg = undefined;
}
this.describe(
key,
msg || this.#usage.deferY18nLookup('Path to JSON config file')
);
(Array.isArray(key) ? key : [key]).forEach(k => {
this.#options.config[k] = parseFn || true;
});
return this;
}
completion(
cmd?: string,
desc?: string | false | CompletionFunction,
fn?: CompletionFunction
): YargsInstance {
argsert(
'[string] [string|boolean|function] [function]',
[cmd, desc, fn],
arguments.length
);
// a function to execute when generating
// completions can be provided as the second
// or third argument to completion.
if (typeof desc === 'function') {
fn = desc;
desc = undefined;
}
// register the completion command.
this.#completionCommand = cmd || this.#completionCommand || 'completion';
if (!desc && desc !== false) {
desc = 'generate completion script';
}
this.command(this.#completionCommand, desc);
// a function can be provided
if (fn) this.#completion!.registerFunction(fn);
return this;
}
command(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
argsert(
'<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]',
[cmd, description, builder, handler, middlewares, deprecated],
arguments.length
);
this.#command.addHandler(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
return this;
}
commands(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
middlewares?: Middleware[],
deprecated?: boolean
): YargsInstance {
return this.command(
cmd,
description,
builder,
handler,
middlewares,
deprecated
);
}
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance {
argsert('<string> [object]', [dir, opts], arguments.length);
const req = this.#parentRequire || this.#shim.require;
this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts);
return this;
}
count(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('count', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
argsert(
'<object|string|array> [*] [string]',
[key, value, defaultDescription],
arguments.length
);
if (defaultDescription) {
assertSingleKey(key, this.#shim);
this.#options.defaultDescription[key] = defaultDescription;
}
if (typeof value === 'function') {
assertSingleKey(key, this.#shim);
if (!this.#options.defaultDescription[key])
this.#options.defaultDescription[key] =
this.#usage.functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary]<'default'>(
this.default.bind(this),
'default',
key,
value
);
return this;
}
defaults(
key: string | string[] | Dictionary<any>,
value?: any,
defaultDescription?: string
): YargsInstance {
return this.default(key, value, defaultDescription);
}
demandCommand(
min = 1,
max?: number | string,
minMsg?: string | null,
maxMsg?: string | null
): YargsInstance {
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);
this.#options.demandedCommands._ = {
min,
max,
minMsg,
maxMsg,
};
return this;
}
demand(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
// you can optionally provide a 'max' key,
// which will raise an exception if too many '_'
// options are provided.
if (Array.isArray(max)) {
max.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== 'number') {
msg = max;
max = Infinity;
}
if (typeof keys === 'number') {
assertNotStrictEqual(msg, true as const, this.#shim);
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach(key => {
assertNotStrictEqual(msg, true as const, this.#shim);
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: string | string[] | Dictionary<string | undefined>,
msg?: string
): YargsInstance {
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.demandOption.bind(this),
'demandedOptions',
keys,
msg
);
return this;
}
deprecateOption(option: string, message: string | boolean): YargsInstance {
argsert('<string> [string|boolean]', [option, message], arguments.length);
this.#options.deprecatedOptions[option] = message;
return this;
}
describe(
keys: string | string[] | Dictionary<string>,
description?: string
): YargsInstance {
argsert(
'<object|string|array> [string]',
[keys, description],
arguments.length
);
this[kSetKey](keys, true);
this.#usage.describe(keys, description);
return this;
}
detectLocale(detect: boolean): YargsInstance {
argsert('<boolean>', [detect], arguments.length);
this.#detectLocale = detect;
return this;
}
// as long as options.envPrefix is not undefined,
// parser will apply env vars matching prefix to argv
env(prefix?: string | false): YargsInstance {
argsert('[string|boolean]', [prefix], arguments.length);
if (prefix === false) delete this.#options.envPrefix;
else this.#options.envPrefix = prefix || '';
return this;
}
epilogue(msg: string): YargsInstance {
argsert('<string>', [msg], arguments.length);
this.#usage.epilog(msg);
return this;
}
epilog(msg: string): YargsInstance {
return this.epilogue(msg);
}
example(
cmd: string | [string, string?][],
description?: string
): YargsInstance {
argsert('<string|array> [string]', [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach(exampleParams => this.example(...exampleParams));
} else {
this.#usage.example(cmd, description);
}
return this;
}
// maybe exit, always capture context about why we wanted to exit:
exit(code: number, err?: YError | string): void {
this.#hasOutput = true;
this.#exitError = err;
if (this.#exitProcess) this.#shim.process.exit(code);
}
exitProcess(enabled = true): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#exitProcess = enabled;
return this;
}
fail(f: FailureFunction | boolean): YargsInstance {
argsert('<function|boolean>', [f], arguments.length);
if (typeof f === 'boolean' && f !== false) {
throw new YError(
"Invalid first argument. Expected function or boolean 'false'"
);
}
this.#usage.failFn(f);
return this;
}
getAliases(): Dictionary<string[]> {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(
args: string[],
done?: (err: Error | null, completions: string[] | undefined) => void
): Promise<string[] | void> {
argsert('<array> [function]', [args, done], arguments.length);
if (!done) {
return new Promise((resolve, reject) => {
this.#completion!.getCompletion(args, (err, completions) => {
if (err) reject(err);
else resolve(completions);
});
});
} else {
return this.#completion!.getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return this.#options.demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return this.#options.demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return this.#options.deprecatedOptions;
}
getDetectLocale(): boolean {
return this.#detectLocale;
}
getExitProcess(): boolean {
return this.#exitProcess;
}
// combine explicit and preserved groups. explicit groups should be first
getGroups(): Dictionary<string[]> {
return Object.assign({}, this.#groups, this.#preservedGroups);
}
getHelp(): Promise<string> {
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
return parse.then(() => {
return this.#usage.help();
});
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return this.#usage.help();
});
}
}
return Promise.resolve(this.#usage.help());
}
getOptions(): Options {
return this.#options;
}
getStrict(): boolean {
return this.#strict;
}
getStrictCommands(): boolean {
return this.#strictCommands;
}
getStrictOptions(): boolean {
return this.#strictOptions;
}
global(globals: string | string[], global?: boolean): YargsInstance {
argsert('<string|array> [boolean]', [globals, global], arguments.length);
globals = ([] as string[]).concat(globals);
if (global !== false) {
this.#options.local = this.#options.local.filter(
l => globals.indexOf(l) === -1
);
} else {
globals.forEach(g => {
if (!this.#options.local.includes(g)) this.#options.local.push(g);
});
}
return this;
}
group(opts: string | string[], groupName: string): YargsInstance {
argsert('<string|array> <string>', [opts, groupName], arguments.length);
const existing =
this.#preservedGroups[groupName] || this.#groups[groupName];
if (this.#preservedGroups[groupName]) {
// we now only need to track this group name in groups.
delete this.#preservedGroups[groupName];
}
const seen: Dictionary<boolean> = {};
this.#groups[groupName] = (existing || []).concat(opts).filter(key => {
if (seen[key]) return false;
return (seen[key] = true);
});
return this;
}
hide(key: string): YargsInstance {
argsert('<string>', [key], arguments.length);
this.#options.hiddenOptions.push(key);
return this;
}
implies(
key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
value?: KeyOrPos | KeyOrPos[]
): YargsInstance {
argsert(
'<string|object> [number|string|array]',
[key, value],
arguments.length
);
this.#validation.implies(key, value);
return this;
}
locale(locale?: string): YargsInstance | string {
argsert('[string]', [locale], arguments.length);
if (locale === undefined) {
this[kGuessLocale]();
return this.#shim.y18n.getLocale();
}
this.#detectLocale = false;
this.#shim.y18n.setLocale(locale);
return this;
}
middleware(
callback: MiddlewareCallback | MiddlewareCallback[],
applyBeforeValidation?: boolean,
global?: boolean
): YargsInstance {
return this.#globalMiddleware.addMiddleware(
callback,
!!applyBeforeValidation,
global
);
}
nargs(
key: string | string[] | Dictionary<number>,
value?: number
): YargsInstance {
argsert('<string|object|array> [number]', [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](
this.nargs.bind(this),
'narg',
key,
value
);
return this;
}
normalize(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('normalize', keys);
return this;
}
number(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('number', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(
key: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
argsert('<string|object> [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);
// Warn about version name collision
// Addresses: https://github.com/yargs/yargs/issues/1979
if (this.#versionOpt && (key === 'version' || 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' // TODO: better dedupeId
);
}
this.#options.key[key] = true; // track manually set keys.
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;
// A required option can be specified via "demand: true".
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) {
this.#options.defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = this.#usage.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: string | Dictionary<OptionDefinition>,
opt?: OptionDefinition
): YargsInstance {
return this.option(key, opt);
}
parse(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments | Promise<Arguments> {
argsert(
'[string|array] [function|boolean|object] [function]',
[args, shortCircuit, _parseFn],
arguments.length
);
this[kFreeze](); // Push current state of parser onto stack.
if (typeof args === 'undefined') {
args = this.#processArgs;
}
// a context object can optionally be provided, this allows
// additional information to be passed to a command handler.
if (typeof shortCircuit === 'object') {
this.#parseContext = shortCircuit;
shortCircuit = _parseFn;
}
// by providing a function as a second argument to
// parse you can capture output that would otherwise
// default to printing to stdout/stderr.
if (typeof shortCircuit === 'function') {
this.#parseFn = shortCircuit as ParseCallback;
shortCircuit = false;
}
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) this.#processArgs = args;
if (this.#parseFn) this.#exitProcess = false;
const parsed = this[kRunYargsParserAndExecuteCommands](
args,
!!shortCircuit
);
const tmpParsed = this.parsed;
this.#completion!.setParsed(this.parsed as DetailedArguments);
if (isPromise(parsed)) {
return parsed
.then(argv => {
if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output);
return argv;
})
.catch(err => {
if (this.#parseFn) {
this.#parseFn!(
err,
(this.parsed as DetailedArguments).argv,
this.#output
);
}
throw err;
})
.finally(() => {
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
});
} else {
if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output);
this[kUnfreeze](); // Pop the stack.
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Promise<Arguments> {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise)
? Promise.resolve(maybePromise)
: maybePromise;
}
parseSync(
args?: string | string[],
shortCircuit?: object | ParseCallback | boolean,
_parseFn?: ParseCallback
): Arguments {
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: Configuration) {
argsert('<object>', [config], arguments.length);
this.#parserConfig = config;
return this;
}
pkgConf(key: string, rootPath?: string): YargsInstance {
argsert('<string> [string]', [key, rootPath], arguments.length);
let conf = null;
// prefer cwd to require-main-filename in this method
// since we're looking for e.g. "nyc" config in nyc consumer
// rather than "yargs" config in nyc (where nyc is the main filename)
const obj = this[kPkgUp](rootPath || this.#cwd);
// If an object exists in the key, add it to options.configObjects
if (obj[key] && typeof obj[key] === 'object') {
conf = applyExtends(
obj[key] as {[key: string]: string},
rootPath || this.#cwd,
this[kGetParserConfiguration]()['deep-merge-config'] || false,
this.#shim
);
this.#options.configObjects = (this.#options.configObjects || []).concat(
conf
);
}
return this;
}
positional(key: string, opts: PositionalDefinition): YargsInstance {
argsert('<string> <object>', [key, opts], arguments.length);
// .positional() only supports a subset of the configuration
// options available to .option():
const supportedOpts: (keyof PositionalDefinition)[] = [
'default',
'defaultDescription',
'implies',
'normalize',
'choices',
'conflicts',
'coerce',
'type',
'describe',
'desc',
'description',
'alias',
];
opts = objFilter(opts, (k, v) => {
// type can be one of string|number|boolean.
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
return false;
return supportedOpts.includes(k);
});
// copy over any settings that can be inferred from the command string.
const fullCommand =
this.#context.fullCommands[this.#context.fullCommands.length - 1];
const parseOptions = fullCommand
? this.#command.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, this.#usage.getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true): YargsInstance {
argsert('[boolean]', [recommend], arguments.length);
this.#recommendCommands = recommend;
return this;
}
required(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
require(
keys: string | string[] | Dictionary<string | undefined> | number,
max?: number | string[] | string | true,
msg?: string | true
): YargsInstance {
return this.demand(keys, max, msg);
}
requiresArg(keys: string | string[] | Dictionary): YargsInstance {
// the 2nd paramter [number] in the argsert the assertion is mandatory
// as populateParserHintSingleValueDictionary recursively calls requiresArg
// with Nan as a 2nd parameter, although we ignore it
argsert('<array|string|object> [number]', [keys], arguments.length);
// If someone configures nargs at the same time as requiresArg,
// nargs should take precedence,
// see: https://github.com/yargs/yargs/pull/1572
// TODO: make this work with aliases, using a check similar to
// checkAllAliases() in yargs-parser.
if (typeof keys === 'string' && this.#options.narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](
this.requiresArg.bind(this),
'narg',
keys,
NaN
);
}
return this;
}
showCompletionScript($0?: string, cmd?: string): YargsInstance {
argsert('[string] [string]', [$0, cmd], arguments.length);
$0 = $0 || this.$0;
this.#logger.log(
this.#completion!.generateCompletionScript(
$0,
cmd || this.#completionCommand || 'completion'
)
);
return this;
}
showHelp(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#hasOutput = true;
if (!this.#usage.hasCachedHelpMessage()) {
if (!this.parsed) {
// Run the parser as if --help was passed to it (this is what
// the last parameter `true` indicates).
const parse = this[kRunYargsParserAndExecuteCommands](
this.#processArgs,
undefined,
undefined,
0,
true
);
if (isPromise(parse)) {
parse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
// Ensure top level options/positionals have been configured:
const builderResponse = this.#command.runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
this.#usage.showHelp(level);
});
return this;
}
}
this.#usage.showHelp(level);
return this;
}
scriptName(scriptName: string): YargsInstance {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance {
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
this.#usage.showHelpOnFail(enabled, message);
return this;
}
showVersion(
level: 'error' | 'log' | ((message: string) => void)
): YargsInstance {
argsert('[string|function]', [level], arguments.length);
this.#usage.showVersion(level);
return this;
}
skipValidation(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('skipValidation', keys);
return this;
}
strict(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strict = enabled !== false;
return this;
}
strictCommands(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictCommands = enabled !== false;
return this;
}
strictOptions(enabled?: boolean): YargsInstance {
argsert('[boolean]', [enabled], arguments.length);
this.#strictOptions = enabled !== false;
return this;
}
string(keys: string | string[]): YargsInstance {
argsert('<array|string>', [keys], arguments.length);
this[kPopulateParserHintArray]('string', keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth(): number | null {
argsert([], 0);
return this.#shim.process.stdColumns;
}
updateLocale(obj: Dictionary<string>): YargsInstance {
return this.updateStrings(obj);
}
updateStrings(obj: Dictionary<string>): YargsInstance {
argsert('<object>', [obj], arguments.length);
this.#detectLocale = false;
this.#shim.y18n.updateLocale(obj);
return this;
}
usage(
msg: string | null,
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback
): YargsInstance {
argsert(
'<string|null|undefined> [string|boolean] [function|object] [function]',
[msg, description, builder, handler],
arguments.length
);
if (description !== undefined) {
assertNotStrictEqual(msg, null, this.#shim);
// .usage() can be used as an alias for defining
// a default command.
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 {
this.#usage.usage(msg);
return this;
}
}
usageConfiguration(config: UsageConfiguration) {
argsert('<object>', [config], arguments.length);
this.#usageConfig = config;
return this;
}
version(opt?: string | false, msg?: string, ver?: string): YargsInstance {
const defaultVersionOpt = 'version';
argsert(
'[boolean|string] [string] [string]',
[opt, msg, ver],
arguments.length
);
// nuke the key previously configured
// to return version #.
if (this.#versionOpt) {
this[kDeleteFromParserHintObject](this.#versionOpt);
this.#usage.version(undefined);
this.#versionOpt = null;
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
// disable default 'version' key.
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = undefined;
}
this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
msg = msg || this.#usage.deferY18nLookup('Show version number');
this.#usage.version(ver || undefined);
this.boolean(this.#versionOpt);
this.describe(this.#versionOpt, msg);
return this;
}
wrap(cols: number | nil): YargsInstance {
argsert('<number|null|undefined>', [cols], arguments.length);
this.#usage.wrap(cols);
return this;
}
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
// after the '--' directive. After the parse, we copy these back.
[kCopyDoubleDash](argv: Arguments): any {
if (!argv._ || !argv['--']) return argv;
// eslint-disable-next-line prefer-spread
argv._.push.apply(argv._, argv['--']);
// We catch an error here, in case someone has called Object.seal()
// on the parsed object, see: https://github.com/babel/babel/pull/10733
try {
delete argv['--'];
// eslint-disable-next-line no-empty
} catch (_err) {}
return argv;
}
[kCreateLogger](): LoggerInstance {
return {
log: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.log(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
error: (...args: any[]) => {
if (!this[kHasParseCallback]()) console.error(...args);
this.#hasOutput = true;
if (this.#output.length) this.#output += '\n';
this.#output += args.join(' ');
},
};
}
[kDeleteFromParserHintObject](optionKey: string) {
// delete from all parsing hints:
// boolean, array, key, alias, etc.
objectKeys(this.#options).forEach((hintKey: keyof Options) => {
// configObjects is not a parsing hint array
if (((key): key is 'configObjects' => key === 'configObjects')(hintKey))
return;
const hint = this.#options[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === 'object') {
delete (hint as Dictionary)[optionKey];
}
});
// now delete the description from usage.js.
delete this.#usage.getDescriptions()[optionKey];
}
[kEmitWarning](
warning: string,
type: string | undefined,
deduplicationId: string
) {
// prevent duplicate warning emissions
if (!this.#emittedWarnings[deduplicationId]) {
this.#shim.process.emitWarning(warning, type);
this.#emittedWarnings[deduplicationId] = true;
}
}
[kFreeze]() {
this.#frozens.push({
options: this.#options,
configObjects: this.#options.configObjects.slice(0),
exitProcess: this.#exitProcess,
groups: this.#groups,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
output: this.#output,
exitError: this.#exitError!,
hasOutput: this.#hasOutput,
parsed: this.parsed,
parseFn: this.#parseFn!,
parseContext: this.#parseContext,
});
this.#usage.freeze();
this.#validation.freeze();
this.#command.freeze();
this.#globalMiddleware.freeze();
}
[kGetDollarZero](): string {
let $0 = '';
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
let default$0: string[];
if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) {
default$0 = this.#shim.process.argv().slice(1, 2);
} else {
default$0 = this.#shim.process.argv().slice(0, 1);
}
$0 = default$0
.map(x => {
const b = this[kRebase](this.#cwd, x);
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
})
.join(' ')
.trim();
if (
this.#shim.getEnv('_') &&
this.#shim.getProcessArgvBin() === this.#shim.getEnv('_')
) {
$0 = this.#shim
.getEnv('_')!
.replace(
`${this.#shim.path.dirname(this.#shim.process.execPath())}/`,
''
);
}
return $0;
}
[kGetParserConfiguration](): Configuration {
return this.#parserConfig;
}
[kGetUsageConfiguration](): UsageConfiguration {
return this.#usageConfig;
}
[kGuessLocale]() {
if (!this.#detectLocale) return;
const locale =
this.#shim.getEnv('LC_ALL') ||
this.#shim.getEnv('LC_MESSAGES') ||
this.#shim.getEnv('LANG') ||
this.#shim.getEnv('LANGUAGE') ||
'en_US';
this.locale(locale.replace(/[.:].*/, ''));
}
[kGuessVersion](): string {
const obj = this[kPkgUp]();
return (obj.version as string) || 'unknown';
}
// We wait to coerce numbers for positionals until after the initial parse.
// This allows commands to configure number parsing on a positional by
// positional basis:
[kParsePositionalNumbers](argv: Arguments): any {
const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
if (
this.#shim.Parser.looksLikeNumber(arg) &&
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))
) {
args[i] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath?: string) {
const npath = rootPath || '*';
if (this.#pkgs[npath]) return this.#pkgs[npath];
let obj = {};
try {
let startDir = rootPath || this.#shim.mainFilename;
// When called in an environment that lacks require.main.filename, such as a jest test runner,
// startDir is already process.cwd(), and should not be shortened.
// Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
if (!rootPath && this.#shim.path.extname(startDir)) {
startDir = this.#shim.path.dirname(startDir);
}
const pkgJsonPath = this.#shim.findUp(
startDir,
(dir: string[], names: string[]) => {
if (names.includes('package.json')) {
return 'package.json';
} else {
return undefined;
}
}
);
assertNotStrictEqual(pkgJsonPath, undefined, this.#shim);
obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8'));
// eslint-disable-next-line no-empty
} catch (_noop) {}
this.#pkgs[npath] = obj || {};
return this.#pkgs[npath];
}
[kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>(
type: T,
keys: string | string[]
) {
keys = ([] as string[]).concat(keys);
keys.forEach(key => {
key = this[kSanitizeKey](key);
this.#options[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary]<
T extends
| Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
| 'default',
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<Options[T]> = ValueOf<Options[T]>
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = value as ValueOf<Options[T]>;
}
);
}
[kPopulateParserHintArrayDictionary]<
T extends DictionaryKeyof<Options, any[]>,
K extends keyof Options[T] & string = keyof Options[T] & string,
V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] =
| ValueOf<ValueOf<Options[T]>>
| ValueOf<ValueOf<Options[T]>>[]
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value?: V
) {
this[kPopulateParserHintDictionary]<T, K, V>(
builder,
type,
key,
value,
(type, key, value) => {
this.#options[type][key] = (
this.#options[type][key] || ([] as Options[T][keyof Options[T]])
).concat(value);
}
);
}
[kPopulateParserHintDictionary]<
T extends keyof Options,
K extends keyof Options[T],
V
>(
builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance,
type: T,
key: K | K[] | {[key in K]: V},
value: V | undefined,
singleKeyHandler: (type: T, key: K, value?: V) => void
) {
if (Array.isArray(key)) {
// an array of keys with one value ['x', 'y', 'z'], function parse () {}
key.forEach(k => {
builder(k, value!);
});
} else if (
((key): key is {[key in K]: V} => typeof key === 'object')(key)
) {
// an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
for (const k of objectKeys(key)) {
builder(k, key[k]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key: any) {
if (key === '__proto__') return '___proto___';
return key;
}
[kSetKey](
key: string | string[] | Dictionary<string | boolean>,
set?: boolean | string
) {
this[kPopulateParserHintSingleValueDictionary](
this[kSetKey].bind(this),
'key',
key,
set
);
return this;
}
[kUnfreeze]() {
const frozen = this.#frozens.pop();
assertNotStrictEqual(frozen, undefined, this.#shim);
let configObjects: Dictionary[];
({
options: this.#options,
configObjects,
exitProcess: this.#exitProcess,
groups: this.#groups,
output: this.#output,
exitError: this.#exitError,
hasOutput: this.#hasOutput,
parsed: this.parsed,
strict: this.#strict,
strictCommands: this.#strictCommands,
strictOptions: this.#strictOptions,
completionCommand: this.#completionCommand,
parseFn: this.#parseFn,
parseContext: this.#parseContext,
} = frozen);
this.#options.configObjects = configObjects;
this.#usage.unfreeze();
this.#validation.unfreeze();
this.#command.unfreeze();
this.#globalMiddleware.unfreeze();
}
// If argv is a promise (which is possible if async middleware is used)
// delay applying validation until the promise has resolved:
[kValidateAsync](
validation: (argv: Arguments) => void,
argv: Arguments | Promise<Arguments>
): Arguments | Promise<Arguments> {
return maybeAsyncResult<Arguments>(argv, result => {
validation(result);
return result;
});
}
// Note: these method names could change at any time, and should not be
// depended upon externally:
getInternalMethods(): YargsInternalMethods {
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](): CommandInstance {
return this.#command;
}
[kGetContext](): Context {
return this.#context;
}
[kGetHasOutput](): boolean {
return this.#hasOutput;
}
[kGetLoggerInstance](): LoggerInstance {
return this.#logger;
}
[kGetParseContext](): Object {
return this.#parseContext || {};
}
[kGetUsageInstance](): UsageInstance {
return this.#usage;
}
[kGetValidationInstance](): ValidationInstance {
return this.#validation;
}
[kHasParseCallback](): boolean {
return !!this.#parseFn;
}
[kIsGlobalContext](): boolean {
return this.#isGlobalContext;
}
[kPostProcess]<T extends Arguments | Promise<Arguments>>(
argv: Arguments | Promise<Arguments>,
populateDoubleDash: boolean,
calledFromCommand: boolean,
runGlobalMiddleware: boolean
): any {
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 as Arguments);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
}
return argv;
}
// put yargs back into an initial state; this is used mainly for running
// commands in a breadth first manner:
[kReset](aliases: Aliases = {}): YargsInstance {
this.#options = this.#options || ({} as Options);
const tmpOptions = {} as Options;
tmpOptions.local = this.#options.local || [];
tmpOptions.configObjects = this.#options.configObjects || [];
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
const localLookup: Dictionary<boolean> = {};
tmpOptions.local.forEach(l => {
localLookup[l] = true;
(aliases[l] || []).forEach(a => {
localLookup[a] = true;
});
});
// add all groups not set to local to preserved groups
Object.assign(
this.#preservedGroups,
Object.keys(this.#groups).reduce((acc, groupName) => {
const keys = this.#groups[groupName].filter(
key => !(key in localLookup)
);
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {} as Dictionary<string[]>)
);
// groups can now be reset
this.#groups = {};
const arrayOptions: KeyOf<Options, string[]>[] = [
'array',
'boolean',
'string',
'skipValidation',
'count',
'normalize',
'number',
'hiddenOptions',
];
const objectOptions: DictionaryKeyof<Options>[] = [
'narg',
'key',
'alias',
'default',
'defaultDescription',
'config',
'choices',
'demandedOptions',
'demandedCommands',
'deprecatedOptions',
];
arrayOptions.forEach(k => {
tmpOptions[k] = (this.#options[k] || []).filter(
(k: string) => !localLookup[k]
);
});
objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => {
tmpOptions[k] = objFilter(
this.#options[k],
k => !localLookup[k as string]
);
});
tmpOptions.envPrefix = this.#options.envPrefix;
this.#options = tmpOptions;
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
this.#usage = this.#usage
? this.#usage.reset(localLookup)
: Usage(this, this.#shim);
this.#validation = this.#validation
? this.#validation.reset(localLookup)
: Validation(this, this.#usage, this.#shim);
this.#command = this.#command
? this.#command.reset()
: Command(
this.#usage,
this.#validation,
this.#globalMiddleware,
this.#shim
);
if (!this.#completion)
this.#completion = Completion(
this,
this.#usage,
this.#command,
this.#shim
);
this.#globalMiddleware.reset();
this.#completionCommand = null;
this.#output = '';
this.#exitError = null;
this.#hasOutput = false;
this.parsed = false;
return this;
}
[kRebase](base: string, dir: string): string {
return this.#shim.path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](
args: string | string[] | null,
shortCircuit?: boolean | null,
calledFromCommand?: boolean,
commandIndex = 0,
helpOnly = false
): Arguments | Promise<Arguments> {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || this.#processArgs;
this.#options.__ = this.#shim.y18n.__;
this.#options.configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!this.#options.configuration['populate--'];
const config = Object.assign({}, this.#options.configuration, {
'populate--': true,
});
const parsed = this.#shim.Parser.detailed(
args,
Object.assign({}, this.#options, {
configuration: {'parse-positional-numbers': false, ...config},
})
) as DetailedArguments;
const argv: Arguments = Object.assign(
parsed.argv,
this.#parseContext
) as Arguments;
let argvPromise: Arguments | Promise<Arguments> | undefined = undefined;
const aliases = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach(key => {
if (key === this.#helpOpt && argv[key]) {
helpOptSet = true;
} else if (key === this.#versionOpt && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
// A single yargs instance may be used multiple times, e.g.
// const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo').
// When a prior parse has completed and a new parse is beginning, we
// need to clear the cached help message from the previous parse:
if (commandIndex === 0) {
this.#usage.clearCachedHelpMessage();
}
try {
this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain.
// while building up the argv object, there
// are two passes through the parser. If completion
// is being performed short-circuit on the first pass.
if (shortCircuit) {
return this[kPostProcess](
argv,
populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// if there's a handler associated with a
// command defer processing to it.
if (this.#helpOpt) {
// consider any multi-char helpOpt alias as a valid help command
// unless all helpOpt aliases are single-char
// note that parsed.aliases is a normalized bidirectional map :)
const helpCmds = [this.#helpOpt]
.concat(aliases[this.#helpOpt] || [])
.filter(k => k.length > 1);
// check if help should trigger and strip it from _.
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
this.#isGlobalContext = false;
const handlerKeys = this.#command.getCommands();
const requestCompletions = this.#completion!.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 !== this.#completionCommand) {
// commands are executed using a recursive algorithm that executes
// the deepest command first; we keep track of the position in the
// argv._ array that is currently being executed.
const innerArgv = this.#command.runCommand(
cmd,
this,
parsed,
i + 1,
// Don't run a handler, just figure out the help string:
helpOnly,
// Passed to builder so that expensive commands can be deferred:
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
} else if (
!firstUnknownCommand &&
cmd !== this.#completionCommand
) {
firstUnknownCommand = cmd;
break;
}
}
// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (
!this.#command.hasDefaultCommand() &&
this.#recommendCommands &&
firstUnknownCommand &&
!skipRecommendation
) {
this.#validation.recommendCommands(
firstUnknownCommand,
handlerKeys
);
}
}
// generate a completion script for adding to ~/.bashrc.
if (
this.#completionCommand &&
argv._.includes(this.#completionCommand) &&
!requestCompletions
) {
if (this.#exitProcess) setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (this.#command.hasDefaultCommand() && !skipRecommendation) {
const innerArgv = this.#command.runCommand(
null,
this,
parsed,
0,
helpOnly,
helpOptSet || versionOptSet || helpOnly
);
return this[kPostProcess](
innerArgv,
populateDoubleDash,
!!calledFromCommand,
false
);
}
// we must run completions first, a user might
// want to complete the --help or --version option.
if (requestCompletions) {
if (this.#exitProcess) setBlocking(true);
// we allow for asynchronous completions,
// e.g., loading in a list of commands from an API.
args = ([] as string[]).concat(args);
const completionArgs = args.slice(
args.indexOf(`--${this.#completion!.completionKey}`) + 1
);
this.#completion!.getCompletion(completionArgs, (err, completions) => {
if (err) throw new YError(err.message);
(completions || []).forEach(completion => {
this.#logger.log(completion);
});
this.exit(0);
});
return this[kPostProcess](
argv,
!populateDoubleDash,
!!calledFromCommand,
false // Don't run middleware when figuring out completion.
);
}
// Handle 'help' and 'version' options
// if we haven't already output help!
if (!this.#hasOutput) {
if (helpOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.showHelp('log');
this.exit(0);
} else if (versionOptSet) {
if (this.#exitProcess) setBlocking(true);
skipValidation = true;
this.#usage.showVersion('log');
this.exit(0);
}
}
// Check if any of the options to skip validation were provided
if (!skipValidation && this.#options.skipValidation.length > 0) {
skipValidation = Object.keys(argv).some(
key =>
this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true
);
}
// If the help or version options were used and exitProcess is false,
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message);
// if we're executed via bash completion, don't
// bother with validation.
if (!requestCompletions) {
const validation = this[kRunValidation](aliases, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
true
);
}
argvPromise = this[kValidateAsync](validation, argvPromise ?? argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(
argv,
this,
this.#globalMiddleware.getMiddleware(),
false
);
});
}
}
}
} catch (err) {
if (err instanceof YError) this.#usage.fail(err.message, err);
else throw err;
}
return this[kPostProcess](
argvPromise ?? argv,
populateDoubleDash,
!!calledFromCommand,
true
);
}
[kRunValidation](
aliases: Dictionary<string[]>,
positionalMap: Dictionary<string[]>,
parseErrors: Error | null,
isDefaultCommand?: boolean
): (argv: Arguments) => void {
const demandedOptions = {...this.getDemandedOptions()};
return (argv: Arguments) => {
if (parseErrors) throw new YError(parseErrors.message);
this.#validation.nonOptionCount(argv);
this.#validation.requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (this.#strictCommands) {
failedStrictCommands = this.#validation.unknownCommands(argv);
}
if (this.#strict && !failedStrictCommands) {
this.#validation.unknownArguments(
argv,
aliases,
positionalMap,
!!isDefaultCommand
);
} else if (this.#strictOptions) {
this.#validation.unknownArguments(argv, aliases, {}, false, false);
}
this.#validation.limitedChoices(argv);
this.#validation.implications(argv);
this.#validation.conflicting(argv);
};
}
[kSetHasOutput]() {
this.#hasOutput = true;
}
[kTrackManuallySetKeys](keys: string | string[]) {
if (typeof keys === 'string') {
this.#options.key[keys] = true;
} else {
for (const k of keys) {
this.#options.key[k] = true;
}
}
}
} |
2,793 | (argv: Arguments) => this.customCompletion(args, argv, current, done) | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,794 | (argv: Arguments) => this.customCompletion(args, argv, current, done) | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,795 | (argv: Arguments) => this.customCompletion(args, argv, current, done) | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,796 | (argv: Arguments) => this.defaultCompletion(args, argv, current, done) | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,797 | (argv: Arguments) => this.defaultCompletion(args, argv, current, done) | interface Arguments {
/** The script name or node command */
$0: string;
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,798 | (argv: Arguments) => this.defaultCompletion(args, argv, current, done) | interface Arguments {
/** Non-option arguments */
_: ArgsOutput;
/** Arguments after the end-of-options flag `--` */
'--'?: ArgsOutput;
/** All remaining options */
[argName: string]: any;
} |
2,799 | registerFunction(fn: CompletionFunction) {
this.customCompletionFunction = fn;
} | type CompletionFunction =
| SyncCompletionFunction
| AsyncCompletionFunction
| FallbackCompletionFunction; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.