This commit is contained in:
Michael Diolosa 2015-01-05 15:40:04 -05:00
parent b70f6571bd
commit 8e299b09cc
3 changed files with 25 additions and 18 deletions

View File

@ -120,24 +120,27 @@
};
exports["eval"] = function(code, options) {
var Module, Script, js, k, o, r, sandbox, v, _i, _len, _module, _ref, _ref1, _require;
var Module, createContext, isContext, js, k, o, r, sandbox, v, _i, _len, _module, _ref, _ref1, _ref2, _ref3, _require;
if (options == null) {
options = {};
}
if (!(code = code.trim())) {
return;
}
Script = vm.Script;
if (Script) {
createContext = (_ref = vm.Script.createContext) != null ? _ref : vm.createContext;
isContext = (_ref1 = vm.isContext) != null ? _ref1 : function(ctx) {
return options.sandbox instanceof createContext().constructor;
};
if (createContext) {
if (options.sandbox != null) {
if (options.sandbox instanceof Script.createContext().constructor) {
if (isContext(options.sandbox)) {
sandbox = options.sandbox;
} else {
sandbox = Script.createContext();
_ref = options.sandbox;
for (k in _ref) {
if (!__hasProp.call(_ref, k)) continue;
v = _ref[k];
sandbox = createContext();
_ref2 = options.sandbox;
for (k in _ref2) {
if (!__hasProp.call(_ref2, k)) continue;
v = _ref2[k];
sandbox[k] = v;
}
}
@ -154,9 +157,9 @@
return Module._load(path, _module, true);
};
_module.filename = sandbox.__filename;
_ref1 = Object.getOwnPropertyNames(require);
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
r = _ref1[_i];
_ref3 = Object.getOwnPropertyNames(require);
for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
r = _ref3[_i];
if (r !== 'paths') {
_require[r] = require[r];
}

View File

@ -124,13 +124,17 @@ exports.run = (code, options = {}) ->
# The CoffeeScript REPL uses this to run the input.
exports.eval = (code, options = {}) ->
return unless code = code.trim()
Script = vm.Script
if Script
createContext = vm.Script.createContext ? vm.createContext
isContext = vm.isContext ? (ctx) ->
options.sandbox instanceof createContext().constructor
if createContext
if options.sandbox?
if options.sandbox instanceof Script.createContext().constructor
if isContext options.sandbox
sandbox = options.sandbox
else
sandbox = Script.createContext()
sandbox = createContext()
sandbox[k] = v for own k, v of options.sandbox
sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox
else
@ -303,4 +307,3 @@ Error.prepareStackTrace = (err, stack) ->
" at #{formatSourcePosition frame, getSourceMapping}"
"#{err.toString()}\n#{frames.join '\n'}\n"

View File

@ -10,7 +10,8 @@ if vm = require? 'vm'
eq fhqwhgads, 'global superpower!'
test "CoffeeScript.eval can run in, and modify, a Script context sandbox", ->
sandbox = vm.Script.createContext()
createContext = vm.Script.createContext ? vm.createContext
sandbox = createContext()
sandbox.foo = 'bar'
code = '''
global.foo = 'not bar!'