1 | /*
|
2 | * Licensed under the Apache License, Version 2.0 (the "License");
|
3 | * you may not use this file except in compliance with the License.
|
4 | * You may obtain a copy of the License at
|
5 | *
|
6 | * http://www.apache.org/licenses/LICENSE-2.0
|
7 | *
|
8 | * Unless required by applicable law or agreed to in writing, software
|
9 | * distributed under the License is distributed on an "AS IS" BASIS,
|
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
11 | * See the License for the specific language governing permissions and
|
12 | * limitations under the License.
|
13 | */
|
14 |
|
15 | ;
|
16 |
|
17 | const Logger = require('@accordproject/ergo-compiler').Logger;
|
18 | const Util = require('@accordproject/ergo-compiler').Util;
|
19 | const moment = require('moment-mini');
|
20 | // Make sure Moment serialization preserves utcOffset. See https://momentjs.com/docs/#/displaying/as-json/
|
21 | moment.fn.toJSON = Util.momentToJson;
|
22 |
|
23 | const Engine = require('./engine');
|
24 |
|
25 | const {
|
26 | VM,
|
27 | VMScript
|
28 | } = require('vm2');
|
29 |
|
30 | /**
|
31 | * <p>
|
32 | * VMEngine class. Execution of template logic against a request object, returning a response to the caller.
|
33 | * This is the vm2-based engine.
|
34 | * </p>
|
35 | * @class
|
36 | * @public
|
37 | * @memberof module:ergo-engine
|
38 | */
|
39 | class VMEngine extends Engine {
|
40 | /**
|
41 | * Engine kind
|
42 | * @return {string} which kind of engine
|
43 | */
|
44 | kind() {
|
45 | return 'vm2';
|
46 | }
|
47 |
|
48 | /**
|
49 | * Call to compile a script for a JavaScript machine
|
50 | * @param {string} script - the script
|
51 | * @return {object} the VM-ready script object
|
52 | */
|
53 | compileVMScript(script) {
|
54 | return new VMScript(script);
|
55 | }
|
56 |
|
57 | /**
|
58 | * Call to execute a call in a JavaScript machine
|
59 | * @param {number} utcOffset - UTC Offset for this execution
|
60 | * @param {object} context - global variables to set in the VM
|
61 | * @param {object} script - the initial script to load
|
62 | * @param {object} call - the execution call
|
63 | * @return {object} the result of execution
|
64 | */
|
65 | runVMScriptCall(utcOffset,context,script,call) {
|
66 | const vm = new VM({
|
67 | timeout: 1000,
|
68 | sandbox: {
|
69 | moment: moment,
|
70 | logger: Logger,
|
71 | utcOffset: utcOffset
|
72 | }
|
73 | });
|
74 | vm.freeze(context, 'context');
|
75 | vm.run(script);
|
76 | return vm.run(call);
|
77 | }
|
78 |
|
79 | }
|
80 |
|
81 | module.exports = VMEngine;
|