Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/vm.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ function getContextOptions(options) {
}

let defaultContextNameIndex = 1;
function createContext(contextObject = {}, options = kEmptyObject) {
function createContext(contextObject = vm_context_no_contextify, options = kEmptyObject) {
if (contextObject !== vm_context_no_contextify && isContext(contextObject)) {
return contextObject;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const common = require('../common');
const vm = require('vm');
const assert = require('assert');

const ctx = vm.createContext();
const ctx = vm.createContext({});
Object.defineProperty(ctx, 'x', {
enumerable: true,
configurable: true,
Expand Down
51 changes: 51 additions & 0 deletions test/parallel/test-vm-strict-define.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
'use strict';
require('../common');
const assert = require('assert');

const vm = require('vm');

// Declared with `var`.
{
const ctx = vm.createContext();
vm.runInContext(`"use strict"; var x; x = 42;`, ctx);
assert.strictEqual(ctx.x, 42);
}

// Define on `globalThis`.
{
const ctx = vm.createContext();
vm.runInContext(`
"use strict";
Object.defineProperty(globalThis, "x", {
configurable: true,
value: 42,
});
`, ctx);
const ret = vm.runInContext(`"use strict"; x`, ctx);
assert.strictEqual(ret, 42);
assert.strictEqual(ctx.x, 42);
}

// Set on globalThis.
{
const ctx = vm.createContext();
vm.runInContext(`"use strict"; globalThis.x = 42`, ctx);
const ret = vm.runInContext(`"use strict"; x`, ctx);
assert.strictEqual(ret, 42);
assert.strictEqual(ctx.x, 42);
}

// Set on context.
// Should throw a ReferenceError when a variable is not defined in strict-mode.
assert.throws(() => vm.runInNewContext(`"use strict"; x = 42`),
/ReferenceError: x is not defined/);

// Known issue since V8 14.6.
// When the context is a "contextified" object, ReferenceError can not be thrown.
// TODO(legendecas): https://github.com/nodejs/node/pull/61898#issuecomment-4142811603
// Refs: https://chromium-review.googlesource.com/c/v8/v8/+/7474608
{
const ctx = vm.createContext({});
assert.throws(() => vm.runInContext(`"use strict"; x = 42`, ctx),
/ReferenceError: x is not defined/);
}
Loading