forked from mgechev/codelyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
relativeUrlPrefixRule.ts
66 lines (59 loc) · 2.52 KB
/
relativeUrlPrefixRule.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
import { IOptions, IRuleMetadata, RuleFailure, Rules } from 'tslint/lib';
import { SourceFile } from 'typescript/lib/typescript';
import { NgWalker } from './angular/ngWalker';
import * as ts from 'typescript';
export class Rule extends Rules.AbstractRule {
static readonly metadata: IRuleMetadata = {
description: "The ./ prefix is standard syntax for relative URLs; don't depend on Angular's current ability to do without that prefix.",
descriptionDetails: 'See more at https://angular.io/styleguide#style-05-04.',
rationale: 'A component relative URL requires no change when you move the component files, as long as the files stay together.',
ruleName: 'relative-url-prefix',
options: null,
optionsDescription: 'Not configurable.',
type: 'maintainability',
typescriptOnly: true
};
static readonly FAILURE_STRING = 'The ./ prefix is standard syntax for relative URLs. (https://angular.io/styleguide#style-05-04)';
apply(sourceFile: SourceFile): RuleFailure[] {
return this.applyWithWalker(new RelativePathExternalResourcesRuleWalker(sourceFile, this.getOptions()));
}
}
export class RelativePathExternalResourcesRuleWalker extends NgWalker {
constructor(sourceFile: SourceFile, options: IOptions) {
super(sourceFile, options);
}
visitClassDecorator(decorator: ts.Decorator) {
if (ts.isCallExpression(decorator.expression) && decorator.expression.arguments) {
decorator.expression.arguments.forEach(arg => {
if (ts.isObjectLiteralExpression(arg) && arg.properties) {
arg.properties.forEach((prop: any) => {
if (prop && prop.name.text === 'templateUrl') {
const url = prop.initializer.text;
this.checkTemplateUrl(url, prop.initializer);
} else if (prop && prop.name.text === 'styleUrls') {
if (prop.initializer.elements.length > 0) {
prop.initializer.elements.forEach(e => {
const url = e.text;
this.checkStyleUrls(e);
});
}
}
});
}
});
}
super.visitClassDecorator(decorator);
}
private checkTemplateUrl(url: string, initializer: ts.StringLiteral) {
if (url && !/^\.\/[^\.\/|\.\.\/]/.test(url)) {
this.addFailureAtNode(initializer, Rule.FAILURE_STRING);
}
}
private checkStyleUrls(token: ts.StringLiteral) {
if (token && token.text) {
if (!/^\.\/[^\.\/|\.\.\/]/.test(token.text)) {
this.addFailureAtNode(token, Rule.FAILURE_STRING);
}
}
}
}