UNPKG

@graphql-eslint/eslint-plugin

Version:
94 lines (88 loc) 3.27 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _nodepath = require('node:path'); var _graphql = require('graphql'); var _utilsjs = require('../../utils.js'); const RULE_ID = "unique-fragment-name"; const checkNode = (context, node, ruleId) => { const documentName = node.name.value; const siblings = _utilsjs.requireGraphQLOperations.call(void 0, ruleId, context); const siblingDocuments = node.kind === _graphql.Kind.FRAGMENT_DEFINITION ? siblings.getFragment(documentName) : siblings.getOperation(documentName); const filepath = context.filename; const conflictingDocuments = siblingDocuments.filter((f) => { const isSameName = _optionalChain([f, 'access', _ => _.document, 'access', _2 => _2.name, 'optionalAccess', _3 => _3.value]) === documentName; const isSamePath = _utilsjs.slash.call(void 0, f.filePath) === _utilsjs.slash.call(void 0, filepath); return isSameName && !isSamePath; }); if (conflictingDocuments.length > 0) { context.report({ messageId: ruleId, data: { documentName, summary: conflictingDocuments.map((f) => ` ${_nodepath.relative.call(void 0, _utilsjs.CWD, f.filePath.replace(_utilsjs.VIRTUAL_DOCUMENT_REGEX, ""))}`).join("\n") }, // @ts-expect-error name will exist node: node.name }); } }; const rule = { meta: { type: "suggestion", docs: { category: "Operations", description: "Enforce unique fragment names across your project.", url: `https://the-guild.dev/graphql/eslint/rules/${RULE_ID}`, requiresSiblings: true, recommended: true, examples: [ { title: "Incorrect", code: ( /* GraphQL */ ` # user.fragment.graphql fragment UserFields on User { id name fullName } # user-fields.graphql fragment UserFields on User { id } ` ) }, { title: "Correct", code: ( /* GraphQL */ ` # user.fragment.graphql fragment AllUserFields on User { id name fullName } # user-fields.graphql fragment UserFields on User { id } ` ) } ] }, messages: { [RULE_ID]: 'Fragment named "{{ documentName }}" already defined in:\n{{ summary }}' }, schema: [] }, create(context) { return { FragmentDefinition(node) { checkNode(context, node, RULE_ID); } }; } }; exports.checkNode = checkNode; exports.rule = rule;