-
-
Notifications
You must be signed in to change notification settings - Fork 314
Expand file tree
/
Copy pathmakeFsImporter.ts
More file actions
291 lines (242 loc) · 8.08 KB
/
makeFsImporter.ts
File metadata and controls
291 lines (242 loc) · 8.08 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
import { shallowIgnoreVisitors } from '../utils/traverse.js';
import resolve from 'resolve';
import { dirname, extname } from 'path';
import fs from 'fs';
import type { NodePath } from '@babel/traverse';
import { visitors } from '@babel/traverse';
import type { ExportSpecifier, ObjectProperty } from '@babel/types';
import type { Importer, ImportPath } from './index.js';
import type FileState from '../FileState.js';
import { resolveObjectPatternPropertyToValue } from '../utils/index.js';
// These extensions are sorted by priority
// resolve() will check for files in the order these extensions are sorted
const RESOLVE_EXTENSIONS = [
'.js',
'.ts',
'.tsx',
'.mjs',
'.cjs',
'.mts',
'.cts',
'.jsx',
];
function defaultLookupModule(filename: string, basedir: string): string {
const resolveOptions = {
basedir,
extensions: RESOLVE_EXTENSIONS,
// we do not need to check core modules as we cannot import them anyway
includeCoreModules: false,
};
try {
return resolve.sync(filename, resolveOptions);
} catch (error) {
const ext = extname(filename);
let newFilename: string;
// if we try to import a JavaScript file it might be that we are actually pointing to
// a TypeScript file. This can happen in ES modules as TypeScript requires to import other
// TypeScript files with .js extensions
// https://www.typescriptlang.org/docs/handbook/esm-node.html#type-in-packagejson-and-new-extensions
switch (ext) {
case '.js':
case '.mjs':
case '.cjs':
newFilename = `${filename.slice(0, -2)}ts`;
break;
case '.jsx':
newFilename = `${filename.slice(0, -3)}tsx`;
break;
default:
throw error;
}
return resolve.sync(newFilename, {
...resolveOptions,
// we already know that there is an extension at this point, so no need to check other extensions
extensions: [],
});
}
}
interface TraverseState {
readonly name: string;
readonly file: FileState;
readonly seen: Set<string>;
resultPath?: NodePath | null;
}
interface FsImporterCache {
parseCache: Map<string, FileState>;
resolveCache: Map<string, string | null>;
}
// Factory for the resolveImports importer
// If this resolver is used in an environment where the source files change (e.g. watch)
// then the cache needs to be cleared on file changes.
export default function makeFsImporter(
lookupModule: (
filename: string,
basedir: string,
) => string = defaultLookupModule,
{ parseCache, resolveCache }: FsImporterCache = {
parseCache: new Map(),
resolveCache: new Map(),
},
): Importer {
function resolveImportedValue(
path: ImportPath,
name: string,
file: FileState,
seen: Set<string> = new Set(),
): NodePath | null {
// Bail if no filename was provided for the current source file.
// Also never traverse into react itself.
const source = path.node.source?.value;
const { filename } = file.opts;
if (!source || !filename || source === 'react') {
return null;
}
// Resolve the imported module using the Node resolver
const basedir = dirname(filename);
const resolveCacheKey = `${basedir}|${source}`;
let resolvedSource = resolveCache.get(resolveCacheKey);
// We haven't found it before, so no need to look again
if (resolvedSource === null) {
return null;
}
// First time we try to resolve this file
if (resolvedSource === undefined) {
try {
resolvedSource = lookupModule(source, basedir);
} catch (error) {
const { code } = error as NodeJS.ErrnoException;
if (code === 'MODULE_NOT_FOUND' || code === 'INVALID_PACKAGE_MAIN') {
resolveCache.set(resolveCacheKey, null);
return null;
}
throw error;
}
resolveCache.set(resolveCacheKey, resolvedSource);
}
// Prevent recursive imports
if (seen.has(resolvedSource)) {
return null;
}
seen.add(resolvedSource);
let nextFile = parseCache.get(resolvedSource);
if (!nextFile) {
// Read and parse the code
const src = fs.readFileSync(resolvedSource, 'utf8');
nextFile = file.parse(src, resolvedSource);
parseCache.set(resolvedSource, nextFile);
}
return findExportedValue(nextFile, name, seen);
}
const explodedVisitors = visitors.explode<TraverseState>({
...shallowIgnoreVisitors,
ExportNamedDeclaration: {
enter: function (path, state) {
const { file, name, seen } = state;
const declaration = path.get('declaration');
// export const/var ...
if (declaration.hasNode() && declaration.isVariableDeclaration()) {
for (const declPath of declaration.get('declarations')) {
const id = declPath.get('id');
const init = declPath.get('init');
if (id.isIdentifier({ name }) && init.hasNode()) {
// export const/var a = <init>
state.resultPath = init;
break;
} else if (id.isObjectPattern()) {
// export const/var { a } = <init>
state.resultPath = id.get('properties').find(prop => {
if (prop.isObjectProperty()) {
const value = prop.get('value');
return value.isIdentifier({ name });
}
// We don't handle RestElement here yet as complicated
return false;
});
if (state.resultPath) {
state.resultPath = resolveObjectPatternPropertyToValue(
state.resultPath as NodePath<ObjectProperty>,
);
break;
}
}
// ArrayPattern not handled yet
}
} else if (
declaration.hasNode() &&
declaration.has('id') &&
(declaration.get('id') as NodePath).isIdentifier({ name })
) {
// export function/class/type/interface/enum ...
state.resultPath = declaration;
} else if (path.has('specifiers')) {
// export { ... } or export x from ... or export * as x from ...
for (const specifierPath of path.get('specifiers')) {
if (specifierPath.isExportNamespaceSpecifier()) {
continue;
}
const exported = specifierPath.get('exported');
if (exported.isIdentifier({ name })) {
// export ... from ''
if (path.has('source')) {
const local = specifierPath.isExportSpecifier()
? specifierPath.node.local.name
: 'default';
state.resultPath = resolveImportedValue(
path,
local,
file,
seen,
);
if (state.resultPath) {
break;
}
} else {
state.resultPath = (
specifierPath as NodePath<ExportSpecifier>
).get('local');
break;
}
}
}
}
state.resultPath ? path.stop() : path.skip();
},
},
ExportDefaultDeclaration: {
enter: function (path, state) {
const { name } = state;
if (name === 'default') {
state.resultPath = path.get('declaration');
return path.stop();
}
path.skip();
},
},
ExportAllDeclaration: {
enter: function (path, state) {
const { name, file, seen } = state;
const resolvedPath = resolveImportedValue(path, name, file, seen);
if (resolvedPath) {
state.resultPath = resolvedPath;
return path.stop();
}
path.skip();
},
},
});
// Traverses the program looking for an export that matches the requested name
function findExportedValue(
file: FileState,
name: string,
seen: Set<string>,
): NodePath | null {
const state: TraverseState = {
file,
name,
seen,
};
file.traverse(explodedVisitors, state);
return state.resultPath || null;
}
return resolveImportedValue;
}