Last active
January 22, 2020 01:36
-
-
Save sukima/6088546 to your computer and use it in GitHub Desktop.
A simple implementation of a javascript parser in javascript. (Used as a REPL implementation)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Sandbox; | |
Sandbox = (function() { | |
function Sandbox() {} | |
Sandbox.prototype.alert = function(message) { | |
return console.log(message); | |
}; | |
Sandbox.exec = function(code, sandbox, module) { | |
var func; | |
if (sandbox == null) { | |
sandbox = new Sandbox(); | |
} | |
if (module == null) { | |
module = {}; | |
} | |
func = new Function("module", "with(this){return(function(module,global,window){\"use strict\";return eval(\"" + code + "\");})(module,this,this)}"); | |
return func.call(sandbox, module); | |
}; | |
return Sandbox; | |
}).call(this); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe "Sandbox", -> | |
beforeEach -> | |
@sandbox = new Sandbox() | |
@module = createSpyObj "module", [ "module_test_fn" ] | |
describe "#exec", -> | |
it "should provide access to context based globals", -> | |
spyOn @sandbox, "alert" | |
Sandbox.exec "alert('foobar');", @sandbox, @module | |
expect( @sandbox.alert ).toHaveBeenCalled() | |
it "should provide access to module", -> | |
Sandbox.exec "module.module_test_fn();", @sandbox, @module | |
expect( @module.module_test_fn ).toHaveBeenCalled() | |
it "should not leak variables to global scope", -> | |
try Sandbox.exec "variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module | |
try Sandbox.exec "this.variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module | |
try Sandbox.exec "global.variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module | |
try Sandbox.exec "window.variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module | |
try Sandbox.exec "var variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module | |
expect( global.variable_should_not_be_global ).not.toBeDefined() | |
it "should return output from code", -> | |
expect( Sandbox.exec("'return_value'", @sandbox, @module) ).toBe "return_value" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment