From 74a5ef2775dd45635dddbb65026768d35632d41a Mon Sep 17 00:00:00 2001 From: naveentehrpariya Date: Sun, 8 Nov 2026 16:13:41 +0530 Subject: [PATCH] fix: don't throw when a coerce function returns a non-primitive `looksLikeNumber` converts its argument to a string to run its regex checks. A coerce function can return any value, and converting one to a string throws for objects with no `toString` -- for example the null prototype object returned by `pg-connection-string`'s `parse`: TypeError: Cannot convert object to primitive value Return `false` for anything that is neither a number nor a string: such a value can never be parsed as a number anyway. Fixes #352 --- lib/string-utils.ts | 3 +++ test/string-utils.mjs | 11 +++++++++++ test/yargs-parser.mjs | 15 +++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/lib/string-utils.ts b/lib/string-utils.ts index 61424d8e..4ba963bb 100644 --- a/lib/string-utils.ts +++ b/lib/string-utils.ts @@ -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'. diff --git a/test/string-utils.mjs b/test/string-utils.mjs index f1ad4368..d755f815 100644 --- a/test/string-utils.mjs +++ b/test/string-utils.mjs @@ -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); + }); }); }); diff --git a/test/yargs-parser.mjs b/test/yargs-parser.mjs index 91c042a0..470e4331 100644 --- a/test/yargs-parser.mjs +++ b/test/yargs-parser.mjs @@ -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: {