Merge branch 'isolated-vm-wrapper' into fix-bson

This commit is contained in:
Adria Navarro 2024-02-08 10:58:12 +01:00
commit d293abc8e8
2 changed files with 35 additions and 24 deletions

View File

@ -16,6 +16,35 @@ class ExecutionTimeoutError extends Error {
}
}
class ModuleHandler {
#modules: {
import: string
moduleKey: string
module: ivm.Module
}[] = []
#generateRandomKey = () => `i${crypto.randomUUID().replace(/-/g, "")}`
registerModule(module: ivm.Module, imports: string) {
this.#modules.push({
moduleKey: this.#generateRandomKey(),
import: imports,
module: module,
})
}
generateImports() {
return this.#modules
.map(m => `import ${m.import} from "${m.moduleKey}"`)
.join(";")
}
getModule(key: string) {
const module = this.#modules.find(m => m.moduleKey === key)
return module?.module
}
}
export class IsolatedVM implements VM {
#isolate: ivm.Isolate
#vm: ivm.Context
@ -25,11 +54,7 @@ export class IsolatedVM implements VM {
#parseBson?: boolean
#modules: {
import: string
moduleKey: string
module: ivm.Module
}[] = []
#moduleHandler = new ModuleHandler()
readonly #resultKey = "results"
@ -100,11 +125,7 @@ export class IsolatedVM implements VM {
throw new Error(`No imports allowed. Required: ${specifier}`)
})
this.#modules.push({
import: "helpers",
moduleKey: `i${crypto.randomUUID().replace(/-/g, "")}`,
module: helpersModule,
})
this.#moduleHandler.registerModule(helpersModule, "helpers")
return this
}
@ -124,12 +145,7 @@ export class IsolatedVM implements VM {
throw new Error(`No imports allowed. Required: ${specifier}`)
})
this.#modules.push({
import: "{deserialize, toJson}",
moduleKey: `i${crypto.randomUUID().replace(/-/g, "")}`,
module: bsonModule,
})
this.#moduleHandler.registerModule(bsonModule, "{deserialize, toJson}")
return this
}
@ -174,17 +190,14 @@ export class IsolatedVM implements VM {
);`
}
code = [
...this.#modules.map(m => `import ${m.import} from "${m.moduleKey}"`),
`results.out=${code};`,
].join(";")
code = `${this.#moduleHandler.generateImports()};results.out=${code};`
const script = this.#isolate.compileModuleSync(code)
script.instantiateSync(this.#vm, specifier => {
const module = this.#modules.find(m => m.moduleKey === specifier)
const module = this.#moduleHandler.getModule(specifier)
if (module) {
return module.module
return module
}
throw new Error(`"${specifier}" import not allowed`)

View File

@ -1,5 +1,3 @@
import bson from "bson"
import env from "../environment"
import { IsolatedVM } from "../jsRunner/vm"