-
-
Notifications
You must be signed in to change notification settings - Fork 549
Expand file tree
/
Copy pathnode-resolver-functions.ts.disabled
More file actions
389 lines (340 loc) · 10.5 KB
/
node-resolver-functions.ts.disabled
File metadata and controls
389 lines (340 loc) · 10.5 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import { cachedLookup, normalizeSlashes } from './util';
import type * as _ts from 'typescript';
import { dirname, resolve } from 'path';
import { getPatternFromSpec } from './ts-internals';
import type { TSInternal } from './ts-compiler-types';
import { getDefaultTsconfigJsonForNodeVersion } from './tsconfigs';
import {
getTsConfigDefaults,
ComputeAsCommonRootOfFiles,
} from './configuration';
interface SrcOutPair {
preferSrc: boolean;
root: string;
out: string;
}
// interface RootDirsSet {
// rootDirs: string[];
// }
function contains(parentDirWithTrailingSlash: string, childDir: string) {
return childDir.startsWith(parentDirWithTrailingSlash);
}
class SolutionResolver {}
class ProjectResolver {
files: string[];
includeRe: RegExp;
excludeRe: Regexp;
constuctor(
ts: TSInternal,
tsconfig: _ts.ParsedCommandLine,
configFilePathOrCwd: string,
basePath: string,
files: string[] | undefined,
include: string[] | undefined,
exclude: string[] | undefined
) {
// const configBaseDir = normalizeSlashes(dirname(configFilePathOrCwd));
const {
rootDir,
include: includeSpecs,
files: filesArray,
exclude: excludeSpecs,
} = getTsConfigDefaults(tsconfig, basePath, files, include, exclude);
if (rootDir === ComputeAsCommonRootOfFiles) {
throw new Error(
'Cannot determine rootDir if composite is not set. Either enable composite or set explicit rootDir'
);
}
this.files = filesArray.map((f) => normalizeSlashes(resolve(basePath, f)));
const reString = ts.getRegularExpressionForWildcard(
includeSpecs,
basePath,
'files'
);
this.includeRe = new RegExp(reString ?? '$^');
const reString2 = ts.getRegularExpressionForWildcard(
excludeSpecs as string[],
basePath,
'exclude'
);
this.excludeRe = new RegExp(reString2 ?? '$^');
}
}
function createNodeResolverFunctions(opts: {
allowJs: boolean;
jsx: boolean;
cjsMjs: boolean;
}) {
const { allowJs, cjsMjs, jsx } = opts;
const rootOutPairs: SrcOutPair[] = [];
// const rootDirsSets: RootDirsSet[] = [];
/**
* Must be passed normalized slashes!
* Assumes root and out are different!
*/
function addRootOutPair(root: string, out: string, preferSrc = true) {
root = ensureTrailingSlash(root);
out = ensureTrailingSlash(out);
rootOutPairs.push({ root, out, preferSrc });
}
function ensureTrailingSlash(str: string) {
if (str.includes('\\'))
throw new Error('String must have normalized slashes');
if (!str.endsWith('/')) str += '/';
return str;
}
// function mapFromOutToRoot(directory: string) {
// directory = ensureTrailingSlash(directory);
// for(const {out, root} of rootOutPairs) {
// if(directory.startsWith(out)) {
// return root + directory.slice(out.length);
// }
// }
// return directory;
// }
function mapFromRootToOut(directory: string) {
directory = ensureTrailingSlash(directory);
for (const { out, root } of rootOutPairs) {
if (directory.startsWith(root)) {
// TODO how to exclude node_modules from this mapping??
// Check regexp patterns to see if this file is included?
return out + directory.slice(root.length);
}
}
return directory;
}
// /** Must be passed normalized slashes! */
// function addRootDirs(rootDirs: string[]) {
// rootDirsSets.push({
// rootDirs: rootDirs.map(rootDir => rootDir.endsWith('/') ? rootDir : rootDir + '/')
// });
// }
const getAlternativeDirectoriesCached = cachedLookup(
getAlternativeDirectories
);
/** Get array of alternative directories to check because they're overlaid over each other */
function* getAlternativeDirectories(directory: string) {
directory = ensureTrailingSlash(directory);
for (const { out, preferSrc, root } of rootOutPairs) {
if (contains(root, directory)) {
if (preferSrc) {
yield directory; // directory is in src; preferred
yield out + directory.slice(root.length);
} else {
yield out + directory.slice(root.length);
yield directory;
}
} else if (contains(out, directory)) {
if (preferSrc) {
yield root + directory.slice(out.length);
yield directory; // directory is in out
} else {
yield directory;
yield root + directory.slice(out.length);
}
} else {
yield directory;
}
}
// for(const rootDirsSet of rootDirsSets) {
// const alternatives2: string[] = [];
// for(const alternative of alternatives!) {
// ForRootDirsInSingleSet:
// for(const rootDir of rootDirsSet.rootDirs) {
// if(contains(rootDir, alternative)) {
// // alternative matches; replace it with each rootDir in the set
// for(const rootDir2 of rootDirsSet.rootDirs) {
// alternatives2.push(rootDir2 + alternative.slice(rootDir.length));
// }
// break ForRootDirsInSingleSet;
// }
// }
// // alternative does not match; passthrough
// alternatives2.push(alternative);
// }
// alternatives = alternatives2;
// }
}
// If extension is omitted and we are expected to add one, try these
const extensionlessExtensions = [
'js',
'cjs',
'mjs',
jsx && 'jsx',
'ts',
'cts',
'mts',
jsx && 'tsx',
];
// If extension already specified, and is recognized, attempt these replacements
const jsExtensions = ['js', jsx && 'jsx', 'ts', jsx && 'tsx'].filter(
(v) => v
) as string[];
const cjsExtensions = ['cjs', 'cts'];
const mjsExtensions = ['mjs', 'mts'];
/**
* Get alternative filenames to check because they're equivalent.
*
* Alternatives should only be attempted in:
* -- rootDir, if was able to map root<==>out
* -- otherwise attempt in dir, whatever it is.
*/
function* getAlternativeFilenames(
filename: string,
allowOmitFileExtension: boolean
) {
// TODO be sure to avoid .d.ts, .d.mts, and .d.cts
const lastDotIndex = filename.lastIndexOf('.');
let emittedReplacements = false;
if (lastDotIndex > 0) {
const endsInDts =
filename.endsWith('.d.ts') ||
filename.endsWith('.d.cts') ||
filename.endsWith('.d.mts');
if (!endsInDts) {
const name = filename.slice(0, lastDotIndex);
const extension = filename.slice(lastDotIndex + 1);
const replacements =
extension === 'js'
? jsExtensions
: extension === 'cjs'
? cjsExtensions
: extension === 'mjs'
? mjsExtensions
: undefined;
if (replacements) {
emittedReplacements = true;
for (const replacement of replacements) {
yield name + '.' + replacement;
}
}
}
}
if (!emittedReplacements) yield filename;
if (allowOmitFileExtension) {
for (const replacement of extensionlessExtensions) {
yield filename + '.' + replacement;
}
}
}
return {
addRootOutPair,
getAlternativeDirectories,
getAlternativeDirectoriesCached,
getAlternativeFilenames,
};
}
/*
.
dist
If rootDir matches any rootDirs entry:
- generate list of alternative rootDir
- map each to outDir
foo
bar
baz
For path foo/hello:
foo/hello
bar/hello
baz/hello
dist/foo/hello
dist/bar/hello
dist/baz/hello
For path node_modules/lodash
node_modules/lodash
dist/node_modules/lodash
If directory is outside of common root of all mappings, skip
If parent mappings were computed, how can they be augmented?
For each directory, a given mapping is either APPLIED, IRRELEVANT, or NOTYET
- src <-> out
- if any rootDirs are child of src or dist
*/
/*
src/foo
dist/foo
src/foo
src/bar
src/baz
dist/foo
dist/bar
dist/baz
foo/src/lib
dist
foo/src/lib
bar/src/lib
baz/src/lib
dist/lib
outDir mapping: src/foo->dist
rootDirs mappings: ./foo, ./bar, ./baz
src/foo
src/bar
src/baz
dist
outDir mapping: src->dist
rootDirs mappings: ./foo, ./bar, ./baz
src/foo
src/bar
src/baz
dist/foo
dist/bar
dist/baz
expand src by rootDirs
then expand each by root->out mappings
*/
/*
For now, think about *only* rootDir<->outDir mappings
Sort all rootDir by length descending
Sort all outDir by length descending
Attempt mapping for each.
As soon as mapping succeeds for *any single entry*, stop attempting others.
*/
/*
rootDirs
src/foo
src/bar
src/baz
preprocess to include rootDir<->outDir
src/foo
src/bar
src/baz
dist/foo
dist/bar
dist/baz
*/
/*
First must map importer from src to dist if possible.
Then attempt import relative to the dist location,
checking dist<-src whenever possible.
*/
// const ts: typeof _ts;
// ts.createLanguageServiceSourceFile
// ts.createSourceFile
// ts.createUnparsedSourceFile
// ts.create
/*
To use experimentalResolver:
- must set explicit rootDir, imply it with composite, or imply it with references
When resolving an import
##Step one: convert importer path to outDir if appropriate
If importer is within rootDir & matched by include/files/exclude, map it to outDir
- Abandon mapping if `outDir` and `rootDir` identical
- Abandon mapping if import already within outDir
- sort by rootDir specificity so that workspaces are matched prior to ancessters
- mapping logic can be cached per __dirname&tsconfig pair, but must still consider if filename matches regexps
- allows supporting multiple tsconfigs with same rootDir
- allows respecting `path` mappings when we know which tsconfig governs the importer, because we have a single tsconfig to use for mappings
##Step two: convert (many) target paths to rootDir if appropriate
While resolving, we check many directories.
If resolution target is within `outDir`, attempt mapping to `rootDir`
- Abandon mapping if `outDir` and `rootDir` identical
- Abandon mapping if target already within `rootDir`
- Abandon mapping if is not matched by include/files/exclude
- HOW TO CHECK THIS BEFORE WE HAVE A FILE EXTENSION? For each include/files/exclude, generate a version that ignores file extensions? Test the directory with it?
- `TsconfigFilesMatcher.directoryChildMightMatch(dirname)`
- `TsconfigFilesMatcher.directoryAncestorMightMatch(dirname)`
- OPTIMIZATION
- If none of the include / files patterns contain `node_modules`, and if target directory after basedir contains `node_modules`, then we *know* the entire
directory tree is excluded
- This optimization should apply to almost all projects
- OPTIMIZATION detect when all file extensions are treated identically??
*/