UNPKG

1.6 kBJavaScriptView Raw
1const {
2 cond, curry, identity, of, prop, T
3} = require('ramda');
4const { List } = require('immutable-ext');
5const { isAbsolute, join } = require('path');
6
7// createPaths :: (String -> String) -> List String
8const createPaths = curry((root, moduleId) => List.of(
9 join(root, moduleId),
10 join(root, 'node_modules', moduleId),
11 moduleId
12));
13
14// exists :: (String -> String) -> Boolean
15const exists = (root, module) => {
16 try {
17 require.resolve(join(root, module));
18 return true;
19 } catch (err) {
20 return false;
21 }
22};
23
24// normalize :: String base -> String path -> String
25const normalizePath = curry((base, path) => (isAbsolute(path) ? path : join(base, path)));
26
27// toArray :: a -> Array
28const toArray = cond([
29 [Array.isArray, identity],
30 [T, of]
31]);
32
33// req :: String moduleId -> a
34const req = (moduleId, root) => {
35 const paths = createPaths(root, moduleId);
36 const path = paths.find((path) => {
37 try {
38 require.resolve(path);
39 return true;
40 } catch (err) {
41 return path === paths.last();
42 }
43 });
44
45 return require(path); // eslint-disable-line
46};
47
48// getRoot :: Object -> String
49const getRoot = prop('root');
50
51// getSource :: Object -> String
52const getSource = prop('source');
53
54// [PATH_PROP_NAME, DEFAULT_VALUE, GET_NORMALIZE_BASE]
55const pathOptions = [
56 ['root', '', () => process.cwd()],
57 ['source', 'src', getRoot],
58 ['output', 'build', getRoot],
59 ['tests', 'test', getRoot],
60 ['node_modules', 'node_modules', getRoot]
61];
62
63module.exports = {
64 createPaths,
65 exists,
66 normalizePath,
67 toArray,
68 req,
69 getRoot,
70 getSource,
71 pathOptions
72};