Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/yargs-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,13 @@ export class YargsParser {
return value
}

function maybeCoerceNumber (key: string, value: string | number | null | undefined) {
function maybeCoerceNumber (key: string, value: unknown) {
// Coercion callbacks may intentionally return objects (for example,
// parsed connection strings). Only strings and numbers can be inspected
// for numeric syntax; passing other values to the regular expressions
// in `looksLikeNumber` can throw for objects without a prototype.
if (typeof value !== 'string' && typeof value !== 'number') return value

if (!configuration['parse-positional-numbers'] && key === '_') return value
if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (
Expand Down
15 changes: 15 additions & 0 deletions test/yargs-parser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3536,6 +3536,21 @@ describe('yargs-parser', function () {
parsed.foo.should.equal('BAR')
})

it('preserves objects returned by coercion functions', function () {
const value = Object.create(null)
value.database = 'postgres'

const parsed = parser(['--connection', 'postgresql://db/example'], {
coerce: {
connection: function () {
return value
}
}
})

parsed.connection.should.equal(value)
})

it('applies coercion function to an implicit array', function () {
const parsed = parser(['--foo', '99', '-f', '33'], {
coerce: {
Expand Down