-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
getDiagnostics.ts
222 lines (195 loc) · 5.73 KB
/
getDiagnostics.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
/**
* Copyright (c) 2021 GraphQL Contributors
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {
ASTNode,
DocumentNode,
FragmentDefinitionNode,
GraphQLError,
GraphQLSchema,
Location,
SourceLocation,
ValidationRule,
print,
validate,
NoDeprecatedCustomRule,
} from 'graphql';
import { parse } from 'graphql';
import { CharacterStream, onlineParser } from '../parser';
import { Range, validateWithCustomRules, Position } from '../utils';
import { DiagnosticSeverity, Diagnostic } from 'vscode-languageserver-types';
import { IRange } from '../types';
// this doesn't work without the 'as', kinda goofy
export const SEVERITY = {
Error: 'Error',
Warning: 'Warning',
Information: 'Information',
Hint: 'Hint',
} as const;
export type Severity = typeof SEVERITY;
export type SeverityEnum = keyof Severity;
export const DIAGNOSTIC_SEVERITY = {
[SEVERITY.Error]: 1 as DiagnosticSeverity,
[SEVERITY.Warning]: 2 as DiagnosticSeverity,
[SEVERITY.Information]: 3 as DiagnosticSeverity,
[SEVERITY.Hint]: 4 as DiagnosticSeverity,
};
const invariant = (condition: any, message: string) => {
if (!condition) {
throw new Error(message);
}
};
export function getDiagnostics(
query: string,
schema: GraphQLSchema | null | undefined = null,
customRules?: Array<ValidationRule>,
isRelayCompatMode?: boolean,
externalFragments?: FragmentDefinitionNode[] | string,
): Array<Diagnostic> {
let ast = null;
if (externalFragments) {
if (typeof externalFragments === 'string') {
query += '\n\n' + externalFragments;
} else {
query +=
'\n\n' +
externalFragments.reduce((agg, node) => {
agg += print(node) + '\n\n';
return agg;
}, '');
}
}
try {
ast = parse(query);
} catch (error) {
if (error instanceof GraphQLError) {
const range = getRange(
error.locations?.[0] ?? { line: 0, column: 0 },
query,
);
return [
{
severity: DIAGNOSTIC_SEVERITY.Error as DiagnosticSeverity,
message: error.message,
source: 'GraphQL: Syntax',
range,
},
];
}
throw error;
}
return validateQuery(ast, schema, customRules, isRelayCompatMode);
}
export function validateQuery(
ast: DocumentNode,
schema: GraphQLSchema | null | undefined = null,
customRules?: Array<ValidationRule> | null,
isRelayCompatMode?: boolean,
): Array<Diagnostic> {
// We cannot validate the query unless a schema is provided.
if (!schema) {
return [];
}
const validationErrorAnnotations = validateWithCustomRules(
schema,
ast,
customRules,
isRelayCompatMode,
).flatMap(error =>
annotations(error, DIAGNOSTIC_SEVERITY.Error, 'Validation'),
);
// TODO: detect if > graphql@15.2.0, and use the new rule for this.
const deprecationWarningAnnotations = validate(schema, ast, [
NoDeprecatedCustomRule,
]).flatMap(error =>
annotations(error, DIAGNOSTIC_SEVERITY.Warning, 'Deprecation'),
);
return validationErrorAnnotations.concat(deprecationWarningAnnotations);
}
function annotations(
error: GraphQLError,
severity: DiagnosticSeverity,
type: string,
): Diagnostic[] {
if (!error.nodes) {
return [];
}
const highlightedNodes: Diagnostic[] = [];
error.nodes.forEach(node => {
const highlightNode =
node.kind !== 'Variable' && 'name' in node && node.name !== undefined
? node.name
: 'variable' in node && node.variable !== undefined
? node.variable
: node;
if (highlightNode) {
invariant(
error.locations,
'GraphQL validation error requires locations.',
);
// @ts-ignore
// https://github.com/microsoft/TypeScript/pull/32695
const loc = error.locations[0];
const highlightLoc = getLocation(highlightNode);
const end = loc.column + (highlightLoc.end - highlightLoc.start);
highlightedNodes.push({
source: `GraphQL: ${type}`,
message: error.message,
severity,
range: new Range(
new Position(loc.line - 1, loc.column - 1),
new Position(loc.line - 1, end),
),
});
}
});
return highlightedNodes;
}
export function getRange(location: SourceLocation, queryText: string): IRange {
const parser = onlineParser();
const state = parser.startState();
const lines = queryText.split('\n');
invariant(
lines.length >= location.line,
'Query text must have more lines than where the error happened',
);
let stream = null;
for (let i = 0; i < location.line; i++) {
stream = new CharacterStream(lines[i]);
while (!stream.eol()) {
const style = parser.token(stream, state);
if (style === 'invalidchar') {
break;
}
}
}
invariant(stream, 'Expected Parser stream to be available.');
const line = location.line - 1;
// @ts-ignore
// https://github.com/microsoft/TypeScript/pull/32695
const start = stream.getStartOfToken();
// @ts-ignore
// https://github.com/microsoft/TypeScript/pull/32695
const end = stream.getCurrentPosition();
return new Range(new Position(line, start), new Position(line, end));
}
/**
* Get location info from a node in a type-safe way.
*
* The only way a node could not have a location is if we initialized the parser
* (and therefore the lexer) with the `noLocation` option, but we always
* call `parse` without options above.
*/
function getLocation(node: any): Location {
const typeCastedNode = node as ASTNode;
const location = typeCastedNode.loc;
invariant(location, 'Expected ASTNode to have a location.');
// @ts-ignore
// https://github.com/microsoft/TypeScript/pull/32695
return location;
}