vscode-apollo 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/.circleci/config.yml +1 -1
  2. package/.vscode/launch.json +4 -1
  3. package/CHANGELOG.md +27 -0
  4. package/package.json +9 -3
  5. package/renovate.json +2 -1
  6. package/sampleWorkspace/localSchema/src/test.js +3 -0
  7. package/sampleWorkspace/rover/apollo.config.js +3 -0
  8. package/sampleWorkspace/rover/src/test.graphql +14 -0
  9. package/sampleWorkspace/rover/src/test.js +30 -0
  10. package/sampleWorkspace/sampleWorkspace.code-workspace +25 -19
  11. package/src/language-server/__tests__/document.test.ts +161 -3
  12. package/src/language-server/__tests__/fixtures/TypeScript.tmLanguage.json +5749 -0
  13. package/src/language-server/__tests__/fixtures/documents/commentWithTemplate.ts +41 -0
  14. package/src/language-server/__tests__/fixtures/documents/commentWithTemplate.ts.snap +185 -0
  15. package/src/language-server/__tests__/fixtures/documents/functionCall.ts +93 -0
  16. package/src/language-server/__tests__/fixtures/documents/functionCall.ts.snap +431 -0
  17. package/src/language-server/__tests__/fixtures/documents/taggedTemplate.ts +80 -0
  18. package/src/language-server/__tests__/fixtures/documents/taggedTemplate.ts.snap +353 -0
  19. package/src/language-server/__tests__/fixtures/documents/templateWithComment.ts +38 -0
  20. package/src/language-server/__tests__/fixtures/documents/templateWithComment.ts.snap +123 -0
  21. package/src/language-server/config/__tests__/loadConfig.ts +19 -10
  22. package/src/language-server/config/config.ts +26 -1
  23. package/src/language-server/config/which.d.ts +19 -0
  24. package/src/language-server/document.ts +86 -53
  25. package/src/language-server/fileSet.ts +7 -0
  26. package/src/language-server/project/base.ts +58 -316
  27. package/src/language-server/project/client.ts +730 -7
  28. package/src/language-server/project/internal.ts +349 -0
  29. package/src/language-server/project/rover/DocumentSynchronization.ts +308 -0
  30. package/src/language-server/project/rover/__tests__/DocumentSynchronization.test.ts +302 -0
  31. package/src/language-server/project/rover/project.ts +276 -0
  32. package/src/language-server/server.ts +129 -62
  33. package/src/language-server/utilities/__tests__/source.test.ts +162 -0
  34. package/src/language-server/utilities/source.ts +38 -3
  35. package/src/language-server/workspace.ts +34 -9
  36. package/syntaxes/graphql.js.json +18 -21
  37. package/src/language-server/languageProvider.ts +0 -795
