-
Notifications
You must be signed in to change notification settings - Fork 41
/
tsconfig.ts
176 lines (165 loc) · 5.41 KB
/
tsconfig.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import ts from 'typescript'
import * as fs from 'fs'
import * as path from 'path'
import glob from 'glob'
/**
* @public
*/
export async function getProjectRootNamesAndCompilerOptions(project: string) {
const { configFilePath, dirname } = getTsConfigFilePath(project)
const config = await getTsConfig(configFilePath, dirname)
const { options: compilerOptions, errors } = ts.convertCompilerOptionsFromJson(config.compilerOptions, config.basePath || dirname)
if (errors && errors.length > 0) {
throw errors
}
const rootNames = await getRootNames(config, dirname)
return { rootNames, compilerOptions }
}
function getTsConfigFilePath(project: string, fallbackProject?: string[]) {
let configFilePath: string
let dirname: string
let projectStats: fs.Stats | undefined
try {
projectStats = fs.statSync(project)
} catch (error: unknown) {
if (fallbackProject) {
while (fallbackProject.length > 0) {
try {
project = fallbackProject[0]
projectStats = fs.statSync(project)
break
} catch {
fallbackProject.shift()
}
}
} else {
throw error
}
}
if (!projectStats) {
try {
projectStats = fs.statSync(project + '.json')
} catch {
if (projectStats) {
project = project + '.json'
}
}
}
if (projectStats && projectStats.isDirectory()) {
configFilePath = path.resolve(project, 'tsconfig.json')
dirname = project
} else if (projectStats && projectStats.isFile()) {
configFilePath = project
dirname = path.dirname(project)
} else {
throw new Error("paramter 'project' should be a file or directory.")
}
return { configFilePath, dirname }
}
interface JsonConfig {
extends?: string
compilerOptions?: { baseUrl?: string; [name: string]: unknown }
include?: string[]
exclude?: string[]
files?: string[]
basePath?: string
}
async function getTsConfig(configFilePath: string, dirname: string): Promise<JsonConfig> {
const configResult = ts.readConfigFile(configFilePath, p => fs.readFileSync(p).toString())
const config = configResult.error ? {
extends: undefined,
compilerOptions: {
lib: [
'dom',
'es5',
'es2015',
'es2016',
'es2017'
],
allowSyntheticDefaultImports: true
}
} : configResult.config as JsonConfig
if (config.extends) {
let project: string
let fallbackProjects: string[] = []
if (path.isAbsolute(config.extends)) {
project = config.extends
} else if (config.extends === '.'
|| config.extends === '..'
|| config.extends.startsWith(`.${path.sep}`)
|| config.extends.startsWith(`..${path.sep}`)
|| config.extends.startsWith('./')
|| config.extends.startsWith('../')
) {
project = path.resolve(dirname, config.extends)
} else {
project = path.resolve(dirname, 'node_modules', config.extends)
const paths = await findParentsWithNodeModules(dirname)
fallbackProjects = paths.map(p => path.resolve(p, 'node_modules', config.extends || ''))
}
const { configFilePath, dirname: extendsBasename } = getTsConfigFilePath(project, fallbackProjects)
const extendsConfig = await getTsConfig(configFilePath, extendsBasename)
const topLevelBaseUrl = config.compilerOptions ? config.compilerOptions.baseUrl : undefined
config.compilerOptions = { ...extendsConfig.compilerOptions, ...config.compilerOptions }
config.basePath = topLevelBaseUrl ? dirname : extendsBasename;
}
return config
}
async function getRootNames(config: JsonConfig, dirname: string) {
const include: string[] | undefined = config.include
const exclude: string[] | undefined = config.exclude || ['node_modules/**']
if (config.files) {
return config.files.map(f => path.resolve(dirname, f))
}
if (include && Array.isArray(include) && include.length > 0) {
const rules: string[] = []
for (const file of include) {
const currentPath = path.resolve(dirname, file)
const stats = await statAsync(currentPath)
if (stats === undefined) {
rules.push(currentPath)
} else if (stats.isDirectory()) {
rules.push(`${currentPath.endsWith('/') ? currentPath.substring(0, currentPath.length - 1) : currentPath}/**/*.{ts,tsx}`)
} else if (stats.isFile()) {
rules.push(currentPath)
}
}
return globAsync(rules.length === 1 ? rules[0] : `{${rules.join(',')}}`, exclude, dirname)
}
const rootNames = await globAsync(`**/*.{ts,tsx}`, exclude, dirname)
return rootNames.map((r) => path.resolve(process.cwd(), dirname, r))
}
function statAsync(file: string) {
return new Promise<fs.Stats | undefined>((resolve) => {
fs.stat(file, (error, stats) => {
if (error) {
resolve(undefined)
} else {
resolve(stats)
}
})
})
}
function globAsync(pattern: string, ignore: string | string[], cwd?: string) {
return new Promise<string[]>((resolve, reject) => {
glob(pattern, { ignore, cwd }, (error, matches) => {
if (error) {
reject(error)
} else {
resolve(matches)
}
})
})
}
async function findParentsWithNodeModules(dir: string) {
const result = [process.cwd()]
dir = path.resolve(dir)
for (let i = 0; i < 3; i++) {
dir = path.dirname(dir)
const stats = await statAsync(path.resolve(dir, 'node_modules'))
if (stats && stats.isDirectory() && !result.includes(dir)) {
result.push(dir)
}
}
return result
}