-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathindex.ts
354 lines (299 loc) · 8.15 KB
/
index.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import debug from 'debug'
import {
FileSystem,
ResolveOptions,
Resolver,
ResolverFactory,
} from 'enhanced-resolve'
import { createPathsMatcher, getTsconfig } from 'get-tsconfig'
import isCore from 'is-core-module'
import isGlob from 'is-glob'
import { createSyncFn } from 'synckit'
const IMPORTER_NAME = 'eslint-import-resolver-typescript'
const log = debug(IMPORTER_NAME)
const _dirname =
typeof __dirname === 'undefined'
? path.dirname(fileURLToPath(import.meta.url))
: __dirname
export const globSync = createSyncFn<typeof import('globby').globby>(
path.resolve(_dirname, 'worker.mjs'),
)
export const defaultConditionNames = [
'types',
'import',
// APF: https://angular.io/guide/angular-package-format
'esm2020',
'es2020',
'es2015',
'require',
'node',
'node-addons',
'browser',
'default',
]
/**
* `.mts`, `.cts`, `.d.mts`, `.d.cts`, `.mjs`, `.cjs` are not included because `.cjs` and `.mjs` must be used explicitly
*/
export const defaultExtensions = [
'.ts',
'.tsx',
'.d.ts',
'.js',
'.jsx',
'.json',
'.node',
]
export const defaultExtensionAlias = {
'.js': [
'.ts',
// `.tsx` can also be compiled as `.js`
'.tsx',
'.d.ts',
'.js',
],
'.jsx': ['.tsx', '.d.ts', '.jsx'],
'.cjs': ['.cts', '.d.cts', '.cjs'],
'.mjs': ['.mts', '.d.mts', '.mjs'],
}
export const defaultMainFields = [
'types',
'typings',
// APF: https://angular.io/guide/angular-package-format
'fesm2020',
'fesm2015',
'esm2020',
'es2020',
'module',
'jsnext:main',
'main',
]
export const interfaceVersion = 2
export interface TsResolverOptions
extends Omit<ResolveOptions, 'fileSystem' | 'useSyncFileSystemCalls'> {
alwaysTryTypes?: boolean
project?: string[] | string
extensions?: string[]
}
type InternalResolverOptions = Required<
Pick<
ResolveOptions,
| 'conditionNames'
| 'extensionAlias'
| 'extensions'
| 'mainFields'
| 'useSyncFileSystemCalls'
>
> &
ResolveOptions &
TsResolverOptions
const fileSystem = fs as FileSystem
const JS_EXT_PATTERN = /\.(?:[cm]js|jsx?)$/
const RELATIVE_PATH_PATTERN = /^\.{1,2}(?:\/.*)?$/
let cachedOptions: InternalResolverOptions | undefined
let mappersCachedOptions: InternalResolverOptions
let mappers: Array<((specifier: string) => string[]) | null> | undefined
let resolverCachedOptions: InternalResolverOptions
let resolver: Resolver | undefined
/**
* @param source the module to resolve; i.e './some-module'
* @param file the importing file's full path; i.e. '/usr/local/bin/file.js'
* @param options
*/
// eslint-disable-next-line sonarjs/cognitive-complexity
export function resolve(
source: string,
file: string,
options?: TsResolverOptions | null,
): {
found: boolean
path?: string | null
} {
if (!cachedOptions || cachedOptions !== options) {
cachedOptions = {
...options,
conditionNames: options?.conditionNames ?? defaultConditionNames,
extensions: options?.extensions ?? defaultExtensions,
extensionAlias: options?.extensionAlias ?? defaultExtensionAlias,
mainFields: options?.mainFields ?? defaultMainFields,
fileSystem,
useSyncFileSystemCalls: true,
}
}
if (!resolver || resolverCachedOptions !== cachedOptions) {
resolver = ResolverFactory.createResolver(cachedOptions)
resolverCachedOptions = cachedOptions
}
log('looking for:', source)
source = removeQuerystring(source)
// don't worry about core node modules
if (isCore(source)) {
log('matched core:', source)
return {
found: true,
path: null,
}
}
initMappers(cachedOptions)
const mappedPath = getMappedPath(source, file, cachedOptions.extensions, true)
if (mappedPath) {
log('matched ts path:', mappedPath)
}
// note that even if we map the path, we still need to do a final resolve
let foundNodePath: string | null
try {
foundNodePath =
resolver.resolveSync(
{},
path.dirname(path.resolve(file)),
mappedPath ?? source,
) || null
} catch {
foundNodePath = null
}
// naive attempt at `@types/*` resolution,
// if path is neither absolute nor relative
if (
(JS_EXT_PATTERN.test(foundNodePath!) ||
(cachedOptions.alwaysTryTypes && !foundNodePath)) &&
!/^@types[/\\]/.test(source) &&
!path.isAbsolute(source) &&
!source.startsWith('.')
) {
const definitelyTyped = resolve(
'@types' + path.sep + mangleScopedPackage(source),
file,
options,
)
if (definitelyTyped.found) {
return definitelyTyped
}
}
if (foundNodePath) {
log('matched node path:', foundNodePath)
return {
found: true,
path: foundNodePath,
}
}
log("didn't find ", source)
return {
found: false,
}
}
/** Remove any trailing querystring from module id. */
function removeQuerystring(id: string) {
const querystringIndex = id.lastIndexOf('?')
if (querystringIndex >= 0) {
return id.slice(0, querystringIndex)
}
return id
}
const isFile = (path?: string | undefined): path is string => {
try {
return !!path && fs.statSync(path).isFile()
} catch {
return false
}
}
/**
* @param {string} source the module to resolve; i.e './some-module'
* @param {string} file the importing file's full path; i.e. '/usr/local/bin/file.js'
* @param {string[]} extensions the extensions to try
* @param {boolean} retry should retry on failed to resolve
* @returns The mapped path of the module or undefined
*/
// eslint-disable-next-line sonarjs/cognitive-complexity
function getMappedPath(
source: string,
file: string,
extensions: string[] = defaultExtensions,
retry?: boolean,
): string | undefined {
const originalExtensions = extensions
extensions = ['', ...extensions]
let paths: string[] | undefined = []
if (RELATIVE_PATH_PATTERN.test(source)) {
const resolved = path.resolve(path.dirname(file), source)
if (isFile(resolved)) {
paths = [resolved]
}
} else {
paths = mappers!
.map(mapper =>
mapper?.(source).map(item => [
...extensions.map(ext => `${item}${ext}`),
...originalExtensions.map(ext => `${item}/index${ext}`),
]),
)
.flat(2)
.filter(isFile)
}
if (retry && paths.length === 0) {
const isJs = JS_EXT_PATTERN.test(source)
if (isJs) {
const jsExt = path.extname(source)
const tsExt = jsExt.replace('js', 'ts')
const basename = source.replace(JS_EXT_PATTERN, '')
const resolved =
getMappedPath(basename + tsExt, file) ||
getMappedPath(
basename + '.d' + (tsExt === '.tsx' ? '.ts' : tsExt),
file,
)
if (resolved) {
return resolved
}
}
for (const ext of extensions) {
const resolved =
(isJs ? null : getMappedPath(source + ext, file)) ||
getMappedPath(source + `/index${ext}`, file)
if (resolved) {
return resolved
}
}
}
if (paths.length > 1) {
log('found multiple matching ts paths:', paths)
}
return paths[0]
}
function initMappers(options: InternalResolverOptions) {
if (mappers && mappersCachedOptions === options) {
return
}
const configPaths =
typeof options.project === 'string'
? [options.project]
: Array.isArray(options.project)
? options.project
: [process.cwd()]
const ignore = ['!**/node_modules/**']
// turn glob patterns into paths
const projectPaths = [
...new Set([
...configPaths.filter(path => !isGlob(path)),
...globSync([...configPaths.filter(path => isGlob(path)), ...ignore]),
]),
]
mappers = projectPaths.map(projectPath => {
const tsconfigResult = getTsconfig(projectPath)
return tsconfigResult && createPathsMatcher(tsconfigResult)
})
mappersCachedOptions = options
}
/**
* For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`.
*/
function mangleScopedPackage(moduleName: string) {
if (moduleName.startsWith('@')) {
const replaceSlash = moduleName.replace(path.sep, '__')
if (replaceSlash !== moduleName) {
return replaceSlash.slice(1) // Take off the "@"
}
}
return moduleName
}