@@ -1,795 +0,0 @@
1
- import {
2
- CancellationToken,
3
- Position,
4
- Location,
5
- Range,
6
- CompletionItem,
7
- Hover,
8
- Definition,
9
- CodeLens,
10
- ReferenceContext,
11
- InsertTextFormat,
12
- DocumentSymbol,
13
- SymbolKind,
14
- SymbolInformation,
15
- CodeAction,
16
- CodeActionKind,
17
- MarkupKind,
18
- CompletionItemKind,
19
- } from "vscode-languageserver/node";
20
-
21
- // should eventually be moved into this package, since we're overriding a lot of the existing behavior here
22
- import { getAutocompleteSuggestions } from "graphql-language-service";
23
- import { Position as GraphQlPosition } from "graphql-language-service";
24
- import { getTokenAtPosition, getTypeInfo } from "graphql-language-service";
25
- import type { GraphQLWorkspace } from "./workspace";
26
- import type { DocumentUri } from "./project/base";
27
-
28
- import {
29
- positionFromPositionInContainingDocument,
30
- rangeForASTNode,
31
- getASTNodeAndTypeInfoAtPosition,
32
- positionToOffset,
33
- } from "./utilities/source";
34
-
35
- import {
36
- GraphQLNamedType,
37
- Kind,
38
- GraphQLField,
39
- GraphQLNonNull,
40
- isAbstractType,
41
- TypeNameMetaFieldDef,
42
- SchemaMetaFieldDef,
43
- TypeMetaFieldDef,
44
- typeFromAST,
45
- GraphQLType,
46
- isObjectType,
47
- isListType,
48
- GraphQLList,
49
- isNonNullType,
50
- ASTNode,
51
- FieldDefinitionNode,
52
- visit,
53
- isExecutableDefinitionNode,
54
- isTypeSystemDefinitionNode,
55
- isTypeSystemExtensionNode,
56
- GraphQLError,
57
- DirectiveLocation,
58
- } from "graphql";
59
- import { highlightNodeForNode } from "./utilities/graphql";
60
-
61
- import { GraphQLClientProject, isClientProject } from "./project/client";
62
- import { isNotNullOrUndefined } from "../tools";
63
- import type { CodeActionInfo } from "./errors/validation";
64
- import { GraphQLDiagnostic } from "./diagnostics";
65
- import type { ProjectStats } from "../messages";
66
- import { isInterfaceType } from "graphql";
67
-
68
- const DirectiveLocations = Object.keys(DirectiveLocation);
69
-
70
- function hasFields(type: GraphQLType): boolean {
71
- return (
72
- isObjectType(type) ||
73
- (isListType(type) && hasFields((type as GraphQLList<any>).ofType)) ||
74
- (isNonNullType(type) && hasFields((type as GraphQLNonNull<any>).ofType))
75
- );
76
- }
77
-
78
- function uriForASTNode(node: ASTNode): DocumentUri | null {
79
- const uri = node.loc && node.loc.source && node.loc.source.name;
80
- if (!uri || uri === "GraphQL") {
81
- return null;
82
- }
83
- return uri;
84
- }
85
-
86
- function locationForASTNode(node: ASTNode): Location | null {
87
- const uri = uriForASTNode(node);
88
- if (!uri) return null;
89
- return Location.create(uri, rangeForASTNode(node));
90
- }
91
-
92
- function symbolForFieldDefinition(
93
- definition: FieldDefinitionNode,
94
- ): DocumentSymbol {
95
- return {
96
- name: definition.name.value,
97
- kind: SymbolKind.Field,
98
- range: rangeForASTNode(definition),
99
- selectionRange: rangeForASTNode(definition),
100
- };
101
- }
102
-
103
- export class GraphQLLanguageProvider {
104
- constructor(public workspace: GraphQLWorkspace) {}
105
-
106
- async provideStats(uri?: DocumentUri): Promise<ProjectStats> {
107
- if (this.workspace.projects.length && uri) {
108
- const project = this.workspace.projectForFile(uri);
109
- return project ? project.getProjectStats() : { loaded: false };
110
- }
111
-
112
- return { loaded: false };
113
- }
114
-
115
- async provideCompletionItems(
116
- uri: DocumentUri,
117
- position: Position,
118
- _token: CancellationToken,
119
- ): Promise<CompletionItem[]> {
120
- const project = this.workspace.projectForFile(uri);
121
- if (!(project && project instanceof GraphQLClientProject)) return [];
122
-
123
- const document = project.documentAt(uri, position);
124
- if (!document) return [];
125
-
126
- if (!project.schema) return [];
127
-
128
- const rawPositionInDocument = positionFromPositionInContainingDocument(
129
- document.source,
130
- position,
131
- );
132
- const positionInDocument = new GraphQlPosition(
133
- rawPositionInDocument.line,
134
- rawPositionInDocument.character,
135
- );
136
-
137
- const token = getTokenAtPosition(document.source.body, positionInDocument);
138
- const state =
139
- token.state.kind === "Invalid" ? token.state.prevState : token.state;
140
- const typeInfo = getTypeInfo(project.schema, token.state);
141
-
142
- if (state?.kind === "DirectiveDef") {
143
- return DirectiveLocations.map((location) => ({
144
- label: location,
145
- kind: CompletionItemKind.Constant,
146
- }));
147
- }
148
-
149
- const suggestions = getAutocompleteSuggestions(
150
- project.schema,
151
- document.source.body,
152
- positionInDocument,
153
- );
154
-
155
- if (
156
- state?.kind === "SelectionSet" ||
157
- state?.kind === "Field" ||
158
- state?.kind === "AliasedField"
159
- ) {
160
- const parentType = typeInfo.parentType;
161
- const parentFields =
162
- isInterfaceType(parentType) || isObjectType(parentType)
163
- ? parentType.getFields()
164
- : {};
165
-
166
- if (isAbstractType(parentType)) {
167
- parentFields[TypeNameMetaFieldDef.name] = TypeNameMetaFieldDef;
168
- }
169
-
170
- if (parentType === project.schema.getQueryType()) {
171
- parentFields[SchemaMetaFieldDef.name] = SchemaMetaFieldDef;
172
- parentFields[TypeMetaFieldDef.name] = TypeMetaFieldDef;
173
- }
174
-
175
- return suggestions.map((suggest) => {
176
- // when code completing fields, expand out required variables and open braces
177
- const suggestedField = parentFields[suggest.label] as GraphQLField<
178
- void,
179
- void
180
- >;
181
- if (!suggestedField) {
182
- return suggest;
183
- } else {
184
- const requiredArgs = suggestedField.args.filter((a) =>
185
- isNonNullType(a.type),
186
- );
187
- const paramsSection =
188
- requiredArgs.length > 0
189
- ? `(${requiredArgs
190
- .map((a, i) => `${a.name}: $${i + 1}`)
191
- .join(", ")})`
192
- : ``;
193
-
194
- const isClientType =
195
- parentType &&
196
- "clientSchema" in parentType &&
197
- parentType.clientSchema?.localFields?.includes(suggestedField.name);
198
- const directives = isClientType ? " @client" : "";
199
-
200
- const snippet = hasFields(suggestedField.type)
201
- ? `${suggest.label}${paramsSection}${directives} {\n\t$0\n}`
202
- : `${suggest.label}${paramsSection}${directives}`;
203
-
204
- return {
205
- ...suggest,
206
- insertText: snippet,
207
- insertTextFormat: InsertTextFormat.Snippet,
208
- };
209
- }
210
- });
211
- }
212
-
213
- if (state?.kind === "Directive") {
214
- return suggestions.map((suggest) => {
215
- const directive = project.schema!.getDirective(suggest.label);
216
- if (!directive) {
217
- return suggest;
218
- }
219
-
220
- const requiredArgs = directive.args.filter(isNonNullType);
221
- const paramsSection =
222
- requiredArgs.length > 0
223
- ? `(${requiredArgs
224
- .map((a, i) => `${a.name}: $${i + 1}`)
225
- .join(", ")})`
226
- : ``;
227
-
228
- const snippet = `${suggest.label}${paramsSection}`;
229
-
230
- const argsString =
231
- directive.args.length > 0
232
- ? `(${directive.args
233
- .map((a) => `${a.name}: ${a.type}`)
234
- .join(", ")})`
235
- : "";
236
-
237
- const content = [
238
- [`\`\`\`graphql`, `@${suggest.label}${argsString}`, `\`\`\``].join(
239
- "\n",
240
- ),
241
- ];
242
-
243
- if (suggest.documentation) {
244
- if (typeof suggest.documentation === "string") {
245
- content.push(suggest.documentation);
246
- } else {
247
- // TODO (jason) `(string | MarkupContent) & (string | null)` is a weird type,
248
- // leaving this for safety for now
249
- content.push((suggest.documentation as any).value);
250
- }
251
- }
252
-
253
- const doc = {
254
- kind: MarkupKind.Markdown,
255
- value: content.join("\n\n"),
256
- };
257
-
258
- return {
259
- ...suggest,
260
- documentation: doc,
261
- insertText: snippet,
262
- insertTextFormat: InsertTextFormat.Snippet,
263
- };
264
- });
265
- }
266
-
267
- return suggestions;
268
- }
269
-
270
- async provideHover(
271
- uri: DocumentUri,
272
- position: Position,
273
- _token: CancellationToken,
274
- ): Promise<Hover | null> {
275
- const project = this.workspace.projectForFile(uri);
276
- if (!(project && project instanceof GraphQLClientProject)) return null;
277
-
278
- const document = project.documentAt(uri, position);
279
- if (!(document && document.ast)) return null;
280
-
281
- if (!project.schema) return null;
282
-
283
- const positionInDocument = positionFromPositionInContainingDocument(
284
- document.source,
285
- position,
286
- );
287
-
288
- const nodeAndTypeInfo = getASTNodeAndTypeInfoAtPosition(
289
- document.source,
290
- positionInDocument,
291
- document.ast,
292
- project.schema,
293
- );
294
-
295
- if (nodeAndTypeInfo) {
296
- const [node, typeInfo] = nodeAndTypeInfo;
297
-
298
- switch (node.kind) {
299
- case Kind.FRAGMENT_SPREAD: {
300
- const fragmentName = node.name.value;
301
- const fragment = project.fragments[fragmentName];
302
- if (fragment) {
303
- return {
304
- contents: {
305
- language: "graphql",
306
- value: `fragment ${fragmentName} on ${fragment.typeCondition.name.value}`,
307
- },
308
- };
309
- }
310
- break;
311
- }
312
-
313
- case Kind.FIELD: {
314
- const parentType = typeInfo.getParentType();
315
- const fieldDef = typeInfo.getFieldDef();
316
-
317
- if (parentType && fieldDef) {
318
- const argsString =
319
- fieldDef.args.length > 0
320
- ? `(${fieldDef.args
321
- .map((a) => `${a.name}: ${a.type}`)
322
- .join(", ")})`
323
- : "";
324
- const isClientType =
325
- parentType.clientSchema &&
326
- parentType.clientSchema.localFields &&
327
- parentType.clientSchema.localFields.includes(fieldDef.name);
328
-
329
- const isResolvedLocally =
330
- node.directives &&
331
- node.directives.some(
332
- (directive) => directive.name.value === "client",
333
- );
334
-
335
- const content = [
336
- [
337
- `\`\`\`graphql`,
338
- `${parentType}.${fieldDef.name}${argsString}: ${fieldDef.type}`,
339
- `\`\`\``,
340
- ].join("\n"),
341
- ];
342
-
343
- const info: string[] = [];
344
- if (isClientType) {
345
- info.push("`Client-Only Field`");
346
- }
347
- if (isResolvedLocally) {
348
- info.push("`Resolved locally`");
349
- }
350
-
351
- if (info.length !== 0) {
352
- content.push(info.join(" "));
353
- }
354
-
355
- if (fieldDef.description) {
356
- content.push(fieldDef.description);
357
- }
358
-
359
- return {
360
- contents: content.join("\n\n---\n\n"),
361
- range: rangeForASTNode(highlightNodeForNode(node)),
362
- };
363
- }
364
-
365
- break;
366
- }
367
-
368
- case Kind.NAMED_TYPE: {
369
- const type = project.schema.getType(
370
- node.name.value,
371
- ) as GraphQLNamedType | void;
372
- if (!type) break;
373
-
374
- const content = [[`\`\`\`graphql`, `${type}`, `\`\`\``].join("\n")];
375
-
376
- if (type.description) {
377
- content.push(type.description);
378
- }
379
-
380
- return {
381
- contents: content.join("\n\n---\n\n"),
382
- range: rangeForASTNode(highlightNodeForNode(node)),
383
- };
384
- }
385
-
386
- case Kind.ARGUMENT: {
387
- const argumentNode = typeInfo.getArgument()!;
388
- const content = [
389
- [
390
- `\`\`\`graphql`,
391
- `${argumentNode.name}: ${argumentNode.type}`,
392
- `\`\`\``,
393
- ].join("\n"),
394
- ];
395
- if (argumentNode.description) {
396
- content.push(argumentNode.description);
397
- }
398
- return {
399
- contents: content.join("\n\n---\n\n"),
400
- range: rangeForASTNode(highlightNodeForNode(node)),
401
- };
402
- }
403
-
404
- case Kind.DIRECTIVE: {
405
- const directiveNode = typeInfo.getDirective();
406
- if (!directiveNode) break;
407
- const argsString =
408
- directiveNode.args.length > 0
409
- ? `(${directiveNode.args
410
- .map((a) => `${a.name}: ${a.type}`)
411
- .join(", ")})`
412
- : "";
413
- const content = [
414
- [
415
- `\`\`\`graphql`,
416
- `@${directiveNode.name}${argsString}`,
417
- `\`\`\``,
418
- ].join("\n"),
419
- ];
420
- if (directiveNode.description) {
421
- content.push(directiveNode.description);
422
- }
423
- return {
424
- contents: content.join("\n\n---\n\n"),
425
- range: rangeForASTNode(highlightNodeForNode(node)),
426
- };
427
- }
428
- }
429
- }
430
- return null;
431
- }
432
-
433
- async provideDefinition(
434
- uri: DocumentUri,
435
- position: Position,
436
- _token: CancellationToken,
437
- ): Promise<Definition | null> {
438
- const project = this.workspace.projectForFile(uri);
439
- if (!(project && project instanceof GraphQLClientProject)) return null;
440
-
441
- const document = project.documentAt(uri, position);
442
- if (!(document && document.ast)) return null;
443
-
444
- if (!project.schema) return null;
445
-
446
- const positionInDocument = positionFromPositionInContainingDocument(
447
- document.source,
448
- position,
449
- );
450
-
451
- const nodeAndTypeInfo = getASTNodeAndTypeInfoAtPosition(
452
- document.source,
453
- positionInDocument,
454
- document.ast,
455
- project.schema,
456
- );
457
-
458
- if (nodeAndTypeInfo) {
459
- const [node, typeInfo] = nodeAndTypeInfo;
460
-
461
- switch (node.kind) {
462
- case Kind.FRAGMENT_SPREAD: {
463
- const fragmentName = node.name.value;
464
- const fragment = project.fragments[fragmentName];
465
- if (fragment && fragment.loc) {
466
- return locationForASTNode(fragment);
467
- }
468
- break;
469
- }
470
- case Kind.FIELD: {
471
- const fieldDef = typeInfo.getFieldDef();
472
-
473
- if (!(fieldDef && fieldDef.astNode && fieldDef.astNode.loc)) break;
474
-
475
- return locationForASTNode(fieldDef.astNode);
476
- }
477
- case Kind.NAMED_TYPE: {
478
- const type = typeFromAST(project.schema, node);
479
-
480
- if (!(type && type.astNode && type.astNode.loc)) break;
481
-
482
- return locationForASTNode(type.astNode);
483
- }
484
- case Kind.DIRECTIVE: {
485
- const directive = project.schema.getDirective(node.name.value);
486
-
487
- if (!(directive && directive.astNode && directive.astNode.loc)) break;
488
-
489
- return locationForASTNode(directive.astNode);
490
- }
491
- }
492
- }
493
- return null;
494
- }
495
-
496
- async provideReferences(
497
- uri: DocumentUri,
498
- position: Position,
499
- _context: ReferenceContext,
500
- _token: CancellationToken,
501
- ): Promise<Location[] | null> {
502
- const project = this.workspace.projectForFile(uri);
503
- if (!project) return null;
504
- const document = project.documentAt(uri, position);
505
- if (!(document && document.ast)) return null;
506
-
507
- if (!project.schema) return null;
508
-
509
- const positionInDocument = positionFromPositionInContainingDocument(
510
- document.source,
511
- position,
512
- );
513
-
514
- const nodeAndTypeInfo = getASTNodeAndTypeInfoAtPosition(
515
- document.source,
516
- positionInDocument,
517
- document.ast,
518
- project.schema,
519
- );
520
-
521
- if (nodeAndTypeInfo) {
522
- const [node, typeInfo] = nodeAndTypeInfo;
523
-
524
- switch (node.kind) {
525
- case Kind.FRAGMENT_DEFINITION: {
526
- if (!isClientProject(project)) return null;
527
- const fragmentName = node.name.value;
528
- return project
529
- .fragmentSpreadsForFragment(fragmentName)
530
- .map((fragmentSpread) => locationForASTNode(fragmentSpread))
531
- .filter(isNotNullOrUndefined);
532
- }
533
- // TODO(jbaxleyiii): manage no parent type references (unions + scalars)
534
- // TODO(jbaxleyiii): support more than fields
535
- case Kind.FIELD_DEFINITION: {
536
- // case Kind.ENUM_VALUE_DEFINITION:
537
- // case Kind.INPUT_OBJECT_TYPE_DEFINITION:
538
- // case Kind.INPUT_OBJECT_TYPE_EXTENSION: {
539
- if (!isClientProject(project)) return null;
540
- const offset = positionToOffset(document.source, positionInDocument);
541
- // withWithTypeInfo doesn't suppport SDL so we instead
542
- // write our own visitor methods here to collect the fields that we
543
- // care about
544
- let parent: ASTNode | null = null;
545
- visit(document.ast, {
546
- enter(node: ASTNode) {
547
- // the parent types we care about
548
- if (
549
- node.loc &&
550
- node.loc.start <= offset &&
551
- offset <= node.loc.end &&
552
- (node.kind === Kind.OBJECT_TYPE_DEFINITION ||
553
- node.kind === Kind.OBJECT_TYPE_EXTENSION ||
554
- node.kind === Kind.INTERFACE_TYPE_DEFINITION ||
555
- node.kind === Kind.INTERFACE_TYPE_EXTENSION ||
556
- node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ||
557
- node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION ||
558
- node.kind === Kind.ENUM_TYPE_DEFINITION ||
559
- node.kind === Kind.ENUM_TYPE_EXTENSION)
560
- ) {
561
- parent = node;
562
- }
563
- return;
564
- },
565
- });
566
- return project
567
- .getOperationFieldsFromFieldDefinition(node.name.value, parent)
568
- .map((fieldNode) => locationForASTNode(fieldNode))
569
- .filter(isNotNullOrUndefined);
570
- }
571
- }
572
- }
573
-
574
- return null;
575
- }
576
-
577
- async provideDocumentSymbol(
578
- uri: DocumentUri,
579
- _token: CancellationToken,
580
- ): Promise<DocumentSymbol[]> {
581
- const project = this.workspace.projectForFile(uri);
582
- if (!project) return [];
583
-
584
- const definitions = project.definitionsAt(uri);
585
-
586
- const symbols: DocumentSymbol[] = [];
587
-
588
- for (const definition of definitions) {
589
- if (isExecutableDefinitionNode(definition)) {
590
- if (!definition.name) continue;
591
- const location = locationForASTNode(definition);
592
- if (!location) continue;
593
- symbols.push({
594
- name: definition.name.value,
595
- kind: SymbolKind.Function,
596
- range: rangeForASTNode(definition),
597
- selectionRange: rangeForASTNode(highlightNodeForNode(definition)),
598
- });
599
- } else if (
600
- isTypeSystemDefinitionNode(definition) ||
601
- isTypeSystemExtensionNode(definition)
602
- ) {
603
- if (
604
- definition.kind === Kind.SCHEMA_DEFINITION ||
605
- definition.kind === Kind.SCHEMA_EXTENSION
606
- ) {
607
- continue;
608
- }
609
- symbols.push({
610
- name: definition.name.value,
611
- kind: SymbolKind.Class,
612
- range: rangeForASTNode(definition),
613
- selectionRange: rangeForASTNode(highlightNodeForNode(definition)),
614
- children:
615
- definition.kind === Kind.OBJECT_TYPE_DEFINITION ||
616
- definition.kind === Kind.OBJECT_TYPE_EXTENSION
617
- ? (definition.fields || []).map(symbolForFieldDefinition)
618
- : undefined,
619
- });
620
- }
621
- }
622
-
623
- return symbols;
624
- }
625
-
626
- async provideWorkspaceSymbol(
627
- query: string,
628
- _token: CancellationToken,
629
- ): Promise<SymbolInformation[]> {
630
- const symbols: SymbolInformation[] = [];
631
- for (const project of this.workspace.projects) {
632
- for (const definition of project.definitions) {
633
- if (isExecutableDefinitionNode(definition)) {
634
- if (!definition.name) continue;
635
- const location = locationForASTNode(definition);
636
- if (!location) continue;
637
- symbols.push({
638
- name: definition.name.value,
639
- kind: SymbolKind.Function,
640
- location,
641
- });
642
- }
643
- }
644
- }
645
- return symbols;
646
- }
647
-
648
- async provideCodeLenses(
649
- uri: DocumentUri,
650
- _token: CancellationToken,
651
- ): Promise<CodeLens[]> {
652
- const project = this.workspace.projectForFile(uri);
653
- if (!(project && project instanceof GraphQLClientProject)) return [];
654
-
655
- // Wait for the project to be fully initialized, so we always provide code lenses for open files, even
656
- // if we receive the request before the project is ready.
657
- await project.whenReady;
658
-
659
- const documents = project.documentsAt(uri);
660
- if (!documents) return [];
661
-
662
- let codeLenses: CodeLens[] = [];
663
-
664
- for (const document of documents) {
665
- if (!document.ast) continue;
666
-
667
- for (const definition of document.ast.definitions) {
668
- if (definition.kind === Kind.OPERATION_DEFINITION) {
669
- /*
670
- if (set.endpoint) {
671
- const fragmentSpreads: Set<
672
- graphql.FragmentDefinitionNode
673
- > = new Set();
674
- const searchForReferencedFragments = (node: graphql.ASTNode) => {
675
- visit(node, {
676
- FragmentSpread(node: FragmentSpreadNode) {
677
- const fragDefn = project.fragments[node.name.value];
678
- if (!fragDefn) return;
679
-
680
- if (!fragmentSpreads.has(fragDefn)) {
681
- fragmentSpreads.add(fragDefn);
682
- searchForReferencedFragments(fragDefn);
683
- }
684
- }
685
- });
686
- };
687
-
688
- searchForReferencedFragments(definition);
689
-
690
- codeLenses.push({
691
- range: rangeForASTNode(definition),
692
- command: Command.create(
693
- `Run ${definition.operation}`,
694
- "apollographql.runQuery",
695
- graphql.parse(
696
- [definition, ...fragmentSpreads]
697
- .map(n => graphql.print(n))
698
- .join("\n")
699
- ),
700
- definition.operation === "subscription"
701
- ? set.endpoint.subscriptions
702
- : set.endpoint.url,
703
- set.endpoint.headers,
704
- graphql.printSchema(set.schema!)
705
- )
706
- });
707
- }
708
- */
709
- } else if (definition.kind === Kind.FRAGMENT_DEFINITION) {
710
- // remove project references for fragment now
711
- // const fragmentName = definition.name.value;
712
- // const locations = project
713
- // .fragmentSpreadsForFragment(fragmentName)
714
- // .map(fragmentSpread => locationForASTNode(fragmentSpread))
715
- // .filter(isNotNullOrUndefined);
716
- // const command = Command.create(
717
- // `${locations.length} references`,
718
- // "editor.action.showReferences",
719
- // uri,
720
- // rangeForASTNode(definition).start,
721
- // locations
722
- // );
723
- // codeLenses.push({
724
- // range: rangeForASTNode(definition),
725
- // command
726
- // });
727
- }
728
- }
729
- }
730
- return codeLenses;
731
- }
732
-
733
- async provideCodeAction(
734
- uri: DocumentUri,
735
- range: Range,
736
- _token: CancellationToken,
737
- ): Promise<CodeAction[]> {
738
- function isPositionLessThanOrEqual(a: Position, b: Position) {
739
- return a.line !== b.line ? a.line < b.line : a.character <= b.character;
740
- }
741
-
742
- const project = this.workspace.projectForFile(uri);
743
- if (
744
- !(
745
- project &&
746
- project instanceof GraphQLClientProject &&
747
- project.diagnosticSet
748
- )
749
- )
750
- return [];
751
-
752
- await project.whenReady;
753
-
754
- const documents = project.documentsAt(uri);
755
- if (!documents) return [];
756
-
757
- const errors: Set<GraphQLError> = new Set();
758
-
759
- for (const [
760
- diagnosticUri,
761
- diagnostics,
762
- ] of project.diagnosticSet.entries()) {
763
- if (diagnosticUri !== uri) continue;
764
-
765
- for (const diagnostic of diagnostics) {
766
- if (
767
- GraphQLDiagnostic.is(diagnostic) &&
768
- isPositionLessThanOrEqual(range.start, diagnostic.range.end) &&
769
- isPositionLessThanOrEqual(diagnostic.range.start, range.end)
770
- ) {
771
- errors.add(diagnostic.error);
772
- }
773
- }
774
- }
775
-
776
- const result: CodeAction[] = [];
777
-
778
- for (const error of errors) {
779
- const { extensions } = error;
780
- if (!extensions || !extensions.codeAction) continue;
781
-
782
- const { message, edits }: CodeActionInfo = extensions.codeAction as any;
783
-
784
- const codeAction = CodeAction.create(
785
- message,
786
- { changes: { [uri]: edits } },
787
- CodeActionKind.QuickFix,
788
- );
789
-
790
- result.push(codeAction);
791
- }
792
-
793
- return result;
794
- }
795
- }