Skip to content

Commit dde811f

Browse files
committed
fix: reject invalid numeric flags
1 parent 3402565 commit dde811f

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

src/args.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,11 @@ export function parseFlags(argv: string[], options: OptionDef[]): GlobalFlags {
131131
if (arr) arr.push(value);
132132
else (flags as Record<string, unknown>)[camelKey] = [value];
133133
} else if (schema.numbers.has(camelKey)) {
134-
(flags as Record<string, unknown>)[camelKey] = Number(value);
134+
const numericValue = Number(value);
135+
if (value.trim() === '' || !Number.isFinite(numericValue)) {
136+
throw new Error(`Flag --${key} requires a numeric value, got "${value}".`);
137+
}
138+
(flags as Record<string, unknown>)[camelKey] = numericValue;
135139
} else {
136140
(flags as Record<string, unknown>)[camelKey] = value;
137141
}

test/args.test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { describe, it, expect } from 'bun:test';
2+
import { parseFlags } from '../src/args';
3+
import type { OptionDef } from '../src/command';
4+
5+
const OPTIONS: OptionDef[] = [
6+
{ flag: '--timeout <seconds>', description: 'Request timeout', type: 'number' },
7+
{ flag: '--message <text>', description: 'Message text', type: 'array' },
8+
];
9+
10+
describe('parseFlags', () => {
11+
it('rejects non-numeric values for number flags', () => {
12+
expect(() => parseFlags(['--timeout', 'abc'], OPTIONS)).toThrow(
13+
'Flag --timeout requires a numeric value, got "abc".',
14+
);
15+
});
16+
17+
it('rejects empty values for number flags', () => {
18+
expect(() => parseFlags(['--timeout='], OPTIONS)).toThrow(
19+
'Flag --timeout requires a numeric value, got "".',
20+
);
21+
});
22+
23+
it('still accepts finite numeric values', () => {
24+
const flags = parseFlags(['--timeout', '1.5'], OPTIONS);
25+
26+
expect(flags.timeout).toBe(1.5);
27+
});
28+
});

0 commit comments

Comments
 (0)