From 9d137ff203bfcef2c633db0cd96f50e21de80227 Mon Sep 17 00:00:00 2001 From: DeepView Autofix <276251120+deepview-autofix@users.noreply.github.com> Date: Fri, 17 Apr 2026 00:25:46 +0300 Subject: [PATCH] fix: skip empty array values in stringify Empty array values caused malformed query strings with leading or trailing `&` separators because the separator was appended unconditionally for every key while the inner loop produced no output. For example, `stringify({a: [], b: "1"})` produced `"&b=1"` and `stringify({a: "1", b: []})` produced `"a=1&"`. Skip empty arrays entirely and only emit the separator when the current key actually contributes a key=value pair, matching the behavior of the native `querystring` module. Co-Authored-By: Claude Co-Authored-By: DeepView Autofix <276251120+deepview-autofix@users.noreply.github.com> Co-Authored-By: Nikita Skovoroda Signed-off-by: Nikita Skovoroda --- lib/stringify.js | 13 +++++++++---- test/stringify.test.ts | 7 +++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/lib/stringify.js b/lib/stringify.js index a2dea7e..c59dba1 100644 --- a/lib/stringify.js +++ b/lib/stringify.js @@ -39,12 +39,14 @@ function stringify(input) { const value = input[key]; const encodedKey = encodeString(key) + "="; - if (i) { - result += separator; - } - if (Array.isArray(value)) { valueLength = value.length; + if (valueLength === 0) { + continue; + } + if (result.length > 0) { + result += separator; + } for (let j = 0; j < valueLength; j++) { if (j) { result += separator; @@ -56,6 +58,9 @@ function stringify(input) { result += getAsPrimitive(value[j]); } } else { + if (result.length > 0) { + result += separator; + } result += encodedKey; result += getAsPrimitive(value); } diff --git a/test/stringify.test.ts b/test/stringify.test.ts index dd3980a..6a671ea 100644 --- a/test/stringify.test.ts +++ b/test/stringify.test.ts @@ -97,6 +97,13 @@ test("should coerce numbers to string", () => { assert.strictEqual(qs.stringify({ foo: Number.POSITIVE_INFINITY }), "foo="); }); +test("should skip empty array values without leaving stray separators", () => { + assert.strictEqual(qs.stringify({ a: [], b: "1" }), "b=1"); + assert.strictEqual(qs.stringify({ a: "1", b: [] }), "a=1"); + assert.strictEqual(qs.stringify({ a: "1", b: [], c: "2" }), "a=1&c=2"); + assert.strictEqual(qs.stringify({ a: [] }), ""); +}); + test("should return empty string on certain inputs", () => { assert.strictEqual(qs.stringify(undefined as never), ""); assert.strictEqual(qs.stringify(0 as never), "");