UNPKG

2.99 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const fs = require("fs-extra");
4const loadJSON = require("load-json-file");
5const path = require("path");
6const tsconfigs = {};
7const rootDirs = [];
8const typeRoots = [`${__dirname}/../node_modules/@types`];
9const debug = require('debug')('@anycli/config');
10function registerTSNode(root) {
11 if (tsconfigs[root])
12 return;
13 const tsconfig = loadTSConfig(root);
14 if (!tsconfig)
15 return;
16 tsconfigs[root] = tsconfig;
17 debug('registering ts-node at', root);
18 const tsNode = require('ts-node');
19 typeRoots.push(`${root}/../node_modules/@types`);
20 if (tsconfig.compilerOptions.rootDirs) {
21 rootDirs.push(...tsconfig.compilerOptions.rootDirs.map(r => path.join(root, r)));
22 }
23 else {
24 rootDirs.push(`${root}/src`);
25 }
26 tsNode.register({
27 project: false,
28 // cache: false,
29 // typeCheck: true,
30 compilerOptions: {
31 target: tsconfig.compilerOptions.target || 'es2017',
32 module: 'commonjs',
33 rootDirs,
34 typeRoots,
35 }
36 });
37}
38function loadTSConfig(root) {
39 try {
40 // // ignore if no .git as it's likely not in dev mode
41 // if (!await fs.pathExists(path.join(this.root, '.git'))) return
42 const tsconfigPath = path.join(root, 'tsconfig.json');
43 const tsconfig = loadJSON.sync(tsconfigPath);
44 if (!tsconfig || !tsconfig.compilerOptions)
45 return;
46 return tsconfig;
47 }
48 catch (err) {
49 if (err.code !== 'ENOENT')
50 throw err;
51 }
52}
53function tsPath(root, orig) {
54 if (!orig)
55 return orig;
56 orig = path.join(root, orig);
57 try {
58 registerTSNode(root);
59 const tsconfig = tsconfigs[root];
60 if (!tsconfig)
61 return orig;
62 const { rootDirs, outDir } = tsconfig.compilerOptions;
63 const rootDir = (rootDirs || [])[0];
64 if (!rootDir || !outDir)
65 return orig;
66 // rewrite path from ./lib/foo to ./src/foo
67 const lib = path.join(root, outDir); // ./lib
68 const src = path.join(root, rootDir); // ./src
69 const relative = path.relative(lib, orig); // ./commands
70 const out = path.join(src, relative); // ./src/commands
71 // this can be a directory of commands or point to a hook file
72 // if it's a directory, we check if the path exists. If so, return the path to the directory.
73 // For hooks, it might point to a module, not a file. Something like "./hooks/myhook"
74 // That file doesn't exist, and the real file is "./hooks/myhook.ts"
75 // In that case we attempt to resolve to the filename. If it fails it will revert back to the lib path
76 if (fs.pathExistsSync(out) || fs.pathExistsSync(out + '.ts'))
77 return out;
78 else
79 return orig;
80 }
81 catch (err) {
82 debug(err);
83 return orig;
84 }
85}
86exports.tsPath = tsPath;