-
Notifications
You must be signed in to change notification settings - Fork 0
/
adm.ts
86 lines (74 loc) · 2.44 KB
/
adm.ts
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
79
80
81
82
83
84
85
86
namespace adm {
var moduleDependencies = {};
var moduleDefinitions = {};
var moduleInstances = {};
export function define(modName: string, reqs: string[], def) {
if (moduleDependencies.hasOwnProperty(modName)) {
throw `Multiple definition of module '${modName}'.`;
}
moduleDependencies[modName] = reqs || [];
moduleDefinitions[modName] = def || {};
let shouldContinue = true;
while (shouldContinue) {
shouldContinue = false;
for (let u in moduleDependencies) {
let resolved = resolve(u);
shouldContinue = shouldContinue || resolved;
}
}
}
export function getUnresolved(): string[] {
return Object.keys(moduleDefinitions).filter(u => !moduleInstances.hasOwnProperty(u));
}
function getInstance(modName: string) {
if (moduleInstances.hasOwnProperty(modName))
return moduleInstances[modName];
throw `Module '${modName}' could not be resolved.`;
}
function resolve(modName): boolean {
if (moduleInstances.hasOwnProperty(modName))
return false;
let exportsObj = null;
let deps = [];
for (let dep of moduleDependencies[modName]) {
if (dep == 'require') {
deps.push(getInstance);
}
else if (dep == 'exports') {
exportsObj = {};
deps.push(exportsObj);
}
else {
// not all deps resolved yet
if (!moduleInstances.hasOwnProperty(dep)) {
return false;
}
deps.push(moduleInstances[dep]);
}
}
let inst = null;
if (typeof moduleDefinitions[modName] == 'object') {
inst = moduleDefinitions[modName];
}
else {
try {
let ret = moduleDefinitions[modName](...deps);
inst = exportsObj || ret;
}
catch(ex)
{
console.log(`Error resolving module '${modName}': ${ex}`);
return false;
}
}
moduleInstances[modName] = inst;
return true;
}
}
// Uncomment for compatability with existing AMD modules
/*
var define: any = function(modName: string, requirements: string[], constructor) {
adm.define(modName, requirements, constructor);
};
define.amd = true;
*/