Repository navigation
Expand file tree
/
Copy pathvm-shim.js
More file actions
83 lines (70 loc) · 2.09 KB
/
Copy pathvm-shim.js
File metadata and controls
83 lines (70 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"use strict";
// We can't use the default browserify vm shim because it doesn't work in a web worker.
var acorn = require("acorn");
var findGlobals = require("acorn-globals");
var escodegen = require("escodegen");
exports.createContext = function (sandbox) {
Object.defineProperty(sandbox, "__isVMShimContext", {
value: true,
writable: true,
configurable: true,
enumerable: false
});
};
exports.isContext = function (sandbox) {
return sandbox.__isVMShimContext;
};
exports.runInContext = function (code, contextifiedSandbox, options) {
if (code === "this") {
// Special case for during window creation.
return contextifiedSandbox;
}
if (options === undefined) {
options = {};
}
var comments = [];
var tokens = [];
var ast = acorn.parse(code, {
ecmaVersion: 6,
allowReturnOutsideFunction: true,
ranges: true,
// collect comments in Esprima's format
onComment: comments,
// collect token ranges
onToken: tokens
});
// make sure we keep comments
escodegen.attachComments(ast, comments, tokens);
var globals = findGlobals(ast);
for (var i = 0; i < globals.length; ++i) {
if (globals[i].name === "window") {
continue;
}
var nodes = globals[i].nodes;
for (var j = 0; j < nodes.length; ++j) {
var type = nodes[j].type;
var name = nodes[j].name;
nodes[j].type = "MemberExpression";
nodes[j].property = {
name: name,
type: type
};
nodes[j].computed = false;
nodes[j].object = {
name: "window",
type: "Identifier"
};
}
}
var lastNode = ast.body[ast.body.length - 1];
if (lastNode.type === "ExpressionStatement") {
lastNode.type = "ReturnStatement";
lastNode.argument = lastNode.expression;
delete lastNode.expression;
}
var rewrittenCode = escodegen.generate(ast, { comment: true });
var suffix = options.filename !== undefined ? "\n//# sourceURL=" + options.filename : "";
/* jshint -W054 */
return new Function("window", rewrittenCode + suffix).bind(contextifiedSandbox)(contextifiedSandbox);
/* jshint +W054 */
};