Skip to content

Commit b433a9b

Browse files
committed
[Fix] stringify: do not let allowEmptyArrays skip cycle detection (or drop own keys) on an empty array with own properties
The `allowEmptyArrays` fast path returned early on any array with `length === 0`, before the loop that records the cyclic-reference bookkeeping and serializes own keys. An empty array carrying own enumerable properties (including one that closes a cycle) was therefore short-circuited to `[]`, silently dropping those keys and bypassing the `RangeError("Cyclic object value")` guard. Only short-circuit when the array has no own keys.
1 parent f3dc5b0 commit b433a9b

2 files changed

Lines changed: 34 additions & 1 deletion

File tree

‎lib/stringify.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ var stringify = function stringify(
165165

166166
var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix;
167167

168-
if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
168+
if (allowEmptyArrays && isArray(obj) && obj.length === 0 && Object.keys(obj).length === 0) {
169169
return adjustedPrefix + '[]';
170170
}
171171

‎test/stringify.js‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,39 @@ test('stringify()', function (t) {
466466
st.end();
467467
});
468468

469+
t.test('allowEmptyArrays only short-circuits arrays with no own keys', function (st) {
470+
st.equal(
471+
qs.stringify({ a: [] }, { allowEmptyArrays: true }),
472+
'a[]',
473+
'a genuinely empty array is still emitted as `[]`'
474+
);
475+
476+
var withKey = [];
477+
withKey.extra = 'x';
478+
st.equal(
479+
qs.stringify({ a: withKey }, { allowEmptyArrays: true }),
480+
'a%5Bextra%5D=x',
481+
'an own key on an empty array is serialized rather than dropped'
482+
);
483+
st.equal(
484+
qs.stringify({ a: withKey }, { allowEmptyArrays: true }),
485+
qs.stringify({ a: withKey }),
486+
'the allowEmptyArrays fast path matches the default path when the array has own keys'
487+
);
488+
489+
var container = {};
490+
var cyclic = [];
491+
cyclic.back = container;
492+
container.a = cyclic;
493+
st['throws'](
494+
function () { qs.stringify(container, { allowEmptyArrays: true }); },
495+
RangeError,
496+
'a cycle through an empty array with an own key is still detected'
497+
);
498+
499+
st.end();
500+
});
501+
469502
t.test('stringifies an array value with one item vs multiple items', function (st) {
470503
st.test('non-array item', function (s2t) {
471504
s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c');

0 commit comments

Comments
 (0)