node_modules.graphql.validation.rules.NoFragmentCycles.mjs Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of apollo-client-maven-plugin Show documentation
Show all versions of apollo-client-maven-plugin Show documentation
Maven plugin for generating graphql clients
import { GraphQLError } from '../../error'; /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict
*/
export function cycleErrorMessage(fragName, spreadNames) {
var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : '';
return 'Cannot spread fragment "' + fragName + '" within itself' + via + '.';
}
export function NoFragmentCycles(context) {
// Tracks already visited fragments to maintain O(N) and to ensure that cycles
// are not redundantly reported.
var visitedFrags = Object.create(null);
// Array of AST nodes used to produce meaningful errors
var spreadPath = [];
// Position in the spread path
var spreadPathIndexByName = Object.create(null);
return {
OperationDefinition: function OperationDefinition() {
return false;
},
FragmentDefinition: function FragmentDefinition(node) {
if (!visitedFrags[node.name.value]) {
detectCycleRecursive(node);
}
return false;
}
};
// This does a straight-forward DFS to find cycles.
// It does not terminate when a cycle was found but continues to explore
// the graph to find all possible cycles.
function detectCycleRecursive(fragment) {
var fragmentName = fragment.name.value;
visitedFrags[fragmentName] = true;
var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
if (spreadNodes.length === 0) {
return;
}
spreadPathIndexByName[fragmentName] = spreadPath.length;
for (var i = 0; i < spreadNodes.length; i++) {
var spreadNode = spreadNodes[i];
var spreadName = spreadNode.name.value;
var cycleIndex = spreadPathIndexByName[spreadName];
if (cycleIndex === undefined) {
spreadPath.push(spreadNode);
if (!visitedFrags[spreadName]) {
var spreadFragment = context.getFragment(spreadName);
if (spreadFragment) {
detectCycleRecursive(spreadFragment);
}
}
spreadPath.pop();
} else {
var cyclePath = spreadPath.slice(cycleIndex);
context.reportError(new GraphQLError(cycleErrorMessage(spreadName, cyclePath.map(function (s) {
return s.name.value;
})), cyclePath.concat(spreadNode)));
}
}
spreadPathIndexByName[fragmentName] = undefined;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy