Sub topic 10
Proxy Invariants: Rules Traps Cannot Break
The earlier chapters showed traps returning nearly anything they wanted. A get trap could make up values, a has trap could hide keys, and an ownKeys trap could filter enumeration. That freedom has limits. After most traps return, the engine checks the result against the target, and it throws a TypeError when the trap breaks one of a fixed set of rules. Those rules are the proxy invariants.
This chapter assumes you know property descriptors (writable, configurable, enumerable), Object.freeze and Object.preventExtensions, and the traps and Reflect methods covered in earlier chapters.
Why Invariants Exist
Some facts about an object are permanent. Once a property is non-configurable and non-writable, its value can never change. Once an object is non-extensible, it can never gain new properties. Code depends on these guarantees. A library that freezes a configuration object assumes no one can change it, and a security check that tests Object.isFrozen(x) assumes the answer stays true.
Without invariants, a proxy could wrap a frozen object and report different values on every read, which would break those guarantees. The engine prevents this. A trap can still invent behavior for anything the target has left open, but it cannot contradict what the target has made permanent.
How the Engine Enforces Them
The check runs after the trap returns. The engine calls your trap and receives its result. Then it inspects the target, usually by reading the target's own property descriptor or its extensibility, and compares the two. If they conflict, the operation throws.
Because the check comes afterward, the trap's side effects have already happened by the time the error is thrown. The trap below logs before it throws:
const frozen = Object.freeze({ x: 1 });
const liar = new Proxy(frozen, {
get(target, prop) {
console.log(`get ${String(prop)}`);
return 2;
}
});
try {
liar.x;
} catch (err) {
console.log(err instanceof TypeError); // true
}
// Output: "get x", then trueHere x is non-writable and non-configurable, so any read must report its real value, 1. The trap returned 2, and the engine rejected it.
The Invariants, Trap by Trap
The table lists the main rules. They all follow from one principle: a trap cannot report anything that contradicts a non-configurable property or a non-extensible target.
| Trap | The trap throws a TypeError if it... |
|---|---|
| `get` | reports a value different from a non-writable, non-configurable data property; reports anything other than `undefined` for a non-configurable accessor with no getter |
| `set` | returns `true` for a non-writable, non-configurable data property when the value differs; returns `true` for a non-configurable accessor with no setter |
| `has` | returns `false` for a non-configurable own property; returns `false` for any own property of a non-extensible target |
| `deleteProperty` | returns `true` for a non-configurable own property; returns `true` for an existing own property of a non-extensible target |
| `ownKeys` | returns something other than a list of unique strings and symbols; omits a non-configurable own key; on a non-extensible target, returns anything other than exactly the target's own keys |
| `getOwnPropertyDescriptor` | hides a non-configurable property; hides any property of a non-extensible target; reports a property as non-configurable when the target's property is configurable or missing; reports a property that does not exist on a non-extensible target |
| `defineProperty` | returns `true` for adding a property to a non-extensible target; returns `true` for a non-configurable definition the target does not match |
| `getPrototypeOf` | on a non-extensible target, returns something other than the real prototype |
| `setPrototypeOf` | on a non-extensible target, returns `true` for a prototype different from the real one |
| `isExtensible` | returns a value different from `Object.isExtensible(target)` |
| `preventExtensions` | returns `true` while the target is still extensible |
| `construct` | returns a primitive instead of an object |
apply has no invariant on its result. A proxy is callable only if its target is callable, and constructible only if its target is constructible. Defining an apply trap on a proxy over a plain object does not make it callable.
get and set
The get rule covers two cases. The frozen-value case appears above. The accessor case looks like this:
const target = {};
Object.defineProperty(target, 'writeOnly', {
set(v) {},
configurable: false
});
const proxy = new Proxy(target, {
get() {
return 5;
}
});
try {
proxy.writeOnly;
} catch (err) {
console.log(err.message); // must report undefined for an accessor with no getter
}The set rules work the same way in reverse. A trap may refuse any write by returning false, but it may not claim success for a write the target makes impossible.
'use strict';
const target = {};
Object.defineProperty(target, 'id', {
value: 1,
writable: false,
configurable: false
});
const proxy = new Proxy(target, {
set() {
return true; // claims the write succeeded
}
});
try {
proxy.id = 2;
} catch (err) {
console.log(err instanceof TypeError); // true: invariant violated
}
proxy.id = 1; // allowed: same value, so "success" is not a liehas, deleteProperty, and ownKeys
These are the invariants people hit most often, because hiding properties is a common use for proxies. The hiding pattern from the earlier chapter works on an ordinary object. Make the target non-extensible and it breaks:
const isHidden = (key) => typeof key === 'string' && key.startsWith('_');
const target = Object.preventExtensions({ _secret: 1, visible: 2 });
const record = new Proxy(target, {
has(t, prop) {
return isHidden(prop) ? false : Reflect.has(t, prop);
},
ownKeys(t) {
return Reflect.ownKeys(t).filter((key) => !isHidden(key));
}
});
try {
'_secret' in record;
} catch (err) {
console.log('has:', err instanceof TypeError); // has: true
}
try {
Object.keys(record);
} catch (err) {
console.log('ownKeys:', err instanceof TypeError); // ownKeys: true
}A non-extensible object promises that its set of keys is fixed and fully visible. Hiding _secret would break that promise. The same failure happens on a frozen or sealed target, because freezing and sealing also make every property non-configurable.
ownKeys also has a shape rule that applies to every target:
const bad = new Proxy({}, {
ownKeys() {
return ['a', 'a', 42];
}
});
try {
Reflect.ownKeys(bad);
} catch (err) {
console.log(err instanceof TypeError); // true: duplicates and non-key values
}Extensibility and prototype traps
isExtensible has the strictest rule: it must report exactly what the target reports. You can't use it to make an object look sealed.
const proxy = new Proxy({}, {
isExtensible() {
return false;
}
});
try {
Object.isExtensible(proxy);
} catch (err) {
console.log(err instanceof TypeError); // true
}To make a proxy actually non-extensible, let preventExtensions forward to the target with Reflect.preventExtensions. After that the target is non-extensible, and every rule tied to non-extensible targets applies to the proxy.
construct
A construct trap must return an object. A primitive throws:
function Point() {}
const proxy = new Proxy(Point, {
construct() {
return 1;
}
});
try {
new proxy();
} catch (err) {
console.log(err instanceof TypeError); // true
}Working Around Invariants: The Shadow Target
Sometimes you need a proxy to present a view the real object would contradict, such as a filtered view of a frozen object. The standard fix is a shadow target: you give the proxy a separate, empty, extensible object as its target, and keep the real data in a closure. The empty target has made no commitments, so the invariants have nothing to enforce. Every trap reads from the real source.
const isHidden = (key) => typeof key === 'string' && key.startsWith('_');
function filteredView(source) {
const shadow = {}; // empty and extensible: no invariants to violate
return new Proxy(shadow, {
get(_, prop) {
return isHidden(prop) ? undefined : Reflect.get(source, prop);
},
has(_, prop) {
return isHidden(prop) ? false : Reflect.has(source, prop);
},
ownKeys() {
return Reflect.ownKeys(source).filter((key) => !isHidden(key));
},
getOwnPropertyDescriptor(_, prop) {
if (isHidden(prop)) return undefined;
const desc = Reflect.getOwnPropertyDescriptor(source, prop);
// The shadow lacks this property, so it must be reported as configurable.
return desc && { ...desc, configurable: true };
},
set() {
return false;
},
deleteProperty() {
return false;
}
});
}
const config = Object.freeze({ _token: 'abc', host: 'example.com' });
const view = filteredView(config);
console.log('_token' in view); // false
console.log(Object.keys(view)); // ['host']
console.log(view.host); // 'example.com'Two details are important here:
Object.keyscallsownKeysand thengetOwnPropertyDescriptorfor each key to check enumerability. Without the descriptor trap, the engine would find nothing on the empty shadow and leavehostout.- The descriptor trap rewrites
configurabletotrue. The source's real descriptor saysconfigurable: false, but the shadow has no such property. Reporting a non-configurable property the target lacks violates thegetOwnPropertyDescriptorinvariant.
The pattern has costs. Object.isFrozen(view) returns false because the shadow is not frozen, so the view gives up the freeze guarantee in exchange for flexibility. To also make the view report itself as frozen, you would need to copy the visible properties onto the shadow and freeze it. At that point the invariants apply again, but they now describe the filtered view.
Predicting Whether a Trap Will Throw
When a trap does something unusual, ask these questions about the target, not the proxy:
- Is the property involved non-configurable on the target? If so, the trap must agree with it: same value, no hiding, no deletion.
- Is the target non-extensible? If so, the set of keys and the prototype are fixed, and the trap must report them exactly.
- Does the trap report a commitment the target hasn't made, such as a non-configurable descriptor or non-extensibility? That throws too.
- Is the result the right type: an object from
construct, or unique strings and symbols fromownKeys?
If all four answers are no, the trap can return anything it likes.
Exercise
A proxy wraps Object.seal({ a: 1 }) with a get trap that always returns 99. Does proxy.a throw? What about a deleteProperty trap that returns true for a?
Show answer
proxy.a returns 99 without throwing. Sealing makes a non-configurable but leaves it writable, and the get invariant only covers properties that are both non-writable and non-configurable. delete proxy.a with a trap that returns true throws a TypeError, because the trap reports a non-configurable property as deleted.
Exercise
An ownKeys trap on a proxy over an ordinary extensible object { x: 1 } returns ['x', 'y'], where y doesn't exist on the target. Does Reflect.ownKeys(proxy) throw? Explain using the invariants.
Show answer
It does not throw. The target is extensible, so the trap may report extra keys, and x is configurable, so it could even be omitted. The invariants only require including non-configurable keys, and exactly the target's keys when the target is non-extensible. Neither condition applies.
Exercise
In the shadow-target example, what happens if you remove the { ...desc, configurable: true } rewrite and return the source's descriptor unchanged? Why?
Show answer
Object.keys(view) throws a TypeError. The frozen source's descriptor for host has configurable: false, but the shadow target has no host property. A getOwnPropertyDescriptor trap may not report a property as non-configurable unless the target has a matching non-configurable property.