1 | const {
|
2 | cond, curry, identity, of, prop, T
|
3 | } = require('ramda');
|
4 | const { List } = require('immutable-ext');
|
5 | const { isAbsolute, join } = require('path');
|
6 |
|
7 |
|
8 | const createPaths = curry((root, moduleId) => List.of(
|
9 | join(root, moduleId),
|
10 | join(root, 'node_modules', moduleId),
|
11 | moduleId
|
12 | ));
|
13 |
|
14 |
|
15 | const exists = (root, module) => {
|
16 | try {
|
17 | require.resolve(join(root, module));
|
18 | return true;
|
19 | } catch (err) {
|
20 | return false;
|
21 | }
|
22 | };
|
23 |
|
24 |
|
25 | const normalizePath = curry((base, path) => (isAbsolute(path) ? path : join(base, path)));
|
26 |
|
27 |
|
28 | const toArray = cond([
|
29 | [Array.isArray, identity],
|
30 | [T, of]
|
31 | ]);
|
32 |
|
33 |
|
34 | const 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);
|
46 | };
|
47 |
|
48 |
|
49 | const getRoot = prop('root');
|
50 |
|
51 |
|
52 | const getSource = prop('source');
|
53 |
|
54 |
|
55 | const 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 |
|
63 | module.exports = {
|
64 | createPaths,
|
65 | exists,
|
66 | normalizePath,
|
67 | toArray,
|
68 | req,
|
69 | getRoot,
|
70 | getSource,
|
71 | pathOptions
|
72 | };
|