Skip to content
Closed
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
3 changes: 3 additions & 0 deletions lib/string-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ export function looksLikeNumber(
if (x === null || x === undefined) return false;
// if loaded from config, may already be a number.
if (typeof x === 'number') return true;
// values returned by a coerce function are not necessarily primitives, and
// converting one to a string for the checks below can throw.
if (typeof x !== 'string') return false;
// hexadecimal.
if (/^0x[0-9a-f]+$/i.test(x)) return true;
// don't treat 0123 as a number; as it drops the leading '0'.
Expand Down
11 changes: 11 additions & 0 deletions test/string-utils.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,16 @@ describe('string-utils', function () {
strictEqual(looksLikeNumber('0100'), false);
strictEqual(looksLikeNumber('apple'), false);
});
it('it does not throw for values that cannot be converted to a string', () => {
const nullPrototype = Object.create(null);
nullPrototype.host = 'localhost';
const throwsOnToString = {
toString() {
throw new Error('nope');
},
};
strictEqual(looksLikeNumber(nullPrototype), false);
strictEqual(looksLikeNumber(throwsOnToString), false);
});
});
});
15 changes: 15 additions & 0 deletions test/yargs-parser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3786,6 +3786,21 @@ describe('yargs-parser', function () {
parsed.foo.should.equal(-99);
});

it('applies coercion function that returns an object without a prototype', function () {
const parsed = parser(['--foo', 'postgresql://db/things'], {
coerce: {
// e.g. pg-connection-string's parse returns a null prototype
// object, which cannot be converted to a primitive.
foo: function () {
const connection = Object.create(null);
connection.host = 'db';
return connection;
},
},
});
parsed.foo.host.should.equal('db');
});

it('applies coercion function to aliases', function () {
const parsed = parser(['--foo', '99'], {
coerce: {
Expand Down