-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
41 lines (34 loc) · 1.12 KB
/
index.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
const vm = require('vm')
const scripts = {}
const modules = {}
const linker = () => { throw new Error('dynamic-imports modules do not allow nested import statements') }
module.exports = {
provide(name, code, { sandbox } = {}) {
let script = new vm.Script(`(module => {${code};return module.exports})({exports:{}})`)
scripts[name] = script.runInContext(vm.createContext(sandbox))
},
require(name) {
if (name in scripts)
return scripts[name]
else
throw new Error(`dynamic-imports unable to require(): "${name}" is not provided`)
},
export(name, code, { sandbox } = {}) {
modules[name] = new Promise(async resolve => {
let module = new vm.Module(code, { context: vm.createContext(sandbox) })
await module.link(linker)
module.instantiate()
await module.evaluate()
modules[name] = module.namespace
resolve()
})
},
async import(name) {
if (name in modules) {
await modules[name]
return modules[name]
}
else
throw new Error(`dynamic-imports unable to import(): "${name}" is not exported`)
}
}