forked from sveltejs/language-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvelte-check.ts
222 lines (203 loc) · 8.05 KB
/
svelte-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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { isAbsolute } from 'path';
import ts from 'typescript';
import { Diagnostic, Position, Range } from 'vscode-languageserver';
import { Document, DocumentManager } from './lib/documents';
import { Logger } from './logger';
import { LSConfigManager } from './ls-config';
import {
CSSPlugin,
LSAndTSDocResolver,
PluginHost,
SveltePlugin,
TypeScriptPlugin
} from './plugins';
import { convertRange, getDiagnosticTag, mapSeverity } from './plugins/typescript/utils';
import { pathToUrl, urlToPath } from './utils';
export type SvelteCheckDiagnosticSource = 'js' | 'css' | 'svelte';
export interface SvelteCheckOptions {
compilerWarnings?: Record<string, 'ignore' | 'error'>;
diagnosticSources?: SvelteCheckDiagnosticSource[];
/**
* Path has to be absolute
*/
tsconfig?: string;
/**
* Whether or not to use the new transformation of svelte2tsx
*/
useNewTransformation?: boolean;
}
/**
* Small wrapper around PluginHost's Diagnostic Capabilities
* for svelte-check, without the overhead of the lsp.
*/
export class SvelteCheck {
private docManager = new DocumentManager(
(textDocument) => new Document(textDocument.uri, textDocument.text)
);
private configManager = new LSConfigManager();
private pluginHost = new PluginHost(this.docManager);
private lsAndTSDocResolver?: LSAndTSDocResolver;
constructor(workspacePath: string, private options: SvelteCheckOptions = {}) {
Logger.setLogErrorsOnly(true);
this.initialize(workspacePath, options);
}
private async initialize(workspacePath: string, options: SvelteCheckOptions) {
if (options.tsconfig && !isAbsolute(options.tsconfig)) {
throw new Error('tsconfigPath needs to be absolute, got ' + options.tsconfig);
}
this.configManager.update({
svelte: {
compilerWarnings: options.compilerWarnings,
useNewTransformation: options.useNewTransformation ?? false
}
});
// No HTMLPlugin, it does not provide diagnostics
if (shouldRegister('svelte')) {
this.pluginHost.register(new SveltePlugin(this.configManager));
}
if (shouldRegister('css')) {
this.pluginHost.register(new CSSPlugin(this.docManager, this.configManager));
}
if (shouldRegister('js') || options.tsconfig) {
this.lsAndTSDocResolver = new LSAndTSDocResolver(
this.docManager,
[pathToUrl(workspacePath)],
this.configManager,
undefined,
true,
options.tsconfig
);
this.pluginHost.register(
new TypeScriptPlugin(this.configManager, this.lsAndTSDocResolver)
);
}
function shouldRegister(source: SvelteCheckDiagnosticSource) {
return !options.diagnosticSources || options.diagnosticSources.includes(source);
}
}
/**
* Creates/updates given document
*
* @param doc Text and Uri of the document
* @param isNew Whether or not this is the creation of the document
*/
async upsertDocument(doc: { text: string; uri: string }, isNew: boolean): Promise<void> {
const filePath = urlToPath(doc.uri) || '';
if (isNew && this.options.tsconfig) {
const lsContainer = await this.getLSContainer(this.options.tsconfig);
if (!lsContainer.fileBelongsToProject(filePath)) {
return;
}
}
if (doc.uri.endsWith('.ts') || doc.uri.endsWith('.js')) {
this.pluginHost.updateTsOrJsFile(filePath, [
{
range: Range.create(
Position.create(0, 0),
Position.create(Number.MAX_VALUE, Number.MAX_VALUE)
),
text: doc.text
}
]);
} else {
this.docManager.openDocument({
text: doc.text,
uri: doc.uri
});
this.docManager.markAsOpenedInClient(doc.uri);
}
}
/**
* Removes/closes document
*
* @param uri Uri of the document
*/
async removeDocument(uri: string): Promise<void> {
if (!this.docManager.get(uri)) {
return;
}
this.docManager.closeDocument(uri);
this.docManager.releaseDocument(uri);
if (this.options.tsconfig) {
const lsContainer = await this.getLSContainer(this.options.tsconfig);
lsContainer.deleteSnapshot(urlToPath(uri) || '');
}
}
/**
* Gets the diagnostics for all currently open files.
*/
async getDiagnostics(): Promise<
Array<{ filePath: string; text: string; diagnostics: Diagnostic[] }>
> {
if (this.options.tsconfig) {
return this.getDiagnosticsForTsconfig(this.options.tsconfig);
}
return await Promise.all(
this.docManager.getAllOpenedByClient().map(async (doc) => {
const uri = doc[1].uri;
return await this.getDiagnosticsForFile(uri);
})
);
}
private async getDiagnosticsForTsconfig(tsconfigPath: string) {
const lsContainer = await this.getLSContainer(tsconfigPath);
const lang = lsContainer.getService();
const files = lang.getProgram()?.getSourceFiles() || [];
const options = lang.getProgram()?.getCompilerOptions() || {};
return await Promise.all(
files.map((file) => {
const uri = pathToUrl(file.fileName);
const doc = this.docManager.get(uri);
if (doc) {
this.docManager.markAsOpenedInClient(uri);
return this.getDiagnosticsForFile(uri);
} else {
// This check is done inside TS mostly, too, but for some diagnostics like suggestions it
// doesn't apply to all code paths. That's why we do it here, too.
const skipDiagnosticsForFile =
(options.skipLibCheck && file.isDeclarationFile) ||
(options.skipDefaultLibCheck && file.hasNoDefaultLib);
const diagnostics = skipDiagnosticsForFile
? []
: [
...lang.getSyntacticDiagnostics(file.fileName),
...lang.getSuggestionDiagnostics(file.fileName),
...lang.getSemanticDiagnostics(file.fileName)
].map<Diagnostic>((diagnostic) => ({
range: convertRange(
{ positionAt: file.getLineAndCharacterOfPosition.bind(file) },
diagnostic
),
severity: mapSeverity(diagnostic.category),
source: diagnostic.source,
message: ts.flattenDiagnosticMessageText(
diagnostic.messageText,
'\n'
),
code: diagnostic.code,
tags: getDiagnosticTag(diagnostic)
}));
return {
filePath: file.fileName,
text: file.text,
diagnostics
};
}
})
);
}
private async getDiagnosticsForFile(uri: string) {
const diagnostics = await this.pluginHost.getDiagnostics({ uri });
return {
filePath: urlToPath(uri) || '',
text: this.docManager.get(uri)?.getText() || '',
diagnostics
};
}
private getLSContainer(tsconfigPath: string) {
if (!this.lsAndTSDocResolver) {
throw new Error('Cannot run with tsconfig path without LS/TSdoc resolver');
}
return this.lsAndTSDocResolver.getTSService(tsconfigPath);
}
}