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 Error clone() when structuredClone uses bad prototype #399

Merged
merged 1 commit into from
Oct 24, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
});