vm: introduce vanilla contexts via vm.constants.DONT_CONTEXTIFY
vm: introduce vanilla contexts via vm.constants.DONT_CONTEXTIFY
Text for releasers:
new option for vm.createContext() to create a context with a freezable globalThis
This implements a flavor of vm.createContext()
and friends that creates a context without contextifying its global object when vm.constants.DONT_CONTEXTIFY is used.
This is suitable when users want to freeze the context (impossible when the global is contextified i.e. has interceptors installed) or speed up the global access if they don't need the interceptor behavior.
const vm = require('node:vm');
{
const oldContext = vm.createContext();
console.log(vm.runInContext('globalThis', context) === oldContext); // false
console.log(oldContext.Array); // undefined
// In contextified contexts, freezing doesn't work
try {
vm.runInContext('Object.freeze(globalThis);', oldContext);
} catch {
// TypeError: Cannot freeze
}
console.log(vm.runInContext('globalThis.foo = 1; foo;', oldContext)); // 1
}
{
const newContext = vm.createContext(vm.constants.DONT_CONTEXTIFY);
console.log(vm.runInContext('globalThis', newContext) === newContext); // true
console.log(newContext.Array); // [Function: Array]
// In contexts without its global contextifyed, freezing works and prevents scripts from
// accidentally leaking globals.
vm.runInContext('Object.freeze(globalThis);', newContext);
try {
vm.runInContext('globalThis.foo = 1; foo;', newContext);
} catch(e) {
console.log(e); // Uncaught ReferenceError: foo is not defined
}
}