Skip to content

extract GraphQL documents from *.vue/*.svelte code-files as well #1200

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@
"access": "restricted",
"baseBranch": "master",
"updateInternalDependencies": "patch",
"ignore": [
"@graphql-eslint/example-code-file",
"@graphql-eslint/example-basic",
"@graphql-eslint/example-graphql-config",
"@graphql-eslint/example-graphql-config-code-file",
"@graphql-eslint/example-prettier"
"ignore": ["@graphql-eslint/example-*"],
"changelog": [
"@changesets/changelog-github",
{
"repo": "B2o5T/graphql-eslint"
}
],
"changelog": ["@changesets/changelog-github", { "repo": "B2o5T/graphql-eslint" }],
"snapshot": {
"useCalculatedVersion": true,
"prereleaseTemplate": "{tag}-{datetime}-{commit}"
Expand Down
5 changes: 5 additions & 0 deletions .changeset/tame-baboons-retire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-eslint/eslint-plugin': minor
---

support extracting GraphQL documents from `*.vue`/`*.svelte` code-files
2 changes: 1 addition & 1 deletion .prettierrc.cjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = {
trailingComma: 'es5',
trailingComma: 'all',
printWidth: 100,
singleQuote: true,
arrowParens: 'avoid',
Expand Down
2 changes: 1 addition & 1 deletion examples/graphql-config-code-file/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"repository": "https://github.com/B2o5T/graphql-eslint",
"author": "Dotan Simha <dotansimha@gmail.com>",
"scripts": {
"lint": "eslint --ext graphql,js ."
"lint": "eslint ."
},
"dependencies": {
"graphql": "16.6.0",
Expand Down
2 changes: 1 addition & 1 deletion examples/monorepo/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "monorepo",
"name": "@graphql-eslint/example-monorepo",
"version": "0.0.0",
"private": true,
"author": "Dimitri POSTOLOV",
Expand Down
37 changes: 37 additions & 0 deletions examples/svelte-code-file/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
module.exports = {
root: true,
// ❗️ It's very important that you don't have any rules configured at the top-level config,
// and to move all configurations into the overrides section. Since JavaScript rules
// can't run on GraphQL files and vice versa, if you have rules configured at the top level,
// they will try to also execute for all overrides, as ESLint's configs cascade
overrides: [
{
files: ['*.js', '*.svelte'],
parser: 'svelte-eslint-parser',
processor: '@graphql-eslint/graphql',
extends: ['eslint:recommended'],
env: {
es6: true,
},
},
{
files: ['*.graphql'],
parser: '@graphql-eslint/eslint-plugin',
plugins: ['@graphql-eslint'],
rules: {
'@graphql-eslint/no-anonymous-operations': 'error',
'@graphql-eslint/no-duplicate-fields': 'error',
'@graphql-eslint/naming-convention': [
'error',
{
OperationDefinition: {
style: 'PascalCase',
forbiddenPrefixes: ['Query', 'Mutation', 'Subscription', 'Get'],
forbiddenSuffixes: ['Query', 'Mutation', 'Subscription'],
},
},
],
},
},
],
};
19 changes: 19 additions & 0 deletions examples/svelte-code-file/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@graphql-eslint/example-svelte-code-file",
"version": "0.0.0",
"private": true,
"author": "Dimitri POSTOLOV",
"scripts": {
"lint": "eslint ."
},
"dependencies": {
"graphql": "16.6.0"
},
"devDependencies": {
"@graphql-eslint/eslint-plugin": "3.11.2",
"eslint": "8.24.0",
"svelte": "3.50.1",
"svelte-eslint-parser": "0.18.4",
"svelte2tsx": "0.5.19"
}
}
19 changes: 19 additions & 0 deletions examples/svelte-code-file/test.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<script>
/* eslint-disable no-unused-vars */

const GET_USER = /* GraphQL */ `
query {
user {
name
}
}
`;

