@@ -10,50 +10,45 @@ const EXECUTION_TIMEOUT = 5000;
10
10
// The framework can require core libraries
11
11
const fs = require ( 'fs' ) ;
12
12
const vm = require ( 'vm' ) ;
13
+ const sfs = require ( 'sandboxed-fs' ) ;
13
14
14
15
// Create a hash and turn it into the sandboxed context which will be
15
16
// the global context of an application
16
17
const context = {
17
- module : { } , console,
18
+ module : { } ,
19
+ console,
18
20
require : ( name ) => {
19
- if ( name === 'fs' ) {
20
- console . log ( 'Module fs is restricted' ) ;
21
- return null ;
22
- }
23
- return require ( name ) ;
21
+ if ( name === 'fs' ) return sfs . bind ( './' ) ;
22
+ let exported = execute ( './node_modules/' + name + '/index.js' ) ;
23
+ if ( ! exported ) exported = require ( name ) ;
24
24
}
25
25
} ;
26
26
27
27
context . global = context ;
28
28
const sandbox = vm . createContext ( context ) ;
29
29
30
- // Read an application source code from the file
31
- const fileName = './application.js' ;
32
- fs . readFile ( fileName , ( err , src ) => {
33
- // We need to handle errors here
34
-
35
- // Run an application in sandboxed context
36
- let script ;
37
- try {
38
- script = new vm . Script ( src , { timeout : PARSING_TIMEOUT } ) ;
39
- } catch ( e ) {
40
- console . log ( 'Parsing timeout' ) ;
41
- process . exit ( 1 ) ;
42
- }
43
-
44
- try {
45
- script . runInNewContext ( sandbox , { timeout : EXECUTION_TIMEOUT } ) ;
46
- const exported = sandbox . module . exports ;
47
- console . dir ( { exported } ) ;
48
- } catch ( e ) {
49
- console . log ( 'Execution timeout' ) ;
50
- process . exit ( 1 ) ;
51
- }
52
-
53
- // We can access a link to exported interface from sandbox.module.exports
54
- // to execute, save to the cache, print to console, etc.
55
- } ) ;
30
+ function execute ( fileName ) {
31
+ console . log ( fileName ) ;
32
+ fs . readFile ( fileName , ( err , src ) => {
33
+ console . log ( src ) ;
34
+ let script ;
35
+ try {
36
+ script = new vm . Script ( src , { timeout : PARSING_TIMEOUT } ) ;
37
+ console . dir ( { script } ) ;
38
+ } catch ( e ) {
39
+ console . dir ( e ) ;
40
+ process . exit ( 1 ) ;
41
+ }
42
+ try {
43
+ script . runInNewContext ( sandbox , { timeout : EXECUTION_TIMEOUT } ) ;
44
+ const exported = sandbox . module . exports ;
45
+ console . dir ( { exported } ) ;
46
+ return exported ;
47
+ } catch ( e ) {
48
+ console . dir ( e ) ;
49
+ process . exit ( 1 ) ;
50
+ }
51
+ } ) ;
52
+ }
56
53
57
- process . on ( 'uncaughtException' , ( err ) => {
58
- console . log ( 'Unhandled exception: ' + err ) ;
59
- } ) ;
54
+ execute ( './application.js' ) ;
0 commit comments