From 1add88a3b6eadf380187ca66688d208245dd06a1 Mon Sep 17 00:00:00 2001 From: "Mark S. Miller" Date: Tue, 16 Jan 2024 13:16:56 -0800 Subject: [PATCH] refactor(ses): cleaner enable-property-overrides (#1975) --- packages/ses/src/enable-property-overrides.js | 66 +++++++++++-------- 1 file changed, 37 insertions(+), 29 deletions(-) diff --git a/packages/ses/src/enable-property-overrides.js b/packages/ses/src/enable-property-overrides.js index 476a9d9b60..b4b18a41ce 100644 --- a/packages/ses/src/enable-property-overrides.js +++ b/packages/ses/src/enable-property-overrides.js @@ -88,9 +88,43 @@ export default function enablePropertyOverrides( if ('value' in desc && desc.configurable) { const { value } = desc; - function getter() { - return value; - } + const isDebug = setHas(debugProperties, prop); + + // We use concise method syntax to be `this` sensitive, but still + // omit a prototype property or [[Construct]] behavior. + // @ts-expect-error We know there is an accessor descriptor there + const { get: getter, set: setter } = getOwnPropertyDescriptor( + { + get [prop]() { + return value; + }, + set [prop](newValue) { + if (obj === this) { + throw TypeError( + `Cannot assign to read only property '${String( + prop, + )}' of '${path}'`, + ); + } + if (objectHasOwnProperty(this, prop)) { + this[prop] = newValue; + } else { + if (isDebug) { + // eslint-disable-next-line @endo/no-polymorphic-call + console.error(TypeError(`Override property ${prop}`)); + } + defineProperty(this, prop, { + value: newValue, + writable: true, + enumerable: true, + configurable: true, + }); + } + }, + }, + prop, + ); + defineProperty(getter, 'originalValue', { value, writable: false, @@ -98,32 +132,6 @@ export default function enablePropertyOverrides( configurable: false, }); - const isDebug = setHas(debugProperties, prop); - - function setter(newValue) { - if (obj === this) { - throw TypeError( - `Cannot assign to read only property '${String( - prop, - )}' of '${path}'`, - ); - } - if (objectHasOwnProperty(this, prop)) { - this[prop] = newValue; - } else { - if (isDebug) { - // eslint-disable-next-line @endo/no-polymorphic-call - console.error(TypeError(`Override property ${prop}`)); - } - defineProperty(this, prop, { - value: newValue, - writable: true, - enumerable: true, - configurable: true, - }); - } - } - defineProperty(obj, prop, { get: getter, set: setter,