-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
check.ts
208 lines (184 loc) · 5.95 KB
/
check.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
import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import * as kit from '@volar/kit';
import { Diagnostic, DiagnosticSeverity } from '@volar/language-server';
import fg from 'fast-glob';
import { URI } from 'vscode-uri';
import { addAstroTypes, getAstroLanguagePlugin } from './core/index.js';
import { getSvelteLanguagePlugin } from './core/svelte.js';
import { getVueLanguagePlugin } from './core/vue.js';
import { getAstroInstall } from './utils.js';
import { create as createAstroService } from './plugins/astro.js';
import { create as createTypeScriptServices } from './plugins/typescript/index.js';
// Export those for downstream consumers
export { Diagnostic, DiagnosticSeverity };
export interface CheckResult {
status: 'completed' | 'cancelled' | undefined;
fileChecked: number;
errors: number;
warnings: number;
hints: number;
fileResult: {
errors: kit.Diagnostic[];
fileUrl: URL;
fileContent: string;
text: string;
}[];
}
export class AstroCheck {
private ts!: typeof import('typescript');
public linter!: ReturnType<(typeof kit)['createTypeScriptChecker']>;
constructor(
private readonly workspacePath: string,
private readonly typescriptPath: string | undefined,
private readonly tsconfigPath: string | undefined,
) {
this.initialize();
}
/**
* Lint a list of files or the entire project and optionally log the errors found
* @param fileNames List of files to lint, if undefined, all files included in the project will be linted
* @param logErrors Whether to log errors by itself. This is disabled by default.
* @return {CheckResult} The result of the lint, including a list of errors, the file's content and its file path.
*/
public async lint({
fileNames = undefined,
cancel = () => false,
logErrors = undefined,
}: {
fileNames?: string[] | undefined;
cancel?: () => boolean;
logErrors?:
| {
level: 'error' | 'warning' | 'hint';
}
| undefined;
}): Promise<CheckResult> {
let files = (fileNames !== undefined ? fileNames : this.linter.getRootFileNames()).filter(
(file) => {
// We don't have the same understanding of Svelte and Vue files as their own respective tools (vue-tsc, svelte-check)
// So we don't want to check them here
return !file.endsWith('.vue') && !file.endsWith('.svelte');
},
);
const result: CheckResult = {
status: undefined,
fileChecked: 0,
errors: 0,
warnings: 0,
hints: 0,
fileResult: [],
};
for (const file of files) {
if (cancel()) {
result.status = 'cancelled';
return result;
}
const fileDiagnostics = await this.linter.check(file);
// Filter diagnostics based on the logErrors level
const fileDiagnosticsToPrint = fileDiagnostics.filter((diag) => {
const severity = diag.severity ?? DiagnosticSeverity.Error;
switch (logErrors?.level ?? 'hint') {
case 'error':
return severity <= DiagnosticSeverity.Error;
case 'warning':
return severity <= DiagnosticSeverity.Warning;
case 'hint':
return severity <= DiagnosticSeverity.Hint;
}
});
if (fileDiagnostics.length > 0) {
const errorText = this.linter.printErrors(file, fileDiagnosticsToPrint);
if (logErrors !== undefined && errorText) {
console.info(errorText);
}
const fileSnapshot = this.linter.language.scripts.get(URI.file(file))?.snapshot;
const fileContent = fileSnapshot?.getText(0, fileSnapshot.getLength());
result.fileResult.push({
errors: fileDiagnostics,
fileContent: fileContent ?? '',
fileUrl: pathToFileURL(file),
text: errorText,
});
result.errors += fileDiagnostics.filter(
(diag) => diag.severity === DiagnosticSeverity.Error,
).length;
result.warnings += fileDiagnostics.filter(
(diag) => diag.severity === DiagnosticSeverity.Warning,
).length;
result.hints += fileDiagnostics.filter(
(diag) => diag.severity === DiagnosticSeverity.Hint,
).length;
}
result.fileChecked += 1;
}
result.status = 'completed';
return result;
}
private initialize() {
this.ts = this.typescriptPath ? require(this.typescriptPath) : require('typescript');
const tsconfigPath = this.getTsconfig();
const languagePlugins = [
getAstroLanguagePlugin(),
getSvelteLanguagePlugin(),
getVueLanguagePlugin(),
];
const services = [...createTypeScriptServices(this.ts), createAstroService(this.ts)];
if (tsconfigPath) {
const includeProjectReference = false; // #920
this.linter = kit.createTypeScriptChecker(
languagePlugins,
services,
tsconfigPath,
includeProjectReference,
({ project }) => {
const { languageServiceHost } = project.typescript!;
const astroInstall = getAstroInstall([this.workspacePath]);
addAstroTypes(
typeof astroInstall === 'string' ? undefined : astroInstall,
this.ts,
languageServiceHost,
);
},
);
} else {
this.linter = kit.createTypeScriptInferredChecker(
languagePlugins,
services,
() => {
return fg.sync('**/*.astro', {
cwd: this.workspacePath,
ignore: ['node_modules'],
absolute: true,
});
},
undefined,
({ project }) => {
const { languageServiceHost } = project.typescript!;
const astroInstall = getAstroInstall([this.workspacePath]);
addAstroTypes(
typeof astroInstall === 'string' ? undefined : astroInstall,
this.ts,
languageServiceHost,
);
},
);
}
}
private getTsconfig() {
if (this.tsconfigPath) {
const tsconfig = resolve(this.workspacePath, this.tsconfigPath.replace(/^~/, homedir()));
if (!existsSync(tsconfig)) {
throw new Error(`Specified tsconfig file \`${tsconfig}\` does not exist.`);
}
return tsconfig;
}
const searchPath = this.workspacePath;
const tsconfig =
this.ts.findConfigFile(searchPath, this.ts.sys.fileExists) ||
this.ts.findConfigFile(searchPath, this.ts.sys.fileExists, 'jsconfig.json');
return tsconfig;
}
}