-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathfind-all-modules.mts
60 lines (51 loc) · 1.66 KB
/
find-all-modules.mts
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
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as ts from 'typescript';
export async function findAllEntryPointsAndExportedModules(packagePath: string) {
const packageJsonRaw = await fs.readFile(path.join(packagePath, 'package.json'), 'utf8');
const packageJson = JSON.parse(packageJsonRaw) as {
name: string;
exports: Record<string, Record<string, string>>;
};
const tasks: Promise<{importPath: string; symbolName: string}[]>[] = [];
for (const [subpath, conditions] of Object.entries(packageJson.exports)) {
if (conditions.types === undefined) {
continue;
}
tasks.push(
(async () => {
const dtsFile = path.join(packagePath, conditions.types);
const dtsBundleFile = ts.createSourceFile(
dtsFile,
await fs.readFile(dtsFile, 'utf8'),
ts.ScriptTarget.ESNext,
false,
);
return scanExportsForModules(dtsBundleFile).map(e => ({
importPath: path.posix.join(packageJson.name, subpath),
symbolName: e,
}));
})(),
);
}
const moduleExports = (await Promise.all(tasks)).flat();
return {
name: packageJson.name,
packagePath,
moduleExports,
};
}
function scanExportsForModules(sf: ts.SourceFile): string[] {
const moduleExports: string[] = [];
const visit = (node: ts.Node) => {
if (ts.isExportDeclaration(node) && ts.isNamedExports(node.exportClause)) {
moduleExports.push(
...node.exportClause.elements
.filter(e => e.name.text.endsWith('Module'))
.map(e => e.name.text),
);
}
};
ts.forEachChild(sf, visit);
return moduleExports;
}