@graphql-eslint/eslint-plugin 3.2.0-alpha-001cd75.0 → 3.2.0-alpha-4ca7218.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.mjs CHANGED
@@ -1,8 +1,7 @@
1
- import { Kind, validate, TokenKind, isScalarType, isNonNullType, isListType, isObjectType as isObjectType$1, visit, visitWithTypeInfo, GraphQLObjectType, GraphQLInterfaceType, TypeInfo, isInterfaceType, Source, GraphQLError } from 'graphql';
1
+ import { Kind, validate, TypeInfo, visitWithTypeInfo, visit, TokenKind, isScalarType, isNonNullType, isListType, isObjectType as isObjectType$1, GraphQLObjectType, GraphQLInterfaceType, isInterfaceType, Source, GraphQLError } from 'graphql';
2
2
  import { validateSDL } from 'graphql/validation/validate';
3
- import { processImport, parseImportLine } from '@graphql-tools/import';
4
3
  import { statSync, existsSync, readFileSync } from 'fs';
5
- import { dirname, join, extname, basename, relative, resolve } from 'path';
4
+ import { dirname, extname, basename, relative, resolve } from 'path';
6
5
  import { asArray, parseGraphQLSDL } from '@graphql-tools/utils';
7
6
  import lowerCase from 'lodash.lowercase';
8
7
  import depthLimit from 'graphql-depth-limit';
@@ -280,6 +279,14 @@ const TYPES_KINDS = [
280
279
  Kind.INPUT_OBJECT_TYPE_DEFINITION,
281
280
  Kind.UNION_TYPE_DEFINITION,
282
281
  ];
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 = {}));
283
290
  const pascalCase = (str) => lowerCase(str)
284
291
  .split(' ')
285
292
  .map(word => word.charAt(0).toUpperCase() + word.slice(1))
@@ -290,15 +297,15 @@ const camelCase = (str) => {
290
297
  };
291
298
  const convertCase = (style, str) => {
292
299
  switch (style) {
293
- case 'camelCase':
300
+ case CaseStyle.camelCase:
294
301
  return camelCase(str);
295
- case 'PascalCase':
302
+ case CaseStyle.pascalCase:
296
303
  return pascalCase(str);
297
- case 'snake_case':
304
+ case CaseStyle.snakeCase:
298
305
  return lowerCase(str).replace(/ /g, '_');
299
- case 'UPPER_CASE':
306
+ case CaseStyle.upperCase:
300
307
  return lowerCase(str).replace(/ /g, '_').toUpperCase();
301
- case 'kebab-case':
308
+ case CaseStyle.kebabCase:
302
309
  return lowerCase(str).replace(/ /g, '-');
303
310
  }
304
311
  };
@@ -321,59 +328,101 @@ function getLocation(loc, fieldName = '', offset) {
321
328
  };
322
329
  }
323
330
 
