overlookmotel / livepack

Serialize live running code to Javascript
MIT License
30 stars 0 forks source link

Simplify creation of objects with `__proto__` property #565

Open overlookmotel opened 6 months ago

overlookmotel commented 6 months ago

Input:

const obj = {
  ['__proto__']: {x: 123}
};
assert(obj.x === undefined);
assert(Object.getPrototypeOf(obj) === Object.prototype);
assert(Object.keys(obj)[0] === '__proto__');
export default obj;

Current output:

export default Object.defineProperty({}, "__proto__", {
  value: {x: 123},
  writable: true,
  enumerable: true,
  configurable: true
});

This verbose output was to avoid outputting {__proto__: {x: 1}}, which would set the prototype of the object, not a property called '__proto__'. But wrapping __proto__ as ['__proto__'] achieves the same effect and is shorter.

It would also allow removing some code which handles this special case in the serializer.

NB: When setting a circular property, Object.defineProperties() is still needed - obj.__proto__ = obj or Object.assign(obj, {['__proto__']: obj}) both trigger the setter on Object.prototype.__proto__, which results in setting the prototype.