Refactor code structure for improved readability and maintainability
This commit is contained in:
19
src/vm/module.class.ts
Normal file
19
src/vm/module.class.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import * as fs from "fs";
|
||||
|
||||
export class Module {
|
||||
private name: string;
|
||||
private source: string;
|
||||
|
||||
constructor(name: string, sourcePath: string) {
|
||||
this.name = name;
|
||||
this.source = fs.readFileSync(sourcePath, "utf-8");
|
||||
}
|
||||
|
||||
getSource() {
|
||||
return this.source;
|
||||
}
|
||||
|
||||
getName() {
|
||||
return this.name;
|
||||
}
|
||||
}
|
||||
4
src/vm/modules/async.js
Normal file
4
src/vm/modules/async.js
Normal file
@ -0,0 +1,4 @@
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
async function asyncCall(reference, args) {
|
||||
return await reference.apply(undefined, args, { result: { promise: true } });
|
||||
}
|
||||
31
src/vm/vm.class.ts
Normal file
31
src/vm/vm.class.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import * as ivm from "isolated-vm";
|
||||
import { Module } from "./module.class";
|
||||
|
||||
export class Vm {
|
||||
private memoryLimit: number;
|
||||
private modules: Module[];
|
||||
private context: any;
|
||||
private jail: any;
|
||||
|
||||
constructor(configs: { memoryLimit: number; modules: Module[] }) {
|
||||
this.memoryLimit = configs.memoryLimit;
|
||||
this.modules = configs.modules;
|
||||
}
|
||||
|
||||
async init() {
|
||||
const isolate = new ivm.Isolate({ memoryLimit: this.memoryLimit });
|
||||
this.context = isolate.createContext();
|
||||
this.jail = this.context.global;
|
||||
|
||||
this.jail.set("global", this.jail.derefInto());
|
||||
|
||||
for (const mod of this.modules) {
|
||||
this.jail.setSync(mod.getName(), mod.getSource());
|
||||
}
|
||||
}
|
||||
|
||||
async runScript(script: string) {
|
||||
const compiledScript = await this.context.isolate.compileScript(script);
|
||||
return compiledScript.run(this.context);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user