const GET_ANOTHER_USER = /* GraphQL */ `
query UserQuery {
user {
name
}
}
`;
</script>
37 changes: 37 additions & 0 deletions examples/vue-code-file/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
module.exports = {
root: true,
// ❗️ It's very important that you don't have any rules configured at the top-level config,
// and to move all configurations into the overrides section. Since JavaScript rules
// can't run on GraphQL files and vice versa, if you have rules configured at the top level,
// they will try to also execute for all overrides, as ESLint's configs cascade
overrides: [
{
files: ['*.js', '*.vue'],
parser: 'vue-eslint-parser',
processor: '@graphql-eslint/graphql',
extends: ['eslint:recommended'],
env: {
es6: true,
},
},
{
files: ['*.graphql'],
parser: '@graphql-eslint/eslint-plugin',
plugins: ['@graphql-eslint'],
rules: {
'@graphql-eslint/no-anonymous-operations': 'error',
'@graphql-eslint/no-duplicate-fields': 'error',
'@graphql-eslint/naming-convention': [
'error',
{
OperationDefinition: {
style: 'PascalCase',
forbiddenPrefixes: ['Query', 'Mutation', 'Subscription', 'Get'],
forbiddenSuffixes: ['Query', 'Mutation', 'Subscription'],
},
},
],
},
},
],
};
18 changes: 18 additions & 0 deletions examples/vue-code-file/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "@graphql-eslint/example-vue-code-file",
"version": "0.0.0",
"private": true,
"author": "Dimitri POSTOLOV",
"scripts": {
"lint": "eslint ."
},
"dependencies": {
"graphql": "16.6.0"
},
"devDependencies": {
"@graphql-eslint/eslint-plugin": "3.11.2",
"@vue/compiler-sfc": "3.2.40",
"eslint": "8.24.0",
"vue-eslint-parser": "9.1.0"
}
}
19 changes: 19 additions & 0 deletions examples/vue-code-file/test.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<script>
/* eslint-disable no-unused-vars */

const GET_USER = /* GraphQL */ `
query {
user {
name
}
}
`;

const GET_ANOTHER_USER = /* GraphQL */ `
query UserQuery {
user {
name
}
}
`;
</script>
4 changes: 2 additions & 2 deletions packages/plugin/src/estree-converter/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export function convertToESTree<T extends DocumentNode>(node: T, schema?: GraphQ
? <DocumentNode>{
...node,
definitions: node.definitions.map(definition =>
(definition as unknown as GraphQLESTreeNode<DefinitionNode>).rawNode()
(definition as unknown as GraphQLESTreeNode<DefinitionNode>).rawNode(),
),
}
: node;
Expand Down Expand Up @@ -77,6 +77,6 @@ export function convertToESTree<T extends DocumentNode>(node: T, schema?: GraphQ

return visit(
node,
typeInfo ? visitWithTypeInfo(typeInfo, visitor) : visitor
typeInfo ? visitWithTypeInfo(typeInfo, visitor) : visitor,
) as GraphQLESTreeNode<T>;
}
4 changes: 2 additions & 2 deletions packages/plugin/src/estree-converter/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ type TokenKindValue =

export function convertToken<T extends 'Line' | 'Block' | TokenKindValue>(
token: Token,
type: T
type: T,
): Omit<AST.Token, 'type'> & { type: T } {
const { line, column, end, start, value } = token;
return {
Expand Down Expand Up @@ -118,7 +118,7 @@ export function extractComments(loc: Location): Comment[] {
const comment = convertToken(
token,
// `eslint-disable` directive works only with `Block` type comment
token.value.trimStart().startsWith('eslint') ? 'Block' : 'Line'
token.value.trimStart().startsWith('eslint') ? 'Block' : 'Line',
);
comments.push(comment);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin/src/graphql-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function loadGraphQLConfig(options: ParserOptions): GraphQLConfig {
config: configOptions,
filepath: 'virtual-config',
},
[codeFileLoaderExtension(options.extensions?.pluckConfig)]
[codeFileLoaderExtension(options.extensions?.pluckConfig)],
);

return graphQLConfig;
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ export const configs = Object.fromEntries(
'operations-recommended',
'operations-all',
'relay',
].map(configName => [configName, { extends: `./configs/${configName}.json` }])
].map(configName => [configName, { extends: `./configs/${configName}.json` }]),
);
24 changes: 12 additions & 12 deletions packages/plugin/src/processor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Linter } from 'eslint';
import { parseCode, GraphQLTagPluckOptions } from '@graphql-tools/graphql-tag-pluck';
import {
gqlPluckFromCodeStringSync,
GraphQLTagPluckOptions,
} from '@graphql-tools/graphql-tag-pluck';
import { asArray } from '@graphql-tools/utils';
import { GraphQLConfig } from 'graphql-config';
import { loadOnDiskGraphQLConfig } from './graphql-config';
Expand Down Expand Up @@ -39,27 +42,24 @@ export const processor: Linter.Processor<Block | string> = {
...modules.map(({ identifier }) => identifier),
...asArray(globalGqlIdentifierName),
gqlMagicComment,
].filter(Boolean)
].filter(Boolean),
),
];
}

