Skip to content

Commit

Permalink
Fix Error clone() when structuredClone uses bad prototype
Browse files Browse the repository at this point in the history
This can happen in jest which uses node vm to isolate runs
  • Loading branch information
kanongil authored and Marsup committed Oct 24, 2024
1 parent d9960cf commit 721762a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ internals.base = function (obj, baseProto, options) {
/* $lab:coverage:off$ */
else if (baseProto === Types.error && internals.structuredCloneExists) {
const err = structuredClone(obj); // Needed to copy internal stack state
if (proto !== baseProto) {
if (Object.getPrototypeOf(err) !== proto) {
Object.setPrototypeOf(err, proto); // Fix prototype
}

Expand Down
28 changes: 28 additions & 0 deletions test/clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -886,4 +886,32 @@ describe('clone()', () => {
const b = Hoek.clone(a);
expect(b.x).to.not.exist();
});

it('handles structuredClone not returning proper Error instances', { skip: typeof structuredClone !== 'function' }, () => {

// This can happen when running in a VM

const error = new Error('blam');

const origStructuredClone = structuredClone;
try {
structuredClone = function (obj) {

const clone = origStructuredClone.call(this, obj);
if (obj === error) {
Object.setPrototypeOf(clone, Object);
}

return clone;
};

var cloned = Hoek.clone(error);
}
finally {
structuredClone = origStructuredClone;
}

expect(cloned).to.be.instanceOf(Error);
expect(cloned).to.equal(error);
});
});

0 comments on commit 721762a

Please sign in to comment.