-
Notifications
You must be signed in to change notification settings - Fork 31
/
analyze.ts
433 lines (386 loc) · 12.3 KB
/
analyze.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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import { tokenizer } from "acorn";
import { matchAll, clearImports, getImportNames } from "./_utils";
import { resolvePath, ResolveOptions } from "./resolve";
import { loadURL } from "./utils";
export interface ESMImport {
type: "static" | "dynamic";
code: string;
start: number;
end: number;
}
export interface StaticImport extends ESMImport {
type: "static";
imports: string;
specifier: string;
}
export interface ParsedStaticImport extends StaticImport {
defaultImport?: string;
namespacedImport?: string;
namedImports?: { [name: string]: string };
}
export interface DynamicImport extends ESMImport {
type: "dynamic";
expression: string;
}
export interface TypeImport extends Omit<ESMImport, "type"> {
type: "type";
imports: string;
specifier: string;
}
export interface ESMExport {
_type?: "declaration" | "named" | "default" | "star";
type: "declaration" | "named" | "default" | "star";
declarationType?:
| "let"
| "var"
| "const"
| "enum"
| "const enum"
| "class"
| "function"
| "async function";
code: string;
start: number;
end: number;
name?: string;
defaultName?: string;
names: string[];
specifier?: string;
}
export interface DeclarationExport extends ESMExport {
type: "declaration";
declaration: string;
name: string;
}
export interface NamedExport extends ESMExport {
type: "named";
exports: string;
names: string[];
specifier?: string;
}
export interface DefaultExport extends ESMExport {
type: "default";
}
export const ESM_STATIC_IMPORT_RE =
/(?<=\s|^|;|\})import\s*([\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu;
export const DYNAMIC_IMPORT_RE =
/import\s*\((?<expression>(?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)\)/gm;
const IMPORT_NAMED_TYPE_RE =
/(?<=\s|^|;|})import\s*type\s+([\s"']*(?<imports>[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gm;
export const EXPORT_DECAL_RE =
/\bexport\s+(?<declaration>(async function\s*\*?|function\s*\*?|let|const enum|const|enum|var|class))\s+\*?(?<name>[\w$]+)(?<extraNames>.*,\s*[\w$]+)*/g;
export const EXPORT_DECAL_TYPE_RE =
/\bexport\s+(?<declaration>(interface|type|declare (async function|function|let|const enum|const|enum|var|class)))\s+(?<name>[\w$]+)/g;
const EXPORT_NAMED_RE =
/\bexport\s+{(?<exports>[^}]+?)[\s,]*}(\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
const EXPORT_NAMED_TYPE_RE =
/\bexport\s+type\s+{(?<exports>[^}]+?)[\s,]*}(\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
const EXPORT_NAMED_DESTRUCT =
/\bexport\s+(let|var|const)\s+(?:{(?<exports1>[^}]+?)[\s,]*}|\[(?<exports2>[^\]]+?)[\s,]*])\s+=/gm;
const EXPORT_STAR_RE =
/\bexport\s*(\*)(\s*as\s+(?<name>[\w$]+)\s+)?\s*(\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
const EXPORT_DEFAULT_RE =
/\bexport\s+default\s+(async function|function|class|true|false|\W|\d)|\bexport\s+default\s+(?<defaultName>.*)/g;
const TYPE_RE = /^\s*?type\s/;
export function findStaticImports(code: string): StaticImport[] {
return _filterStatement(
_tryGetLocations(code, "import"),
matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }),
);
}
export function findDynamicImports(code: string): DynamicImport[] {
return _filterStatement(
_tryGetLocations(code, "import"),
matchAll(DYNAMIC_IMPORT_RE, code, { type: "dynamic" }),
);
}
export function findTypeImports(code: string): TypeImport[] {
return [
...matchAll(IMPORT_NAMED_TYPE_RE, code, { type: "type" }),
...matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }).filter(
(match) => /[^A-Za-z]type\s/.test(match.imports),
),
];
}
export function parseStaticImport(
matched: StaticImport | TypeImport,
): ParsedStaticImport {
const cleanedImports = clearImports(matched.imports);
const namedImports: Record<string, string> = {};
const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
for (const namedImport of _matches) {
const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
const source = _match?.[1] || namedImport.trim();
const importName = _match?.[2] || source;
if (source && !TYPE_RE.test(source)) {
namedImports[source] = importName;
}
}
const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
return {
...matched,
defaultImport,
namespacedImport,
namedImports,
} as ParsedStaticImport;
}
export function parseTypeImport(
matched: TypeImport | StaticImport,
): ParsedStaticImport {
if (matched.type === "type") {
return parseStaticImport(matched);
}
const cleanedImports = clearImports(matched.imports);
const namedImports: Record<string, string> = {};
const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
for (const namedImport of _matches) {
const _match = /\s+as\s+/.test(namedImport)
? namedImport.match(/^\s*type\s+(\S*) as (\S*)\s*$/)
: namedImport.match(/^\s*type\s+(\S*)\s*$/);
const source = _match?.[1] || namedImport.trim();
const importName = _match?.[2] || source;
if (source && TYPE_RE.test(namedImport)) {
namedImports[source] = importName;
}
}
const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
return {
...matched,
defaultImport,
namespacedImport,
namedImports,
} as ParsedStaticImport;
}
export function findExports(code: string): ESMExport[] {
// Find declarations like export const foo = 'bar'
const declaredExports: DeclarationExport[] = matchAll(EXPORT_DECAL_RE, code, {
type: "declaration",
});
// Parse extra names (foo, bar)
for (const declaredExport of declaredExports) {
const extraNamesStr = (declaredExport as any).extraNames as
| string
| undefined;
if (extraNamesStr) {
const extraNames = matchAll(/,\s*(?<name>\w+)/g, extraNamesStr, {}).map(
(m) => m.name,
);
declaredExport.names = [declaredExport.name, ...extraNames];
}
delete (declaredExport as any).extraNames;
}
// Find named exports
const namedExports: NamedExport[] = normalizeNamedExports(
matchAll(EXPORT_NAMED_RE, code, {
type: "named",
}),
);
const destructuredExports: NamedExport[] = matchAll(
EXPORT_NAMED_DESTRUCT,
code,
{ type: "named" },
);
for (const namedExport of destructuredExports) {
// @ts-expect-error groups
namedExport.exports = namedExport.exports1 || namedExport.exports2;
namedExport.names = namedExport.exports
.replace(/^\r?\n?/, "")
.split(/\s*,\s*/g)
.filter((name) => !TYPE_RE.test(name))
.map((name) =>
name
.replace(/^.*?\s*:\s*/, "")
.replace(/\s*=\s*.*$/, "")
.trim(),
);
}
// Find export default
const defaultExport: DefaultExport[] = matchAll(EXPORT_DEFAULT_RE, code, {
type: "default",
name: "default",
});
// Find export star
const starExports: ESMExport[] = matchAll(EXPORT_STAR_RE, code, {
type: "star",
});
// Merge and normalize exports
// eslint-disable-next-line unicorn/no-array-push-push
const exports: ESMExport[] = normalizeExports([
...declaredExports,
...namedExports,
...destructuredExports,
...defaultExport,
...starExports,
]);
// Return early when there is no export statement
if (exports.length === 0) {
return [];
}
const exportLocations = _tryGetLocations(code, "export");
if (exportLocations && exportLocations.length === 0) {
return [];
}
return (
// Filter false positive export matches
_filterStatement(exportLocations, exports)
// Prevent multiple exports of same function, only keep latest iteration of signatures
.filter((exp, index, exports) => {
const nextExport = exports[index + 1];
return (
!nextExport ||
exp.type !== nextExport.type ||
!exp.name ||
exp.name !== nextExport.name
);
})
);
}
export function findTypeExports(code: string): ESMExport[] {
// Find declarations like export const foo = 'bar'
const declaredExports: DeclarationExport[] = matchAll(
EXPORT_DECAL_TYPE_RE,
code,
{ type: "declaration" },
);
// Find named exports
const namedExports: NamedExport[] = normalizeNamedExports(
matchAll(EXPORT_NAMED_TYPE_RE, code, {
type: "named",
}),
);
// Merge and normalize exports
const exports: ESMExport[] = normalizeExports([
...declaredExports,
...namedExports,
]);
// Return early when there is no export statement
if (exports.length === 0) {
return [];
}
const exportLocations = _tryGetLocations(code, "export");
if (exportLocations && exportLocations.length === 0) {
return [];
}
return (
// Filter false positive export matches
_filterStatement(exportLocations, exports)
// Prevent multiple exports of same function, only keep latest iteration of signatures
.filter((exp, index, exports) => {
const nextExport = exports[index + 1];
return (
!nextExport ||
exp.type !== nextExport.type ||
!exp.name ||
exp.name !== nextExport.name
);
})
);
}
function normalizeExports(exports: (ESMExport & { declaration?: string })[]) {
for (const exp of exports) {
if (!exp.name && exp.names && exp.names.length === 1) {
exp.name = exp.names[0];
}
if (exp.name === "default" && exp.type !== "default") {
exp._type = exp.type;
exp.type = "default";
}
if (!exp.names && exp.name) {
exp.names = [exp.name];
}
if (exp.type === "declaration" && exp.declaration) {
exp.declarationType = exp.declaration.replace(
/^declare\s*/,
"",
) as ESMExport["declarationType"];
}
}
return exports;
}
function normalizeNamedExports(namedExports: NamedExport[]) {
for (const namedExport of namedExports) {
namedExport.names = namedExport.exports
.replace(/^\r?\n?/, "")
.split(/\s*,\s*/g)
.filter((name) => !TYPE_RE.test(name))
.map((name) => name.replace(/^.*?\sas\s/, "").trim());
}
return namedExports;
}
export function findExportNames(code: string): string[] {
return findExports(code)
.flatMap((exp) => exp.names)
.filter(Boolean);
}
export async function resolveModuleExportNames(
id: string,
options?: ResolveOptions,
): Promise<string[]> {
const url = await resolvePath(id, options);
const code = await loadURL(url);
const exports = findExports(code);
// Explicit named exports
const exportNames = new Set(
exports.flatMap((exp) => exp.names).filter(Boolean),
);
// Recursive * exports
for (const exp of exports) {
if (exp.type !== "star" || !exp.specifier) {
continue;
}
const subExports = await resolveModuleExportNames(exp.specifier, {
...options,
url,
});
for (const subExport of subExports) {
exportNames.add(subExport);
}
}
return [...exportNames];
}
// --- Internal ---
interface TokenLocation {
start: number;
end: number;
}
function _filterStatement<T extends TokenLocation>(
locations: TokenLocation[] | undefined,
statements: T[],
): T[] {
return statements.filter((exp) => {
return (
!locations ||
locations.some((location) => {
// AST token inside the regex match
return exp.start <= location.start && exp.end >= location.end;
// AST Token start or end is within the regex match
// return (exp.start <= location.start && location.start <= exp.end) ||
// (exp.start <= location.end && location.end <= exp.end)
})
);
});
}
function _tryGetLocations(code: string, label: string) {
try {
return _getLocations(code, label);
} catch {}
}
function _getLocations(code: string, label: string) {
const tokens = tokenizer(code, {
ecmaVersion: "latest",
sourceType: "module",
allowHashBang: true,
allowAwaitOutsideFunction: true,
allowImportExportEverywhere: true,
});
const locations: TokenLocation[] = [];
for (const token of tokens) {
if (token.type.label === label) {
locations.push({
start: token.start,
end: token.end,
});
}
}
return locations;
}