@graphql-eslint/eslint-plugin
Version:
GraphQL plugin for ESLint
109 lines (108 loc) • 3.03 kB
JavaScript
import debugFactory from "debug";
import { GraphQLError } from "graphql";
import { parseGraphQLSDL } from "@graphql-tools/utils";
import { getDocuments } from "./documents.js";
import { convertToESTree, extractComments, extractTokens } from "./estree-converter/index.js";
import { getFirstExistingPath, loadGraphQLConfig } from "./graphql-config.js";
import { version } from "./meta.js";
import { getSchema } from "./schema.js";
import { getSiblings } from "./siblings.js";
import { CWD } from "./utils.js";
const debug = debugFactory("graphql-eslint:parser");
debug("cwd %o", CWD);
const LEGACY_PARSER_OPTIONS_KEYS = [
"schema",
"documents",
"extensions",
"include",
"exclude",
"projects",
"schemaOptions",
"graphQLParserOptions",
"skipGraphQLConfig",
"operations"
];
function parseForESLint(code, options) {
for (const key of LEGACY_PARSER_OPTIONS_KEYS) {
if (key in options) {
throw new Error(
`\`parserOptions.${key}\` was removed in graphql-eslint@4. Use physical graphql-config for setting schema and documents or \`parserOptions.graphQLConfig\` for programmatic usage.`
);
}
}
try {
const { filePath } = options;
const { document } = parseGraphQLSDL(filePath, code, { noLocation: false });
let project;
let schema, documents;
if (true) {
const gqlConfig = loadGraphQLConfig(options);
project = gqlConfig.getProjectForFile(getFirstExistingPath(filePath));
documents = getDocuments(project);
} else {
documents = [
parseGraphQLSDL(
"operation.graphql",
options.graphQLConfig.documents,
{ noLocation: true }
)
];
}
try {
if (true) {
schema = getSchema(project);
} else {
schema = buildSchema(options.graphQLConfig.schema);
}
} catch (error) {
if (error instanceof Error) {
error.message = `Error while loading schema: ${error.message}`;
}
throw error;
}
const rootTree = convertToESTree(document, schema);
return {
services: {
schema,
siblingOperations: getSiblings(documents)
},
ast: {
comments: extractComments(document.loc),
tokens: extractTokens(filePath, code),
loc: rootTree.loc,
range: rootTree.range,
type: "Program",
sourceType: "script",
body: [rootTree]
}
};
} catch (error) {
if (error instanceof Error) {
error.message = `[graphql-eslint] ${error.message}`;
}
if (error instanceof GraphQLError) {
const location = error.locations?.[0];
const eslintError = {
index: error.positions?.[0],
...location && {
lineNumber: location.line,
column: location.column - 1
},
message: error.message
};
throw eslintError;
}
throw error;
}
}
const parser = {
parseForESLint,
meta: {
name: "@graphql-eslint/parser",
version
}
};
export {
parseForESLint,
parser
};