-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodejs-loader.mjs
74 lines (62 loc) · 1.75 KB
/
nodejs-loader.mjs
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
import * as es6Loader from "./es6-https-loader.mjs";
import fs from 'fs';
let instanceJS = `
let allowedDomain = process.env.BLACKPRINT_ALLOWED_MODULE_ORIGIN;
if(!!allowedDomain){
if(allowedDomain.includes('|'))
Blackprint.allowModuleOrigin(allowedDomain.split('|'));
else Blackprint.allowModuleOrigin(allowedDomain);
}
let instance = new Blackprint.Engine();
instance.importJSON(%json_here%);
export default instance;
let {
variables: Variables,
events: Events,
ref: Ports,
} = instance;
export {
instance,
Variables,
Events,
Ports,
};
await instance.ready();
`;
export function resolve(specifier, context, nextResolve) {
return es6Loader.resolve(specifier, context, function() {
if(/.*\.(bpi)($|\?|#)$/m.test(specifier)) return { shortCircuit: true, url: 'bpi://'+specifier };
return nextResolve(specifier, context);
});
}
export function load(url, context, nextLoad) {
return es6Loader.load(url, context, function() {
if(/.*\.(bpi)($|\?|#)$/m.test(url)) {
return new Promise((resolve, reject) => {
function buildInstance(json){
let temp = JSON.parse(json);
if(temp.instance == null) throw new Error("Blackprint instance file is not valid: " + url);
resolve({
format: 'module',
shortCircuit: true,
source: instanceJS.replace('%json_here%', JSON.stringify(json)),
});
}
url = url.replace('bpi://', '');
if(url.includes('//')){
return es6Loader.request(url, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk)
.on('error', console.log)
.on('end', () => { buildInstance(data) });
});
}
fs.readFile(url, 'utf8', (err, data) => {
if(err) throw err;
buildInstance(data);
});
});
}
return nextLoad(url, context);
});
}