/
utils.ts
347 lines (315 loc) · 11.9 KB
/
utils.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import { dirname } from 'path';
import ts from 'typescript';
import {
CompletionItemKind,
DiagnosticSeverity,
DiagnosticTag,
Position,
Range,
SymbolKind
} from 'vscode-languageserver';
import { Document, isInTag, mapRangeToOriginal } from '../../lib/documents';
import { pathToUrl } from '../../utils';
import { DocumentSnapshot, SvelteDocumentSnapshot } from './DocumentSnapshot';
export function getScriptKindFromFileName(fileName: string): ts.ScriptKind {
const ext = fileName.substr(fileName.lastIndexOf('.'));
switch (ext.toLowerCase()) {
case ts.Extension.Js:
return ts.ScriptKind.JS;
case ts.Extension.Jsx:
return ts.ScriptKind.JSX;
case ts.Extension.Ts:
return ts.ScriptKind.TS;
case ts.Extension.Tsx:
return ts.ScriptKind.TSX;
case ts.Extension.Json:
return ts.ScriptKind.JSON;
default:
return ts.ScriptKind.Unknown;
}
}
export function getExtensionFromScriptKind(kind: ts.ScriptKind | undefined): ts.Extension {
switch (kind) {
case ts.ScriptKind.JSX:
return ts.Extension.Jsx;
case ts.ScriptKind.TS:
return ts.Extension.Ts;
case ts.ScriptKind.TSX:
return ts.Extension.Tsx;
case ts.ScriptKind.JSON:
return ts.Extension.Json;
case ts.ScriptKind.JS:
default:
return ts.Extension.Js;
}
}
export function getScriptKindFromAttributes(
attrs: Record<string, string>
): ts.ScriptKind.TSX | ts.ScriptKind.JSX {
const type = attrs.lang || attrs.type;
switch (type) {
case 'ts':
case 'typescript':
case 'text/ts':
case 'text/typescript':
return ts.ScriptKind.TSX;
case 'javascript':
case 'text/javascript':
default:
return ts.ScriptKind.JSX;
}
}
export function isSvelteFilePath(filePath: string) {
return filePath.endsWith('.svelte');
}
export function isVirtualSvelteFilePath(filePath: string) {
return filePath.endsWith('.svelte.ts');
}
export function toRealSvelteFilePath(filePath: string) {
return filePath.slice(0, -'.ts'.length);
}
export function toVirtualSvelteFilePath(filePath: string) {
return filePath.endsWith('.ts') ? filePath : filePath + '.ts';
}
export function ensureRealSvelteFilePath(filePath: string) {
return isVirtualSvelteFilePath(filePath) ? toRealSvelteFilePath(filePath) : filePath;
}
export function convertRange(
document: { positionAt: (offset: number) => Position },
range: { start?: number; length?: number }
): Range {
return Range.create(
document.positionAt(range.start || 0),
document.positionAt((range.start || 0) + (range.length || 0))
);
}
export function convertToLocationRange(snapshot: DocumentSnapshot, textSpan: ts.TextSpan): Range {
const range = mapRangeToOriginal(snapshot, convertRange(snapshot, textSpan));
// Some definition like the svelte component class definition don't exist in the original, so we map to 0,1
if (range.start.line < 0) {
range.start.line = 0;
range.start.character = 1;
}
if (range.end.line < 0) {
range.end = range.start;
}
return range;
}
export function hasNonZeroRange({ range }: { range?: Range }): boolean {
return (
!!range &&
(range.start.line !== range.end.line || range.start.character !== range.end.character)
);
}
export function rangeToTextSpan(
range: Range,
document: { offsetAt: (position: Position) => number }
): ts.TextSpan {
const start = document.offsetAt(range.start);
const end = document.offsetAt(range.end);
return { start, length: end - start };
}
export function findTsConfigPath(fileName: string, rootUris: string[]) {
const searchDir = dirname(fileName);
const path =
ts.findConfigFile(searchDir, ts.sys.fileExists, 'tsconfig.json') ||
ts.findConfigFile(searchDir, ts.sys.fileExists, 'jsconfig.json') ||
'';
// Don't return config files that exceed the current workspace context.
return !!path && rootUris.some((rootUri) => isSubPath(rootUri, path)) ? path : '';
}
export function isSubPath(uri: string, possibleSubPath: string): boolean {
return pathToUrl(possibleSubPath).startsWith(uri);
}
export function symbolKindFromString(kind: string): SymbolKind {
switch (kind) {
case 'module':
return SymbolKind.Module;
case 'class':
return SymbolKind.Class;
case 'local class':
return SymbolKind.Class;
case 'interface':
return SymbolKind.Interface;
case 'enum':
return SymbolKind.Enum;
case 'enum member':
return SymbolKind.Constant;
case 'var':
return SymbolKind.Variable;
case 'local var':
return SymbolKind.Variable;
case 'function':
return SymbolKind.Function;
case 'local function':
return SymbolKind.Function;
case 'method':
return SymbolKind.Method;
case 'getter':
return SymbolKind.Method;
case 'setter':
return SymbolKind.Method;
case 'property':
return SymbolKind.Property;
case 'constructor':
return SymbolKind.Constructor;
case 'parameter':
return SymbolKind.Variable;
case 'type parameter':
return SymbolKind.Variable;
case 'alias':
return SymbolKind.Variable;
case 'let':
return SymbolKind.Variable;
case 'const':
return SymbolKind.Constant;
case 'JSX attribute':
return SymbolKind.Property;
default:
return SymbolKind.Variable;
}
}
export function scriptElementKindToCompletionItemKind(
kind: ts.ScriptElementKind
): CompletionItemKind {
switch (kind) {
case ts.ScriptElementKind.primitiveType:
case ts.ScriptElementKind.keyword:
return CompletionItemKind.Keyword;
case ts.ScriptElementKind.constElement:
return CompletionItemKind.Constant;
case ts.ScriptElementKind.letElement:
case ts.ScriptElementKind.variableElement:
case ts.ScriptElementKind.localVariableElement:
case ts.ScriptElementKind.alias:
return CompletionItemKind.Variable;
case ts.ScriptElementKind.memberVariableElement:
case ts.ScriptElementKind.memberGetAccessorElement:
case ts.ScriptElementKind.memberSetAccessorElement:
return CompletionItemKind.Field;
case ts.ScriptElementKind.functionElement:
return CompletionItemKind.Function;
case ts.ScriptElementKind.memberFunctionElement:
case ts.ScriptElementKind.constructSignatureElement:
case ts.ScriptElementKind.callSignatureElement:
case ts.ScriptElementKind.indexSignatureElement:
return CompletionItemKind.Method;
case ts.ScriptElementKind.enumElement:
return CompletionItemKind.Enum;
case ts.ScriptElementKind.moduleElement:
case ts.ScriptElementKind.externalModuleName:
return CompletionItemKind.Module;
case ts.ScriptElementKind.classElement:
case ts.ScriptElementKind.typeElement:
return CompletionItemKind.Class;
case ts.ScriptElementKind.interfaceElement:
return CompletionItemKind.Interface;
case ts.ScriptElementKind.warning:
case ts.ScriptElementKind.scriptElement:
return CompletionItemKind.File;
case ts.ScriptElementKind.directory:
return CompletionItemKind.Folder;
case ts.ScriptElementKind.string:
return CompletionItemKind.Constant;
}
return CompletionItemKind.Property;
}
export function getCommitCharactersForScriptElement(
kind: ts.ScriptElementKind
): string[] | undefined {
const commitCharacters: string[] = [];
switch (kind) {
case ts.ScriptElementKind.memberGetAccessorElement:
case ts.ScriptElementKind.memberSetAccessorElement:
case ts.ScriptElementKind.constructSignatureElement:
case ts.ScriptElementKind.callSignatureElement:
case ts.ScriptElementKind.indexSignatureElement:
case ts.ScriptElementKind.enumElement:
case ts.ScriptElementKind.interfaceElement:
commitCharacters.push('.');
break;
case ts.ScriptElementKind.moduleElement:
case ts.ScriptElementKind.alias:
case ts.ScriptElementKind.constElement:
case ts.ScriptElementKind.letElement:
case ts.ScriptElementKind.variableElement:
case ts.ScriptElementKind.localVariableElement:
case ts.ScriptElementKind.memberVariableElement:
case ts.ScriptElementKind.classElement:
case ts.ScriptElementKind.functionElement:
case ts.ScriptElementKind.memberFunctionElement:
commitCharacters.push('.', ',');
commitCharacters.push('(');
break;
}
return commitCharacters.length === 0 ? undefined : commitCharacters;
}
export function mapSeverity(category: ts.DiagnosticCategory): DiagnosticSeverity {
switch (category) {
case ts.DiagnosticCategory.Error:
return DiagnosticSeverity.Error;
case ts.DiagnosticCategory.Warning:
return DiagnosticSeverity.Warning;
case ts.DiagnosticCategory.Suggestion:
return DiagnosticSeverity.Hint;
case ts.DiagnosticCategory.Message:
return DiagnosticSeverity.Information;
}
return DiagnosticSeverity.Error;
}
// Matches comments that come before any non-comment content
const commentsRegex = /^(\s*\/\/.*\s*)*/;
// The following regex matches @ts-check or @ts-nocheck if:
// - must be @ts-(no)check
// - the comment which has @ts-(no)check can have any type of whitespace before it, but not other characters
// - what's coming after @ts-(no)check is irrelevant as long there is any kind of whitespace or line break, so this would be picked up, too: // @ts-check asdasd
// [ \t\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
// is just \s (a.k.a any whitespace character) without linebreak and vertical tab
// eslint-disable-next-line max-len
const tsCheckRegex =
/\/\/[ \t\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*(@ts-(no)?check)($|\s)/;
/**
* Returns `// @ts-check` or `// @ts-nocheck` if content starts with comments and has one of these
* in its comments.
*/
export function getTsCheckComment(str = ''): string | undefined {
const comments = str.match(commentsRegex)?.[0];
if (comments) {
const tsCheck = comments.match(tsCheckRegex);
if (tsCheck) {
// second-last entry is the capturing group with the exact ts-check wording
return `// ${tsCheck[tsCheck.length - 3]}${ts.sys.newLine}`;
}
}
}
export function convertToTextSpan(range: Range, snapshot: DocumentSnapshot): ts.TextSpan {
const start = snapshot.offsetAt(snapshot.getGeneratedPosition(range.start));
const end = snapshot.offsetAt(snapshot.getGeneratedPosition(range.end));
return {
start,
length: end - start
};
}
export function isInScript(position: Position, snapshot: SvelteDocumentSnapshot | Document) {
return isInTag(position, snapshot.scriptInfo) || isInTag(position, snapshot.moduleScriptInfo);
}
export function getDiagnosticTag(diagnostic: ts.Diagnostic): DiagnosticTag[] {
const tags: DiagnosticTag[] = [];
if (diagnostic.reportsUnnecessary) {
tags.push(DiagnosticTag.Unnecessary);
}
if (diagnostic.reportsDeprecated) {
tags.push(DiagnosticTag.Deprecated);
}
return tags;
}
export function changeSvelteComponentName(name: string) {
return name.replace(/(\w+)__SvelteComponent_/, '$1');
}
export function hasTsExtensions(fileName: string) {
return (
fileName.endsWith(ts.Extension.Dts) ||
fileName.endsWith(ts.Extension.Tsx) ||
fileName.endsWith(ts.Extension.Ts)
);
}