Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix] stringify: actually fix cyclic references #426

Merged
merged 1 commit into from Dec 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 21 additions & 3 deletions lib/stringify.js
Expand Up @@ -56,6 +56,8 @@ var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
|| typeof v === 'bigint';
};

var sentinel = {};

var stringify = function stringify(
object,
prefix,
Expand All @@ -75,8 +77,23 @@ var stringify = function stringify(
) {
var obj = object;

if (sideChannel.has(object)) {
throw new RangeError('Cyclic object value');
var tmpSc = sideChannel;
var step = 0;
var findFlag = false;
while ((tmpSc = tmpSc.get(sentinel)) !== undefined && !findFlag) {
liaokunhua marked this conversation as resolved.
Show resolved Hide resolved
// Where object last appeared in the ref tree
var pos = tmpSc.get(object);
step += 1;
if (typeof pos !== 'undefined') {
if (pos === step) {
throw new RangeError('Cyclic object value');
} else {
findFlag = true; // Break while
}
}
if (typeof tmpSc.get(sentinel) === 'undefined') {
step = 0;
}
}

if (typeof filter === 'function') {
Expand Down Expand Up @@ -145,8 +162,9 @@ var stringify = function stringify(
? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix
: prefix + (allowDots ? '.' + key : '[' + key + ']');

sideChannel.set(object, true);
sideChannel.set(object, step);
var valueSideChannel = getSideChannel();
valueSideChannel.set(sentinel, sideChannel);
pushToArray(values, stringify(
value,
keyPrefix,
Expand Down
10 changes: 8 additions & 2 deletions test/stringify.js
Expand Up @@ -454,7 +454,7 @@ test('stringify()', function (t) {

st['throws'](
function () { qs.stringify({ 'foo[bar]': 'baz', 'foo[baz]': a }); },
RangeError,
/RangeError: Cyclic object value/,
'cyclic values throw'
);

Expand All @@ -464,10 +464,16 @@ test('stringify()', function (t) {
circular.a = circular;
st['throws'](
function () { qs.stringify(circular); },
RangeError,
/RangeError: Cyclic object value/,
'cyclic values throw'
);

var arr = ['a'];
st.doesNotThrow(
function () { qs.stringify({ x: arr, y: arr }); },
'non-cyclic values do not throw'
);

st.end();
});

Expand Down