1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const fs = require("fs");
|
4 | const path = require("path");
|
5 | const debug_1 = require("./debug");
|
6 | const util_1 = require("./util");
|
7 | const tsconfigs = {};
|
8 | const rootDirs = [];
|
9 | const typeRoots = [`${__dirname}/../node_modules/@types`];
|
10 | const debug = debug_1.default();
|
11 | function 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 | skipProject: true,
|
29 |
|
30 |
|
31 | compilerOptions: {
|
32 | target: tsconfig.compilerOptions.target || 'es2017',
|
33 | module: 'commonjs',
|
34 | sourceMap: true,
|
35 | rootDirs,
|
36 | typeRoots,
|
37 | }
|
38 | });
|
39 | }
|
40 | function loadTSConfig(root) {
|
41 | try {
|
42 |
|
43 |
|
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 | }
|
55 | function 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 |
|
69 | const lib = path.join(root, outDir);
|
70 | const src = path.join(root, rootDir);
|
71 | const relative = path.relative(lib, orig);
|
72 | const out = path.join(src, relative);
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
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 | }
|
88 | exports.tsPath = tsPath;
|