-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
99 lines (61 loc) · 2.27 KB
/
index.js
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict';
var version = '0.0.0';
var lodash = require('lodash');
var LoopStopManager = require('./loop-stop/manager');
var LoopStopInjector = require('./loop-stop/injector');
var jailEnvironment = require('./environment');
module.exports = JSJail();
function JSJail() {
// Pre initialization of necessary parameters in jail environment.
jailEnvironment.add({LoopStopManager: LoopStopManager});
var t = {};
t.version = version;
t.make = make;
return t;
/**
* Returns an object which represents the jail (separate environment to JS execution).
*
* @public
*/
function make(code) {
try {
var jailInitializationCode = LoopStopInjector.inject(code);
jailInitializationCode = tryToCoverWindow(jailInitializationCode);
// Preparation for function call.
var parameters = jailEnvironment.getNames();
// Add code as the last parameter of function for an apply call.
parameters.push(jailInitializationCode);
var f = Function.apply(null, parameters);
return new f(jailEnvironment.getValues());
} catch (err) {
// TODO Will make some handling in the near future
console.error("While we were trying to make a jail some problem caused:", err);
}
}
/**
* Makes stubs of variables for avoid the changing of outside environment which has these variables too.
*
* TODO need to take this function into a separate module.
*
* @private
* @param {String} code The source code.
*/
function tryToCoverWindow(code) {
if (typeof window === "object") {
var variables = Object.getOwnPropertyNames(window);
if (!window.hasOwnProperty('window')) {
variables.push('window');
}
var stubDeclarations = '';
variables.forEach(function(name) {
// If the name really can be the name of variable.
if (lodash.isString(name)) {
var stub = 'var ' + name + '; \n';
stubDeclarations = stubDeclarations + stub;
}
});
code = stubDeclarations + code;
}
return code;
}
}