angular/integration/ng-modules-importability/find-all-modules.ts
Paul Gschwendtner 867ea1c88a test: add integration test to ensure all exported modules can be imported (#60489)
This commit adds a new integration test which will help ensure that all
exported `@NgModule`'s of framework packages can be imported by users
without any errors.

This test is generally useful, but with our upcoming changes with
relative imports, this is a good safety-net. Relative imports could
break re-exported NgModules inside NgModule's. For more details, see:
https://github.com/angular/components/pull/30667

Notably we don't expect any issues for framework package as re-exporting
`@NgModule`'s inside `@NgModule`'s is seemingly a rather rare pattern for
APF libraries (confirmed by Material only having like 4-5 instances).

PR Close #60489
2025-03-20 12:32:37 -07:00

70 lines
2 KiB
TypeScript

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;
}
// Skip wild-card conditions. Those are not entry-points. e.g. common/locales.
if (conditions['types'].includes('*')) {
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) &&
node.exportClause !== undefined &&
ts.isNamedExports(node.exportClause)
) {
moduleExports.push(
...node.exportClause.elements
.filter(
(e) =>
e.name.text.endsWith('Module') &&
// Check if the first letter is upper-case.
e.name.text[0].toLowerCase() !== e.name.text[0],
)
.map((e) => e.name.text),
);
}
};
ts.forEachChild(sf, visit);
return moduleExports;
}