Skip to content

maybeCoerceNumber bombs if coerce produced an object without toString #352

Open

Description

@groner

I ran into this trying to use pg-connection-string.parse as a coerce function today, it returns an object with a null prototype which can't be coerced to a string.

import yargs from 'yargs';
import {parse as pgcs_parse} from 'pg-connection-string';


const parser = yargs('--db=postgresql://db/something'.split(/\s+/))
  .strict()
  .option('db', {
    coerce: pgcs_parse,
  })
  .fail((_, err) => {
    console.error(err.stack);
    process.exit(1);
  })
  ;

const argv = parser.parse();

console.log(argv);
:; ts-node test.ts
YError: Cannot convert object to primitive value
    at Object.parseArgs [as _parseArgs] (.../node_modules/yargs/build/index.cjs:2762:27)
    at Object.parse (.../node_modules/yargs/build/index.cjs:2260:31)
    at Object.<anonymous> (.../test.ts:16:21)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:858:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:861:12)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)

The original stack trace is lost when it gets converted to YError, but the problem occurs in looksLikeNumber when the regexp is applied. It seems to me that maybeCoerceNumber could check if value is a string before doing anything more.

Activity

  1. sTEVE7611 commented on Feb 12, 2021

    @sTEVE7611
  2. bcoe commented on Feb 13, 2021

    @bcoe
    Member

    @groner is the correct behavior for us to detect there's no .toString and just return false?

  3. groner commented on Feb 13, 2021

    @groner
    Author

    The bug comes from something looksLikeNumber doing something that tries and fails to coerce an object to a string. My thinking is that if the value is anything but a string, it probably doesn't need further interpretation. I would add a typeof value === 'string' check in maybeCoerceNumber or looksLikeNumber would solve this.

    A more conservative fix might be to check if String(value) works without throwing an exception. Testing for .toString is probably fine too. There's a corner case with null/undefined, but we know they're not numbers.

  4. added a commit that references this issue on Nov 8, 2026
    74a5ef2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions