vike
Version:
The Framework *You* Control - Next.js & Nuxt alternative for unprecedented flexibility and dependability.
31 lines (30 loc) • 1.06 kB
JavaScript
export { freezePartial };
// Unit tests at ./freezePartial.spec.ts
import pc from '@brillout/picocolors';
import { assertIsNotBrowser } from './assertIsNotBrowser.js';
assertIsNotBrowser();
function freezePartial(obj, allowList) {
Object.entries(obj).forEach(([key, val]) => {
Object.defineProperty(obj, key, {
get() {
return val;
},
set(newVal) {
if (key in allowList) {
const isAllowed = allowList[key](newVal);
if (isAllowed) {
val = newVal;
return;
}
else {
throw new Error(`Setting wrong value ${pc.cyan(JSON.stringify(newVal))} for property ${pc.cyan(key)}`);
}
}
throw new Error(`You aren't allowed to mutate property ${pc.cyan(key)}`);
},
configurable: false,
enumerable: true,
});
});
Object.preventExtensions(obj);
}