if (RELEVANT_KEYWORDS.every(keyword => !code.includes(keyword))) {
return [code];
}

try {
const extractedDocuments = parseCode({
code,
filePath,
options: pluckConfig,
});
const sources = gqlPluckFromCodeStringSync(filePath, code, pluckConfig);
const isSvelte = filePath.endsWith('.svelte')

const blocks: Block[] = extractedDocuments.map(item => ({
const blocks: Block[] = sources.map(item => ({
filename: 'document.graphql',
text: item.content,
lineOffset: item.loc.start.line - 1,
offset: item.start + 1,
text: item.body,
lineOffset: item.locationOffset.line - (isSvelte ? 3 : 1),
// @ts-expect-error -- `index` field exist but show ts error
offset: item.locationOffset.index + (isSvelte ? -52 : 1),
}));
blocksMap.set(filePath, blocks);

Expand Down
12 changes: 6 additions & 6 deletions packages/plugin/src/rules/alphabetize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,11 +306,11 @@ const rule: GraphQLESLintRule<[AlphabetizeConfig]> = {
const currRange = getRangeWithComments(currNode);
yield fixer.replaceTextRange(
prevRange,
sourceCode.getText({ range: currRange } as any)
sourceCode.getText({ range: currRange } as any),
);
yield fixer.replaceTextRange(
currRange,
sourceCode.getText({ range: prevRange } as any)
sourceCode.getText({ range: prevRange } as any),
);
},
});
Expand Down Expand Up @@ -354,7 +354,7 @@ const rule: GraphQLESLintRule<[AlphabetizeConfig]> = {
| InterfaceTypeExtensionNode
| InputObjectTypeDefinitionNode
| InputObjectTypeExtensionNode
>
>,
) => {
checkNodes(node.fields);
};
Expand All @@ -363,15 +363,15 @@ const rule: GraphQLESLintRule<[AlphabetizeConfig]> = {
if (hasEnumValues) {
const enumValuesSelector = [Kind.ENUM_TYPE_DEFINITION, Kind.ENUM_TYPE_EXTENSION].join(',');
listeners[enumValuesSelector] = (
node: GraphQLESTreeNode<EnumTypeDefinitionNode | EnumTypeExtensionNode>
node: GraphQLESTreeNode<EnumTypeDefinitionNode | EnumTypeExtensionNode>,
) => {
checkNodes(node.values);
};
}

if (selectionsSelector) {
listeners[`:matches(${selectionsSelector}) SelectionSet`] = (
node: GraphQLESTreeNode<SelectionSetNode>
node: GraphQLESTreeNode<SelectionSetNode>,
) => {
checkNodes(node.selections);
};
Expand All @@ -387,7 +387,7 @@ const rule: GraphQLESLintRule<[AlphabetizeConfig]> = {
listeners[argumentsSelector] = (
node: GraphQLESTreeNode<
FieldDefinitionNode | FieldNode | DirectiveDefinitionNode | DirectiveNode
>
>,
) => {
checkNodes(node.arguments);
};
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin/src/rules/description-style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const rule: GraphQLESLintRule<[DescriptionStyleRuleConfig]> = {
const isBlock = style === 'block';
return {
[`.description[type=StringValue][block!=${isBlock}]`](
node: GraphQLESTreeNode<StringValueNode>
node: GraphQLESTreeNode<StringValueNode>,
) {
context.report({
loc: isBlock ? node.loc : node.loc.start,
Expand Down
Loading