pax_global_header00006660000000000000000000000064122716673550014530gustar00rootroot0000000000000052 comment=bfd7c5f59edec856dc7efe0b77a4f6b2fa20f226 vm-browserify-0.0.4/000077500000000000000000000000001227166735500143445ustar00rootroot00000000000000vm-browserify-0.0.4/LICENSE000066400000000000000000000020611227166735500153500ustar00rootroot00000000000000This software is released under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. vm-browserify-0.0.4/example/000077500000000000000000000000001227166735500157775ustar00rootroot00000000000000vm-browserify-0.0.4/example/run/000077500000000000000000000000001227166735500166035ustar00rootroot00000000000000vm-browserify-0.0.4/example/run/bundle.js000066400000000000000000000313241227166735500204150ustar00rootroot00000000000000var require = function (file, cwd) { var resolved = require.resolve(file, cwd || '/'); var mod = require.modules[resolved]; if (!mod) throw new Error( 'Failed to resolve module ' + file + ', tried ' + resolved ); var res = mod._cached ? mod._cached : mod(); return res; } require.paths = []; require.modules = {}; require.extensions = [".js",".coffee"]; require._core = { 'assert': true, 'events': true, 'fs': true, 'path': true, 'vm': true }; require.resolve = (function () { return function (x, cwd) { if (!cwd) cwd = '/'; if (require._core[x]) return x; var path = require.modules.path(); var y = cwd || '.'; if (x.match(/^(?:\.\.?\/|\/)/)) { var m = loadAsFileSync(path.resolve(y, x)) || loadAsDirectorySync(path.resolve(y, x)); if (m) return m; } var n = loadNodeModulesSync(x, y); if (n) return n; throw new Error("Cannot find module '" + x + "'"); function loadAsFileSync (x) { if (require.modules[x]) { return x; } for (var i = 0; i < require.extensions.length; i++) { var ext = require.extensions[i]; if (require.modules[x + ext]) return x + ext; } } function loadAsDirectorySync (x) { x = x.replace(/\/+$/, ''); var pkgfile = x + '/package.json'; if (require.modules[pkgfile]) { var pkg = require.modules[pkgfile](); var b = pkg.browserify; if (typeof b === 'object' && b.main) { var m = loadAsFileSync(path.resolve(x, b.main)); if (m) return m; } else if (typeof b === 'string') { var m = loadAsFileSync(path.resolve(x, b)); if (m) return m; } else if (pkg.main) { var m = loadAsFileSync(path.resolve(x, pkg.main)); if (m) return m; } } return loadAsFileSync(x + '/index'); } function loadNodeModulesSync (x, start) { var dirs = nodeModulesPathsSync(start); for (var i = 0; i < dirs.length; i++) { var dir = dirs[i]; var m = loadAsFileSync(dir + '/' + x); if (m) return m; var n = loadAsDirectorySync(dir + '/' + x); if (n) return n; } var m = loadAsFileSync(x); if (m) return m; } function nodeModulesPathsSync (start) { var parts; if (start === '/') parts = [ '' ]; else parts = path.normalize(start).split('/'); var dirs = []; for (var i = parts.length - 1; i >= 0; i--) { if (parts[i] === 'node_modules') continue; var dir = parts.slice(0, i + 1).join('/') + '/node_modules'; dirs.push(dir); } return dirs; } }; })(); require.alias = function (from, to) { var path = require.modules.path(); var res = null; try { res = require.resolve(from + '/package.json', '/'); } catch (err) { res = require.resolve(from, '/'); } var basedir = path.dirname(res); var keys = (Object.keys || function (obj) { var res = []; for (var key in obj) res.push(key) return res; })(require.modules); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key.slice(0, basedir.length + 1) === basedir + '/') { var f = key.slice(basedir.length); require.modules[to + f] = require.modules[basedir + f]; } else if (key === basedir) { require.modules[to] = require.modules[basedir]; } } }; require.define = function (filename, fn) { var dirname = require._core[filename] ? '' : require.modules.path().dirname(filename) ; var require_ = function (file) { return require(file, dirname) }; require_.resolve = function (name) { return require.resolve(name, dirname); }; require_.modules = require.modules; require_.define = require.define; var module_ = { exports : {} }; require.modules[filename] = function () { require.modules[filename]._cached = module_.exports; fn.call( module_.exports, require_, module_, module_.exports, dirname, filename ); require.modules[filename]._cached = module_.exports; return module_.exports; }; }; if (typeof process === 'undefined') process = {}; if (!process.nextTick) process.nextTick = (function () { var queue = []; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canPost) { window.addEventListener('message', function (ev) { if (ev.source === window && ev.data === 'browserify-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); } return function (fn) { if (canPost) { queue.push(fn); window.postMessage('browserify-tick', '*'); } else setTimeout(fn, 0); }; })(); if (!process.title) process.title = 'browser'; if (!process.binding) process.binding = function (name) { if (name === 'evals') return require('vm') else throw new Error('No such module') }; if (!process.cwd) process.cwd = function () { return '.' }; require.define("path", function (require, module, exports, __dirname, __filename) { function filter (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { if (fn(xs[i], i, xs)) res.push(xs[i]); } return res; } // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length; i >= 0; i--) { var last = parts[i]; if (last == '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Regex to split a filename into [*, dir, basename, ext] // posix version var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string' || !path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = path.charAt(0) === '/', trailingSlash = path.slice(-1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { return p && typeof p === 'string'; }).join('/')); }; exports.dirname = function(path) { var dir = splitPathRe.exec(path)[1] || ''; var isWindows = false; if (!dir) { // No dirname return '.'; } else if (dir.length === 1 || (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) { // It is just a slash or a drive letter with a slash return dir; } else { // It is a full dirname, strip trailing slash return dir.substring(0, dir.length - 1); } }; exports.basename = function(path, ext) { var f = splitPathRe.exec(path)[2] || ''; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPathRe.exec(path)[3] || ''; }; }); require.define("vm", function (require, module, exports, __dirname, __filename) { var Object_keys = function (obj) { if (Object.keys) return Object.keys(obj) else { var res = []; for (var key in obj) res.push(key) return res; } }; var forEach = function (xs, fn) { if (xs.forEach) return xs.forEach(fn) else for (var i = 0; i < xs.length; i++) { fn(xs[i], i, xs); } }; var Script = exports.Script = function NodeScript (code) { if (!(this instanceof Script)) return new Script(code); this.code = code; }; var iframe = document.createElement('iframe'); if (!iframe.style) iframe.style = {}; iframe.style.display = 'none'; var iframeCapable = true; // until proven otherwise if (navigator.appName === 'Microsoft Internet Explorer') { var m = navigator.appVersion.match(/\bMSIE (\d+\.\d+);/); if (m && parseFloat(m[1]) <= 9.0) { iframeCapable = false; } } Script.prototype.runInNewContext = function (context) { if (!context) context = {}; if (!iframeCapable) { var keys = Object_keys(context); var args = []; for (var i = 0; i < keys.length; i++) { args.push(context[keys[i]]); } var fn = new Function(keys, 'return ' + this.code); return fn.apply(null, args); } document.body.appendChild(iframe); var win = iframe.contentWindow || (window.frames && window.frames[window.frames.length - 1]) || window[window.length - 1] ; forEach(Object_keys(context), function (key) { win[key] = context[key]; iframe[key] = context[key]; }); if (win.eval) { // chrome and ff can just .eval() var res = win.eval(this.code); } else { // this works in IE9 but not anything newer iframe.setAttribute('src', 'javascript:__browserifyVmResult=(' + this.code + ')' ); if ('__browserifyVmResult' in win) { var res = win.__browserifyVmResult; } else { iframeCapable = false; res = this.runInThisContext(context); } } forEach(Object_keys(win), function (key) { context[key] = win[key]; }); document.body.removeChild(iframe); return res; }; Script.prototype.runInThisContext = function () { return eval(this.code); // maybe... }; Script.prototype.runInContext = function (context) { // seems to be just runInNewContext on magical context objects which are // otherwise indistinguishable from objects except plain old objects // for the parameter segfaults node return this.runInNewContext(context); }; forEach(Object_keys(Script.prototype), function (name) { exports[name] = Script[name] = function (code) { var s = Script(code); return s[name].apply(s, [].slice.call(arguments, 1)); }; }); exports.createScript = function (code) { return exports.Script(code); }; exports.createContext = Script.createContext = function (context) { // not really sure what this one does // seems to just make a shallow copy var copy = {}; forEach(Object_keys(context), function (key) { copy[key] = context[key]; }); return copy; }; }); require.define("/entry.js", function (require, module, exports, __dirname, __filename) { var vm = require('vm'); $(function () { var res = vm.runInNewContext('a + 5', { a : 100 }); $('#res').text(res); }); }); require("/entry.js"); vm-browserify-0.0.4/example/run/entry.js000066400000000000000000000001761227166735500203060ustar00rootroot00000000000000var vm = require('vm'); $(function () { var res = vm.runInNewContext('a + 5', { a : 100 }); $('#res').text(res); }); vm-browserify-0.0.4/example/run/index.html000066400000000000000000000003341227166735500206000ustar00rootroot00000000000000 result = vm-browserify-0.0.4/example/run/server.js000066400000000000000000000003341227166735500204470ustar00rootroot00000000000000var ecstatic = require('ecstatic')(__dirname); var http = require('http'); http.createServer(ecstatic).listen(8000); console.log('listening on :8000'); console.log('# remember to run browserify entry.js -o bundle.js'); vm-browserify-0.0.4/index.js000066400000000000000000000073271227166735500160220ustar00rootroot00000000000000var indexOf = require('indexof'); var Object_keys = function (obj) { if (Object.keys) return Object.keys(obj) else { var res = []; for (var key in obj) res.push(key) return res; } }; var forEach = function (xs, fn) { if (xs.forEach) return xs.forEach(fn) else for (var i = 0; i < xs.length; i++) { fn(xs[i], i, xs); } }; var defineProp = (function() { try { Object.defineProperty({}, '_', {}); return function(obj, name, value) { Object.defineProperty(obj, name, { writable: true, enumerable: false, configurable: true, value: value }) }; } catch(e) { return function(obj, name, value) { obj[name] = value; }; } }()); var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', 'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', 'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', 'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; function Context() {} Context.prototype = {}; var Script = exports.Script = function NodeScript (code) { if (!(this instanceof Script)) return new Script(code); this.code = code; }; Script.prototype.runInContext = function (context) { if (!(context instanceof Context)) { throw new TypeError("needs a 'context' argument."); } var iframe = document.createElement('iframe'); if (!iframe.style) iframe.style = {}; iframe.style.display = 'none'; document.body.appendChild(iframe); var win = iframe.contentWindow; var wEval = win.eval, wExecScript = win.execScript; if (!wEval && wExecScript) { // win.eval() magically appears when this is called in IE: wExecScript.call(win, 'null'); wEval = win.eval; } forEach(Object_keys(context), function (key) { win[key] = context[key]; }); forEach(globals, function (key) { if (context[key]) { win[key] = context[key]; } }); var winKeys = Object_keys(win); var res = wEval.call(win, this.code); forEach(Object_keys(win), function (key) { // Avoid copying circular objects like `top` and `window` by only // updating existing context properties or new properties in the `win` // that was only introduced after the eval. if (key in context || indexOf(winKeys, key) === -1) { context[key] = win[key]; } }); forEach(globals, function (key) { if (!(key in context)) { defineProp(context, key, win[key]); } }); document.body.removeChild(iframe); return res; }; Script.prototype.runInThisContext = function () { return eval(this.code); // maybe... }; Script.prototype.runInNewContext = function (context) { var ctx = Script.createContext(context); var res = this.runInContext(ctx); forEach(Object_keys(ctx), function (key) { context[key] = ctx[key]; }); return res; }; forEach(Object_keys(Script.prototype), function (name) { exports[name] = Script[name] = function (code) { var s = Script(code); return s[name].apply(s, [].slice.call(arguments, 1)); }; }); exports.createScript = function (code) { return exports.Script(code); }; exports.createContext = Script.createContext = function (context) { var copy = new Context(); if(typeof context === 'object') { forEach(Object_keys(context), function (key) { copy[key] = context[key]; }); } return copy; }; vm-browserify-0.0.4/package.json000066400000000000000000000016261227166735500166370ustar00rootroot00000000000000{ "name": "vm-browserify", "version": "0.0.4", "description": "vm module for the browser", "main": "index.js", "repository": { "type": "git", "url": "http://github.com/substack/vm-browserify.git" }, "keywords": [ "vm", "browser", "eval" ], "dependencies": { "indexof": "0.0.1" }, "devDependencies": { "tape": "~2.3.2" }, "author": { "name": "James Halliday", "email": "mail@substack.net", "url": "http://substack.net" }, "scripts": { "test": "tap test/*.js" }, "license": "MIT", "testling": { "files": "test/*.js", "browsers": [ "ie/6..latest", "firefox/16..latest", "firefox/nightly", "chrome/22..latest", "chrome/canary", "opera/12..latest", "opera/next", "safari/5.1..latest", "ipad/6.0..latest", "iphone/6.0..latest", "android-browser/4.2..latest" ] } } vm-browserify-0.0.4/readme.markdown000066400000000000000000000024531227166735500173510ustar00rootroot00000000000000# vm-browserify emulate node's vm module for the browser [![testling badge](https://ci.testling.com/substack/vm-browserify.png)](https://ci.testling.com/substack/vm-browserify) # example Just write some client-side javascript: ``` js var vm = require('vm'); $(function () { var res = vm.runInNewContext('a + 5', { a : 100 }); $('#res').text(res); }); ``` compile it with [browserify](http://github.com/substack/node-browserify): ``` browserify entry.js -o bundle.js ``` then whip up some html: ``` html result = ``` and when you load the page you should see: ``` result = 105 ``` # methods ## vm.runInNewContext(code, context={}) Evaluate some `code` in a new iframe with a `context`. Contexts are like wrapping your code in a `with()` except slightly less terrible because the code is sandboxed into a new iframe. # install This module is depended upon by browserify, so you should just be able to `require('vm')` and it will just work. However if you want to use this module directly you can install it with [npm](http://npmjs.org): ``` npm install vm-browserify ``` # license MIT vm-browserify-0.0.4/test/000077500000000000000000000000001227166735500153235ustar00rootroot00000000000000vm-browserify-0.0.4/test/vm.js000066400000000000000000000014711227166735500163060ustar00rootroot00000000000000var test = require('tape'); var vm = require('../'); test('vmRunInNewContext', function (t) { t.plan(6); t.equal(vm.runInNewContext('a + 5', { a : 100 }), 105); (function () { var vars = { x : 10 }; t.equal(vm.runInNewContext('x++', vars), 10); t.equal(vars.x, 11); })(); (function () { var vars = { x : 10 }; t.equal(vm.runInNewContext('var y = 3; y + x++', vars), 13); t.equal(vars.x, 11); t.equal(vars.y, 3); })(); t.end(); }); test('vmRunInContext', function (t) { t.plan(2); var context = vm.createContext({ foo: 1 }); vm.runInContext('var x = 1', context); t.deepEqual(context, { foo: 1, x: 1 }); vm.runInContext('var y = 1', context); t.deepEqual(context, { foo: 1, x: 1, y: 1 }); });