UNPKG

@graphql-eslint/eslint-plugin

Version:
1,253 lines (1,243 loc) • 180 kB
import { gqlPluckFromCodeStringSync } from '@graphql-tools/graphql-tag-pluck'; import { asArray, getDocumentNodeFromSchema, parseGraphQLSDL } from '@graphql-tools/utils'; import { dirname, extname, basename, relative, resolve } from 'path'; import debugFactory from 'debug'; import { loadConfigSync, GraphQLConfig } from 'graphql-config'; import { CodeFileLoader } from '@graphql-tools/code-file-loader'; import { Kind, visit, validate, TokenKind, isScalarType, DirectiveLocation, isInterfaceType, TypeInfo, visitWithTypeInfo, isObjectType as isObjectType$1, Source, isNonNullType, isListType, GraphQLObjectType, GraphQLInterfaceType, GraphQLSchema, GraphQLError } from 'graphql'; import { validateSDL } from 'graphql/validation/validate'; import lowerCase from 'lodash.lowercase'; import chalk from 'chalk'; import { existsSync, readFileSync } from 'fs'; import { valueFromASTUntyped } from 'graphql/utilities/valueFromASTUntyped'; import depthLimit from 'graphql-depth-limit'; import fg from 'fast-glob'; import { RuleTester, Linter } from 'eslint'; import { codeFrameColumns } from '@babel/code-frame'; const debug = debugFactory('graphql-eslint:graphql-config'); let graphQLConfig; function loadOnDiskGraphQLConfig(filePath) { return loadConfigSync({ // load config relative to the file being linted rootDir: dirname(filePath), throwOnEmpty: false, throwOnMissing: false, extensions: [codeFileLoaderExtension], }); } function loadGraphQLConfig(options) { // We don't want cache config on test environment // Otherwise schema and documents will be same for all tests if (process.env.NODE_ENV !== 'test' && graphQLConfig) { return graphQLConfig; } const onDiskConfig = !options.skipGraphQLConfig && loadOnDiskGraphQLConfig(options.filePath); debug('options.skipGraphQLConfig: %o', options.skipGraphQLConfig); if (onDiskConfig) { debug('Graphql-config path %o', onDiskConfig.filepath); } const configOptions = options.projects ? { projects: options.projects } : { schema: (options.schema || ''), documents: options.documents || options.operations, extensions: options.extensions, include: options.include, exclude: options.exclude, }; graphQLConfig = onDiskConfig || new GraphQLConfig({ config: configOptions, filepath: 'virtual-config', }, [codeFileLoaderExtension]); return graphQLConfig; } const codeFileLoaderExtension = api => { const { schema, documents } = api.loaders; schema.register(new CodeFileLoader()); documents.register(new CodeFileLoader()); return { name: 'graphql-eslint-loaders' }; }; const blocksMap = new Map(); let onDiskConfig; let onDiskConfigLoaded = false; const RELEVANT_KEYWORDS = ['gql', 'graphql', 'GraphQL']; const processor = { supportsAutofix: true, preprocess(code, filePath) { if (!onDiskConfigLoaded) { onDiskConfig = loadOnDiskGraphQLConfig(filePath); onDiskConfigLoaded = true; } let keywords = RELEVANT_KEYWORDS; const pluckConfig = onDiskConfig === null || onDiskConfig === void 0 ? void 0 : onDiskConfig.getProjectForFile(filePath).extensions.pluckConfig; if (pluckConfig) { const { modules = [], globalGqlIdentifierName = ['gql', 'graphql'], gqlMagicComment = 'GraphQL', } = pluckConfig; keywords = [ ...new Set([ ...modules.map(({ identifier }) => identifier), ...asArray(globalGqlIdentifierName), gqlMagicComment, ].filter(Boolean)), ]; } if (keywords.every(keyword => !code.includes(keyword))) { return [code]; } try { const sources = gqlPluckFromCodeStringSync(filePath, code, { skipIndent: true, ...pluckConfig, }); const isSvelte = filePath.endsWith('.svelte'); const blocks = sources.map(item => ({ filename: 'document.graphql', text: item.body, lineOffset: item.locationOffset.line - (isSvelte ? 3 : 1), // @ts-expect-error -- `index` field exist but show ts error offset: item.locationOffset.index + (isSvelte ? -52 : 1), })); blocksMap.set(filePath, blocks); return [...blocks, code /* source code must be provided and be last */]; } catch (_a) { // in case of parsing error return code as is return [code]; } }, postprocess(messages, filePath) { const blocks = blocksMap.get(filePath) || []; for (let i = 0; i < blocks.length; i += 1) { const { lineOffset, offset } = blocks[i]; for (const message of messages[i]) { message.line += lineOffset; // endLine can not exist if only `loc: { start, column }` was provided to context.report if (typeof message.endLine === 'number') { message.endLine += lineOffset; } if (message.fix) { message.fix.range[0] += offset; message.fix.range[1] += offset; } for (const suggestion of message.suggestions || []) { suggestion.fix.range[0] += offset; suggestion.fix.range[1] += offset; } } } const result = messages.flat(); // sort eslint/graphql-eslint messages by line/column return result.sort((a, b) => a.line - b.line || a.column - b.column); }, }; function requireSiblingsOperations(ruleId, context) { const { siblingOperations } = context.parserServices; if (!siblingOperations.available) { throw new Error(`Rule \`${ruleId}\` requires \`parserOptions.operations\` to be set and loaded. See https://bit.ly/graphql-eslint-operations for more info`); } return siblingOperations; } function requireGraphQLSchemaFromContext(ruleId, context) { const { schema } = context.parserServices; if (!schema) { throw new Error(`Rule \`${ruleId}\` requires \`parserOptions.schema\` to be set and loaded. See https://bit.ly/graphql-eslint-schema for more info`); } else if (schema instanceof Error) { throw schema; } return schema; } const logger = { // eslint-disable-next-line no-console error: (...args) => console.error(chalk.red('error'), '[graphql-eslint]', chalk(...args)), // eslint-disable-next-line no-console warn: (...args) => console.warn(chalk.yellow('warning'), '[graphql-eslint]', chalk(...args)), }; const normalizePath = (path) => (path || '').replace(/\\/g, '/'); const VIRTUAL_DOCUMENT_REGEX = /\/\d+_document.graphql$/; const CWD = process.cwd(); const getTypeName = (node) => 'type' in node ? getTypeName(node.type) : node.name.value; const TYPES_KINDS = [ Kind.OBJECT_TYPE_DEFINITION, Kind.INTERFACE_TYPE_DEFINITION, Kind.ENUM_TYPE_DEFINITION, Kind.SCALAR_TYPE_DEFINITION, Kind.INPUT_OBJECT_TYPE_DEFINITION, Kind.UNION_TYPE_DEFINITION, ]; const pascalCase = (str) => lowerCase(str) .split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(''); const camelCase = (str) => { const result = pascalCase(str); return result.charAt(0).toLowerCase() + result.slice(1); }; const convertCase = (style, str) => { switch (style) { case 'camelCase': return camelCase(str); case 'PascalCase': return pascalCase(str); case 'snake_case': return lowerCase(str).replace(/ /g, '_'); case 'UPPER_CASE': return lowerCase(str).replace(/ /g, '_').toUpperCase(); case 'kebab-case': return lowerCase(str).replace(/ /g, '-'); } }; function getLocation(start, fieldName = '') { const { line, column } = start; return { start: { line, column, }, end: { line, column: column + fieldName.length, }, }; } const REPORT_ON_FIRST_CHARACTER = { column: 0, line: 1 }; const ARRAY_DEFAULT_OPTIONS = { type: 'array', uniqueItems: true, minItems: 1, items: { type: 'string', }, }; const englishJoinWords = words => new Intl.ListFormat('en-US', { type: 'disjunction' }).format(words); function validateDocument(context, schema = null, documentNode, rule) { if (documentNode.definitions.length === 0) { return; } try { const validationErrors = schema ? validate(schema, documentNode, [rule]) : validateSDL(documentNode, null, [rule]); for (const error of validationErrors) { const { line, column } = error.locations[0]; const sourceCode = context.getSourceCode(); const { tokens } = sourceCode.ast; const token = tokens.find(token => token.loc.start.line === line && token.loc.start.column === column - 1); let loc = { line, column: column - 1, }; if (token) { loc = // if cursor on `@` symbol than use next node token.type === '@' ? sourceCode.getNodeByRangeIndex(token.range[1] + 1).loc : token.loc; } context.report({ loc, message: error.message, }); } } catch (e) { context.report({ loc: REPORT_ON_FIRST_CHARACTER, message: e.message, }); } } const getFragmentDefsAndFragmentSpreads = (node) => { const fragmentDefs = new Set(); const fragmentSpreads = new Set(); const visitor = { FragmentDefinition(node) { fragmentDefs.add(node.name.value); }, FragmentSpread(node) { fragmentSpreads.add(node.name.value); }, }; visit(node, visitor); return { fragmentDefs, fragmentSpreads }; }; const getMissingFragments = (node) => { const { fragmentDefs, fragmentSpreads } = getFragmentDefsAndFragmentSpreads(node); return [...fragmentSpreads].filter(name => !fragmentDefs.has(name)); }; const handleMissingFragments = ({ ruleId, context, node }) => { const missingFragments = getMissingFragments(node); if (missingFragments.length > 0) { const siblings = requireSiblingsOperations(ruleId, context); const fragmentsToAdd = []; for (const fragmentName of missingFragments) { const [foundFragment] = siblings.getFragment(fragmentName).map(source => source.document); if (foundFragment) { fragmentsToAdd.push(foundFragment); } } if (fragmentsToAdd.length > 0) { // recall fn to make sure to add fragments inside fragments return handleMissingFragments({ ruleId, context, node: { kind: Kind.DOCUMENT, definitions: [...node.definitions, ...fragmentsToAdd], }, }); } } return node; }; const validationToRule = (ruleId, ruleName, docs, getDocumentNode, schema = []) => { let ruleFn = null; try { ruleFn = require(`graphql/validation/rules/${ruleName}Rule`)[`${ruleName}Rule`]; } catch (_a) { try { ruleFn = require(`graphql/validation/rules/${ruleName}`)[`${ruleName}Rule`]; } catch (_b) { ruleFn = require('graphql/validation')[`${ruleName}Rule`]; } } return { [ruleId]: { meta: { docs: { recommended: true, ...docs, graphQLJSRuleName: ruleName, url: `https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/${ruleId}.md`, description: `${docs.description}\n\n> This rule is a wrapper around a \`graphql-js\` validation function.`, }, schema, }, create(context) { if (!ruleFn) { logger.warn(`Rule "${ruleId}" depends on a GraphQL validation rule "${ruleName}" but it's not available in the "graphql" version you are using. Skipping…`); return {}; } return { Document(node) { const schema = docs.requiresSchema ? requireGraphQLSchemaFromContext(ruleId, context) : null; const documentNode = getDocumentNode ? getDocumentNode({ ruleId, context, node: node.rawNode() }) : node.rawNode(); validateDocument(context, schema, documentNode, ruleFn); }, }; }, }, }; }; const GRAPHQL_JS_VALIDATIONS = Object.assign({}, validationToRule('executable-definitions', 'ExecutableDefinitions', { category: 'Operations', description: 'A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.', requiresSchema: true, }), validationToRule('fields-on-correct-type', 'FieldsOnCorrectType', { category: 'Operations', 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`.', requiresSchema: true, }), validationToRule('fragments-on-composite-type', 'FragmentsOnCompositeTypes', { category: 'Operations', 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.', requiresSchema: true, }), validationToRule('known-argument-names', 'KnownArgumentNames', { category: ['Schema', 'Operations'], description: 'A GraphQL field is only valid if all supplied arguments are defined by that field.', requiresSchema: true, }), validationToRule('known-directives', 'KnownDirectives', { category: ['Schema', 'Operations'], description: 'A GraphQL document is only valid if all `@directive`s are known by the schema and legally positioned.', requiresSchema: true, examples: [ { title: 'Valid', usage: [{ ignoreClientDirectives: ['client'] }], code: /* GraphQL */ ` { product { someClientField @client } } `, }, ], }, ({ context, node: documentNode }) => { const { ignoreClientDirectives = [] } = context.options[0] || {}; if (ignoreClientDirectives.length === 0) { return documentNode; } const filterDirectives = (node) => ({ ...node, directives: node.directives.filter(directive => !ignoreClientDirectives.includes(directive.name.value)), }); return visit(documentNode, { Field: filterDirectives, OperationDefinition: filterDirectives, }); }, { type: 'array', maxItems: 1, items: { type: 'object', additionalProperties: false, required: ['ignoreClientDirectives'], properties: { ignoreClientDirectives: ARRAY_DEFAULT_OPTIONS, }, }, }), validationToRule('known-fragment-names', 'KnownFragmentNames', { category: 'Operations', description: 'A GraphQL document is only valid if all `...Fragment` fragment spreads refer to fragments defined in the same document.', requiresSchema: true, requiresSiblings: true, examples: [ { title: 'Incorrect', code: /* GraphQL */ ` query { user { id ...UserFields # fragment not defined in the document } } `, }, { title: 'Correct', code: /* GraphQL */ ` fragment UserFields on User { firstName lastName } query { user { id ...UserFields } } `, }, { title: 'Correct (`UserFields` fragment located in a separate file)', code: /* GraphQL */ ` # user.gql query { user { id ...UserFields } } # user-fields.gql fragment UserFields on User { id } `, }, ], }, handleMissingFragments), validationToRule('known-type-names', 'KnownTypeNames', { category: ['Schema', 'Operations'], description: 'A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.', requiresSchema: true, }), validationToRule('lone-anonymous-operation', 'LoneAnonymousOperation', { category: 'Operations', 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.', requiresSchema: true, }), validationToRule('lone-schema-definition', 'LoneSchemaDefinition', { category: 'Schema', description: 'A GraphQL document is only valid if it contains only one schema definition.', }), validationToRule('no-fragment-cycles', 'NoFragmentCycles', { category: 'Operations', description: 'A GraphQL fragment is only valid when it does not have cycles in fragments usage.', requiresSchema: true, }), validationToRule('no-undefined-variables', 'NoUndefinedVariables', { category: 'Operations', description: 'A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.', requiresSchema: true, requiresSiblings: true, }, handleMissingFragments), validationToRule('no-unused-fragments', 'NoUnusedFragments', { category: 'Operations', description: 'A GraphQL document is only valid if all fragment definitions are spread within operations, or spread within other fragments spread within operations.', requiresSchema: true, requiresSiblings: true, }, ({ ruleId, context, node }) => { const siblings = requireSiblingsOperations(ruleId, context); const FilePathToDocumentsMap = [ ...siblings.getOperations(), ...siblings.getFragments(), ].reduce((map, { filePath, document }) => { var _a; (_a = map[filePath]) !== null && _a !== void 0 ? _a : (map[filePath] = []); map[filePath].push(document); return map; }, Object.create(null)); const getParentNode = (currentFilePath, node) => { const { fragmentDefs } = getFragmentDefsAndFragmentSpreads(node); if (fragmentDefs.size === 0) { return node; } // skip iteration over documents for current filepath delete FilePathToDocumentsMap[currentFilePath]; for (const [filePath, documents] of Object.entries(FilePathToDocumentsMap)) { const missingFragments = getMissingFragments({ kind: Kind.DOCUMENT, definitions: documents, }); const isCurrentFileImportFragment = missingFragments.some(fragment => fragmentDefs.has(fragment)); if (isCurrentFileImportFragment) { return getParentNode(filePath, { kind: Kind.DOCUMENT, definitions: [...node.definitions, ...documents], }); } } return node; }; return getParentNode(context.getFilename(), node); }), validationToRule('no-unused-variables', 'NoUnusedVariables', { category: 'Operations', description: 'A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.', requiresSchema: true, requiresSiblings: true, }, handleMissingFragments), validationToRule('overlapping-fields-can-be-merged', 'OverlappingFieldsCanBeMerged', { category: 'Operations', 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.', requiresSchema: true, }), validationToRule('possible-fragment-spread', 'PossibleFragmentSpreads', { category: 'Operations', 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.', requiresSchema: true, }), validationToRule('possible-type-extension', 'PossibleTypeExtensions', { category: 'Schema', description: 'A type extension is only valid if the type is defined and has the same kind.', // TODO: add in graphql-eslint v4 recommended: false, requiresSchema: true, isDisabledForAllConfig: true, }), validationToRule('provided-required-arguments', 'ProvidedRequiredArguments', { category: ['Schema', 'Operations'], description: 'A field or directive is only valid if all required (non-null without a default value) field arguments have been provided.', requiresSchema: true, }), validationToRule('scalar-leafs', 'ScalarLeafs', { category: 'Operations', description: 'A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.', requiresSchema: true, }), validationToRule('one-field-subscriptions', 'SingleFieldSubscriptions', { category: 'Operations', description: 'A GraphQL subscription is valid only if it contains a single root field.', requiresSchema: true, }), validationToRule('unique-argument-names', 'UniqueArgumentNames', { category: 'Operations', description: 'A GraphQL field or directive is only valid if all supplied arguments are uniquely named.', requiresSchema: true, }), validationToRule('unique-directive-names', 'UniqueDirectiveNames', { category: 'Schema', description: 'A GraphQL document is only valid if all defined directives have unique names.', }), validationToRule('unique-directive-names-per-location', 'UniqueDirectivesPerLocation', { category: ['Schema', 'Operations'], description: 'A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.', requiresSchema: true, }), validationToRule('unique-enum-value-names', 'UniqueEnumValueNames', { category: 'Schema', description: 'A GraphQL enum type is only valid if all its values are uniquely named.', recommended: false, isDisabledForAllConfig: true, }), validationToRule('unique-field-definition-names', 'UniqueFieldDefinitionNames', { category: 'Schema', description: 'A GraphQL complex type is only valid if all its fields are uniquely named.', }), validationToRule('unique-input-field-names', 'UniqueInputFieldNames', { category: 'Operations', description: 'A GraphQL input object value is only valid if all supplied fields are uniquely named.', }), validationToRule('unique-operation-types', 'UniqueOperationTypes', { category: 'Schema', description: 'A GraphQL document is only valid if it has only one type per operation.', }), validationToRule('unique-type-names', 'UniqueTypeNames', { category: 'Schema', description: 'A GraphQL document is only valid if all defined types have unique names.', }), validationToRule('unique-variable-names', 'UniqueVariableNames', { category: 'Operations', description: 'A GraphQL operation is only valid if all its variables are uniquely named.', requiresSchema: true, }), validationToRule('value-literals-of-correct-type', 'ValuesOfCorrectType', { category: 'Operations', description: 'A GraphQL document is only valid if all value literals are of the type expected at their position.', requiresSchema: true, }), validationToRule('variables-are-input-types', 'VariablesAreInputTypes', { category: 'Operations', description: 'A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).', requiresSchema: true, }), validationToRule('variables-in-allowed-position', 'VariablesInAllowedPosition', { category: 'Operations', description: 'Variables passed to field arguments conform to type.', requiresSchema: true, })); const RULE_ID = 'alphabetize'; const fieldsEnum = [ Kind.OBJECT_TYPE_DEFINITION, Kind.INTERFACE_TYPE_DEFINITION, Kind.INPUT_OBJECT_TYPE_DEFINITION, ]; const valuesEnum = [Kind.ENUM_TYPE_DEFINITION]; const selectionsEnum = [ Kind.OPERATION_DEFINITION, Kind.FRAGMENT_DEFINITION, ]; const variablesEnum = [Kind.OPERATION_DEFINITION]; const argumentsEnum = [ Kind.FIELD_DEFINITION, Kind.FIELD, Kind.DIRECTIVE_DEFINITION, Kind.DIRECTIVE, ]; const rule = { meta: { type: 'suggestion', fixable: 'code', docs: { category: ['Schema', 'Operations'], description: 'Enforce arrange in alphabetical order for type fields, enum values, input object fields, operation selections and more.', url: `https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/${RULE_ID}.md`, examples: [ { title: 'Incorrect', usage: [{ fields: [Kind.OBJECT_TYPE_DEFINITION] }], code: /* GraphQL */ ` type User { password: String firstName: String! # should be before "password" age: Int # should be before "firstName" lastName: String! } `, }, { title: 'Correct', usage: [{ fields: [Kind.OBJECT_TYPE_DEFINITION] }], code: /* GraphQL */ ` type User { age: Int firstName: String! lastName: String! password: String } `, }, { title: 'Incorrect', usage: [{ values: [Kind.ENUM_TYPE_DEFINITION] }], code: /* GraphQL */ ` enum Role { SUPER_ADMIN ADMIN # should be before "SUPER_ADMIN" USER GOD # should be before "USER" } `, }, { title: 'Correct', usage: [{ values: [Kind.ENUM_TYPE_DEFINITION] }], code: /* GraphQL */ ` enum Role { ADMIN GOD SUPER_ADMIN USER } `, }, { title: 'Incorrect', usage: [{ selections: [Kind.OPERATION_DEFINITION] }], code: /* GraphQL */ ` query { me { firstName lastName email # should be before "lastName" } } `, }, { title: 'Correct', usage: [{ selections: [Kind.OPERATION_DEFINITION] }], code: /* GraphQL */ ` query { me { email firstName lastName } } `, }, ], configOptions: { schema: [ { fields: fieldsEnum, values: valuesEnum, arguments: argumentsEnum, // TODO: add in graphql-eslint v4 // definitions: true, }, ], operations: [ { selections: selectionsEnum, variables: variablesEnum, arguments: [Kind.FIELD, Kind.DIRECTIVE], }, ], }, }, messages: { [RULE_ID]: '`{{ currName }}` should be before {{ prevName }}.', }, schema: { type: 'array', minItems: 1, maxItems: 1, items: { type: 'object', additionalProperties: false, minProperties: 1, properties: { fields: { ...ARRAY_DEFAULT_OPTIONS, items: { enum: fieldsEnum, }, description: 'Fields of `type`, `interface`, and `input`.', }, values: { ...ARRAY_DEFAULT_OPTIONS, items: { enum: valuesEnum, }, description: 'Values of `enum`.', }, selections: { ...ARRAY_DEFAULT_OPTIONS, items: { enum: selectionsEnum, }, description: 'Selections of `fragment` and operations `query`, `mutation` and `subscription`.', }, variables: { ...ARRAY_DEFAULT_OPTIONS, items: { enum: variablesEnum, }, description: 'Variables of operations `query`, `mutation` and `subscription`.', }, arguments: { ...ARRAY_DEFAULT_OPTIONS, items: { enum: argumentsEnum, }, description: 'Arguments of fields and directives.', }, definitions: { type: 'boolean', description: 'Definitions – `type`, `interface`, `enum`, `scalar`, `input`, `union` and `directive`.', default: false, }, }, }, }, }, create(context) { var _a, _b, _c, _d, _e; const sourceCode = context.getSourceCode(); function isNodeAndCommentOnSameLine(node, comment) { return node.loc.end.line === comment.loc.start.line; } function getBeforeComments(node) { const commentsBefore = sourceCode.getCommentsBefore(node); if (commentsBefore.length === 0) { return []; } const tokenBefore = sourceCode.getTokenBefore(node); if (tokenBefore) { return commentsBefore.filter(comment => !isNodeAndCommentOnSameLine(tokenBefore, comment)); } const filteredComments = []; const nodeLine = node.loc.start.line; // Break on comment that not attached to node for (let i = commentsBefore.length - 1; i >= 0; i -= 1) { const comment = commentsBefore[i]; if (nodeLine - comment.loc.start.line - filteredComments.length > 1) { break; } filteredComments.unshift(comment); } return filteredComments; } function getRangeWithComments(node) { if (node.kind === Kind.VARIABLE) { node = node.parent; } const [firstBeforeComment] = getBeforeComments(node); const [firstAfterComment] = sourceCode.getCommentsAfter(node); const from = firstBeforeComment || node; const to = firstAfterComment && isNodeAndCommentOnSameLine(node, firstAfterComment) ? firstAfterComment : node; return [from.range[0], to.range[1]]; } function checkNodes(nodes) { var _a, _b, _c, _d; // Starts from 1, ignore nodes.length <= 1 for (let i = 1; i < nodes.length; i += 1) { const currNode = nodes[i]; const currName = ('alias' in currNode && ((_a = currNode.alias) === null || _a === void 0 ? void 0 : _a.value)) || ('name' in currNode && ((_b = currNode.name) === null || _b === void 0 ? void 0 : _b.value)); if (!currName) { // we don't move unnamed current nodes continue; } const prevNode = nodes[i - 1]; const prevName = ('alias' in prevNode && ((_c = prevNode.alias) === null || _c === void 0 ? void 0 : _c.value)) || ('name' in prevNode && ((_d = prevNode.name) === null || _d === void 0 ? void 0 : _d.value)); if (prevName) { // Compare with lexicographic order const compareResult = prevName.localeCompare(currName); const shouldSort = compareResult === 1; if (!shouldSort) { const isSameName = compareResult === 0; if (!isSameName || !prevNode.kind.endsWith('Extension') || currNode.kind.endsWith('Extension')) { continue; } } } context.report({ node: ('alias' in currNode && currNode.alias) || currNode.name, messageId: RULE_ID, data: { currName, prevName: prevName ? `\`${prevName}\`` : lowerCase(prevNode.kind), }, *fix(fixer) { const prevRange = getRangeWithComments(prevNode); const currRange = getRangeWithComments(currNode); yield fixer.replaceTextRange(prevRange, sourceCode.getText({ range: currRange })); yield fixer.replaceTextRange(currRange, sourceCode.getText({ range: prevRange })); }, }); } } const opts = context.options[0]; const fields = new Set((_a = opts.fields) !== null && _a !== void 0 ? _a : []); const listeners = {}; const kinds = [ fields.has(Kind.OBJECT_TYPE_DEFINITION) && [ Kind.OBJECT_TYPE_DEFINITION, Kind.OBJECT_TYPE_EXTENSION, ], fields.has(Kind.INTERFACE_TYPE_DEFINITION) && [ Kind.INTERFACE_TYPE_DEFINITION, Kind.INTERFACE_TYPE_EXTENSION, ], fields.has(Kind.INPUT_OBJECT_TYPE_DEFINITION) && [ Kind.INPUT_OBJECT_TYPE_DEFINITION, Kind.INPUT_OBJECT_TYPE_EXTENSION, ], ] .filter(Boolean) .flat(); const fieldsSelector = kinds.join(','); const hasEnumValues = ((_b = opts.values) === null || _b === void 0 ? void 0 : _b[0]) === Kind.ENUM_TYPE_DEFINITION; const selectionsSelector = (_c = opts.selections) === null || _c === void 0 ? void 0 : _c.join(','); const hasVariables = ((_d = opts.variables) === null || _d === void 0 ? void 0 : _d[0]) === Kind.OPERATION_DEFINITION; const argumentsSelector = (_e = opts.arguments) === null || _e === void 0 ? void 0 : _e.join(','); if (fieldsSelector) { listeners[fieldsSelector] = (node) => { checkNodes(node.fields); }; } if (hasEnumValues) { const enumValuesSelector = [Kind.ENUM_TYPE_DEFINITION, Kind.ENUM_TYPE_EXTENSION].join(','); listeners[enumValuesSelector] = (node) => { checkNodes(node.values); }; } if (selectionsSelector) { listeners[`:matches(${selectionsSelector}) SelectionSet`] = (node) => { checkNodes(node.selections); }; } if (hasVariables) { listeners.OperationDefinition = (node) => { checkNodes(node.variableDefinitions.map(varDef => varDef.variable)); }; } if (argumentsSelector) { listeners[argumentsSelector] = (node) => { checkNodes(node.arguments); }; } if (opts.definitions) { listeners.Document = node => { checkNodes(node.definitions); }; } return listeners; }, }; const rule$1 = { meta: { type: 'suggestion', hasSuggestions: true, docs: { examples: [ { title: 'Incorrect', usage: [{ style: 'inline' }], code: /* GraphQL */ ` """ Description """ type someTypeName { # ... } `, }, { title: 'Correct', usage: [{ style: 'inline' }], code: /* GraphQL */ ` " Description " type someTypeName { # ... } `, }, ], description: 'Require all comments to follow the same style (either block or inline).', category: 'Schema', url: 'https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/description-style.md', recommended: true, }, schema: [ { type: 'object', additionalProperties: false, properties: { style: { enum: ['block', 'inline'], default: 'block', }, }, }, ], }, create(context) { const { style = 'block' } = context.options[0] || {}; const isBlock = style === 'block'; return { [`.description[type=StringValue][block!=${isBlock}]`](node) { context.report({ loc: isBlock ? node.loc : node.loc.start, message: `Unexpected ${isBlock ? 'inline' : 'block'} description.`, suggest: [ { desc: `Change to ${isBlock ? 'block' : 'inline'} style description`, fix(fixer) { const sourceCode = context.getSourceCode(); const originalText = sourceCode.getText(node); const newText = isBlock ? originalText.replace(/(^")|("$)/g, '"""') : originalText.replace(/(^""")|("""$)/g, '"').replace(/\s+/g, ' '); return fixer.replaceText(node, newText); }, }, ], }); }, }; }, }; const isObjectType = (node) => [Kind.OBJECT_TYPE_DEFINITION, Kind.OBJECT_TYPE_EXTENSION].includes(node.type); const isQueryType = (node) => isObjectType(node) && node.name.value === 'Query'; const isMutationType = (node) => isObjectType(node) && node.name.value === 'Mutation'; const rule$2 = { meta: { type: 'suggestion', hasSuggestions: true, docs: { description: 'Require mutation argument to be always called "input" and input type to be called Mutation name + "Input".\nUsing the same name for all input parameters will make your schemas easier to consume and more predictable. Using the same name as mutation for InputType will make it easier to find mutations that InputType belongs to.', category: 'Schema', url: 'https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/input-name.md', examples: [ { title: 'Incorrect', usage: [{ checkInputType: true }], code: /* GraphQL */ ` type Mutation { SetMessage(message: InputMessage): String } `, }, { title: 'Correct (with checkInputType)', usage: [{ checkInputType: true }], code: /* GraphQL */ ` type Mutation { SetMessage(input: SetMessageInput): String } `, }, { title: 'Correct (without checkInputType)', usage: [{ checkInputType: false }], code: /* GraphQL */ ` type Mutation { SetMessage(input: AnyInputTypeName): String } `, }, ], }, schema: [ { type: 'object', additionalProperties: false, properties: { checkInputType: { type: 'boolean', default: false, description: 'Check that the input type name follows the convention <mutationName>Input', }, caseSensitiveInputType: { type: 'boolean', default: true, description: 'Allow for case discrepancies in the input type name', }, checkQueries: { type: 'boolean', default: false, description: 'Apply the rule to Queries', }, checkMutations: { type: 'boolean', default: true, description: 'Apply the rule to Mutations', }, }, }, ], }, create(context) { const options = { checkInputType: false, caseSensitiveInputType: true, checkQueries: false, checkMutations: true, ...context.options[0], }; const shouldCheckType = node => (options.checkMutations && isMutationType(node)) || (options.checkQueries && isQueryType(node)); const listeners = { 'FieldDefinition > InputValueDefinition[name.value!=input] > Name'(node) { if (shouldCheckType(node.parent.parent.parent)) { const inputName = node.value; context.report({ node, message: `Input \`${inputName}\` should be called \`input\`.`, suggest: [ { desc: 'Rename to `input`', fix: fixer => fixer.replaceText(node, 'input'), }, ], }); } }, }; if (options.checkInputType) { listeners['FieldDefinition > InputValueDefinition NamedType'] = (node) => { const findInputType = item => { let currentNode = item; while (currentNode.type !== Kind.INPUT_VALUE_DEFINITION) { currentNode = currentNode.parent; } return currentNode; }; const inputValueNode = findInputType(node); if (shouldCheckType(inputValueNode.parent.parent)) { const mutationName = `${inputValueNode.parent.name.value}Input`; const name = node.name.value; if ((options.caseSensitiveInputType && node.name.value !== mutationName) || name.toLowerCase() !== mutationName.toLowerCase()) { context.report({ node: node.name, message: `Input type \`${name}\` name should be \`${mutationName}\`.`, suggest: [ { desc: `Rename to \`${mutationName}\``, fix: fixer => fixer.replaceText(node, mutationName), }, ], }); } } }; } return listeners; }, }; const MATCH_EXTENSION = 'MATCH_EXTENSION'; const MATCH_STYLE = 'MATCH_STYLE'; const ACCEPTED_EXTENSIONS = ['.gql', '.graphql']; const CASE_STYLES = [ 'camelCase', 'PascalCase', 'snake_case', 'UPPER_CASE', 'kebab-case', 'matchDocumentStyle', ]; const schemaOption = { oneOf: [{ $ref: '#/definitions/asString' }, { $ref: '#/definitions/asObject' }], }; const rule$3 = { meta: { type: 'suggestion', docs: { category: 'Operations', description: 'This rule allows you to enforce that the file name should match the operation name.', url: 'https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/match-document-filename.md', examples: [ { title: 'Correct', usage: [{ fileExtension: '.gql' }], code: /* GraphQL */ ` # user.gql type User { id: ID! } `, }, { title: 'Correct', usage: [{ query: 'snake_case' }], code: /* GraphQL */ ` # user_by_id.gql query UserById { userById(id: 5) { id name fullName } } `, }, { title: 'Correct', usage: [{ fragment: { style: 'kebab-case', suffix: '.fragment' } }], code: /* GraphQL */ ` # user-fields.fragment.gql fragment user_fields on User { id email } `, }, { title: 'Correct', usage: [{ mutation: { style: 'PascalCase', suffix: 'Mutation' } }], code: /* GraphQL */ ` # DeleteUserMutation.gql mutation DELETE_USER { deleteUser(id: 5) } `, }, { title: 'Incorrect', usage: [{ fileExtension: '.graphql' }], code: /* GraphQL */ ` # post.gql type Post { id: ID! } `, }, { title: 'Incorrect', usage: [{ query: 'PascalCase' }], code: /* GraphQL */ ` # user-by-id.gql query UserById { userById(id: 5) { id name fullName } } `, }, ], configOptions: [ { query: 'kebab-case', mutation: 'kebab-case', subscription: 'kebab-case', fragment: 'kebab-case', }, ], }, messages: { [MATCH_EXTENSION]: 'File extension "{{ fileExtension }}" don\'t match extension "{{ expectedFileExtension }}"', [MATCH_STYLE]: 'Unexpected filename "{{ filename }}". Rename it to "{{ expectedFilename }}"', }, schema: { definitions: { asString: { enum: CASE_STYLES, description: `One of: ${CASE_STYLES.map(t => `\`${t}\``).join(', ')}`, }, asObject: { type: 'object', additionalProperties: false, minProperties: 1, properties: { style: { enum: CASE_STYLES }, suffix: { type: 'string' }, }, }, }, type: 'array', minItems: 1, maxItems: 1, items: { type: 'object', additionalProperties: false, minProperties: 1, properties: { fileExtension: { enum: ACCEPTED_EXTENSIONS }, query: schemaOption, mutation: schemaOption, subscription: schemaOption, fragment: schemaOption, }, }, }, }, create(context) { const options = context.options[0] || { fileExtension: null, }; const filePath = context.getFilename(); const isVirtualFile = !existsSync(filePath); if (process.env.NODE_ENV !== 'test' && isVirtualFile) { // Skip valid