@graphql-eslint/eslint-plugin 3.2.0-alpha-4ca7218.0 → 3.2.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.
- package/docs/rules/known-fragment-names.md +30 -9
- package/docs/rules/no-undefined-variables.md +1 -1
- package/docs/rules/no-unused-variables.md +1 -1
- package/docs/rules/require-id-when-available.md +16 -1
- package/index.js +251 -258
- package/index.mjs +253 -260
- package/package.json +2 -8
- package/rules/graphql-js-validation.d.ts +5 -2
- package/rules/index.d.ts +2 -129
- package/rules/match-document-filename.d.ts +3 -3
- package/rules/naming-convention.d.ts +1 -1
- package/types.d.ts +2 -2
- package/utils.d.ts +1 -7
package/index.mjs
CHANGED
@@ -1,7 +1,8 @@
|
|
1
|
-
import { Kind, validate,
|
1
|
+
import { Kind, validate, TokenKind, isScalarType, isNonNullType, isListType, isObjectType as isObjectType$1, visit, visitWithTypeInfo, GraphQLObjectType, GraphQLInterfaceType, TypeInfo, isInterfaceType, Source, GraphQLError } from 'graphql';
|
2
2
|
import { validateSDL } from 'graphql/validation/validate';
|
3
|
+
import { processImport, parseImportLine } from '@graphql-tools/import';
|
3
4
|
import { statSync, existsSync, readFileSync } from 'fs';
|
4
|
-
import { dirname, extname, basename, relative, resolve } from 'path';
|
5
|
+
import { dirname, join, extname, basename, relative, resolve } from 'path';
|
5
6
|
import { asArray, parseGraphQLSDL } from '@graphql-tools/utils';
|
6
7
|
import lowerCase from 'lodash.lowercase';
|
7
8
|
import depthLimit from 'graphql-depth-limit';
|
@@ -279,14 +280,6 @@ const TYPES_KINDS = [
|
|
279
280
|
Kind.INPUT_OBJECT_TYPE_DEFINITION,
|
280
281
|
Kind.UNION_TYPE_DEFINITION,
|
281
282
|
];
|
282
|
-
var CaseStyle;
|
283
|
-
(function (CaseStyle) {
|
284
|
-
CaseStyle["camelCase"] = "camelCase";
|
285
|
-
CaseStyle["pascalCase"] = "PascalCase";
|
286
|
-
CaseStyle["snakeCase"] = "snake_case";
|
287
|
-
CaseStyle["upperCase"] = "UPPER_CASE";
|
288
|
-
CaseStyle["kebabCase"] = "kebab-case";
|
289
|
-
})(CaseStyle || (CaseStyle = {}));
|
290
283
|
const pascalCase = (str) => lowerCase(str)
|
291
284
|
.split(' ')
|
292
285
|
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
@@ -297,15 +290,15 @@ const camelCase = (str) => {
|
|
297
290
|
};
|
298
291
|
const convertCase = (style, str) => {
|
299
292
|
switch (style) {
|
300
|
-
case
|
293
|
+
case 'camelCase':
|
301
294
|
return camelCase(str);
|
302
|
-
case
|
295
|
+
case 'PascalCase':
|
303
296
|
return pascalCase(str);
|
304
|
-
case
|
297
|
+
case 'snake_case':
|
305
298
|
return lowerCase(str).replace(/ /g, '_');
|
306
|
-
case
|
299
|
+
case 'UPPER_CASE':
|
307
300
|
return lowerCase(str).replace(/ /g, '_').toUpperCase();
|
308
|
-
case
|
301
|
+
case 'kebab-case':
|
309
302
|
return lowerCase(str).replace(/ /g, '-');
|
310
303
|
}
|
311
304
|
};
|
@@ -328,17 +321,32 @@ function getLocation(loc, fieldName = '', offset) {
|
|
328
321
|
};
|
329
322
|
}
|
330
323
|
|
331
|
-
function
|
324
|
+
function validateDoc(sourceNode, context, schema, documentNode, rules) {
|
332
325
|
if (documentNode.definitions.length === 0) {
|
333
326
|
return;
|
334
327
|
}
|
335
328
|
try {
|
336
329
|
const validationErrors = schema
|
337
|
-
? validate(schema, documentNode,
|
338
|
-
: validateSDL(documentNode, null,
|
330
|
+
? validate(schema, documentNode, rules)
|
331
|
+
: validateSDL(documentNode, null, rules);
|
339
332
|
for (const error of validationErrors) {
|
333
|
+
/*
|
334
|
+
* TODO: Fix ESTree-AST converter because currently it's incorrectly convert loc.end
|
335
|
+
* Example: loc.end always equal loc.start
|
336
|
+
* {
|
337
|
+
* token: {
|
338
|
+
* type: 'Name',
|
339
|
+
* loc: { start: { line: 4, column: 13 }, end: { line: 4, column: 13 } },
|
340
|
+
* value: 'veryBad',
|
341
|
+
* range: [ 40, 47 ]
|
342
|
+
* }
|
343
|
+
* }
|
344
|
+
*/
|
345
|
+
const { line, column } = error.locations[0];
|
346
|
+
const ancestors = context.getAncestors();
|
347
|
+
const token = ancestors[0].tokens.find(token => token.loc.start.line === line && token.loc.start.column === column);
|
340
348
|
context.report({
|
341
|
-
loc: getLocation({ start: error.locations[0] }),
|
349
|
+
loc: getLocation({ start: error.locations[0] }, token === null || token === void 0 ? void 0 : token.value),
|
342
350
|
message: error.message,
|
343
351
|
});
|
344
352
|
}
|
@@ -350,79 +358,34 @@ function validateDocument(sourceNode, context, schema, documentNode, rule) {
|
|
350
358
|
});
|
351
359
|
}
|
352
360
|
}
|
353
|
-
const
|
354
|
-
const
|
355
|
-
|
356
|
-
const fragmentSpreads = new Set();
|
357
|
-
const visitor = visitWithTypeInfo(typeInfo, {
|
358
|
-
FragmentDefinition(node) {
|
359
|
-
fragmentDefs.add(`${node.name.value}:${node.typeCondition.name.value}`);
|
360
|
-
},
|
361
|
-
FragmentSpread(node) {
|
362
|
-
const parentType = typeInfo.getParentType();
|
363
|
-
if (parentType) {
|
364
|
-
fragmentSpreads.add(`${node.name.value}:${parentType.name}`);
|
365
|
-
}
|
366
|
-
},
|
367
|
-
});
|
368
|
-
visit(node, visitor);
|
369
|
-
return { fragmentDefs, fragmentSpreads };
|
370
|
-
};
|
371
|
-
const getMissingFragments = (schema, node) => {
|
372
|
-
const { fragmentDefs, fragmentSpreads } = getFragmentDefsAndFragmentSpreads(schema, node);
|
373
|
-
return [...fragmentSpreads].filter(name => !fragmentDefs.has(name));
|
374
|
-
};
|
375
|
-
const handleMissingFragments = ({ ruleId, context, schema, node }) => {
|
376
|
-
const missingFragments = getMissingFragments(schema, node);
|
377
|
-
if (missingFragments.length > 0) {
|
378
|
-
const siblings = requireSiblingsOperations(ruleId, context);
|
379
|
-
const fragmentsToAdd = [];
|
380
|
-
for (const missingFragment of missingFragments) {
|
381
|
-
const [fragmentName, fragmentTypeName] = missingFragment.split(':');
|
382
|
-
const [foundFragment] = siblings
|
383
|
-
.getFragment(fragmentName)
|
384
|
-
.map(source => source.document)
|
385
|
-
.filter(fragment => fragment.typeCondition.name.value === fragmentTypeName);
|
386
|
-
if (foundFragment) {
|
387
|
-
fragmentsToAdd.push(foundFragment);
|
388
|
-
}
|
389
|
-
}
|
390
|
-
if (fragmentsToAdd.length > 0) {
|
391
|
-
// recall fn to make sure to add fragments inside fragments
|
392
|
-
return handleMissingFragments({
|
393
|
-
ruleId,
|
394
|
-
context,
|
395
|
-
schema,
|
396
|
-
node: {
|
397
|
-
kind: Kind.DOCUMENT,
|
398
|
-
definitions: [...node.definitions, ...fragmentsToAdd],
|
399
|
-
},
|
400
|
-
});
|
401
|
-
}
|
402
|
-
}
|
403
|
-
return node;
|
361
|
+
const isGraphQLImportFile = rawSDL => {
|
362
|
+
const trimmedRawSDL = rawSDL.trimLeft();
|
363
|
+
return trimmedRawSDL.startsWith('# import') || trimmedRawSDL.startsWith('#import');
|
404
364
|
};
|
405
|
-
const validationToRule = (
|
365
|
+
const validationToRule = (name, ruleName, docs, getDocumentNode) => {
|
366
|
+
var _a;
|
406
367
|
let ruleFn = null;
|
407
368
|
try {
|
408
369
|
ruleFn = require(`graphql/validation/rules/${ruleName}Rule`)[`${ruleName}Rule`];
|
409
370
|
}
|
410
|
-
catch (
|
371
|
+
catch (e) {
|
411
372
|
try {
|
412
373
|
ruleFn = require(`graphql/validation/rules/${ruleName}`)[`${ruleName}Rule`];
|
413
374
|
}
|
414
|
-
catch (
|
375
|
+
catch (e) {
|
415
376
|
ruleFn = require('graphql/validation')[`${ruleName}Rule`];
|
416
377
|
}
|
417
378
|
}
|
379
|
+
const requiresSchema = (_a = docs.requiresSchema) !== null && _a !== void 0 ? _a : true;
|
418
380
|
return {
|
419
|
-
[
|
381
|
+
[name]: {
|
420
382
|
meta: {
|
421
383
|
docs: {
|
422
384
|
recommended: true,
|
423
385
|
...docs,
|
424
386
|
graphQLJSRuleName: ruleName,
|
425
|
-
|
387
|
+
requiresSchema,
|
388
|
+
url: `https://github.com/dotansimha/graphql-eslint/blob/master/docs/rules/${name}.md`,
|
426
389
|
description: `${docs.description}\n\n> This rule is a wrapper around a \`graphql-js\` validation function. [You can find its source code here](https://github.com/graphql/graphql-js/blob/main/src/validation/rules/${ruleName}Rule.ts).`,
|
427
390
|
},
|
428
391
|
},
|
@@ -431,53 +394,56 @@ const validationToRule = (ruleId, ruleName, docs, getDocumentNode) => {
|
|
431
394
|
Document(node) {
|
432
395
|
if (!ruleFn) {
|
433
396
|
// eslint-disable-next-line no-console
|
434
|
-
console.warn(`You rule "${
|
397
|
+
console.warn(`You rule "${name}" depends on a GraphQL validation rule ("${ruleName}") but it's not available in the "graphql-js" version you are using. Skipping...`);
|
435
398
|
return;
|
436
399
|
}
|
437
|
-
const schema =
|
438
|
-
|
439
|
-
|
440
|
-
|
441
|
-
|
400
|
+
const schema = requiresSchema ? requireGraphQLSchemaFromContext(name, context) : null;
|
401
|
+
let documentNode;
|
402
|
+
const isRealFile = existsSync(context.getFilename());
|
403
|
+
if (isRealFile && getDocumentNode) {
|
404
|
+
documentNode = getDocumentNode(context);
|
405
|
+
}
|
406
|
+
validateDoc(node, context, schema, documentNode || node.rawNode(), [ruleFn]);
|
442
407
|
},
|
443
408
|
};
|
444
409
|
},
|
445
410
|
},
|
446
411
|
};
|
447
412
|
};
|
413
|
+
const importFiles = (context) => {
|
414
|
+
const code = context.getSourceCode().text;
|
415
|
+
if (!isGraphQLImportFile(code)) {
|
416
|
+
return null;
|
417
|
+
}
|
418
|
+
// Import documents because file contains '#import' comments
|
419
|
+
return processImport(context.getFilename());
|
420
|
+
};
|
448
421
|
const GRAPHQL_JS_VALIDATIONS = Object.assign({}, validationToRule('executable-definitions', 'ExecutableDefinitions', {
|
449
422
|
category: 'Operations',
|
450
423
|
description: `A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.`,
|
451
|
-
requiresSchema: true,
|
452
424
|
}), validationToRule('fields-on-correct-type', 'FieldsOnCorrectType', {
|
453
425
|
category: 'Operations',
|
454
426
|
description: 'A GraphQL document is only valid if all fields selected are defined by the parent type, or are an allowed meta field such as `__typename`.',
|
455
|
-
requiresSchema: true,
|
456
427
|
}), validationToRule('fragments-on-composite-type', 'FragmentsOnCompositeTypes', {
|
457
428
|
category: 'Operations',
|
458
429
|
description: `Fragments use a type condition to determine if they apply, since fragments can only be spread into a composite type (object, interface, or union), the type condition must also be a composite type.`,
|
459
|
-
requiresSchema: true,
|
460
430
|
}), validationToRule('known-argument-names', 'KnownArgumentNames', {
|
461
431
|
category: ['Schema', 'Operations'],
|
462
432
|
description: `A GraphQL field is only valid if all supplied arguments are defined by that field.`,
|
463
|
-
requiresSchema: true,
|
464
433
|
}), validationToRule('known-directives', 'KnownDirectives', {
|
465
434
|
category: ['Schema', 'Operations'],
|
466
435
|
description: `A GraphQL document is only valid if all \`@directives\` are known by the schema and legally positioned.`,
|
467
|
-
requiresSchema: true,
|
468
436
|
}), validationToRule('known-fragment-names', 'KnownFragmentNames', {
|
469
437
|
category: 'Operations',
|
470
438
|
description: `A GraphQL document is only valid if all \`...Fragment\` fragment spreads refer to fragments defined in the same document.`,
|
471
|
-
requiresSchema: true,
|
472
|
-
requiresSiblings: true,
|
473
439
|
examples: [
|
474
440
|
{
|
475
|
-
title: 'Incorrect',
|
441
|
+
title: 'Incorrect (fragment not defined in the document)',
|
476
442
|
code: /* GraphQL */ `
|
477
443
|
query {
|
478
444
|
user {
|
479
445
|
id
|
480
|
-
...UserFields
|
446
|
+
...UserFields
|
481
447
|
}
|
482
448
|
}
|
483
449
|
`,
|
@@ -499,151 +465,153 @@ const GRAPHQL_JS_VALIDATIONS = Object.assign({}, validationToRule('executable-de
|
|
499
465
|
`,
|
500
466
|
},
|
501
467
|
{
|
502
|
-
title: 'Correct (
|
468
|
+
title: 'Correct (existing import to UserFields fragment)',
|
503
469
|
code: /* GraphQL */ `
|
504
|
-
#
|
470
|
+
#import '../UserFields.gql'
|
471
|
+
|
505
472
|
query {
|
506
473
|
user {
|
507
474
|
id
|
508
475
|
...UserFields
|
509
476
|
}
|
510
477
|
}
|
511
|
-
|
512
|
-
# user-fields.gql
|
513
|
-
fragment UserFields on User {
|
514
|
-
id
|
515
|
-
}
|
516
478
|
`,
|
517
479
|
},
|
480
|
+
{
|
481
|
+
title: "False positive case\n\nFor extracting documents from code under the hood we use [graphql-tag-pluck](https://graphql-tools.com/docs/graphql-tag-pluck) that [don't support string interpolation](https://stackoverflow.com/questions/62749847/graphql-codegen-dynamic-fields-with-interpolation/62751311#62751311) for this moment.",
|
482
|
+
code: `
|
483
|
+
const USER_FIELDS = gql\`
|
484
|
+
fragment UserFields on User {
|
485
|
+
id
|
486
|
+
}
|
487
|
+
\`
|
488
|
+
|
489
|
+
const GET_USER = /* GraphQL */ \`
|
490
|
+
# eslint @graphql-eslint/known-fragment-names: 'error'
|
491
|
+
|
492
|
+
query User {
|
493
|
+
user {
|
494
|
+
...UserFields
|
495
|
+
}
|
496
|
+
}
|
497
|
+
|
498
|
+
# Will give false positive error 'Unknown fragment "UserFields"'
|
499
|
+
\${USER_FIELDS}
|
500
|
+
\``,
|
501
|
+
},
|
518
502
|
],
|
519
|
-
},
|
503
|
+
}, importFiles), validationToRule('known-type-names', 'KnownTypeNames', {
|
520
504
|
category: ['Schema', 'Operations'],
|
521
505
|
description: `A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.`,
|
522
|
-
requiresSchema: true,
|
523
506
|
}), validationToRule('lone-anonymous-operation', 'LoneAnonymousOperation', {
|
524
507
|
category: 'Operations',
|
525
508
|
description: `A GraphQL document is only valid if when it contains an anonymous operation (the query short-hand) that it contains only that one operation definition.`,
|
526
|
-
requiresSchema: true,
|
527
509
|
}), validationToRule('lone-schema-definition', 'LoneSchemaDefinition', {
|
528
510
|
category: 'Schema',
|
529
511
|
description: `A GraphQL document is only valid if it contains only one schema definition.`,
|
512
|
+
requiresSchema: false,
|
530
513
|
}), validationToRule('no-fragment-cycles', 'NoFragmentCycles', {
|
531
514
|
category: 'Operations',
|
532
515
|
description: `A GraphQL fragment is only valid when it does not have cycles in fragments usage.`,
|
533
|
-
requiresSchema: true,
|
534
516
|
}), validationToRule('no-undefined-variables', 'NoUndefinedVariables', {
|
535
517
|
category: 'Operations',
|
536
518
|
description: `A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.`,
|
537
|
-
|
538
|
-
requiresSiblings: true,
|
539
|
-
}, handleMissingFragments), validationToRule('no-unused-fragments', 'NoUnusedFragments', {
|
519
|
+
}, importFiles), validationToRule('no-unused-fragments', 'NoUnusedFragments', {
|
540
520
|
category: 'Operations',
|
541
521
|
description: `A GraphQL document is only valid if all fragment definitions are spread within operations, or spread within other fragments spread within operations.`,
|
542
|
-
requiresSchema: true,
|
543
522
|
requiresSiblings: true,
|
544
|
-
},
|
545
|
-
const siblings = requireSiblingsOperations(
|
546
|
-
const
|
547
|
-
|
548
|
-
(
|
549
|
-
|
550
|
-
|
551
|
-
}
|
552
|
-
const getParentNode = (
|
553
|
-
const {
|
554
|
-
|
555
|
-
|
523
|
+
}, context => {
|
524
|
+
const siblings = requireSiblingsOperations('no-unused-fragments', context);
|
525
|
+
const documents = [...siblings.getOperations(), ...siblings.getFragments()]
|
526
|
+
.filter(({ document }) => isGraphQLImportFile(document.loc.source.body))
|
527
|
+
.map(({ filePath, document }) => ({
|
528
|
+
filePath,
|
529
|
+
code: document.loc.source.body,
|
530
|
+
}));
|
531
|
+
const getParentNode = (filePath) => {
|
532
|
+
for (const { filePath: docFilePath, code } of documents) {
|
533
|
+
const isFileImported = code
|
534
|
+
.split('\n')
|
535
|
+
.filter(isGraphQLImportFile)
|
536
|
+
.map(line => parseImportLine(line.replace('#', '')))
|
537
|
+
.some(o => filePath === join(dirname(docFilePath), o.from));
|
538
|
+
if (!isFileImported) {
|
539
|
+
continue;
|
540
|
+
}
|
541
|
+
// Import first file that import this file
|
542
|
+
const document = processImport(docFilePath);
|
543
|
+
// Import most top file that import this file
|
544
|
+
return getParentNode(docFilePath) || document;
|
556
545
|
}
|
557
|
-
|
558
|
-
delete FilePathToDocumentsMap[currentFilePath];
|
559
|
-
for (const [filePath, documents] of Object.entries(FilePathToDocumentsMap)) {
|
560
|
-
const missingFragments = getMissingFragments(schema, {
|
561
|
-
kind: Kind.DOCUMENT,
|
562
|
-
definitions: documents,
|
563
|
-
});
|
564
|
-
const isCurrentFileImportFragment = missingFragments.some(fragment => fragmentDefs.has(fragment));
|
565
|
-
if (isCurrentFileImportFragment) {
|
566
|
-
return getParentNode(filePath, {
|
567
|
-
kind: Kind.DOCUMENT,
|
568
|
-
definitions: [...node.definitions, ...documents],
|
569
|
-
});
|
570
|
-
}
|
571
|
-
}
|
572
|
-
return node;
|
546
|
+
return null;
|
573
547
|
};
|
574
|
-
return getParentNode(context.getFilename()
|
548
|
+
return getParentNode(context.getFilename());
|
575
549
|
}), validationToRule('no-unused-variables', 'NoUnusedVariables', {
|
576
550
|
category: 'Operations',
|
577
551
|
description: `A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.`,
|
578
|
-
|
579
|
-
requiresSiblings: true,
|
580
|
-
}, handleMissingFragments), validationToRule('overlapping-fields-can-be-merged', 'OverlappingFieldsCanBeMerged', {
|
552
|
+
}, importFiles), validationToRule('overlapping-fields-can-be-merged', 'OverlappingFieldsCanBeMerged', {
|
581
553
|
category: 'Operations',
|
582
554
|
description: `A selection set is only valid if all fields (including spreading any fragments) either correspond to distinct response names or can be merged without ambiguity.`,
|
583
|
-
requiresSchema: true,
|
584
555
|
}), validationToRule('possible-fragment-spread', 'PossibleFragmentSpreads', {
|
585
556
|
category: 'Operations',
|
586
557
|
description: `A fragment spread is only valid if the type condition could ever possibly be true: if there is a non-empty intersection of the possible parent types, and possible types which pass the type condition.`,
|
587
|
-
requiresSchema: true,
|
588
558
|
}), validationToRule('possible-type-extension', 'PossibleTypeExtensions', {
|
589
559
|
category: 'Schema',
|
590
560
|
description: `A type extension is only valid if the type is defined and has the same kind.`,
|
561
|
+
requiresSchema: false,
|
591
562
|
recommended: false, // TODO: enable after https://github.com/dotansimha/graphql-eslint/issues/787 will be fixed
|
592
563
|
}), validationToRule('provided-required-arguments', 'ProvidedRequiredArguments', {
|
593
564
|
category: ['Schema', 'Operations'],
|
594
565
|
description: `A field or directive is only valid if all required (non-null without a default value) field arguments have been provided.`,
|
595
|
-
requiresSchema: true,
|
596
566
|
}), validationToRule('scalar-leafs', 'ScalarLeafs', {
|
597
567
|
category: 'Operations',
|
598
568
|
description: `A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.`,
|
599
|
-
requiresSchema: true,
|
600
569
|
}), validationToRule('one-field-subscriptions', 'SingleFieldSubscriptions', {
|
601
570
|
category: 'Operations',
|
602
571
|
description: `A GraphQL subscription is valid only if it contains a single root field.`,
|
603
|
-
requiresSchema: true,
|
604
572
|
}), validationToRule('unique-argument-names', 'UniqueArgumentNames', {
|
605
573
|
category: 'Operations',
|
606
574
|
description: `A GraphQL field or directive is only valid if all supplied arguments are uniquely named.`,
|
607
|
-
requiresSchema: true,
|
608
575
|
}), validationToRule('unique-directive-names', 'UniqueDirectiveNames', {
|
609
576
|
category: 'Schema',
|
610
577
|
description: `A GraphQL document is only valid if all defined directives have unique names.`,
|
578
|
+
requiresSchema: false,
|
611
579
|
}), validationToRule('unique-directive-names-per-location', 'UniqueDirectivesPerLocation', {
|
612
580
|
category: ['Schema', 'Operations'],
|
613
581
|
description: `A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.`,
|
614
|
-
requiresSchema: true,
|
615
582
|
}), validationToRule('unique-enum-value-names', 'UniqueEnumValueNames', {
|
616
583
|
category: 'Schema',
|
617
584
|
description: `A GraphQL enum type is only valid if all its values are uniquely named.`,
|
585
|
+
requiresSchema: false,
|
618
586
|
recommended: false,
|
619
587
|
}), validationToRule('unique-field-definition-names', 'UniqueFieldDefinitionNames', {
|
620
588
|
category: 'Schema',
|
621
589
|
description: `A GraphQL complex type is only valid if all its fields are uniquely named.`,
|
590
|
+
requiresSchema: false,
|
622
591
|
}), validationToRule('unique-input-field-names', 'UniqueInputFieldNames', {
|
623
592
|
category: 'Operations',
|
624
593
|
description: `A GraphQL input object value is only valid if all supplied fields are uniquely named.`,
|
594
|
+
requiresSchema: false,
|
625
595
|
}), validationToRule('unique-operation-types', 'UniqueOperationTypes', {
|
626
596
|
category: 'Schema',
|
627
597
|
description: `A GraphQL document is only valid if it has only one type per operation.`,
|
598
|
+
requiresSchema: false,
|
628
599
|
}), validationToRule('unique-type-names', 'UniqueTypeNames', {
|
629
600
|
category: 'Schema',
|
630
601
|
description: `A GraphQL document is only valid if all defined types have unique names.`,
|
602
|
+
requiresSchema: false,
|
631
603
|
}), validationToRule('unique-variable-names', 'UniqueVariableNames', {
|
632
604
|
category: 'Operations',
|
633
605
|
description: `A GraphQL operation is only valid if all its variables are uniquely named.`,
|
634
|
-
requiresSchema: true,
|
635
606
|
}), validationToRule('value-literals-of-correct-type', 'ValuesOfCorrectType', {
|
636
607
|
category: 'Operations',
|
637
608
|
description: `A GraphQL document is only valid if all value literals are of the type expected at their position.`,
|
638
|
-
requiresSchema: true,
|
639
609
|
}), validationToRule('variables-are-input-types', 'VariablesAreInputTypes', {
|
640
610
|
category: 'Operations',
|
641
611
|
description: `A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).`,
|
642
|
-
requiresSchema: true,
|
643
612
|
}), validationToRule('variables-in-allowed-position', 'VariablesInAllowedPosition', {
|
644
613
|
category: 'Operations',
|
645
614
|
description: `Variables passed to field arguments conform to type.`,
|
646
|
-
requiresSchema: true,
|
647
615
|
}));
|
648
616
|
|
649
617
|
const ALPHABETIZE = 'ALPHABETIZE';
|
@@ -1077,13 +1045,7 @@ const rule$2 = {
|
|
1077
1045
|
const MATCH_EXTENSION = 'MATCH_EXTENSION';
|
1078
1046
|
const MATCH_STYLE = 'MATCH_STYLE';
|
1079
1047
|
const ACCEPTED_EXTENSIONS = ['.gql', '.graphql'];
|
1080
|
-
const CASE_STYLES = [
|
1081
|
-
CaseStyle.camelCase,
|
1082
|
-
CaseStyle.pascalCase,
|
1083
|
-
CaseStyle.snakeCase,
|
1084
|
-
CaseStyle.upperCase,
|
1085
|
-
CaseStyle.kebabCase,
|
1086
|
-
];
|
1048
|
+
const CASE_STYLES = ['camelCase', 'PascalCase', 'snake_case', 'UPPER_CASE', 'kebab-case'];
|
1087
1049
|
const schemaOption = {
|
1088
1050
|
oneOf: [{ $ref: '#/definitions/asString' }, { $ref: '#/definitions/asObject' }],
|
1089
1051
|
};
|
@@ -1107,7 +1069,7 @@ const rule$3 = {
|
|
1107
1069
|
},
|
1108
1070
|
{
|
1109
1071
|
title: 'Correct',
|
1110
|
-
usage: [{ query:
|
1072
|
+
usage: [{ query: 'snake_case' }],
|
1111
1073
|
code: /* GraphQL */ `
|
1112
1074
|
# user_by_id.gql
|
1113
1075
|
query UserById {
|
@@ -1121,7 +1083,7 @@ const rule$3 = {
|
|
1121
1083
|
},
|
1122
1084
|
{
|
1123
1085
|
title: 'Correct',
|
1124
|
-
usage: [{ fragment: { style:
|
1086
|
+
usage: [{ fragment: { style: 'kebab-case', suffix: '.fragment' } }],
|
1125
1087
|
code: /* GraphQL */ `
|
1126
1088
|
# user-fields.fragment.gql
|
1127
1089
|
fragment user_fields on User {
|
@@ -1132,7 +1094,7 @@ const rule$3 = {
|
|
1132
1094
|
},
|
1133
1095
|
{
|
1134
1096
|
title: 'Correct',
|
1135
|
-
usage: [{ mutation: { style:
|
1097
|
+
usage: [{ mutation: { style: 'PascalCase', suffix: 'Mutation' } }],
|
1136
1098
|
code: /* GraphQL */ `
|
1137
1099
|
# DeleteUserMutation.gql
|
1138
1100
|
mutation DELETE_USER {
|
@@ -1152,7 +1114,7 @@ const rule$3 = {
|
|
1152
1114
|
},
|
1153
1115
|
{
|
1154
1116
|
title: 'Incorrect',
|
1155
|
-
usage: [{ query:
|
1117
|
+
usage: [{ query: 'PascalCase' }],
|
1156
1118
|
code: /* GraphQL */ `
|
1157
1119
|
# user-by-id.gql
|
1158
1120
|
query UserById {
|
@@ -1167,10 +1129,10 @@ const rule$3 = {
|
|
1167
1129
|
],
|
1168
1130
|
configOptions: [
|
1169
1131
|
{
|
1170
|
-
query:
|
1171
|
-
mutation:
|
1172
|
-
subscription:
|
1173
|
-
fragment:
|
1132
|
+
query: 'kebab-case',
|
1133
|
+
mutation: 'kebab-case',
|
1134
|
+
subscription: 'kebab-case',
|
1135
|
+
fragment: 'kebab-case',
|
1174
1136
|
},
|
1175
1137
|
],
|
1176
1138
|
},
|
@@ -1187,25 +1149,22 @@ const rule$3 = {
|
|
1187
1149
|
asObject: {
|
1188
1150
|
type: 'object',
|
1189
1151
|
additionalProperties: false,
|
1152
|
+
minProperties: 1,
|
1190
1153
|
properties: {
|
1191
|
-
style: {
|
1192
|
-
|
1193
|
-
},
|
1194
|
-
suffix: {
|
1195
|
-
type: 'string',
|
1196
|
-
},
|
1154
|
+
style: { enum: CASE_STYLES },
|
1155
|
+
suffix: { type: 'string' },
|
1197
1156
|
},
|
1198
1157
|
},
|
1199
1158
|
},
|
1200
1159
|
type: 'array',
|
1160
|
+
minItems: 1,
|
1201
1161
|
maxItems: 1,
|
1202
1162
|
items: {
|
1203
1163
|
type: 'object',
|
1204
1164
|
additionalProperties: false,
|
1165
|
+
minProperties: 1,
|
1205
1166
|
properties: {
|
1206
|
-
fileExtension: {
|
1207
|
-
enum: ACCEPTED_EXTENSIONS,
|
1208
|
-
},
|
1167
|
+
fileExtension: { enum: ACCEPTED_EXTENSIONS },
|
1209
1168
|
query: schemaOption,
|
1210
1169
|
mutation: schemaOption,
|
1211
1170
|
subscription: schemaOption,
|
@@ -1260,7 +1219,7 @@ const rule$3 = {
|
|
1260
1219
|
option = { style: option };
|
1261
1220
|
}
|
1262
1221
|
const expectedExtension = options.fileExtension || fileExtension;
|
1263
|
-
const expectedFilename = convertCase(option.style, docName) + (option.suffix || '') + expectedExtension;
|
1222
|
+
const expectedFilename = (option.style ? convertCase(option.style, docName) : filename) + (option.suffix || '') + expectedExtension;
|
1264
1223
|
const filenameWithExtension = filename + expectedExtension;
|
1265
1224
|
if (expectedFilename !== filenameWithExtension) {
|
1266
1225
|
context.report({
|
@@ -1412,6 +1371,7 @@ const rule$4 = {
|
|
1412
1371
|
],
|
1413
1372
|
},
|
1414
1373
|
},
|
1374
|
+
hasSuggestions: true,
|
1415
1375
|
schema: {
|
1416
1376
|
definitions: {
|
1417
1377
|
asString: {
|
@@ -1486,65 +1446,90 @@ const rule$4 = {
|
|
1486
1446
|
const style = restOptions[kind] || types;
|
1487
1447
|
return typeof style === 'object' ? style : { style };
|
1488
1448
|
}
|
1489
|
-
const checkNode = (selector) => (
|
1490
|
-
const { name } =
|
1491
|
-
if (!
|
1449
|
+
const checkNode = (selector) => (n) => {
|
1450
|
+
const { name: node } = n.kind === Kind.VARIABLE_DEFINITION ? n.variable : n;
|
1451
|
+
if (!node) {
|
1492
1452
|
return;
|
1493
1453
|
}
|
1494
1454
|
const { prefix, suffix, forbiddenPrefixes, forbiddenSuffixes, style } = normalisePropertyOption(selector);
|
1495
|
-
const nodeType = KindToDisplayName[
|
1496
|
-
const nodeName =
|
1497
|
-
const
|
1498
|
-
if (
|
1455
|
+
const nodeType = KindToDisplayName[n.kind] || n.kind;
|
1456
|
+
const nodeName = node.value;
|
1457
|
+
const error = getError();
|
1458
|
+
if (error) {
|
1459
|
+
const { errorMessage, renameToName } = error;
|
1460
|
+
const [leadingUnderscore] = nodeName.match(/^_*/);
|
1461
|
+
const [trailingUnderscore] = nodeName.match(/_*$/);
|
1462
|
+
const suggestedName = leadingUnderscore + renameToName + trailingUnderscore;
|
1499
1463
|
context.report({
|
1500
|
-
loc: getLocation(
|
1464
|
+
loc: getLocation(node.loc, node.value),
|
1501
1465
|
message: `${nodeType} "${nodeName}" should ${errorMessage}`,
|
1466
|
+
suggest: [
|
1467
|
+
{
|
1468
|
+
desc: `Rename to "${suggestedName}"`,
|
1469
|
+
fix: fixer => fixer.replaceText(node, suggestedName),
|
1470
|
+
},
|
1471
|
+
],
|
1502
1472
|
});
|
1503
1473
|
}
|
1504
|
-
function
|
1505
|
-
|
1506
|
-
if (allowLeadingUnderscore) {
|
1507
|
-
name = name.replace(/^_*/, '');
|
1508
|
-
}
|
1509
|
-
if (allowTrailingUnderscore) {
|
1510
|
-
name = name.replace(/_*$/, '');
|
1511
|
-
}
|
1474
|
+
function getError() {
|
1475
|
+
const name = nodeName.replace(/(^_+)|(_+$)/g, '');
|
1512
1476
|
if (prefix && !name.startsWith(prefix)) {
|
1513
|
-
return
|
1477
|
+
return {
|
1478
|
+
errorMessage: `have "${prefix}" prefix`,
|
1479
|
+
renameToName: prefix + name,
|
1480
|
+
};
|
1514
1481
|
}
|
1515
1482
|
if (suffix && !name.endsWith(suffix)) {
|
1516
|
-
return
|
1483
|
+
return {
|
1484
|
+
errorMessage: `have "${suffix}" suffix`,
|
1485
|
+
renameToName: name + suffix,
|
1486
|
+
};
|
1517
1487
|
}
|
1518
1488
|
const forbiddenPrefix = forbiddenPrefixes === null || forbiddenPrefixes === void 0 ? void 0 : forbiddenPrefixes.find(prefix => name.startsWith(prefix));
|
1519
1489
|
if (forbiddenPrefix) {
|
1520
|
-
return
|
1490
|
+
return {
|
1491
|
+
errorMessage: `not have "${forbiddenPrefix}" prefix`,
|
1492
|
+
renameToName: name.replace(new RegExp(`^${forbiddenPrefix}`), ''),
|
1493
|
+
};
|
1521
1494
|
}
|
1522
1495
|
const forbiddenSuffix = forbiddenSuffixes === null || forbiddenSuffixes === void 0 ? void 0 : forbiddenSuffixes.find(suffix => name.endsWith(suffix));
|
1523
1496
|
if (forbiddenSuffix) {
|
1524
|
-
return
|
1525
|
-
|
1526
|
-
|
1527
|
-
|
1497
|
+
return {
|
1498
|
+
errorMessage: `not have "${forbiddenSuffix}" suffix`,
|
1499
|
+
renameToName: name.replace(new RegExp(`${forbiddenSuffix}$`), ''),
|
1500
|
+
};
|
1528
1501
|
}
|
1529
1502
|
const caseRegex = StyleToRegex[style];
|
1530
1503
|
if (caseRegex && !caseRegex.test(name)) {
|
1531
|
-
return
|
1504
|
+
return {
|
1505
|
+
errorMessage: `be in ${style} format`,
|
1506
|
+
renameToName: convertCase(style, name),
|
1507
|
+
};
|
1532
1508
|
}
|
1533
1509
|
}
|
1534
1510
|
};
|
1535
|
-
const checkUnderscore = (node) => {
|
1511
|
+
const checkUnderscore = (isLeading) => (node) => {
|
1536
1512
|
const name = node.value;
|
1513
|
+
const renameToName = name.replace(new RegExp(isLeading ? '^_+' : '_+$'), '');
|
1537
1514
|
context.report({
|
1538
1515
|
loc: getLocation(node.loc, name),
|
1539
|
-
message: `${
|
1516
|
+
message: `${isLeading ? 'Leading' : 'Trailing'} underscores are not allowed`,
|
1517
|
+
suggest: [
|
1518
|
+
{
|
1519
|
+
desc: `Rename to "${renameToName}"`,
|
1520
|
+
fix: fixer => fixer.replaceText(node, renameToName),
|
1521
|
+
},
|
1522
|
+
],
|
1540
1523
|
});
|
1541
1524
|
};
|
1542
1525
|
const listeners = {};
|
1543
1526
|
if (!allowLeadingUnderscore) {
|
1544
|
-
listeners['Name[value=/^_/]:matches([parent.kind!=Field], [parent.kind=Field][parent.alias])'] =
|
1527
|
+
listeners['Name[value=/^_/]:matches([parent.kind!=Field], [parent.kind=Field][parent.alias])'] =
|
1528
|
+
checkUnderscore(true);
|
1545
1529
|
}
|
1546
1530
|
if (!allowTrailingUnderscore) {
|
1547
|
-
listeners['Name[value=/_$/]:matches([parent.kind!=Field], [parent.kind=Field][parent.alias])'] =
|
1531
|
+
listeners['Name[value=/_$/]:matches([parent.kind!=Field], [parent.kind=Field][parent.alias])'] =
|
1532
|
+
checkUnderscore(false);
|
1548
1533
|
}
|
1549
1534
|
const selectors = new Set([types && TYPES_KINDS, Object.keys(restOptions)].flat().filter(Boolean));
|
1550
1535
|
for (const selector of selectors) {
|
@@ -2887,9 +2872,22 @@ const rule$j = {
|
|
2887
2872
|
recommended: true,
|
2888
2873
|
},
|
2889
2874
|
messages: {
|
2890
|
-
[REQUIRE_ID_WHEN_AVAILABLE]:
|
2875
|
+
[REQUIRE_ID_WHEN_AVAILABLE]: [
|
2876
|
+
`Field {{ fieldName }} must be selected when it's available on a type. Please make sure to include it in your selection set!`,
|
2877
|
+
`If you are using fragments, make sure that all used fragments {{ checkedFragments }}specifies the field {{ fieldName }}.`,
|
2878
|
+
].join('\n'),
|
2891
2879
|
},
|
2892
2880
|
schema: {
|
2881
|
+
definitions: {
|
2882
|
+
asString: {
|
2883
|
+
type: 'string',
|
2884
|
+
},
|
2885
|
+
asArray: {
|
2886
|
+
type: 'array',
|
2887
|
+
minItems: 1,
|
2888
|
+
uniqueItems: true,
|
2889
|
+
},
|
2890
|
+
},
|
2893
2891
|
type: 'array',
|
2894
2892
|
maxItems: 1,
|
2895
2893
|
items: {
|
@@ -2897,7 +2895,7 @@ const rule$j = {
|
|
2897
2895
|
additionalProperties: false,
|
2898
2896
|
properties: {
|
2899
2897
|
fieldName: {
|
2900
|
-
|
2898
|
+
oneOf: [{ $ref: '#/definitions/asString' }, { $ref: '#/definitions/asArray' }],
|
2901
2899
|
default: DEFAULT_ID_FIELD_NAME,
|
2902
2900
|
},
|
2903
2901
|
},
|
@@ -2905,69 +2903,64 @@ const rule$j = {
|
|
2905
2903
|
},
|
2906
2904
|
},
|
2907
2905
|
create(context) {
|
2906
|
+
requireGraphQLSchemaFromContext('require-id-when-available', context);
|
2907
|
+
const siblings = requireSiblingsOperations('require-id-when-available', context);
|
2908
|
+
const { fieldName = DEFAULT_ID_FIELD_NAME } = context.options[0] || {};
|
2909
|
+
const idNames = Array.isArray(fieldName) ? fieldName : [fieldName];
|
2910
|
+
const isFound = (s) => s.kind === Kind.FIELD && idNames.includes(s.name.value);
|
2908
2911
|
return {
|
2909
2912
|
SelectionSet(node) {
|
2910
2913
|
var _a, _b;
|
2911
|
-
|
2912
|
-
|
2913
|
-
const fieldName = (context.options[0] || {}).fieldName || DEFAULT_ID_FIELD_NAME;
|
2914
|
-
if (!node.selections || node.selections.length === 0) {
|
2914
|
+
const typeInfo = node.typeInfo();
|
2915
|
+
if (!typeInfo.gqlType) {
|
2915
2916
|
return;
|
2916
2917
|
}
|
2917
|
-
const
|
2918
|
-
|
2919
|
-
|
2920
|
-
|
2921
|
-
|
2922
|
-
|
2923
|
-
|
2924
|
-
|
2925
|
-
|
2926
|
-
|
2927
|
-
|
2928
|
-
|
2929
|
-
|
2930
|
-
|
2931
|
-
|
2932
|
-
|
2933
|
-
|
2934
|
-
|
2935
|
-
|
2936
|
-
|
2937
|
-
|
2938
|
-
|
2939
|
-
|
2940
|
-
|
2941
|
-
|
2942
|
-
}
|
2943
|
-
}
|
2944
|
-
const { parent } = node;
|
2945
|
-
const hasIdFieldInInterfaceSelectionSet = parent &&
|
2946
|
-
parent.kind === 'InlineFragment' &&
|
2947
|
-
parent.parent &&
|
2948
|
-
parent.parent.kind === 'SelectionSet' &&
|
2949
|
-
parent.parent.selections.some(s => s.kind === 'Field' && s.name.value === fieldName);
|
2950
|
-
if (!found && !hasIdFieldInInterfaceSelectionSet) {
|
2951
|
-
context.report({
|
2952
|
-
loc: {
|
2953
|
-
start: {
|
2954
|
-
line: node.loc.start.line,
|
2955
|
-
column: node.loc.start.column - 1,
|
2956
|
-
},
|
2957
|
-
end: {
|
2958
|
-
line: node.loc.end.line,
|
2959
|
-
column: node.loc.end.column - 1,
|
2960
|
-
},
|
2961
|
-
},
|
2962
|
-
messageId: REQUIRE_ID_WHEN_AVAILABLE,
|
2963
|
-
data: {
|
2964
|
-
checkedFragments: checkedFragmentSpreads.size === 0 ? '' : `(${Array.from(checkedFragmentSpreads).join(', ')})`,
|
2965
|
-
fieldName,
|
2966
|
-
},
|
2967
|
-
});
|
2968
|
-
}
|
2918
|
+
const rawType = getBaseType(typeInfo.gqlType);
|
2919
|
+
const isObjectType = rawType instanceof GraphQLObjectType;
|
2920
|
+
const isInterfaceType = rawType instanceof GraphQLInterfaceType;
|
2921
|
+
if (!isObjectType && !isInterfaceType) {
|
2922
|
+
return;
|
2923
|
+
}
|
2924
|
+
const fields = rawType.getFields();
|
2925
|
+
const hasIdFieldInType = idNames.some(name => fields[name]);
|
2926
|
+
if (!hasIdFieldInType) {
|
2927
|
+
return;
|
2928
|
+
}
|
2929
|
+
const checkedFragmentSpreads = new Set();
|
2930
|
+
let found = false;
|
2931
|
+
for (const selection of node.selections) {
|
2932
|
+
if (isFound(selection)) {
|
2933
|
+
found = true;
|
2934
|
+
}
|
2935
|
+
else if (selection.kind === Kind.INLINE_FRAGMENT) {
|
2936
|
+
found = (_a = selection.selectionSet) === null || _a === void 0 ? void 0 : _a.selections.some(s => isFound(s));
|
2937
|
+
}
|
2938
|
+
else if (selection.kind === Kind.FRAGMENT_SPREAD) {
|
2939
|
+
const [foundSpread] = siblings.getFragment(selection.name.value);
|
2940
|
+
if (foundSpread) {
|
2941
|
+
checkedFragmentSpreads.add(foundSpread.document.name.value);
|
2942
|
+
found = (_b = foundSpread.document.selectionSet) === null || _b === void 0 ? void 0 : _b.selections.some(s => isFound(s));
|
2969
2943
|
}
|
2970
2944
|
}
|
2945
|
+
if (found) {
|
2946
|
+
break;
|
2947
|
+
}
|
2948
|
+
}
|
2949
|
+
const { parent } = node;
|
2950
|
+
const hasIdFieldInInterfaceSelectionSet = parent &&
|
2951
|
+
parent.kind === Kind.INLINE_FRAGMENT &&
|
2952
|
+
parent.parent &&
|
2953
|
+
parent.parent.kind === Kind.SELECTION_SET &&
|
2954
|
+
parent.parent.selections.some(s => isFound(s));
|
2955
|
+
if (!found && !hasIdFieldInInterfaceSelectionSet) {
|
2956
|
+
context.report({
|
2957
|
+
loc: getLocation(node.loc),
|
2958
|
+
messageId: REQUIRE_ID_WHEN_AVAILABLE,
|
2959
|
+
data: {
|
2960
|
+
checkedFragments: checkedFragmentSpreads.size === 0 ? '' : `(${[...checkedFragmentSpreads].join(', ')}) `,
|
2961
|
+
fieldName: idNames.map(name => `"${name}"`).join(' or '),
|
2962
|
+
},
|
2963
|
+
});
|
2971
2964
|
}
|
2972
2965
|
},
|
2973
2966
|
};
|
@@ -3059,7 +3052,7 @@ const rule$k = {
|
|
3059
3052
|
// eslint-disable-next-line no-console
|
3060
3053
|
console.warn(`Rule "selection-set-depth" works best with siblings operations loaded. For more info: http://bit.ly/graphql-eslint-operations`);
|
3061
3054
|
}
|
3062
|
-
const maxDepth = context.options[0]
|
3055
|
+
const { maxDepth } = context.options[0];
|
3063
3056
|
const ignore = context.options[0].ignore || [];
|
3064
3057
|
const checkFn = depthLimit(maxDepth, { ignore });
|
3065
3058
|
return {
|