@graphql-eslint/eslint-plugin 3.2.0-alpha-6aa2721.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 -256
- package/index.mjs +253 -258
- package/package.json +4 -10
- 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,77 +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 };
|
361
|
+
const isGraphQLImportFile = rawSDL => {
|
362
|
+
const trimmedRawSDL = rawSDL.trimLeft();
|
363
|
+
return trimmedRawSDL.startsWith('# import') || trimmedRawSDL.startsWith('#import');
|
370
364
|
};
|
371
|
-
const
|
372
|
-
|
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 fragments = siblings
|
383
|
-
.getFragment(fragmentName)
|
384
|
-
.map(source => source.document)
|
385
|
-
.filter(fragment => fragment.typeCondition.name.value === fragmentTypeName);
|
386
|
-
fragmentsToAdd.push(fragments[0]);
|
387
|
-
}
|
388
|
-
if (fragmentsToAdd.length > 0) {
|
389
|
-
// recall fn to make sure to add fragments inside fragments
|
390
|
-
return handleMissingFragments({
|
391
|
-
ruleId,
|
392
|
-
context,
|
393
|
-
schema,
|
394
|
-
node: {
|
395
|
-
kind: Kind.DOCUMENT,
|
396
|
-
definitions: [...node.definitions, ...fragmentsToAdd],
|
397
|
-
},
|
398
|
-
});
|
399
|
-
}
|
400
|
-
}
|
401
|
-
return node;
|
402
|
-
};
|
403
|
-
const validationToRule = (ruleId, ruleName, docs, getDocumentNode) => {
|
365
|
+
const validationToRule = (name, ruleName, docs, getDocumentNode) => {
|
366
|
+
var _a;
|
404
367
|
let ruleFn = null;
|
405
368
|
try {
|
406
369
|
ruleFn = require(`graphql/validation/rules/${ruleName}Rule`)[`${ruleName}Rule`];
|
407
370
|
}
|
408
|
-
catch (
|
371
|
+
catch (e) {
|
409
372
|
try {
|
410
373
|
ruleFn = require(`graphql/validation/rules/${ruleName}`)[`${ruleName}Rule`];
|
411
374
|
}
|
412
|
-
catch (
|
375
|
+
catch (e) {
|
413
376
|
ruleFn = require('graphql/validation')[`${ruleName}Rule`];
|
414
377
|
}
|
415
378
|
}
|
379
|
+
const requiresSchema = (_a = docs.requiresSchema) !== null && _a !== void 0 ? _a : true;
|
416
380
|
return {
|
417
|
-
[
|
381
|
+
[name]: {
|
418
382
|
meta: {
|
419
383
|
docs: {
|
420
384
|
recommended: true,
|
421
385
|
...docs,
|
422
386
|
graphQLJSRuleName: ruleName,
|
423
|
-
|
387
|
+
requiresSchema,
|
388
|
+
url: `https://github.com/dotansimha/graphql-eslint/blob/master/docs/rules/${name}.md`,
|
424
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).`,
|
425
390
|
},
|
426
391
|
},
|
@@ -429,53 +394,56 @@ const validationToRule = (ruleId, ruleName, docs, getDocumentNode) => {
|
|
429
394
|
Document(node) {
|
430
395
|
if (!ruleFn) {
|
431
396
|
// eslint-disable-next-line no-console
|
432
|
-
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...`);
|
433
398
|
return;
|
434
399
|
}
|
435
|
-
const schema =
|
436
|
-
|
437
|
-
|
438
|
-
|
439
|
-
|
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]);
|
440
407
|
},
|
441
408
|
};
|
442
409
|
},
|
443
410
|
},
|
444
411
|
};
|
445
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
|
+
};
|
446
421
|
const GRAPHQL_JS_VALIDATIONS = Object.assign({}, validationToRule('executable-definitions', 'ExecutableDefinitions', {
|
447
422
|
category: 'Operations',
|
448
423
|
description: `A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.`,
|
449
|
-
requiresSchema: true,
|
450
424
|
}), validationToRule('fields-on-correct-type', 'FieldsOnCorrectType', {
|
451
425
|
category: 'Operations',
|
452
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`.',
|
453
|
-
requiresSchema: true,
|
454
427
|
}), validationToRule('fragments-on-composite-type', 'FragmentsOnCompositeTypes', {
|
455
428
|
category: 'Operations',
|
456
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.`,
|
457
|
-
requiresSchema: true,
|
458
430
|
}), validationToRule('known-argument-names', 'KnownArgumentNames', {
|
459
431
|
category: ['Schema', 'Operations'],
|
460
432
|
description: `A GraphQL field is only valid if all supplied arguments are defined by that field.`,
|
461
|
-
requiresSchema: true,
|
462
433
|
}), validationToRule('known-directives', 'KnownDirectives', {
|
463
434
|
category: ['Schema', 'Operations'],
|
464
435
|
description: `A GraphQL document is only valid if all \`@directives\` are known by the schema and legally positioned.`,
|
465
|
-
requiresSchema: true,
|
466
436
|
}), validationToRule('known-fragment-names', 'KnownFragmentNames', {
|
467
437
|
category: 'Operations',
|
468
438
|
description: `A GraphQL document is only valid if all \`...Fragment\` fragment spreads refer to fragments defined in the same document.`,
|
469
|
-
requiresSchema: true,
|
470
|
-
requiresSiblings: true,
|
471
439
|
examples: [
|
472
440
|
{
|
473
|
-
title: 'Incorrect',
|
441
|
+
title: 'Incorrect (fragment not defined in the document)',
|
474
442
|
code: /* GraphQL */ `
|
475
443
|
query {
|
476
444
|
user {
|
477
445
|
id
|
478
|
-
...UserFields
|
446
|
+
...UserFields
|
479
447
|
}
|
480
448
|
}
|
481
449
|
`,
|
@@ -497,151 +465,153 @@ const GRAPHQL_JS_VALIDATIONS = Object.assign({}, validationToRule('executable-de
|
|
497
465
|
`,
|
498
466
|
},
|
499
467
|
{
|
500
|
-
title: 'Correct (
|
468
|
+
title: 'Correct (existing import to UserFields fragment)',
|
501
469
|
code: /* GraphQL */ `
|
502
|
-
#
|
470
|
+
#import '../UserFields.gql'
|
471
|
+
|
503
472
|
query {
|
504
473
|
user {
|
505
474
|
id
|
506
475
|
...UserFields
|
507
476
|
}
|
508
477
|
}
|
509
|
-
|
510
|
-
# user-fields.gql
|
511
|
-
fragment UserFields on User {
|
512
|
-
id
|
513
|
-
}
|
514
478
|
`,
|
515
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
|
+
},
|
516
502
|
],
|
517
|
-
},
|
503
|
+
}, importFiles), validationToRule('known-type-names', 'KnownTypeNames', {
|
518
504
|
category: ['Schema', 'Operations'],
|
519
505
|
description: `A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.`,
|
520
|
-
requiresSchema: true,
|
521
506
|
}), validationToRule('lone-anonymous-operation', 'LoneAnonymousOperation', {
|
522
507
|
category: 'Operations',
|
523
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.`,
|
524
|
-
requiresSchema: true,
|
525
509
|
}), validationToRule('lone-schema-definition', 'LoneSchemaDefinition', {
|
526
510
|
category: 'Schema',
|
527
511
|
description: `A GraphQL document is only valid if it contains only one schema definition.`,
|
512
|
+
requiresSchema: false,
|
528
513
|
}), validationToRule('no-fragment-cycles', 'NoFragmentCycles', {
|
529
514
|
category: 'Operations',
|
530
515
|
description: `A GraphQL fragment is only valid when it does not have cycles in fragments usage.`,
|
531
|
-
requiresSchema: true,
|
532
516
|
}), validationToRule('no-undefined-variables', 'NoUndefinedVariables', {
|
533
517
|
category: 'Operations',
|
534
518
|
description: `A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.`,
|
535
|
-
|
536
|
-
requiresSiblings: true,
|
537
|
-
}, handleMissingFragments), validationToRule('no-unused-fragments', 'NoUnusedFragments', {
|
519
|
+
}, importFiles), validationToRule('no-unused-fragments', 'NoUnusedFragments', {
|
538
520
|
category: 'Operations',
|
539
521
|
description: `A GraphQL document is only valid if all fragment definitions are spread within operations, or spread within other fragments spread within operations.`,
|
540
|
-
requiresSchema: true,
|
541
522
|
requiresSiblings: true,
|
542
|
-
},
|
543
|
-
const siblings = requireSiblingsOperations(
|
544
|
-
const
|
545
|
-
|
546
|
-
(
|
547
|
-
|
548
|
-
|
549
|
-
}
|
550
|
-
const getParentNode = (
|
551
|
-
const {
|
552
|
-
|
553
|
-
|
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;
|
554
545
|
}
|
555
|
-
|
556
|
-
delete FilePathToDocumentsMap[currentFilePath];
|
557
|
-
for (const [filePath, documents] of Object.entries(FilePathToDocumentsMap)) {
|
558
|
-
const missingFragments = getMissingFragments(schema, {
|
559
|
-
kind: Kind.DOCUMENT,
|
560
|
-
definitions: documents,
|
561
|
-
});
|
562
|
-
const isCurrentFileImportFragment = missingFragments.some(fragment => fragmentDefs.has(fragment));
|
563
|
-
if (isCurrentFileImportFragment) {
|
564
|
-
return getParentNode(filePath, {
|
565
|
-
kind: Kind.DOCUMENT,
|
566
|
-
definitions: [...node.definitions, ...documents],
|
567
|
-
});
|
568
|
-
}
|
569
|
-
}
|
570
|
-
return node;
|
546
|
+
return null;
|
571
547
|
};
|
572
|
-
return getParentNode(context.getFilename()
|
548
|
+
return getParentNode(context.getFilename());
|
573
549
|
}), validationToRule('no-unused-variables', 'NoUnusedVariables', {
|
574
550
|
category: 'Operations',
|
575
551
|
description: `A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.`,
|
576
|
-
|
577
|
-
requiresSiblings: true,
|
578
|
-
}, handleMissingFragments), validationToRule('overlapping-fields-can-be-merged', 'OverlappingFieldsCanBeMerged', {
|
552
|
+
}, importFiles), validationToRule('overlapping-fields-can-be-merged', 'OverlappingFieldsCanBeMerged', {
|
579
553
|
category: 'Operations',
|
580
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.`,
|
581
|
-
requiresSchema: true,
|
582
555
|
}), validationToRule('possible-fragment-spread', 'PossibleFragmentSpreads', {
|
583
556
|
category: 'Operations',
|
584
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.`,
|
585
|
-
requiresSchema: true,
|
586
558
|
}), validationToRule('possible-type-extension', 'PossibleTypeExtensions', {
|
587
559
|
category: 'Schema',
|
588
560
|
description: `A type extension is only valid if the type is defined and has the same kind.`,
|
561
|
+
requiresSchema: false,
|
589
562
|
recommended: false, // TODO: enable after https://github.com/dotansimha/graphql-eslint/issues/787 will be fixed
|
590
563
|
}), validationToRule('provided-required-arguments', 'ProvidedRequiredArguments', {
|
591
564
|
category: ['Schema', 'Operations'],
|
592
565
|
description: `A field or directive is only valid if all required (non-null without a default value) field arguments have been provided.`,
|
593
|
-
requiresSchema: true,
|
594
566
|
}), validationToRule('scalar-leafs', 'ScalarLeafs', {
|
595
567
|
category: 'Operations',
|
596
568
|
description: `A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.`,
|
597
|
-
requiresSchema: true,
|
598
569
|
}), validationToRule('one-field-subscriptions', 'SingleFieldSubscriptions', {
|
599
570
|
category: 'Operations',
|
600
571
|
description: `A GraphQL subscription is valid only if it contains a single root field.`,
|
601
|
-
requiresSchema: true,
|
602
572
|
}), validationToRule('unique-argument-names', 'UniqueArgumentNames', {
|
603
573
|
category: 'Operations',
|
604
574
|
description: `A GraphQL field or directive is only valid if all supplied arguments are uniquely named.`,
|
605
|
-
requiresSchema: true,
|
606
575
|
}), validationToRule('unique-directive-names', 'UniqueDirectiveNames', {
|
607
576
|
category: 'Schema',
|
608
577
|
description: `A GraphQL document is only valid if all defined directives have unique names.`,
|
578
|
+
requiresSchema: false,
|
609
579
|
}), validationToRule('unique-directive-names-per-location', 'UniqueDirectivesPerLocation', {
|
610
580
|
category: ['Schema', 'Operations'],
|
611
581
|
description: `A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.`,
|
612
|
-
requiresSchema: true,
|
613
582
|
}), validationToRule('unique-enum-value-names', 'UniqueEnumValueNames', {
|
614
583
|
category: 'Schema',
|
615
584
|
description: `A GraphQL enum type is only valid if all its values are uniquely named.`,
|
585
|
+
requiresSchema: false,
|
616
586
|
recommended: false,
|
617
587
|
}), validationToRule('unique-field-definition-names', 'UniqueFieldDefinitionNames', {
|
618
588
|
category: 'Schema',
|
619
589
|
description: `A GraphQL complex type is only valid if all its fields are uniquely named.`,
|
590
|
+
requiresSchema: false,
|
620
591
|
}), validationToRule('unique-input-field-names', 'UniqueInputFieldNames', {
|
621
592
|
category: 'Operations',
|
622
593
|
description: `A GraphQL input object value is only valid if all supplied fields are uniquely named.`,
|
594
|
+
requiresSchema: false,
|
623
595
|
}), validationToRule('unique-operation-types', 'UniqueOperationTypes', {
|
624
596
|
category: 'Schema',
|
625
597
|
description: `A GraphQL document is only valid if it has only one type per operation.`,
|
598
|
+
requiresSchema: false,
|
626
599
|
}), validationToRule('unique-type-names', 'UniqueTypeNames', {
|
627
600
|
category: 'Schema',
|
628
601
|
description: `A GraphQL document is only valid if all defined types have unique names.`,
|
602
|
+
requiresSchema: false,
|
629
603
|
}), validationToRule('unique-variable-names', 'UniqueVariableNames', {
|
630
604
|
category: 'Operations',
|
631
605
|
description: `A GraphQL operation is only valid if all its variables are uniquely named.`,
|
632
|
-
requiresSchema: true,
|
633
606
|
}), validationToRule('value-literals-of-correct-type', 'ValuesOfCorrectType', {
|
634
607
|
category: 'Operations',
|
635
608
|
description: `A GraphQL document is only valid if all value literals are of the type expected at their position.`,
|
636
|
-
requiresSchema: true,
|
637
609
|
}), validationToRule('variables-are-input-types', 'VariablesAreInputTypes', {
|
638
610
|
category: 'Operations',
|
639
611
|
description: `A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).`,
|
640
|
-
requiresSchema: true,
|
641
612
|
}), validationToRule('variables-in-allowed-position', 'VariablesInAllowedPosition', {
|
642
613
|
category: 'Operations',
|
643
614
|
description: `Variables passed to field arguments conform to type.`,
|
644
|
-
requiresSchema: true,
|
645
615
|
}));
|
646
616
|
|
647
617
|
const ALPHABETIZE = 'ALPHABETIZE';
|
@@ -1075,13 +1045,7 @@ const rule$2 = {
|
|
1075
1045
|
const MATCH_EXTENSION = 'MATCH_EXTENSION';
|
1076
1046
|
const MATCH_STYLE = 'MATCH_STYLE';
|
1077
1047
|
const ACCEPTED_EXTENSIONS = ['.gql', '.graphql'];
|
1078
|
-
const CASE_STYLES = [
|
1079
|
-
CaseStyle.camelCase,
|
1080
|
-
CaseStyle.pascalCase,
|
1081
|
-
CaseStyle.snakeCase,
|
1082
|
-
CaseStyle.upperCase,
|
1083
|
-
CaseStyle.kebabCase,
|
1084
|
-
];
|
1048
|
+
const CASE_STYLES = ['camelCase', 'PascalCase', 'snake_case', 'UPPER_CASE', 'kebab-case'];
|
1085
1049
|
const schemaOption = {
|
1086
1050
|
oneOf: [{ $ref: '#/definitions/asString' }, { $ref: '#/definitions/asObject' }],
|
1087
1051
|
};
|
@@ -1105,7 +1069,7 @@ const rule$3 = {
|
|
1105
1069
|
},
|
1106
1070
|
{
|
1107
1071
|
title: 'Correct',
|
1108
|
-
usage: [{ query:
|
1072
|
+
usage: [{ query: 'snake_case' }],
|
1109
1073
|
code: /* GraphQL */ `
|
1110
1074
|
# user_by_id.gql
|
1111
1075
|
query UserById {
|
@@ -1119,7 +1083,7 @@ const rule$3 = {
|
|
1119
1083
|
},
|
1120
1084
|
{
|
1121
1085
|
title: 'Correct',
|
1122
|
-
usage: [{ fragment: { style:
|
1086
|
+
usage: [{ fragment: { style: 'kebab-case', suffix: '.fragment' } }],
|
1123
1087
|
code: /* GraphQL */ `
|
1124
1088
|
# user-fields.fragment.gql
|
1125
1089
|
fragment user_fields on User {
|
@@ -1130,7 +1094,7 @@ const rule$3 = {
|
|
1130
1094
|
},
|
1131
1095
|
{
|
1132
1096
|
title: 'Correct',
|
1133
|
-
usage: [{ mutation: { style:
|
1097
|
+
usage: [{ mutation: { style: 'PascalCase', suffix: 'Mutation' } }],
|
1134
1098
|
code: /* GraphQL */ `
|
1135
1099
|
# DeleteUserMutation.gql
|
1136
1100
|
mutation DELETE_USER {
|
@@ -1150,7 +1114,7 @@ const rule$3 = {
|
|
1150
1114
|
},
|
1151
1115
|
{
|
1152
1116
|
title: 'Incorrect',
|
1153
|
-
usage: [{ query:
|
1117
|
+
usage: [{ query: 'PascalCase' }],
|
1154
1118
|
code: /* GraphQL */ `
|
1155
1119
|
# user-by-id.gql
|
1156
1120
|
query UserById {
|
@@ -1165,10 +1129,10 @@ const rule$3 = {
|
|
1165
1129
|
],
|
1166
1130
|
configOptions: [
|
1167
1131
|
{
|
1168
|
-
query:
|
1169
|
-
mutation:
|
1170
|
-
subscription:
|
1171
|
-
fragment:
|
1132
|
+
query: 'kebab-case',
|
1133
|
+
mutation: 'kebab-case',
|
1134
|
+
subscription: 'kebab-case',
|
1135
|
+
fragment: 'kebab-case',
|
1172
1136
|
},
|
1173
1137
|
],
|
1174
1138
|
},
|
@@ -1185,25 +1149,22 @@ const rule$3 = {
|
|
1185
1149
|
asObject: {
|
1186
1150
|
type: 'object',
|
1187
1151
|
additionalProperties: false,
|
1152
|
+
minProperties: 1,
|
1188
1153
|
properties: {
|
1189
|
-
style: {
|
1190
|
-
|
1191
|
-
},
|
1192
|
-
suffix: {
|
1193
|
-
type: 'string',
|
1194
|
-
},
|
1154
|
+
style: { enum: CASE_STYLES },
|
1155
|
+
suffix: { type: 'string' },
|
1195
1156
|
},
|
1196
1157
|
},
|
1197
1158
|
},
|
1198
1159
|
type: 'array',
|
1160
|
+
minItems: 1,
|
1199
1161
|
maxItems: 1,
|
1200
1162
|
items: {
|
1201
1163
|
type: 'object',
|
1202
1164
|
additionalProperties: false,
|
1165
|
+
minProperties: 1,
|
1203
1166
|
properties: {
|
1204
|
-
fileExtension: {
|
1205
|
-
enum: ACCEPTED_EXTENSIONS,
|
1206
|
-
},
|
1167
|
+
fileExtension: { enum: ACCEPTED_EXTENSIONS },
|
1207
1168
|
query: schemaOption,
|
1208
1169
|
mutation: schemaOption,
|
1209
1170
|
subscription: schemaOption,
|
@@ -1258,7 +1219,7 @@ const rule$3 = {
|
|
1258
1219
|
option = { style: option };
|
1259
1220
|
}
|
1260
1221
|
const expectedExtension = options.fileExtension || fileExtension;
|
1261
|
-
const expectedFilename = convertCase(option.style, docName) + (option.suffix || '') + expectedExtension;
|
1222
|
+
const expectedFilename = (option.style ? convertCase(option.style, docName) : filename) + (option.suffix || '') + expectedExtension;
|
1262
1223
|
const filenameWithExtension = filename + expectedExtension;
|
1263
1224
|
if (expectedFilename !== filenameWithExtension) {
|
1264
1225
|
context.report({
|
@@ -1410,6 +1371,7 @@ const rule$4 = {
|
|
1410
1371
|
],
|
1411
1372
|
},
|
1412
1373
|
},
|
1374
|
+
hasSuggestions: true,
|
1413
1375
|
schema: {
|
1414
1376
|
definitions: {
|
1415
1377
|
asString: {
|
@@ -1484,65 +1446,90 @@ const rule$4 = {
|
|
1484
1446
|
const style = restOptions[kind] || types;
|
1485
1447
|
return typeof style === 'object' ? style : { style };
|
1486
1448
|
}
|
1487
|
-
const checkNode = (selector) => (
|
1488
|
-
const { name } =
|
1489
|
-
if (!
|
1449
|
+
const checkNode = (selector) => (n) => {
|
1450
|
+
const { name: node } = n.kind === Kind.VARIABLE_DEFINITION ? n.variable : n;
|
1451
|
+
if (!node) {
|
1490
1452
|
return;
|
1491
1453
|
}
|
1492
1454
|
const { prefix, suffix, forbiddenPrefixes, forbiddenSuffixes, style } = normalisePropertyOption(selector);
|
1493
|
-
const nodeType = KindToDisplayName[
|
1494
|
-
const nodeName =
|
1495
|
-
const
|
1496
|
-
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;
|
1497
1463
|
context.report({
|
1498
|
-
loc: getLocation(
|
1464
|
+
loc: getLocation(node.loc, node.value),
|
1499
1465
|
message: `${nodeType} "${nodeName}" should ${errorMessage}`,
|
1466
|
+
suggest: [
|
1467
|
+
{
|
1468
|
+
desc: `Rename to "${suggestedName}"`,
|
1469
|
+
fix: fixer => fixer.replaceText(node, suggestedName),
|
1470
|
+
},
|
1471
|
+
],
|
1500
1472
|
});
|
1501
1473
|
}
|
1502
|
-
function
|
1503
|
-
|
1504
|
-
if (allowLeadingUnderscore) {
|
1505
|
-
name = name.replace(/^_*/, '');
|
1506
|
-
}
|
1507
|
-
if (allowTrailingUnderscore) {
|
1508
|
-
name = name.replace(/_*$/, '');
|
1509
|
-
}
|
1474
|
+
function getError() {
|
1475
|
+
const name = nodeName.replace(/(^_+)|(_+$)/g, '');
|
1510
1476
|
if (prefix && !name.startsWith(prefix)) {
|
1511
|
-
return
|
1477
|
+
return {
|
1478
|
+
errorMessage: `have "${prefix}" prefix`,
|
1479
|
+
renameToName: prefix + name,
|
1480
|
+
};
|
1512
1481
|
}
|
1513
1482
|
if (suffix && !name.endsWith(suffix)) {
|
1514
|
-
return
|
1483
|
+
return {
|
1484
|
+
errorMessage: `have "${suffix}" suffix`,
|
1485
|
+
renameToName: name + suffix,
|
1486
|
+
};
|
1515
1487
|
}
|
1516
1488
|
const forbiddenPrefix = forbiddenPrefixes === null || forbiddenPrefixes === void 0 ? void 0 : forbiddenPrefixes.find(prefix => name.startsWith(prefix));
|
1517
1489
|
if (forbiddenPrefix) {
|
1518
|
-
return
|
1490
|
+
return {
|
1491
|
+
errorMessage: `not have "${forbiddenPrefix}" prefix`,
|
1492
|
+
renameToName: name.replace(new RegExp(`^${forbiddenPrefix}`), ''),
|
1493
|
+
};
|
1519
1494
|
}
|
1520
1495
|
const forbiddenSuffix = forbiddenSuffixes === null || forbiddenSuffixes === void 0 ? void 0 : forbiddenSuffixes.find(suffix => name.endsWith(suffix));
|
1521
1496
|
if (forbiddenSuffix) {
|
1522
|
-
return
|
1523
|
-
|
1524
|
-
|
1525
|
-
|
1497
|
+
return {
|
1498
|
+
errorMessage: `not have "${forbiddenSuffix}" suffix`,
|
1499
|
+
renameToName: name.replace(new RegExp(`${forbiddenSuffix}$`), ''),
|
1500
|
+
};
|
1526
1501
|
}
|
1527
1502
|
const caseRegex = StyleToRegex[style];
|
1528
1503
|
if (caseRegex && !caseRegex.test(name)) {
|
1529
|
-
return
|
1504
|
+
return {
|
1505
|
+
errorMessage: `be in ${style} format`,
|
1506
|
+
renameToName: convertCase(style, name),
|
1507
|
+
};
|
1530
1508
|
}
|
1531
1509
|
}
|
1532
1510
|
};
|
1533
|
-
const checkUnderscore = (node) => {
|
1511
|
+
const checkUnderscore = (isLeading) => (node) => {
|
1534
1512
|
const name = node.value;
|
1513
|
+
const renameToName = name.replace(new RegExp(isLeading ? '^_+' : '_+$'), '');
|
1535
1514
|
context.report({
|
1536
1515
|
loc: getLocation(node.loc, name),
|
1537
|
-
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
|
+
],
|
1538
1523
|
});
|
1539
1524
|
};
|
1540
1525
|
const listeners = {};
|
1541
1526
|
if (!allowLeadingUnderscore) {
|
1542
|
-
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);
|
1543
1529
|
}
|
1544
1530
|
if (!allowTrailingUnderscore) {
|
1545
|
-
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);
|
1546
1533
|
}
|
1547
1534
|
const selectors = new Set([types && TYPES_KINDS, Object.keys(restOptions)].flat().filter(Boolean));
|
1548
1535
|
for (const selector of selectors) {
|
@@ -2885,9 +2872,22 @@ const rule$j = {
|
|
2885
2872
|
recommended: true,
|
2886
2873
|
},
|
2887
2874
|
messages: {
|
2888
|
-
[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'),
|
2889
2879
|
},
|
2890
2880
|
schema: {
|
2881
|
+
definitions: {
|
2882
|
+
asString: {
|
2883
|
+
type: 'string',
|
2884
|
+
},
|
2885
|
+
asArray: {
|
2886
|
+
type: 'array',
|
2887
|
+
minItems: 1,
|
2888
|
+
uniqueItems: true,
|
2889
|
+
},
|
2890
|
+
},
|
2891
2891
|
type: 'array',
|
2892
2892
|
maxItems: 1,
|
2893
2893
|
items: {
|
@@ -2895,7 +2895,7 @@ const rule$j = {
|
|
2895
2895
|
additionalProperties: false,
|
2896
2896
|
properties: {
|
2897
2897
|
fieldName: {
|
2898
|
-
|
2898
|
+
oneOf: [{ $ref: '#/definitions/asString' }, { $ref: '#/definitions/asArray' }],
|
2899
2899
|
default: DEFAULT_ID_FIELD_NAME,
|
2900
2900
|
},
|
2901
2901
|
},
|
@@ -2903,69 +2903,64 @@ const rule$j = {
|
|
2903
2903
|
},
|
2904
2904
|
},
|
2905
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);
|
2906
2911
|
return {
|
2907
2912
|
SelectionSet(node) {
|
2908
2913
|
var _a, _b;
|
2909
|
-
|
2910
|
-
|
2911
|
-
const fieldName = (context.options[0] || {}).fieldName || DEFAULT_ID_FIELD_NAME;
|
2912
|
-
if (!node.selections || node.selections.length === 0) {
|
2914
|
+
const typeInfo = node.typeInfo();
|
2915
|
+
if (!typeInfo.gqlType) {
|
2913
2916
|
return;
|
2914
2917
|
}
|
2915
|
-
const
|
2916
|
-
|
2917
|
-
|
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
|
-
const { parent } = node;
|
2943
|
-
const hasIdFieldInInterfaceSelectionSet = parent &&
|
2944
|
-
parent.kind === 'InlineFragment' &&
|
2945
|
-
parent.parent &&
|
2946
|
-
parent.parent.kind === 'SelectionSet' &&
|
2947
|
-
parent.parent.selections.some(s => s.kind === 'Field' && s.name.value === fieldName);
|
2948
|
-
if (!found && !hasIdFieldInInterfaceSelectionSet) {
|
2949
|
-
context.report({
|
2950
|
-
loc: {
|
2951
|
-
start: {
|
2952
|
-
line: node.loc.start.line,
|
2953
|
-
column: node.loc.start.column - 1,
|
2954
|
-
},
|
2955
|
-
end: {
|
2956
|
-
line: node.loc.end.line,
|
2957
|
-
column: node.loc.end.column - 1,
|
2958
|
-
},
|
2959
|
-
},
|
2960
|
-
messageId: REQUIRE_ID_WHEN_AVAILABLE,
|
2961
|
-
data: {
|
2962
|
-
checkedFragments: checkedFragmentSpreads.size === 0 ? '' : `(${Array.from(checkedFragmentSpreads).join(', ')})`,
|
2963
|
-
fieldName,
|
2964
|
-
},
|
2965
|
-
});
|
2966
|
-
}
|
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));
|
2967
2943
|
}
|
2968
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
|
+
});
|
2969
2964
|
}
|
2970
2965
|
},
|
2971
2966
|
};
|
@@ -3057,7 +3052,7 @@ const rule$k = {
|
|
3057
3052
|
// eslint-disable-next-line no-console
|
3058
3053
|
console.warn(`Rule "selection-set-depth" works best with siblings operations loaded. For more info: http://bit.ly/graphql-eslint-operations`);
|
3059
3054
|
}
|
3060
|
-
const maxDepth = context.options[0]
|
3055
|
+
const { maxDepth } = context.options[0];
|
3061
3056
|
const ignore = context.options[0].ignore || [];
|
3062
3057
|
const checkFn = depthLimit(maxDepth, { ignore });
|
3063
3058
|
return {
|