/
main.js
1384 lines (1270 loc) · 39.1 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable global-require, no-use-before-define */
'use strict';
/**
* This callback will be called to transform a script to JavaScript.
*
* @callback compileCallback
* @param {string} code - Script code to transform to JavaScript.
* @param {string} filename - Filename of this script.
* @return {string} JavaScript code that represents the script code.
*/
/**
* This callback will be called to resolve a module if it couldn't be found.
*
* @callback resolveCallback
* @param {string} moduleName - Name of the module to resolve.
* @param {string} dirname - Name of the current directory.
* @return {(string|undefined)} The file or directory to use to load the requested module.
*/
const fs = require('fs');
const vm = require('vm');
const pa = require('path');
const {EventEmitter} = require('events');
const {INSPECT_MAX_BYTES} = require('buffer');
const helpers = require('./helpers.js');
const importModuleDynamically = () => {
// We can't throw an error object here because since vm.Script doesn't store a context, we can't properly contextify that error object.
// eslint-disable-next-line no-throw-literal
throw 'Dynamic imports are not allowed.';
};
const MODULE_PREFIX = '(function (exports, require, module, __filename, __dirname) { ';
const STRICT_MODULE_PREFIX = MODULE_PREFIX + '"use strict"; ';
const MODULE_SUFFIX = '\n});';
/**
* Load a script from a file and compile it.
*
* @private
* @param {string} filename - File to load and compile to a script.
* @param {string} prefix - Prefix for the script.
* @param {string} suffix - Suffix for the script.
* @return {vm.Script} The compiled script.
*/
function loadAndCompileScript(filename, prefix, suffix) {
const data = fs.readFileSync(filename, 'utf8');
return new vm.Script(prefix + data + suffix, {
filename,
displayErrors: false,
importModuleDynamically
});
}
/**
* Cache where we can cache some things
*
* @private
* @property {?compileCallback} coffeeScriptCompiler - The coffee script compiler or null if not yet used.
* @property {?Object} timeoutContext - The context used for the timeout functionality of null if not yet used.
* @property {?vm.Script} timeoutScript - The compiled script used for the timeout functionality of null if not yet used.
* @property {vm.Script} contextifyScript - The compiled script used to setup a sandbox.
* @property {?vm.Script} sandboxScript - The compiled script used to setup the NodeVM require mechanism of null if not yet used.
* @property {?vm.Script} hookScript - The compiled script used to setup the async hooking functionality.
* @property {?vm.Script} getGlobalScript - The compiled script used to get the global sandbox object.
* @property {?vm.Script} getGeneratorFunctionScript - The compiled script used to get the generator function constructor.
* @property {?vm.Script} getAsyncFunctionScript - The compiled script used to get the async function constructor.
* @property {?vm.Script} getAsyncGeneratorFunctionScript - The compiled script used to get the async generator function constructor.
*/
const CACHE = {
coffeeScriptCompiler: null,
timeoutContext: null,
timeoutScript: null,
contextifyScript: loadAndCompileScript(`${__dirname}/contextify.js`, '(function(require, host) { ', '\n})'),
sandboxScript: null,
hookScript: null,
getGlobalScript: null,
getGeneratorFunctionScript: null,
getAsyncFunctionScript: null,
getAsyncGeneratorFunctionScript: null,
};
/**
* Default run options for vm.Script.runInContext
*
* @private
*/
const DEFAULT_RUN_OPTIONS = {displayErrors: false, importModuleDynamically};
/**
* Returns the cached coffee script compiler or loads it
* if it is not found in the cache.
*
* @private
* @return {compileCallback} The coffee script compiler.
* @throws {VMError} If the coffee-script module can't be found.
*/
function getCoffeeScriptCompiler() {
if (!CACHE.coffeeScriptCompiler) {
try {
const coffeeScript = require('coffee-script');
CACHE.coffeeScriptCompiler = (code, filename) => {
return coffeeScript.compile(code, {header: false, bare: true});
};
} catch (e) {
throw new VMError('Coffee-Script compiler is not installed.');
}
}
return CACHE.coffeeScriptCompiler;
}
/**
* The JavaScript compiler, just a identity function.
*
* @private
* @type {compileCallback}
* @param {string} code - The JavaScript code.
* @param {string} filename - Filename of this script.
* @return {string} The code.
*/
function jsCompiler(code, filename) {
return removeShebang(code);
}
/**
* Look up the compiler for a specific name.
*
* @private
* @param {(string|compileCallback)} compiler - A compile callback or the name of the compiler.
* @return {compileCallback} The resolved compiler.
* @throws {VMError} If the compiler is unknown or the coffee script module was needed and couldn't be found.
*/
function lookupCompiler(compiler) {
if ('function' === typeof compiler) return compiler;
switch (compiler) {
case 'coffeescript':
case 'coffee-script':
case 'cs':
case 'text/coffeescript':
return getCoffeeScriptCompiler();
case 'javascript':
case 'java-script':
case 'js':
case 'text/javascript':
return jsCompiler;
default:
throw new VMError(`Unsupported compiler '${compiler}'.`);
}
}
/**
* Remove the shebang from source code.
*
* @private
* @param {string} code - Code from which to remove the shebang.
* @return {string} code without the shebang.
*/
function removeShebang(code) {
if (!code.startsWith('#!')) return code;
return '//' + code.substr(2);
}
/**
* Class Script
*
* @public
*/
class VMScript {
/**
* The script code with wrapping. If set will invalidate the cache.<br>
* Writable only for backwards compatibility.
*
* @public
* @readonly
* @member {string} code
* @memberOf VMScript#
*/
/**
* The filename used for this script.
*
* @public
* @readonly
* @since v3.9.0
* @member {string} filename
* @memberOf VMScript#
*/
/**
* The line offset use for stack traces.
*
* @public
* @readonly
* @since v3.9.0
* @member {number} lineOffset
* @memberOf VMScript#
*/
/**
* The column offset use for stack traces.
*
* @public
* @readonly
* @since v3.9.0
* @member {number} columnOffset
* @memberOf VMScript#
*/
/**
* The compiler to use to get the JavaScript code.
*
* @public
* @readonly
* @since v3.9.0
* @member {(string|compileCallback)} compiler
* @memberOf VMScript#
*/
/**
* The prefix for the script.
*
* @private
* @member {string} _prefix
* @memberOf VMScript#
*/
/**
* The suffix for the script.
*
* @private
* @member {string} _suffix
* @memberOf VMScript#
*/
/**
* The compiled vm.Script for the VM or if not compiled <code>null</code>.
*
* @private
* @member {?vm.Script} _compiledVM
* @memberOf VMScript#
*/
/**
* The compiled vm.Script for the NodeVM or if not compiled <code>null</code>.
*
* @private
* @member {?vm.Script} _compiledNodeVM
* @memberOf VMScript#
*/
/**
* The compiled vm.Script for the NodeVM in strict mode or if not compiled <code>null</code>.
*
* @private
* @member {?vm.Script} _compiledNodeVMStrict
* @memberOf VMScript#
*/
/**
* The resolved compiler to use to get the JavaScript code.
*
* @private
* @readonly
* @member {compileCallback} _compiler
* @memberOf VMScript#
*/
/**
* The script to run without wrapping.
*
* @private
* @member {string} _code
* @memberOf VMScript#
*/
/**
* Create VMScript instance.
*
* @public
* @param {string} code - Code to run.
* @param {(string|Object)} [options] - Options map or filename.
* @param {string} [options.filename="vm.js"] - Filename that shows up in any stack traces produced from this script.
* @param {number} [options.lineOffset=0] - Passed to vm.Script options.
* @param {number} [options.columnOffset=0] - Passed to vm.Script options.
* @param {(string|compileCallback)} [options.compiler="javascript"] - The compiler to use.
* @throws {VMError} If the compiler is unknown or if coffee-script was requested but the module not found.
*/
constructor(code, options) {
const sCode = `${code}`;
let useFileName;
let useOptions;
if (arguments.length === 2) {
if (typeof options === 'object' && options.toString === Object.prototype.toString) {
useOptions = options || {};
useFileName = useOptions.filename;
} else {
useOptions = {};
useFileName = options;
}
} else if (arguments.length > 2) {
// We do it this way so that there are no more arguments in the function.
// eslint-disable-next-line prefer-rest-params
useOptions = arguments[2] || {};
useFileName = options || useOptions.filename;
} else {
useOptions = {};
}
const {
compiler = 'javascript',
lineOffset = 0,
columnOffset = 0
} = useOptions;
// Throw if the compiler is unknown.
const resolvedCompiler = lookupCompiler(compiler);
Object.defineProperties(this, {
code: {
// Put this here so that it is enumerable, and looks like a property.
get() {
return this._prefix + this._code + this._suffix;
},
set(value) {
const strNewCode = String(value);
if (strNewCode === this._code && this._prefix === '' && this._suffix === '') return;
this._code = strNewCode;
this._prefix = '';
this._suffix = '';
this._compiledVM = null;
this._compiledNodeVM = null;
this._compiledCode = null;
},
enumerable: true
},
filename: {
value: useFileName || 'vm.js',
enumerable: true
},
lineOffset: {
value: lineOffset,
enumerable: true
},
columnOffset: {
value: columnOffset,
enumerable: true
},
compiler: {
value: compiler,
enumerable: true
},
_code: {
value: sCode,
writable: true
},
_prefix: {
value: '',
writable: true
},
_suffix: {
value: '',
writable: true
},
_compiledVM: {
value: null,
writable: true
},
_compiledNodeVM: {
value: null,
writable: true
},
_compiledNodeVMStrict: {
value: null,
writable: true
},
_compiledCode: {
value: null,
writable: true
},
_compiler: {value: resolvedCompiler}
});
}
/**
* Wraps the code.<br>
* This will replace the old wrapping.<br>
* Will invalidate the code cache.
*
* @public
* @deprecated Since v3.9.0. Wrap your code before passing it into the VMScript object.
* @param {string} prefix - String that will be appended before the script code.
* @param {script} suffix - String that will be appended behind the script code.
* @return {this} This for chaining.
* @throws {TypeError} If prefix or suffix is a Symbol.
*/
wrap(prefix, suffix) {
const strPrefix = `${prefix}`;
const strSuffix = `${suffix}`;
if (this._prefix === strPrefix && this._suffix === strSuffix) return this;
this._prefix = strPrefix;
this._suffix = strSuffix;
this._compiledVM = null;
this._compiledNodeVM = null;
this._compiledNodeVMStrict = null;
return this;
}
/**
* Compile this script. <br>
* This is useful to detect syntax errors in the script.
*
* @public
* @return {this} This for chaining.
* @throws {SyntaxError} If there is a syntax error in the script.
*/
compile() {
this._compileVM();
return this;
}
/**
* Get the compiled code.
*
* @private
* @return {string} The code.
*/
getCompiledCode() {
if (!this._compiledCode) {
this._compiledCode = this._compiler(this._prefix + removeShebang(this._code) + this._suffix, this.filename);
}
return this._compiledCode;
}
/**
* Compiles this script to a vm.Script.
*
* @private
* @param {string} prefix - JavaScript code that will be used as prefix.
* @param {string} suffix - JavaScript code that will be used as suffix.
* @return {vm.Script} The compiled vm.Script.
* @throws {SyntaxError} If there is a syntax error in the script.
*/
_compile(prefix, suffix) {
return new vm.Script(prefix + this.getCompiledCode() + suffix, {
filename: this.filename,
displayErrors: false,
lineOffset: this.lineOffset,
columnOffset: this.columnOffset,
importModuleDynamically
});
}
/**
* Will return the cached version of the script intended for VM or compile it.
*
* @private
* @return {vm.Script} The compiled script
* @throws {SyntaxError} If there is a syntax error in the script.
*/
_compileVM() {
let script = this._compiledVM;
if (!script) {
this._compiledVM = script = this._compile('', '');
}
return script;
}
/**
* Will return the cached version of the script intended for NodeVM or compile it.
*
* @private
* @return {vm.Script} The compiled script
* @throws {SyntaxError} If there is a syntax error in the script.
*/
_compileNodeVM() {
let script = this._compiledNodeVM;
if (!script) {
this._compiledNodeVM = script = this._compile(MODULE_PREFIX, MODULE_SUFFIX);
}
return script;
}
/**
* Will return the cached version of the script intended for NodeVM in strict mode or compile it.
*
* @private
* @return {vm.Script} The compiled script
* @throws {SyntaxError} If there is a syntax error in the script.
*/
_compileNodeVMStrict() {
let script = this._compiledNodeVMStrict;
if (!script) {
this._compiledNodeVMStrict = script = this._compile(STRICT_MODULE_PREFIX, MODULE_SUFFIX);
}
return script;
}
}
/**
*
* This callback will be called and has a specific time to finish.<br>
* No parameters will be supplied.<br>
* If parameters are required, use a closure.
*
* @private
* @callback runWithTimeout
* @return {*}
*
*/
/**
* Run a function with a specific timeout.
*
* @private
* @param {runWithTimeout} fn - Function to run with the specific timeout.
* @param {number} timeout - The amount of time to give the function to finish.
* @return {*} The value returned by the function.
* @throws {Error} If the function took to long.
*/
function doWithTimeout(fn, timeout) {
let ctx = CACHE.timeoutContext;
let script = CACHE.timeoutScript;
if (!ctx) {
CACHE.timeoutContext = ctx = vm.createContext();
CACHE.timeoutScript = script = new vm.Script('fn()', {
filename: 'timeout_bridge.js',
displayErrors: false,
importModuleDynamically
});
}
ctx.fn = fn;
try {
return script.runInContext(ctx, {
displayErrors: false,
importModuleDynamically,
timeout
});
} finally {
ctx.fn = null;
}
}
function tryCompile(args) {
const code = args[args.length - 1];
const params = args.slice(0, -1);
vm.compileFunction(code, params);
}
function makeCheckHook(checkAsync, checkImport) {
if (!checkAsync && !checkImport) return null;
return (hook, args) => {
if (hook === 'function' || hook === 'generator_function' || hook === 'eval' || hook === 'run' ||
(!checkAsync && (hook === 'async_function' || hook === 'async_generator_function'))) {
if (hook === 'eval') {
const script = args[0];
args = [script];
if (typeof(script) !== 'string') return args;
} else {
// Next line throws on Symbol, this is the same behavior as function constructor calls
args = args.map(arg => `${arg}`);
}
const hasAsync = checkAsync && args.findIndex(arg => /\basync\b/.test(arg)) !== -1;
const hasImport = checkImport && args.findIndex(arg => /\bimport\b/.test(arg)) !== -1;
if (!hasAsync && !hasImport) return args;
const mapped = args.map(arg => {
if (hasAsync) arg = arg.replace(/async/g, 'a\\u0073ync');
if (hasImport) arg = arg.replace(/import/g, 'i\\u006dport');
return arg;
});
try {
tryCompile(mapped);
} catch (u) {
// Some random syntax error or error because of async or import.
// First report real syntax errors
tryCompile(args);
if (hasAsync && hasImport) {
const mapped2 = args.map(arg => arg.replace(/async/g, 'a\\u0073ync'));
try {
tryCompile(mapped2);
} catch (e) {
throw new VMError('Async not available');
}
throw new VMError('Dynamic Import not supported');
}
if (hasAsync) {
// Then async error
throw new VMError('Async not available');
}
throw new VMError('Dynamic Import not supported');
}
return args;
}
if (checkAsync) throw new VMError('Async not available');
return args;
};
}
/**
* Class VM.
*
* @public
*/
class VM extends EventEmitter {
/**
* The timeout for {@link VM#run} calls.
*
* @public
* @since v3.9.0
* @member {number} timeout
* @memberOf VM#
*/
/**
* Get the global sandbox object.
*
* @public
* @readonly
* @since v3.9.0
* @member {Object} sandbox
* @memberOf VM#
*/
/**
* The compiler to use to get the JavaScript code.
*
* @public
* @readonly
* @since v3.9.0
* @member {(string|compileCallback)} compiler
* @memberOf VM#
*/
/**
* The context for this sandbox.
*
* @private
* @readonly
* @member {Object} _context
* @memberOf VM#
*/
/**
* The internal methods for this sandbox.
*
* @private
* @readonly
* @member {{Contextify: Object, Decontextify: Object, Buffer: Object, sandbox:Object}} _internal
* @memberOf VM#
*/
/**
* The resolved compiler to use to get the JavaScript code.
*
* @private
* @readonly
* @member {compileCallback} _compiler
* @memberOf VM#
*/
/**
* The hook called when some events occurs.
*
* @private
* @readonly
* @since v3.9.2
* @member {Function} _hook
* @memberOf VM#
*/
/**
* Create a new VM instance.
*
* @public
* @param {Object} [options] - VM options.
* @param {number} [options.timeout] - The amount of time until a call to {@link VM#run} will timeout.
* @param {Object} [options.sandbox] - Objects that will be copied into the global object of the sandbox.
* @param {(string|compileCallback)} [options.compiler="javascript"] - The compiler to use.
* @param {boolean} [options.eval=true] - Allow the dynamic evaluation of code via eval(code) or Function(code)().<br>
* Only available for node v10+.
* @param {boolean} [options.wasm=true] - Allow to run wasm code.<br>
* Only available for node v10+.
* @param {boolean} [options.fixAsync=false] - Filters for async functions.
* @throws {VMError} If the compiler is unknown.
*/
constructor(options = {}) {
super();
// Read all options
const {
timeout,
sandbox,
compiler = 'javascript'
} = options;
const allowEval = options.eval !== false;
const allowWasm = options.wasm !== false;
const fixAsync = !!options.fixAsync;
// Early error if sandbox is not an object.
if (sandbox && 'object' !== typeof sandbox) {
throw new VMError('Sandbox must be object.');
}
// Early error if compiler can't be found.
const resolvedCompiler = lookupCompiler(compiler);
// Create a new context for this vm.
const _context = vm.createContext(undefined, {
codeGeneration: {
strings: allowEval,
wasm: allowWasm
}
});
// Create the bridge between the host and the sandbox.
const _internal = CACHE.contextifyScript.runInContext(_context, DEFAULT_RUN_OPTIONS).call(_context, require, HOST);
const hook = makeCheckHook(fixAsync, true);
// Define the properties of this object.
// Use Object.defineProperties here to be able to
// hide and set properties write only.
Object.defineProperties(this, {
timeout: {
value: timeout,
writable: true,
enumerable: true
},
compiler: {
value: compiler,
enumerable: true
},
sandbox: {
value: _internal.sandbox,
enumerable: true
},
_context: {value: _context},
_internal: {value: _internal},
_compiler: {value: resolvedCompiler},
_hook: {value: hook}
});
if (hook) {
if (!CACHE.hookScript) {
CACHE.hookScript = loadAndCompileScript(`${__dirname}/fixasync.js`, '(function() { ', '\n})');
CACHE.getGlobalScript = new vm.Script('this', {
filename: 'get_global.js',
displayErrors: false,
importModuleDynamically
});
try {
CACHE.getGeneratorFunctionScript = new vm.Script('(function*(){}).constructor', {
filename: 'get_generator_function.js',
displayErrors: false,
importModuleDynamically
});
} catch (ex) {}
try {
CACHE.getAsyncFunctionScript = new vm.Script('(async function(){}).constructor', {
filename: 'get_async_function.js',
displayErrors: false,
importModuleDynamically
});
} catch (ex) {}
try {
CACHE.getAsyncGeneratorFunctionScript = new vm.Script('(async function*(){}).constructor', {
filename: 'get_async_generator_function.js',
displayErrors: false,
importModuleDynamically
});
} catch (ex) {}
}
const internal = {
__proto__: null,
global: CACHE.getGlobalScript.runInContext(_context, DEFAULT_RUN_OPTIONS),
internal: _internal,
host: HOST,
hook
};
if (CACHE.getGeneratorFunctionScript) {
try {
internal.GeneratorFunction = CACHE.getGeneratorFunctionScript.runInContext(_context, DEFAULT_RUN_OPTIONS);
} catch (ex) {}
}
if (CACHE.getAsyncFunctionScript) {
try {
internal.AsyncFunction = CACHE.getAsyncFunctionScript.runInContext(_context, DEFAULT_RUN_OPTIONS);
} catch (ex) {}
}
if (CACHE.getAsyncGeneratorFunctionScript) {
try {
internal.AsyncGeneratorFunction = CACHE.getAsyncGeneratorFunctionScript.runInContext(_context, DEFAULT_RUN_OPTIONS);
} catch (ex) {}
}
CACHE.hookScript.runInContext(_context, DEFAULT_RUN_OPTIONS).call(internal);
}
// prepare global sandbox
if (sandbox) {
this.setGlobals(sandbox);
}
}
/**
* Adds all the values to the globals.
*
* @public
* @since v3.9.0
* @param {Object} values - All values that will be added to the globals.
* @return {this} This for chaining.
* @throws {*} If the setter of a global throws an exception it is propagated. And the remaining globals will not be written.
*/
setGlobals(values) {
for (const name in values) {
if (Object.prototype.hasOwnProperty.call(values, name)) {
this._internal.Contextify.setGlobal(name, values[name]);
}
}
return this;
}
/**
* Set a global value.
*
* @public
* @since v3.9.0
* @param {string} name - The name of the global.
* @param {*} value - The value of the global.
* @return {this} This for chaining.
* @throws {*} If the setter of the global throws an exception it is propagated.
*/
setGlobal(name, value) {
this._internal.Contextify.setGlobal(name, value);
return this;
}
/**
* Get a global value.
*
* @public
* @since v3.9.0
* @param {string} name - The name of the global.
* @return {*} The value of the global.
* @throws {*} If the getter of the global throws an exception it is propagated.
*/
getGlobal(name) {
return this._internal.Contextify.getGlobal(name);
}
/**
* Freezes the object inside VM making it read-only. Not available for primitive values.
*
* @public
* @param {*} value - Object to freeze.
* @param {string} [globalName] - Whether to add the object to global.
* @return {*} Object to freeze.
* @throws {*} If the setter of the global throws an exception it is propagated.
*/
freeze(value, globalName) {
this._internal.Contextify.readonly(value);
if (globalName) this._internal.Contextify.setGlobal(globalName, value);
return value;
}
/**
* Protects the object inside VM making impossible to set functions as it's properties. Not available for primitive values.
*
* @public
* @param {*} value - Object to protect.
* @param {string} [globalName] - Whether to add the object to global.
* @return {*} Object to protect.
* @throws {*} If the setter of the global throws an exception it is propagated.
*/
protect(value, globalName) {
this._internal.Contextify.protected(value);
if (globalName) this._internal.Contextify.setGlobal(globalName, value);
return value;
}
/**
* Run the code in VM.
*
* @public
* @param {(string|VMScript)} code - Code to run.
* @param {string} [filename="vm.js"] - Filename that shows up in any stack traces produced from this script.<br>
* This is only used if code is a String.
* @return {*} Result of executed code.
* @throws {SyntaxError} If there is a syntax error in the script.
* @throws {Error} An error is thrown when the script took to long and there is a timeout.
* @throws {*} If the script execution terminated with an exception it is propagated.
*/
run(code, filename) {
let script;
if (code instanceof VMScript) {
if (this._hook) {
const scriptCode = code.getCompiledCode();
const changed = this._hook('run', [scriptCode])[0];
if (changed === scriptCode) {
script = code._compileVM();
} else {
script = new vm.Script(changed, {
filename: code.filename,
displayErrors: false,
importModuleDynamically
});
}
} else {
script = code._compileVM();
}
} else {
const useFileName = filename || 'vm.js';
let scriptCode = this._compiler(code, useFileName);
if (this._hook) {
scriptCode = this._hook('run', [scriptCode])[0];
}
// Compile the script here so that we don't need to create a instance of VMScript.
script = new vm.Script(scriptCode, {
filename: useFileName,
displayErrors: false,
importModuleDynamically
});
}
if (!this.timeout) {
// If no timeout is given, directly run the script.
try {
return this._internal.Decontextify.value(script.runInContext(this._context, DEFAULT_RUN_OPTIONS));
} catch (e) {
throw this._internal.Decontextify.value(e);
}
}
return doWithTimeout(()=>{
try {
return this._internal.Decontextify.value(script.runInContext(this._context, DEFAULT_RUN_OPTIONS));
} catch (e) {
throw this._internal.Decontextify.value(e);
}
}, this.timeout);
}
/**
* Run the code in VM.
*
* @public
* @since v3.9.0
* @param {string} filename - Filename of file to load and execute in a NodeVM.
* @return {*} Result of executed code.
* @throws {Error} If filename is not a valid filename.
* @throws {SyntaxError} If there is a syntax error in the script.
* @throws {Error} An error is thrown when the script took to long and there is a timeout.
* @throws {*} If the script execution terminated with an exception it is propagated.
*/
runFile(filename) {
const resolvedFilename = pa.resolve(filename);
if (!fs.existsSync(resolvedFilename)) {
throw new VMError(`Script '${filename}' not found.`);
}
if (fs.statSync(resolvedFilename).isDirectory()) {
throw new VMError('Script must be file, got directory.');
}
return this.run(fs.readFileSync(resolvedFilename, 'utf8'), resolvedFilename);
}
}
/**
* Event caused by a <code>console.debug</code> call if <code>options.console="redirect"</code> is specified.
*
* @public
* @event NodeVM."console.debug"
* @type {...*}
*/
/**
* Event caused by a <code>console.log</code> call if <code>options.console="redirect"</code> is specified.
*
* @public
* @event NodeVM."console.log"
* @type {...*}
*/
/**
* Event caused by a <code>console.info</code> call if <code>options.console="redirect"</code> is specified.
*
* @public
* @event NodeVM."console.info"
* @type {...*}
*/
/**