324
- function extractRuleName(stack) {
325
- const match = (stack || '').match(/validation[/\\]rules[/\\](.*?)\.js:/) || [];
326
- return match[1] || null;
331
+ function validateDocument(sourceNode, context, schema, documentNode, rule) {
332
+ if (documentNode.definitions.length === 0) {
333
+ return;
334
+ }
335
+ try {
336
+ const validationErrors = schema
337
+ ? validate(schema, documentNode, [rule])
338
+ : validateSDL(documentNode, null, [rule]);
339
+ for (const error of validationErrors) {
340
+ context.report({
341
+ loc: getLocation({ start: error.locations[0] }),
342
+ message: error.message,
343
+ });
344
+ }
345
+ }
346
+ catch (e) {
347
+ context.report({
348
+ node: sourceNode,
349
+ message: e.message,
350
+ });
351
+ }
327
352
  }
328
- function validateDoc(sourceNode, context, schema, documentNode, rules, ruleName = null) {
329
- var _a;
330
- if (((_a = documentNode === null || documentNode === void 0 ? void 0 : documentNode.definitions) === null || _a === void 0 ? void 0 : _a.length) > 0) {
331
- try {
332
- const validationErrors = schema ? validate(schema, documentNode, rules) : validateSDL(documentNode, null, rules);
333
- for (const error of validationErrors) {
334
- const validateRuleName = ruleName || `[${extractRuleName(error.stack)}]`;
335
- context.report({
336
- loc: getLocation({ start: error.locations[0] }),
337
- message: ruleName ? error.message : `${validateRuleName} ${error.message}`,
338
- });
353
+ const getFragmentDefsAndFragmentSpreads = (schema, node) => {
354
+ const typeInfo = new TypeInfo(schema);
355
+ const fragmentDefs = new Set();
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);
339
388
  }
340
389
  }
341
- catch (e) {
342
- context.report({
343
- node: sourceNode,
344
- message: e.message,
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
+ },
345
400
  });
346
401
  }
347
402
  }
348
- }
349
- const isGraphQLImportFile = rawSDL => {
350
- const trimmedRawSDL = rawSDL.trimLeft();
351
- return trimmedRawSDL.startsWith('# import') || trimmedRawSDL.startsWith('#import');
403
+ return node;
352
404
  };
