@graphql-eslint/eslint-plugin
Version:
GraphQL plugin for ESLint
70 lines (69 loc) • 3.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseForESLint = void 0;
const tslib_1 = require("tslib");
const utils_1 = require("@graphql-tools/utils");
const debug_1 = tslib_1.__importDefault(require("debug"));
const graphql_1 = require("graphql");
const index_js_1 = require("./estree-converter/index.js");
const graphql_config_js_1 = require("./graphql-config.js");
const schema_js_1 = require("./schema.js");
const siblings_js_1 = require("./siblings.js");
const utils_js_1 = require("./utils.js");
const debug = (0, debug_1.default)('graphql-eslint:parser');
debug('cwd %o', utils_js_1.CWD);
function parseForESLint(code, options) {
try {
const { filePath } = options;
// TODO: remove in graphql-eslint v4
options.documents || (options.documents = options.operations);
// First parse code from file, in case of syntax error do not try load schema,
// documents or even graphql-config instance
const { document } = (0, utils_1.parseGraphQLSDL)(filePath, code, {
...options.graphQLParserOptions,
noLocation: false,
});
const gqlConfig = (0, graphql_config_js_1.loadGraphQLConfig)(options);
const realFilepath = filePath.replace(utils_js_1.VIRTUAL_DOCUMENT_REGEX, '');
const project = gqlConfig.getProjectForFile(realFilepath);
const schema = project
? (0, schema_js_1.getSchema)(project, options.schemaOptions)
: typeof options.schema === 'string'
? (0, graphql_1.buildSchema)(options.schema)
: null;
const rootTree = (0, index_js_1.convertToESTree)(document, schema instanceof graphql_1.GraphQLSchema ? schema : undefined);
return {
services: {
schema,
siblingOperations: (0, siblings_js_1.getSiblings)(project, options.documents),
},
ast: {
comments: (0, index_js_1.extractComments)(document.loc),
tokens: (0, index_js_1.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}`;
}
// In case of GraphQL parser error, we report it to ESLint as a parser error that matches the requirements
// of ESLint. This will make sure to display it correctly in IDEs and lint results.
if (error instanceof graphql_1.GraphQLError) {
const eslintError = {
index: error.positions[0],
lineNumber: error.locations[0].line,
column: error.locations[0].column - 1,
message: error.message,
};
throw eslintError;
}
throw error;
}
}
exports.parseForESLint = parseForESLint;