-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathnoCrossEntryPointRelativeImportsRule.ts
81 lines (72 loc) · 2.7 KB
/
noCrossEntryPointRelativeImportsRule.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
import ts from 'typescript';
import minimatch from 'minimatch';
import {existsSync} from 'fs';
import {dirname, join, normalize, resolve} from 'path';
import * as Lint from 'tslint';
const BUILD_BAZEL_FILE = 'BUILD.bazel';
/**
* Rule that enforces that imports or exports with relative paths do not resolve to
* source files outside of the current Bazel package. This enforcement is necessary
* because relative cross entry-point imports/exports can cause code being inlined
* unintentionally and could break module resolution since the folder structure
* changes in the Angular Package release output.
*/
export class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, checkSourceFile, this.getOptions().ruleArguments[0]);
}
}
/**
* Rule walker function that checks the source file for imports/exports
* with relative cross entry-point references.
*/
function checkSourceFile(ctx: Lint.WalkContext<string[]>) {
if (ctx.options.some(o => minimatch(ctx.sourceFile.fileName, o))) {
return;
}
(function visitNode(node: ts.Node) {
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
if (
!node.moduleSpecifier ||
!ts.isStringLiteralLike(node.moduleSpecifier) ||
!node.moduleSpecifier.text.startsWith('.')
) {
return;
}
const modulePath = node.moduleSpecifier.text;
const basePath = dirname(ctx.sourceFile.fileName);
const currentPackage = findClosestBazelPackage(basePath);
const resolvedPackage = findClosestBazelPackage(resolve(basePath, modulePath));
if (
currentPackage &&
resolvedPackage &&
normalize(currentPackage) !== normalize(resolvedPackage)
) {
const humanizedType = ts.isImportDeclaration(node) ? 'Import' : 'Export';
ctx.addFailureAtNode(
node,
`${humanizedType} resolves to a different Bazel build package through a relative ` +
`path. This is not allowed and can be fixed by using the actual module import.`,
);
}
return;
}
ts.forEachChild(node, visitNode);
})(ctx.sourceFile);
}
/** Finds the closest Bazel build package for the given path. */
function findClosestBazelPackage(startPath: string): string | null {
let currentPath = startPath;
while (!hasBuildFile(currentPath)) {
const parentPath = dirname(currentPath);
if (parentPath === currentPath) {
return null;
}
currentPath = parentPath;
}
return currentPath;
}
/** Checks whether the given directory has a Bazel build file. */
function hasBuildFile(dirPath: string): boolean {
return existsSync(join(dirPath, BUILD_BAZEL_FILE));
}