From ee2f6cbfcab96bb229d427e2f02909bd07768f22 Mon Sep 17 00:00:00 2001 From: Sami Puro Date: Wed, 2 Dec 2026 03:11:03 +0200 Subject: [PATCH] fix: validate precision and output for zero values --- src/helpers.js | 15 +++++++++++++++ tests/unit/filesize.test.js | 9 +++++++++ 2 files changed, 24 insertions(+) diff --git a/src/helpers.js b/src/helpers.js index 89b24bb..55b22ac 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -79,6 +79,7 @@ export function getBaseConfiguration(standard, base) { * @param {Object} [localeOptions={}] - Locale formatting options * @param {string} [separator=""] - Custom decimal separator * @returns {string|Array|Object|number} Formatted result + * @throws {TypeError} When precision is out of range (1-100) or output is not a supported format */ export function handleZeroValue( precision, @@ -96,6 +97,20 @@ export function handleZeroValue( localeOptions = {}, separator = EMPTY, ) { + // Validate precision and output the same way the non-zero path does, so a + // zero input throws the documented TypeError instead of a raw RangeError + // from toPrecision() or a silently formatted string. + if ( + precision > 0 && + (typeof precision !== "number" || precision < 1 || Math.floor(precision) > 100) + ) { + throw new TypeError(INVALID_PRECISION); + } + + if (output !== ARRAY && output !== OBJECT && output !== STRING && output !== EXPONENT) { + throw new TypeError(`Invalid output: ${output}`); + } + let value; if (precision > 0) { value = (0).toPrecision(precision); diff --git a/tests/unit/filesize.test.js b/tests/unit/filesize.test.js index 73e3390..2efde10 100644 --- a/tests/unit/filesize.test.js +++ b/tests/unit/filesize.test.js @@ -772,6 +772,15 @@ describe("filesize", () => { assert.throws(() => filesize(1000, { output: "foo" }), TypeError); }); + it("should validate precision and output for zero like any other value", () => { + assert.throws(() => filesize(0, { precision: 101 }), TypeError); + assert.throws(() => filesize(0, { precision: 0.5 }), TypeError); + assert.throws(() => filesize(0, { precision: "3" }), TypeError); + assert.throws(() => filesize(0, { output: "foo" }), TypeError); + assert.throws(() => filesize(0n, { output: "foo" }), TypeError); + assert.strictEqual(filesize(0, { precision: 100.5 }), `0.${"0".repeat(99)} B`); + }); + it("should throw TypeError for invalid numeric strings", () => { assert.throws(() => filesize("1_000"), TypeError); assert.throws(() => filesize("1000n"), TypeError);