-
-
Notifications
You must be signed in to change notification settings - Fork 128
/
modules.js
78 lines (69 loc) · 2.12 KB
/
modules.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
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
75
76
77
78
'use strict';
const { node, metarhia } = require('./dependencies.js');
const { path } = node;
const { metavm, metautil } = metarhia;
const { Cache } = require('./cache.js');
const parsePath = (relPath) => {
const name = path.basename(relPath, '.js');
const names = relPath.split(path.sep);
names[names.length - 1] = name;
return names;
};
class Modules extends Cache {
constructor(place, application) {
super(place, application);
this.tree = {};
}
stop(name, method) {
const timeout = this.application.config.server.timeouts.watch;
setTimeout(() => {
if (this.tree[name] !== undefined) return;
this.application.execute(method);
}, timeout);
}
set(relPath, exports, iface) {
const names = parsePath(relPath);
let level = this.tree;
const last = names.length - 1;
for (let depth = 0; depth <= last; depth++) {
const name = names[depth];
let next = level[name];
if (depth === last) {
if (exports === null) {
if (name === 'stop') this.stop(names[0], level.stop);
delete level[name];
return;
}
next = iface.method || iface;
exports.parent = level;
}
if (next === undefined) next = {};
level[name] = next;
if (depth === 1 && name === 'start') {
this.application.starts.push(iface.method);
}
level = next;
}
}
delete(filePath) {
const relPath = filePath.substring(this.path.length + 1);
this.set(relPath, null, null);
}
async change(filePath) {
if (!filePath.endsWith('.js')) return;
const options = { context: this.application.sandbox, filename: filePath };
try {
const script = await metavm.readScript(filePath, options);
let exports = script.exports;
if (typeof exports === 'function') exports = { method: exports };
const iface = metautil.makePrivate(exports);
const relPath = filePath.substring(this.path.length + 1);
this.set(relPath, exports, iface);
} catch (err) {
if (err.code !== 'ENOENT') {
this.application.console.error(err.stack);
}
}
}
}
module.exports = { Modules };