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