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 index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ class ArgError extends Error {
}
}

// Same acceptance as /^-?\d*(\.(?=\d))?\d*$/ without nested optional
// digit runs that backtrack on long non matching input (ReDoS).
function looksLikeNumber(str) {
return /^-?\d*(?:\.\d+)?$/.test(str);
}

function arg(
opts,
{
Expand Down Expand Up @@ -153,7 +159,7 @@ function arg(
(argv[i + 1].length > 1 &&
argv[i + 1][0] === '-' &&
!(
argv[i + 1].match(/^-?\d*(\.(?=\d))?\d*$/) &&
looksLikeNumber(argv[i + 1]) &&
(type === Number ||
// eslint-disable-next-line no-undef
(typeof BigInt !== 'undefined' && type === BigInt))
Expand Down
21 changes: 21 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -551,3 +551,24 @@ test('should error if negative numeric argument is passed to non-negative argume
)
).to.throw(arg.ArgError, 'option requires argument: --str');
});

test('should parse negative decimal numbers as option values', () => {
const argv = ['--num', '-1.5'];

expect(arg({ '--num': Number }, { argv })).to.deep.equal({
_: [],
'--num': -1.5
});
});

test('should reject long non numeric option values without hanging', () => {
const argv = ['--foo', `-${'0'.repeat(20000)}-`];
const start = Date.now();

expect(() => arg({ '--foo': Number }, { argv })).to.throw(
arg.ArgError,
'option requires argument: --foo'
);

expect(Date.now() - start).to.be.below(1000);
});