-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmodule-loader.js
85 lines (80 loc) · 2.29 KB
/
module-loader.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
79
80
81
82
83
84
// MOST Web Framework 2.0 Codename Blueshift BSD-3-Clause license Copyright (c) 2017-2022, THEMOST LP All rights reserved
var {LangUtils} = require('@themost/common');
var Symbol = require('symbol');
var path = require('path');
var executionPathProperty = Symbol('executionPath');
/**
* @class
* @constructor
* @abstract
*/
function ModuleLoader() {
if (this.constructor.name === 'ModuleLoader') {
throw new Error('An abstract class cannot be instantiated.');
}
}
/**
* @param {string} modulePath
* @returns {*}
* @abstract
*/
// eslint-disable-next-line no-unused-vars
ModuleLoader.prototype.require = function(modulePath) {
throw new Error('Class does not implement inherited abstract method.');
};
/**
* @param {string} anyPath
* @returns { {path: string, member: string} }
*/
ModuleLoader.parseRequire = function(anyPath) {
if (anyPath == null) {
throw new Error('Module path must be a string');
}
var hashIndex = anyPath.indexOf('#');
// if path does not contain hash
if (hashIndex < 0) {
// return only path
return {
path: anyPath
};
}
// otherwise, split the given path and return path and member
// e.g. { path: './my-module', member: 'MyClass' }
return {
path: anyPath.substr(0, hashIndex),
member: anyPath.substr(hashIndex + 1)
}
};
/**
* @class
* @param {string} executionPath
* @constructor
* @augments ModuleLoader
* @extends ModuleLoader
*/
function DefaultModuleLoader(executionPath) {
DefaultModuleLoader.super_.bind(this)();
this[executionPathProperty] = path.resolve(executionPath) || process.cwd();
}
LangUtils.inherits(DefaultModuleLoader, ModuleLoader);
DefaultModuleLoader.prototype.getExecutionPath = function() {
return this[executionPathProperty];
};
/**
* @param {string} modulePath
* @returns {*}
*/
DefaultModuleLoader.prototype.require = function(modulePath) {
if (!/^.\//i.test(modulePath)) {
//load module which is not starting with ./
if (require.main && typeof require.main.require === 'function') {
return require.main.require(modulePath)
}
return require(modulePath);
}
return require(path.join(this.getExecutionPath(),modulePath));
};
module.exports = {
ModuleLoader,
DefaultModuleLoader
}