UNPKG

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