UNPKG

@graphql-eslint/eslint-plugin

Version:
596 lines (593 loc) • 19.1 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: !0 }); }, __copyProps = (to, from, except, desc) => { if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod); var graphql_js_validation_exports = {}; __export(graphql_js_validation_exports, { GRAPHQL_JS_VALIDATIONS: () => GRAPHQL_JS_VALIDATIONS }); module.exports = __toCommonJS(graphql_js_validation_exports); var import_graphql = require("graphql"), import_validation = require("graphql/validation/index.js"), import_validate = require("graphql/validation/validate.js"), import_utils = require("../utils.js"); function validateDocument({ context, schema = null, documentNode, rule, hasDidYouMeanSuggestions }) { if (documentNode.definitions.length !== 0) try { const validationErrors = schema ? (0, import_graphql.validate)(schema, documentNode, [rule]) : (0, import_validate.validateSDL)(documentNode, null, [rule]); for (const error of validationErrors) { const { line, column } = error.locations[0], sourceCode = context.getSourceCode(), { tokens } = sourceCode.ast, token = tokens.find( (token2) => token2.loc.start.line === line && token2.loc.start.column === column - 1 ); let loc = { line, column: column - 1 }; token && (loc = // if cursor on `@` symbol than use next node token.type === "@" ? sourceCode.getNodeByRangeIndex(token.range[1] + 1).loc : token.loc); const didYouMeanContent = error.message.match(/Did you mean (?<content>.*)\?$/)?.groups.content, matches = didYouMeanContent ? [...didYouMeanContent.matchAll(/"(?<name>[^"]*)"/g)] : []; context.report({ loc, message: error.message, suggest: hasDidYouMeanSuggestions ? matches.map((match) => { const { name } = match.groups; return { desc: `Rename to \`${name}\``, fix: (fixer) => fixer.replaceText(token, name) }; }) : [] }); } } catch (error) { context.report({ loc: import_utils.REPORT_ON_FIRST_CHARACTER, message: error.message }); } } const getFragmentDefsAndFragmentSpreads = (node) => { const fragmentDefs = /* @__PURE__ */ new Set(), fragmentSpreads = /* @__PURE__ */ new Set(); return (0, import_graphql.visit)(node, { FragmentDefinition(node2) { fragmentDefs.add(node2.name.value); }, FragmentSpread(node2) { fragmentSpreads.add(node2.name.value); } }), { fragmentDefs, fragmentSpreads }; }, getMissingFragments = (node) => { const { fragmentDefs, fragmentSpreads } = getFragmentDefsAndFragmentSpreads(node); return [...fragmentSpreads].filter((name) => !fragmentDefs.has(name)); }, handleMissingFragments = ({ ruleId, context, node }) => { const missingFragments = getMissingFragments(node); if (missingFragments.length > 0) { const siblings = (0, import_utils.requireSiblingsOperations)(ruleId, context), fragmentsToAdd = []; for (const fragmentName of missingFragments) { const [foundFragment] = siblings.getFragment(fragmentName).map((source) => source.document); foundFragment && fragmentsToAdd.push(foundFragment); } if (fragmentsToAdd.length > 0) return handleMissingFragments({ ruleId, context, node: { kind: import_graphql.Kind.DOCUMENT, definitions: [...node.definitions, ...fragmentsToAdd] } }); } return node; }, validationToRule = ({ ruleId, rule, getDocumentNode, schema = [], hasDidYouMeanSuggestions }, docs) => ({ [ruleId]: { meta: { docs: { recommended: !0, ...docs, graphQLJSRuleName: rule.name, url: `https://the-guild.dev/graphql/eslint/rules/${ruleId}`, description: `${docs.description} > This rule is a wrapper around a \`graphql-js\` validation function.` }, schema, hasSuggestions: hasDidYouMeanSuggestions }, create(context) { return { Document(node) { const schema2 = docs.requiresSchema ? (0, import_utils.requireGraphQLSchemaFromContext)(ruleId, context) : null, documentNode = getDocumentNode ? getDocumentNode({ ruleId, context, node: node.rawNode() }) : node.rawNode(); validateDocument({ context, schema: schema2, documentNode, rule, hasDidYouMeanSuggestions }); } }; } } }), GRAPHQL_JS_VALIDATIONS = Object.assign( {}, validationToRule( { ruleId: "executable-definitions", rule: import_validation.ExecutableDefinitionsRule }, { category: "Operations", description: "A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.", requiresSchema: !0 } ), validationToRule( { ruleId: "fields-on-correct-type", rule: import_validation.FieldsOnCorrectTypeRule, hasDidYouMeanSuggestions: !0 }, { 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: !0 } ), validationToRule( { ruleId: "fragments-on-composite-type", rule: import_validation.FragmentsOnCompositeTypesRule }, { 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: !0 } ), validationToRule( { ruleId: "known-argument-names", rule: import_validation.KnownArgumentNamesRule, hasDidYouMeanSuggestions: !0 }, { category: ["Schema", "Operations"], description: "A GraphQL field is only valid if all supplied arguments are defined by that field.", requiresSchema: !0 } ), validationToRule( { ruleId: "known-directives", rule: import_validation.KnownDirectivesRule, getDocumentNode({ 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 (0, import_graphql.visit)(documentNode, { Field: filterDirectives, OperationDefinition: filterDirectives }); }, schema: { type: "array", maxItems: 1, items: { type: "object", additionalProperties: !1, required: ["ignoreClientDirectives"], properties: { ignoreClientDirectives: import_utils.ARRAY_DEFAULT_OPTIONS } } } }, { category: ["Schema", "Operations"], description: "A GraphQL document is only valid if all `@directive`s are known by the schema and legally positioned.", requiresSchema: !0, examples: [ { title: "Valid", usage: [{ ignoreClientDirectives: ["client"] }], code: ( /* GraphQL */ ` { product { someClientField @client } } ` ) } ] } ), validationToRule( { ruleId: "known-fragment-names", rule: import_validation.KnownFragmentNamesRule, getDocumentNode: handleMissingFragments }, { category: "Operations", description: "A GraphQL document is only valid if all `...Fragment` fragment spreads refer to fragments defined in the same document.", requiresSchema: !0, requiresSiblings: !0, 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 } ` ) } ] } ), validationToRule( { ruleId: "known-type-names", rule: import_validation.KnownTypeNamesRule, hasDidYouMeanSuggestions: !0 }, { 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: !0 } ), validationToRule( { ruleId: "lone-anonymous-operation", rule: import_validation.LoneAnonymousOperationRule }, { category: "Operations", description: "A GraphQL document that contains an anonymous operation (the `query` short-hand) is only valid if it contains only that one operation definition.", requiresSchema: !0 } ), validationToRule( { ruleId: "lone-schema-definition", rule: import_validation.LoneSchemaDefinitionRule }, { category: "Schema", description: "A GraphQL document is only valid if it contains only one schema definition." } ), validationToRule( { ruleId: "no-fragment-cycles", rule: import_validation.NoFragmentCyclesRule }, { category: "Operations", description: "A GraphQL fragment is only valid when it does not have cycles in fragments usage.", requiresSchema: !0 } ), validationToRule( { ruleId: "no-undefined-variables", rule: import_validation.NoUndefinedVariablesRule, getDocumentNode: handleMissingFragments }, { 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: !0, requiresSiblings: !0 } ), validationToRule( { ruleId: "no-unused-fragments", rule: import_validation.NoUnusedFragmentsRule, getDocumentNode: ({ ruleId, context, node }) => { const siblings = (0, import_utils.requireSiblingsOperations)(ruleId, context), FilePathToDocumentsMap = [ ...siblings.getOperations(), ...siblings.getFragments() ].reduce((map, { filePath, document }) => (map[filePath] ??= [], map[filePath].push(document), map), /* @__PURE__ */ Object.create(null)), getParentNode = (currentFilePath, node2) => { const { fragmentDefs } = getFragmentDefsAndFragmentSpreads(node2); if (fragmentDefs.size === 0) return node2; delete FilePathToDocumentsMap[currentFilePath]; for (const [filePath, documents] of Object.entries(FilePathToDocumentsMap)) if (getMissingFragments({ kind: import_graphql.Kind.DOCUMENT, definitions: documents }).some( (fragment) => fragmentDefs.has(fragment) )) return getParentNode(filePath, { kind: import_graphql.Kind.DOCUMENT, definitions: [...node2.definitions, ...documents] }); return node2; }; return getParentNode(context.filename, node); } }, { 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: !0, requiresSiblings: !0 } ), validationToRule( { ruleId: "no-unused-variables", rule: import_validation.NoUnusedVariablesRule, getDocumentNode: handleMissingFragments }, { 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: !0, requiresSiblings: !0 } ), validationToRule( { ruleId: "overlapping-fields-can-be-merged", rule: import_validation.OverlappingFieldsCanBeMergedRule }, { 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: !0 } ), validationToRule( { ruleId: "possible-fragment-spread", rule: import_validation.PossibleFragmentSpreadsRule }, { 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: !0 } ), validationToRule( { ruleId: "possible-type-extension", rule: import_validation.PossibleTypeExtensionsRule, hasDidYouMeanSuggestions: !0 }, { category: "Schema", description: "A type extension is only valid if the type is defined and has the same kind.", recommended: !0, requiresSchema: !0 } ), validationToRule( { ruleId: "provided-required-arguments", rule: import_validation.ProvidedRequiredArgumentsRule }, { 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: !0 } ), validationToRule( { ruleId: "scalar-leafs", rule: import_validation.ScalarLeafsRule, hasDidYouMeanSuggestions: !0 }, { category: "Operations", description: "A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.", requiresSchema: !0 } ), validationToRule( { ruleId: "one-field-subscriptions", rule: import_validation.SingleFieldSubscriptionsRule }, { category: "Operations", description: "A GraphQL subscription is valid only if it contains a single root field.", requiresSchema: !0 } ), validationToRule( { ruleId: "unique-argument-names", rule: import_validation.UniqueArgumentNamesRule }, { category: "Operations", description: "A GraphQL field or directive is only valid if all supplied arguments are uniquely named.", requiresSchema: !0 } ), validationToRule( { ruleId: "unique-directive-names", rule: import_validation.UniqueDirectiveNamesRule }, { category: "Schema", description: "A GraphQL document is only valid if all defined directives have unique names." } ), validationToRule( { ruleId: "unique-directive-names-per-location", rule: import_validation.UniqueDirectivesPerLocationRule }, { category: ["Schema", "Operations"], description: "A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.", requiresSchema: !0 } ), validationToRule( { ruleId: "unique-field-definition-names", rule: import_validation.UniqueFieldDefinitionNamesRule }, { category: "Schema", description: "A GraphQL complex type is only valid if all its fields are uniquely named." } ), validationToRule( { ruleId: "unique-input-field-names", rule: import_validation.UniqueInputFieldNamesRule }, { category: "Operations", description: "A GraphQL input object value is only valid if all supplied fields are uniquely named." } ), validationToRule( { ruleId: "unique-operation-types", rule: import_validation.UniqueOperationTypesRule }, { category: "Schema", description: "A GraphQL document is only valid if it has only one type per operation." } ), validationToRule( { ruleId: "unique-type-names", rule: import_validation.UniqueTypeNamesRule }, { category: "Schema", description: "A GraphQL document is only valid if all defined types have unique names." } ), validationToRule( { ruleId: "unique-variable-names", rule: import_validation.UniqueVariableNamesRule }, { category: "Operations", description: "A GraphQL operation is only valid if all its variables are uniquely named.", requiresSchema: !0 } ), validationToRule( { ruleId: "value-literals-of-correct-type", rule: import_validation.ValuesOfCorrectTypeRule, hasDidYouMeanSuggestions: !0 }, { category: "Operations", description: "A GraphQL document is only valid if all value literals are of the type expected at their position.", requiresSchema: !0 } ), validationToRule( { ruleId: "variables-are-input-types", rule: import_validation.VariablesAreInputTypesRule }, { 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: !0 } ), validationToRule( { ruleId: "variables-in-allowed-position", rule: import_validation.VariablesInAllowedPositionRule }, { category: "Operations", description: "Variables passed to field arguments conform to type.", requiresSchema: !0 } ) ); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { GRAPHQL_JS_VALIDATIONS });