Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-circular-custom-revivers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': patch
---

fix: resolve circular references through custom revivers when payload is already hydrated
4 changes: 4 additions & 0 deletions src/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ export function unflatten(parsed, revivers) {
i = values.push(value[1]) - 1;
}

if (i in hydrated) {
return (hydrated[index] = reviver(hydrated[i]));
}

hydrating ??= new Set();

if (hydrating.has(i)) {
Expand Down
78 changes: 78 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1682,3 +1682,81 @@ asyncErrorTests('throws for promise resolving to function', async () => {
});

asyncErrorTests.run();

const circularCustomTypes = uvu.suite('circular references through custom types');

circularCustomTypes('resolves circular reference through two custom types', () => {
const foo = new Foo({ name: 'outer' });
const bar = new Bar({ name: 'inner', ref: foo });
foo.value.ref = bar;

const reducers = {
Foo: (x) => x instanceof Foo && x.value,
Bar: (x) => x instanceof Bar && x.value
};
const fooCache = new WeakMap();
const barCache = new WeakMap();
const revivers = {
Foo: (x) => {
let inst = fooCache.get(x);
if (!inst) {
inst = Object.create(Foo.prototype);
fooCache.set(x, inst);
}
inst.value = x;
return inst;
},
Bar: (x) => {
let inst = barCache.get(x);
if (!inst) {
inst = Object.create(Bar.prototype);
barCache.set(x, inst);
}
inst.value = x;
return inst;
}
};

const json = stringify(foo, reducers);
const result = parse(json, revivers);

assert.ok(result instanceof Foo);
assert.ok(result.value.ref instanceof Bar);
assert.is(result.value.ref.value.ref, result);
});

circularCustomTypes('resolves self-referencing custom type', () => {
const foo = new Foo({ name: 'self' });
foo.value.ref = foo;

const reducers = {
Foo: (x) => x instanceof Foo && x.value
};
const fooCache = new WeakMap();
const revivers = {
Foo: (x) => {
let inst = fooCache.get(x);
if (!inst) {
inst = Object.create(Foo.prototype);
fooCache.set(x, inst);
}
inst.value = x;
return inst;
}
};

const json = stringify(foo, reducers);
const result = parse(json, revivers);

assert.ok(result instanceof Foo);
assert.is(result.value.ref, result);
});

circularCustomTypes('still rejects genuinely invalid circular reference', () => {
assert.throws(
() => parse('[["Custom", 0]]', { Custom: (v) => v }),
(error) => error.message === 'Invalid circular reference'
);
});

circularCustomTypes.run();