353
- const validationToRule = (name, ruleName, docs, getDocumentNode) => {
354
- var _a;
405
+ const validationToRule = (ruleId, ruleName, docs, getDocumentNode) => {
355
406
  let ruleFn = null;
356
407
  try {
357
408
  ruleFn = require(`graphql/validation/rules/${ruleName}Rule`)[`${ruleName}Rule`];
358
409
  }
359
- catch (e) {
410
+ catch (_a) {
360
411
  try {
361
412
  ruleFn = require(`graphql/validation/rules/${ruleName}`)[`${ruleName}Rule`];
362
413
  }
363
- catch (e) {
414
+ catch (_b) {
364
415
  ruleFn = require('graphql/validation')[`${ruleName}Rule`];
365
416
  }
366
417
  }
367
- const requiresSchema = (_a = docs.requiresSchema) !== null && _a !== void 0 ? _a : true;
368
418
  return {
369
- [name]: {
419
+ [ruleId]: {
370
420
  meta: {
371
421
  docs: {
372
422
  recommended: true,
373
423
  ...docs,
374
424
  graphQLJSRuleName: ruleName,
375
- requiresSchema,
376
- url: `https://github.com/dotansimha/graphql-eslint/blob/master/docs/rules/${name}.md`,
425
+ url: `https://github.com/dotansimha/graphql-eslint/blob/master/docs/rules/${ruleId}.md`,
377
426
  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).`,
378
427
  },
379
428
  },
@@ -382,56 +431,53 @@ const validationToRule = (name, ruleName, docs, getDocumentNode) => {
382
431
  Document(node) {
383
432
  if (!ruleFn) {
384
433
  // eslint-disable-next-line no-console
385
- 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...`);
434
+ 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...`);
386
435
  return;
387
436
  }
388
- const schema = requiresSchema ? requireGraphQLSchemaFromContext(name, context) : null;
389
- let documentNode;
390
- const isRealFile = existsSync(context.getFilename());
391
- if (isRealFile && getDocumentNode) {
392
- documentNode = getDocumentNode(context);
393
- }
394
- validateDoc(node, context, schema, documentNode || node.rawNode(), [ruleFn], ruleName);
437
+ const schema = docs.requiresSchema ? requireGraphQLSchemaFromContext(ruleId, context) : null;
438
+ const documentNode = getDocumentNode
439
+ ? getDocumentNode({ ruleId, context, schema, node: node.rawNode() })
440
+ : node.rawNode();
441
+ validateDocument(node, context, schema, documentNode, ruleFn);
395
442
  },
396
443
  };
397
444
  },
398
445
  },
399
446
  };
400
447
  };
401
- const importFiles = (context) => {
402
- const code = context.getSourceCode().text;
403
- if (!isGraphQLImportFile(code)) {
404
- return null;
405
- }
406
- // Import documents because file contains '#import' comments
407
- return processImport(context.getFilename());
408
- };
409
448
  const GRAPHQL_JS_VALIDATIONS = Object.assign({}, validationToRule('executable-definitions', 'ExecutableDefinitions', {
410
449
  category: 'Operations',
411
450
  description: `A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.`,
451
+ requiresSchema: true,
412
452
  }), validationToRule('fields-on-correct-type', 'FieldsOnCorrectType', {
413
453
  category: 'Operations',
414
454
  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,
415
456
  }), validationToRule('fragments-on-composite-type', 'FragmentsOnCompositeTypes', {
416
457
  category: 'Operations',
417
458
  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,
418
460
  }), validationToRule('known-argument-names', 'KnownArgumentNames', {
419
461
  category: ['Schema', 'Operations'],
420
462
  description: `A GraphQL field is only valid if all supplied arguments are defined by that field.`,
463
+ requiresSchema: true,
421
464
  }), validationToRule('known-directives', 'KnownDirectives', {
422
465
  category: ['Schema', 'Operations'],
423
466
  description: `A GraphQL document is only valid if all \`@directives\` are known by the schema and legally positioned.`,
467
+ requiresSchema: true,
424
468
  }), validationToRule('known-fragment-names', 'KnownFragmentNames', {
425
469
  category: 'Operations',
426
470
  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,
427
473
  examples: [
428
474
  {
429
- title: 'Incorrect (fragment not defined in the document)',
475
+ title: 'Incorrect',
430
476
  code: /* GraphQL */ `
431
477
  query {
432
478
  user {
433
479
  id
434
- ...UserFields
480
+ ...UserFields # fragment not defined in the document
435
481
  }
436
482
  }
437
483
  `,
@@ -453,153 +499,151 @@ const GRAPHQL_JS_VALIDATIONS = Object.assign({}, validationToRule('executable-de
453
499
  `,
454
500
  },
455
501
  {
456
- title: 'Correct (existing import to UserFields fragment)',
502
+ title: 'Correct (`UserFields` fragment located in a separate file)',
457
503
  code: /* GraphQL */ `
458
- #import '../UserFields.gql'
459
-
504
+ # user.gql
460
505
  query {
461
506
  user {
462
507
  id
463
508
  ...UserFields
464
509
  }
465
510
  }
466
- `,
467
- },
468
- {
469
- 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.",
470
- code: `
471
- const USER_FIELDS = gql\`
472
- fragment UserFields on User {
473
- id
474
- }
475
- \`
476
-
477
- const GET_USER = /* GraphQL */ \`
478
- # eslint @graphql-eslint/known-fragment-names: 'error'
479
-
480
- query User {
481
- user {
482
- ...UserFields
483
- }
484
- }
485
511
 
486
- # Will give false positive error 'Unknown fragment "UserFields"'
487
- \${USER_FIELDS}
488
- \``,
512
+ # user-fields.gql
513
+ fragment UserFields on User {
514
+ id
515
+ }
516
+ `,
489
517
  },
490
518
  ],
491
- }, importFiles), validationToRule('known-type-names', 'KnownTypeNames', {
519
+ }, handleMissingFragments), validationToRule('known-type-names', 'KnownTypeNames', {
492
520
  category: ['Schema', 'Operations'],
493
521
  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,
494
523
  }), validationToRule('lone-anonymous-operation', 'LoneAnonymousOperation', {
495
524
  category: 'Operations',
496
525
  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,
497
527
  }), validationToRule('lone-schema-definition', 'LoneSchemaDefinition', {
498
528
  category: 'Schema',
499
529
  description: `A GraphQL document is only valid if it contains only one schema definition.`,
500
- requiresSchema: false,
501
530
  }), validationToRule('no-fragment-cycles', 'NoFragmentCycles', {
502
531
  category: 'Operations',
503
532
  description: `A GraphQL fragment is only valid when it does not have cycles in fragments usage.`,
533
+ requiresSchema: true,
504
534
  }), validationToRule('no-undefined-variables', 'NoUndefinedVariables', {
505
535
  category: 'Operations',
506
536
  description: `A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.`,
507
- }, importFiles), validationToRule('no-unused-fragments', 'NoUnusedFragments', {
537
+ requiresSchema: true,
538
+ requiresSiblings: true,
539
+ }, handleMissingFragments), validationToRule('no-unused-fragments', 'NoUnusedFragments', {
508
540
  category: 'Operations',
509
541
  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,
510
543
  requiresSiblings: true,
511
- }, context => {
512
- const siblings = requireSiblingsOperations('no-unused-fragments', context);
513
- const documents = [...siblings.getOperations(), ...siblings.getFragments()]
514
- .filter(({ document }) => isGraphQLImportFile(document.loc.source.body))
515
- .map(({ filePath, document }) => ({
516
- filePath,
517
- code: document.loc.source.body,
518
- }));
519
- const getParentNode = (filePath) => {
520
- for (const { filePath: docFilePath, code } of documents) {
521
- const isFileImported = code
522
- .split('\n')
523
- .filter(isGraphQLImportFile)
524
- .map(line => parseImportLine(line.replace('#', '')))
525
- .some(o => filePath === join(dirname(docFilePath), o.from));
526
- if (!isFileImported) {
527
- continue;
528
- }
529
- // Import first file that import this file
530
- const document = processImport(docFilePath);
531
- // Import most top file that import this file
532
- return getParentNode(docFilePath) || document;
544
+ }, ({ ruleId, context, schema, node }) => {
545
+ const siblings = requireSiblingsOperations(ruleId, context);
546
+ const FilePathToDocumentsMap = [...siblings.getOperations(), ...siblings.getFragments()].reduce((map, { filePath, document }) => {
547
+ var _a;
548
+ (_a = map[filePath]) !== null && _a !== void 0 ? _a : (map[filePath] = []);
549
+ map[filePath].push(document);
550
+ return map;
551
+ }, Object.create(null));
552
+ const getParentNode = (currentFilePath, node) => {
553
+ const { fragmentDefs } = getFragmentDefsAndFragmentSpreads(schema, node);
554
+ if (fragmentDefs.size === 0) {
555
+ return node;
533
556
  }
534
- return null;
557
+ // skip iteration over documents for current filepath
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;
535
573
  };
536
- return getParentNode(context.getFilename());
574
+ return getParentNode(context.getFilename(), node);
537
575
  }), validationToRule('no-unused-variables', 'NoUnusedVariables', {
538
576
  category: 'Operations',
539
577
  description: `A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.`,
540
- }, importFiles), validationToRule('overlapping-fields-can-be-merged', 'OverlappingFieldsCanBeMerged', {
578
+ requiresSchema: true,
579
+ requiresSiblings: true,
580
+ }, handleMissingFragments), validationToRule('overlapping-fields-can-be-merged', 'OverlappingFieldsCanBeMerged', {
541
581
  category: 'Operations',
542
582
  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,
543
584
  }), validationToRule('possible-fragment-spread', 'PossibleFragmentSpreads', {
544
585
  category: 'Operations',
545
586
  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,
546
588
  }), validationToRule('possible-type-extension', 'PossibleTypeExtensions', {
547
589
  category: 'Schema',
548
590
  description: `A type extension is only valid if the type is defined and has the same kind.`,
549
- requiresSchema: false,
550
591
  recommended: false, // TODO: enable after https://github.com/dotansimha/graphql-eslint/issues/787 will be fixed
551
592
  }), validationToRule('provided-required-arguments', 'ProvidedRequiredArguments', {
552
593
  category: ['Schema', 'Operations'],
553
594
  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,
554
596
  }), validationToRule('scalar-leafs', 'ScalarLeafs', {
555
597
  category: 'Operations',
556
598
  description: `A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.`,
599
+ requiresSchema: true,
557
600
  }), validationToRule('one-field-subscriptions', 'SingleFieldSubscriptions', {
558
601
  category: 'Operations',
559
602
  description: `A GraphQL subscription is valid only if it contains a single root field.`,
603
+ requiresSchema: true,
560
604
  }), validationToRule('unique-argument-names', 'UniqueArgumentNames', {
561
605
  category: 'Operations',
562
606
  description: `A GraphQL field or directive is only valid if all supplied arguments are uniquely named.`,
607
+ requiresSchema: true,
563
608
  }), validationToRule('unique-directive-names', 'UniqueDirectiveNames', {
564
609
  category: 'Schema',
565
610
  description: `A GraphQL document is only valid if all defined directives have unique names.`,
566
- requiresSchema: false,
567
611
  }), validationToRule('unique-directive-names-per-location', 'UniqueDirectivesPerLocation', {
568
612
  category: ['Schema', 'Operations'],
569
613
  description: `A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.`,
614
+ requiresSchema: true,
570
615
  }), validationToRule('unique-enum-value-names', 'UniqueEnumValueNames', {
571
616
  category: 'Schema',
572
617
  description: `A GraphQL enum type is only valid if all its values are uniquely named.`,
573
- requiresSchema: false,
574
618
  recommended: false,
575
619
  }), validationToRule('unique-field-definition-names', 'UniqueFieldDefinitionNames', {
576
620
  category: 'Schema',
577
621
  description: `A GraphQL complex type is only valid if all its fields are uniquely named.`,
578
- requiresSchema: false,
579
622
  }), validationToRule('unique-input-field-names', 'UniqueInputFieldNames', {
580
623
  category: 'Operations',
581
624
  description: `A GraphQL input object value is only valid if all supplied fields are uniquely named.`,
582
- requiresSchema: false,
583
625
  }), validationToRule('unique-operation-types', 'UniqueOperationTypes', {
584
626
  category: 'Schema',
585
627
  description: `A GraphQL document is only valid if it has only one type per operation.`,
586
- requiresSchema: false,
587
628
  }), validationToRule('unique-type-names', 'UniqueTypeNames', {
588
629
  category: 'Schema',
589
630
  description: `A GraphQL document is only valid if all defined types have unique names.`,
590
- requiresSchema: false,
591
631
  }), validationToRule('unique-variable-names', 'UniqueVariableNames', {
592
632
  category: 'Operations',
593
633
  description: `A GraphQL operation is only valid if all its variables are uniquely named.`,
634
+ requiresSchema: true,
594
635
  }), validationToRule('value-literals-of-correct-type', 'ValuesOfCorrectType', {
595
636
  category: 'Operations',
596
637
  description: `A GraphQL document is only valid if all value literals are of the type expected at their position.`,
638
+ requiresSchema: true,
597
639
  }), validationToRule('variables-are-input-types', 'VariablesAreInputTypes', {
598
640
  category: 'Operations',
599
641
  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,
600
643
  }), validationToRule('variables-in-allowed-position', 'VariablesInAllowedPosition', {
601
644
  category: 'Operations',
602
645
  description: `Variables passed to field arguments conform to type.`,
646
+ requiresSchema: true,
603
647
  }));
604
648
 
605
649
  const ALPHABETIZE = 'ALPHABETIZE';
@@ -1033,7 +1077,13 @@ const rule$2 = {
1033
1077
  const MATCH_EXTENSION = 'MATCH_EXTENSION';
1034
1078
  const MATCH_STYLE = 'MATCH_STYLE';
1035
1079
  const ACCEPTED_EXTENSIONS = ['.gql', '.graphql'];
1036
- const CASE_STYLES = ['camelCase', 'PascalCase', 'snake_case', 'UPPER_CASE', 'kebab-case'];
1080
+ const CASE_STYLES = [
1081
+ CaseStyle.camelCase,
1082
+ CaseStyle.pascalCase,
1083
+ CaseStyle.snakeCase,
1084
+ CaseStyle.upperCase,
1085
+ CaseStyle.kebabCase,
1086
+ ];
1037
1087
  const schemaOption = {
1038
1088
  oneOf: [{ $ref: '#/definitions/asString' }, { $ref: '#/definitions/asObject' }],
1039
1089
  };
@@ -1057,7 +1107,7 @@ const rule$3 = {
1057
1107
  },
1058
1108
  {
1059
1109
  title: 'Correct',
1060
- usage: [{ query: 'snake_case' }],
1110
+ usage: [{ query: CaseStyle.snakeCase }],
1061
1111
  code: /* GraphQL */ `
1062
1112
  # user_by_id.gql
1063
1113
  query UserById {
@@ -1071,7 +1121,7 @@ const rule$3 = {
1071
1121
  },
1072
1122
  {
1073
1123
  title: 'Correct',
1074
- usage: [{ fragment: { style: 'kebab-case', suffix: '.fragment' } }],
1124
+ usage: [{ fragment: { style: CaseStyle.kebabCase, suffix: '.fragment' } }],
1075
1125
  code: /* GraphQL */ `
1076
1126
  # user-fields.fragment.gql
1077
1127
  fragment user_fields on User {
@@ -1082,7 +1132,7 @@ const rule$3 = {
1082
1132
  },
1083
1133
  {
1084
1134
  title: 'Correct',
1085
- usage: [{ mutation: { style: 'PascalCase', suffix: 'Mutation' } }],
1135
+ usage: [{ mutation: { style: CaseStyle.pascalCase, suffix: 'Mutation' } }],
1086
1136
  code: /* GraphQL */ `
1087
1137
  # DeleteUserMutation.gql
1088
1138
  mutation DELETE_USER {
@@ -1102,7 +1152,7 @@ const rule$3 = {
1102
1152
  },
1103
1153
  {
1104
1154
  title: 'Incorrect',
1105
- usage: [{ query: 'PascalCase' }],
1155
+ usage: [{ query: CaseStyle.pascalCase }],
1106
1156
  code: /* GraphQL */ `
1107
1157
  # user-by-id.gql
1108
1158
  query UserById {
@@ -1117,10 +1167,10 @@ const rule$3 = {
1117
1167
  ],
1118
1168
  configOptions: [
1119
1169
  {
1120
- query: 'kebab-case',
1121
- mutation: 'kebab-case',
1122
- subscription: 'kebab-case',
1123
- fragment: 'kebab-case',
1170
+ query: CaseStyle.kebabCase,
1171
+ mutation: CaseStyle.kebabCase,
1172
+ subscription: CaseStyle.kebabCase,
1173
+ fragment: CaseStyle.kebabCase,
1124
1174
  },
1125
1175
  ],
1126
1176
  },
@@ -1137,22 +1187,25 @@ const rule$3 = {
1137
1187
  asObject: {
1138
1188
  type: 'object',
1139
1189
  additionalProperties: false,
1140
- minProperties: 1,
1141
1190
  properties: {
1142
- style: { enum: CASE_STYLES },
1143
- suffix: { type: 'string' },
1191
+ style: {
1192
+ enum: CASE_STYLES,
1193
+ },
1194
+ suffix: {
1195
+ type: 'string',
1196
+ },
1144
1197
  },
1145
1198
  },
1146
1199
  },
1147
1200
  type: 'array',
1148
- minItems: 1,
1149
1201
  maxItems: 1,
1150
1202
  items: {
1151
1203
  type: 'object',
1152
1204
  additionalProperties: false,
1153
- minProperties: 1,
1154
1205
  properties: {
1155
- fileExtension: { enum: ACCEPTED_EXTENSIONS },
1206
+ fileExtension: {
1207
+ enum: ACCEPTED_EXTENSIONS,
1208
+ },
1156
1209
  query: schemaOption,
1157
1210
  mutation: schemaOption,
1158
1211
  subscription: schemaOption,
@@ -1207,7 +1260,7 @@ const rule$3 = {
1207
1260
  option = { style: option };
1208
1261
  }
1209
1262
  const expectedExtension = options.fileExtension || fileExtension;
1210
- const expectedFilename = (option.style ? convertCase(option.style, docName) : filename) + (option.suffix || '') + expectedExtension;
1263
+ const expectedFilename = convertCase(option.style, docName) + (option.suffix || '') + expectedExtension;
1211
1264
  const filenameWithExtension = filename + expectedExtension;
1212
1265
  if (expectedFilename !== filenameWithExtension) {
1213
1266
  context.report({
@@ -1359,7 +1412,6 @@ const rule$4 = {
1359
1412
  ],
1360
1413
  },
1361
1414
  },
1362
- hasSuggestions: true,
1363
1415
  schema: {
1364
1416
  definitions: {
1365
1417
  asString: {
@@ -1434,90 +1486,65 @@ const rule$4 = {
1434
1486
  const style = restOptions[kind] || types;
1435
1487
  return typeof style === 'object' ? style : { style };
1436
1488
  }
1437
- const checkNode = (selector) => (n) => {
1438
- const { name: node } = n.kind === Kind.VARIABLE_DEFINITION ? n.variable : n;
1439
- if (!node) {
1489
+ const checkNode = (selector) => (node) => {
1490
+ const { name } = node.kind === Kind.VARIABLE_DEFINITION ? node.variable : node;
1491
+ if (!name) {
1440
1492
  return;
1441
1493
  }
1442
1494
  const { prefix, suffix, forbiddenPrefixes, forbiddenSuffixes, style } = normalisePropertyOption(selector);
1443
- const nodeType = KindToDisplayName[n.kind] || n.kind;
1444
- const nodeName = node.value;
1445
- const error = getError();
1446
- if (error) {
1447
- const { errorMessage, renameToName } = error;
1448
- const [leadingUnderscore] = nodeName.match(/^_*/);
1449
- const [trailingUnderscore] = nodeName.match(/_*$/);
1450
- const suggestedName = leadingUnderscore + renameToName + trailingUnderscore;
1495
+ const nodeType = KindToDisplayName[node.kind] || node.kind;
1496
+ const nodeName = name.value;
1497
+ const errorMessage = getErrorMessage();
1498
+ if (errorMessage) {
1451
1499
  context.report({
1452
- loc: getLocation(node.loc, node.value),
1500
+ loc: getLocation(name.loc, name.value),
1453
1501
  message: `${nodeType} "${nodeName}" should ${errorMessage}`,
1454
- suggest: [
1455
- {
1456
- desc: `Rename to "${suggestedName}"`,
1457
- fix: fixer => fixer.replaceText(node, suggestedName),
1458
- },
1459
- ],
1460
1502
  });
1461
1503
  }
1462
- function getError() {
1463
- const name = nodeName.replace(/(^_+)|(_+$)/g, '');
1504
+ function getErrorMessage() {
1505
+ let name = nodeName;
1506
+ if (allowLeadingUnderscore) {
1507
+ name = name.replace(/^_*/, '');
1508
+ }
1509
+ if (allowTrailingUnderscore) {
1510
+ name = name.replace(/_*$/, '');
1511
+ }
1464
1512
  if (prefix && !name.startsWith(prefix)) {
1465
- return {
1466
- errorMessage: `have "${prefix}" prefix`,
1467
- renameToName: prefix + name,
1468
- };
1513
+ return `have "${prefix}" prefix`;
1469
1514
  }
1470
1515
  if (suffix && !name.endsWith(suffix)) {
1471
- return {
1472
- errorMessage: `have "${suffix}" suffix`,
1473
- renameToName: name + suffix,
1474
- };
1516
+ return `have "${suffix}" suffix`;
1475
1517
  }
1476
1518
  const forbiddenPrefix = forbiddenPrefixes === null || forbiddenPrefixes === void 0 ? void 0 : forbiddenPrefixes.find(prefix => name.startsWith(prefix));
1477
1519
  if (forbiddenPrefix) {
1478
- return {
1479
- errorMessage: `not have "${forbiddenPrefix}" prefix`,
1480
- renameToName: name.replace(new RegExp(`^${forbiddenPrefix}`), ''),
1481
- };
1520
+ return `not have "${forbiddenPrefix}" prefix`;
1482
1521
  }
1483
1522
  const forbiddenSuffix = forbiddenSuffixes === null || forbiddenSuffixes === void 0 ? void 0 : forbiddenSuffixes.find(suffix => name.endsWith(suffix));
1484
1523
  if (forbiddenSuffix) {
1485
- return {
1486
- errorMessage: `not have "${forbiddenSuffix}" suffix`,
1487
- renameToName: name.replace(new RegExp(`${forbiddenSuffix}$`), ''),
1488
- };
1524
+ return `not have "${forbiddenSuffix}" suffix`;
1525
+ }
1526
+ if (style && !ALLOWED_STYLES.includes(style)) {
1527
+ return `be in one of the following options: ${ALLOWED_STYLES.join(', ')}`;
1489
1528
  }
1490
1529
  const caseRegex = StyleToRegex[style];
1491
1530
  if (caseRegex && !caseRegex.test(name)) {
1492
- return {
1493
- errorMessage: `be in ${style} format`,
1494
- renameToName: convertCase(style, name),
1495
- };
1531
+ return `be in ${style} format`;
1496
1532
  }
1497
1533
  }
1498
1534
  };
1499
- const checkUnderscore = (isLeading) => (node) => {
1535
+ const checkUnderscore = (node) => {
1500
1536
  const name = node.value;
1501
- const renameToName = name.replace(new RegExp(isLeading ? '^_+' : '_+$'), '');
1502
1537
  context.report({
1503
1538
  loc: getLocation(node.loc, name),
1504
- message: `${isLeading ? 'Leading' : 'Trailing'} underscores are not allowed`,
1505
- suggest: [
1506
- {
1507
- desc: `Rename to "${renameToName}"`,
1508
- fix: fixer => fixer.replaceText(node, renameToName),
1509
- },
1510
- ],
1539
+ message: `${name.startsWith('_') ? 'Leading' : 'Trailing'} underscores are not allowed`,
1511
1540
  });
1512
1541
  };
1513
1542
  const listeners = {};
1514
1543
  if (!allowLeadingUnderscore) {
1515
- listeners['Name[value=/^_/]:matches([parent.kind!=Field], [parent.kind=Field][parent.alias])'] =
1516
- checkUnderscore(true);
1544
+ listeners['Name[value=/^_/]:matches([parent.kind!=Field], [parent.kind=Field][parent.alias])'] = checkUnderscore;
1517
1545
  }
1518
1546
  if (!allowTrailingUnderscore) {
1519
- listeners['Name[value=/_$/]:matches([parent.kind!=Field], [parent.kind=Field][parent.alias])'] =
1520
- checkUnderscore(false);
1547
+ listeners['Name[value=/_$/]:matches([parent.kind!=Field], [parent.kind=Field][parent.alias])'] = checkUnderscore;
1521
1548
  }
1522
1549
  const selectors = new Set([types && TYPES_KINDS, Object.keys(restOptions)].flat().filter(Boolean));
1523
1550
  for (const selector of selectors) {