├── .changeset ├── README.md └── config.json ├── .github └── workflows │ └── release.yml ├── .gitignore ├── .prettierrc ├── .vscode └── settings.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src └── index.ts └── tsconfig.json /.changeset/README.md: -------------------------------------------------------------------------------- 1 | # Changesets 2 | 3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works 4 | with multi-package repos, or single-package repos to help you version and publish your code. You can 5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets) 6 | 7 | We have a quick list of common questions to get you started engaging with this project in 8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) 9 | -------------------------------------------------------------------------------- /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@1.6.4/schema.json", 3 | "changelog": "@changesets/cli/changelog", 4 | "commit": false, 5 | "linked": [], 6 | "access": "public", 7 | "baseBranch": "main", 8 | "updateInternalDependencies": "patch", 9 | "ignore": [] 10 | } 11 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - 'main' 7 | 8 | jobs: 9 | release: 10 | name: Release 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout Repo 14 | uses: actions/checkout@master 15 | with: 16 | # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits 17 | fetch-depth: 0 18 | 19 | - name: Setup Node.js 16.x 20 | uses: actions/setup-node@master 21 | with: 22 | node-version: 16.x 23 | 24 | - name: Install Dependencies 25 | run: npm install 26 | 27 | - name: Create Release Pull Request or Publish to npm 28 | id: changesets 29 | uses: changesets/action@master 30 | with: 31 | publish: npm run release 32 | commit: 'release: update package versions' 33 | title: 'Upcoming Release Changes' 34 | env: 35 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 36 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | validate-graphql/ 107 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "singleQuote": true, 4 | "trailingComma": "all", 5 | "semi": false, 6 | "overrides": [ 7 | { 8 | "files": ".prettierrc", 9 | "options": { 10 | "parser": "json" 11 | } 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.autoSave": "onFocusChange", 3 | "eslint.format.enable": true, 4 | "editor.formatOnSave": true, 5 | "editor.defaultFormatter": "esbenp.prettier-vscode" 6 | } 7 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # validate-graphql 2 | 3 | ## 0.2.0 4 | 5 | ### Minor Changes 6 | 7 | - 453a13f: Add -r/--rules option support 8 | 9 | ## 0.1.0 10 | 11 | ### Minor Changes 12 | 13 | - 3096798: update docs 14 | 15 | ## 0.0.1 16 | 17 | ### Patch Changes 18 | 19 | - 1b16d5e: setup new name 20 | 21 | ## 0.1.7 22 | 23 | ### Patch Changes 24 | 25 | - 9173324: update errors links 26 | 27 | ## 0.1.6 28 | 29 | ### Patch Changes 30 | 31 | - f3b59a0: Add migration guide links to errors 32 | 33 | ## 0.1.5 34 | 35 | ### Patch Changes 36 | 37 | - 03e6ab0: add version info and some docs 38 | 39 | ## 0.1.4 40 | 41 | ### Patch Changes 42 | 43 | - 3c51e2f: add system call to run 44 | 45 | ## 0.1.3 46 | 47 | ### Patch Changes 48 | 49 | - 4f9e486: hopefully this works! 50 | 51 | ## 0.1.2 52 | 53 | ### Patch Changes 54 | 55 | - a939334: fixing binary 56 | 57 | ## 0.1.1 58 | 59 | ### Patch Changes 60 | 61 | - 4422719: fix publish path 62 | 63 | ## 0.1.0 64 | 65 | ### Minor Changes 66 | 67 | - 56613a9: Initial release 68 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Saihajpreet Singh 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `@graphql-validate` 2 | 3 | With the power of GraphQL-Tools and GraphQL-JS, we are able to provide a smooth experience for validation your GraphQL operations during development, or in CI. 4 | 5 | `@graphql-validate/cli` is a simple CLI tools that helps you validate GraphQL operations against a given schema. To use it you can 6 | 7 | Usage: 8 | 9 | ```bash 10 | Usage: @graphql-validate/cli [options] 11 | 12 | CLI to validate GraphQL operations against a schema 13 | 14 | Options: 15 | -V, --version output the version number 16 | -s, --schema Path to the schema file or URL to fetch the schema from 17 | -o, --operation Path to the operation files (default: "**/*.graphql") 18 | -h, --help display help for command 19 | ``` 20 | 21 | You can load schema from a [local file](https://www.graphql-tools.com/docs/schema-loading#graphql-file-loader) or a [remote url](https://www.graphql-tools.com/docs/schema-loading#url-loader). 22 | 23 | For operations it supports following extensions `[graphql](https://www.graphql-tools.com/docs/schema-loading#graphql-file-loader), [ts,js](https://www.graphql-tools.com/docs/schema-loading#code-file-loader)` 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@graphql-validate/cli", 3 | "version": "0.2.0", 4 | "description": "CLI tool to validate GraphQL operations against a schema.", 5 | "main": "dist/index.js", 6 | "bin": { 7 | "@graphql-validate": "dist/index.js", 8 | "gql-validate": "dist/index.js", 9 | "validate-operations": "dist/index.js" 10 | }, 11 | "files": [ 12 | "dist" 13 | ], 14 | "type": "commonjs", 15 | "author": "Saihajpreet Singh (https://saihaj.dev/)", 16 | "license": "MIT", 17 | "publishConfig": { 18 | "access": "public" 19 | }, 20 | "homepage": "https://github.com/saihaj/graphql-validate", 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/saihaj/graphql-validate" 24 | }, 25 | "bugs": { 26 | "url": "https://github.com/saihaj/graphql-validate/issues" 27 | }, 28 | "scripts": { 29 | "start": "tsx src/index.ts", 30 | "build": "rimraf dist && tsup src --format cjs", 31 | "prerelease": "npm run build", 32 | "release": "changeset publish", 33 | "changeset": "changeset" 34 | }, 35 | "dependencies": { 36 | "@graphql-tools/code-file-loader": "^8.1.2", 37 | "@graphql-tools/graphql-file-loader": "^8.0.1", 38 | "@graphql-tools/json-file-loader": "^8.0.1", 39 | "@graphql-tools/load": "^8.0.2", 40 | "@graphql-tools/url-loader": "^8.0.2", 41 | "chalk": "4.1.2", 42 | "commander": "^9.0.0", 43 | "graphql": "^16.9.0", 44 | "terminal-link": "^2.1.1" 45 | }, 46 | "devDependencies": { 47 | "@changesets/cli": "^2.20.0", 48 | "prettier": "^3.3.2", 49 | "rimraf": "^3.0.2", 50 | "tsx": "^4.16.2", 51 | "tsup": "^8.1.0", 52 | "typescript": "^5.5.3" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Command } from 'commander' 2 | import { Source } from '@graphql-tools/utils' 3 | import { 4 | GraphQLError, 5 | SourceLocation, 6 | validate, 7 | specifiedRules, 8 | ValidationRule, 9 | NoDeprecatedCustomRule, 10 | } from 'graphql' 11 | import { loadDocuments, loadSchema } from '@graphql-tools/load' 12 | import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader' 13 | import { JsonFileLoader } from '@graphql-tools/json-file-loader' 14 | import { UrlLoader } from '@graphql-tools/url-loader' 15 | import { CodeFileLoader } from '@graphql-tools/code-file-loader' 16 | import chalk from 'chalk' 17 | import { version } from '../package.json' 18 | import terminalLink from 'terminal-link' 19 | 20 | const GRAPHQL_ERROR_GUIDE_LINKS_MAP: [ 21 | rule_message_regex: RegExp, 22 | link: string, 23 | ][] = [ 24 | [ 25 | /Cannot query field "(.*)" on type "(.*)"/, 26 | 'https://thegraph.com/docs/en/#UnknownX', 27 | ], 28 | [/Unknown directive "(.*)"/, 'https://thegraph.com/docs/en/#UnknownX'], 29 | [/Unknown fragment "(.*)"/, 'https://thegraph.com/docs/en/#UnknownX'], 30 | [/Unknown type "(.*)"/, 'https://thegraph.com/docs/en/#UnknownX'], 31 | [/Variable "(.*)" is not defined/, 'https://thegraph.com/docs/en/#UnknownX'], 32 | [ 33 | /This anonymous operation must be the only defined operation/, 34 | 'https://thegraph.com/docs/en/#LoneAnonymousOperationRule', 35 | ], 36 | [ 37 | /Fragment "(.*)" is never used/, 38 | 'https://thegraph.com/docs/en/#NoUnusedFragmentsRule', 39 | ], 40 | [ 41 | /Variable "(.*)" is never used/, 42 | 'https://thegraph.com/docs/en/#NoUnusedVariablesRule', 43 | ], 44 | [ 45 | /Fields "(.*)" conflict because (.*)\. Use different aliases on the fields to fetch both if this was intentional\./, 46 | 'https://thegraph.com/docs/en/#OverlappingFieldsCanBeMergedRule', 47 | ], 48 | [ 49 | /Fragment cannot condition on non composite type "(.*)"/, 50 | 'https://thegraph.com/docs/en/#FragmentsOnCompositeTypesRule', 51 | ], 52 | [ 53 | /Fragment cannot be spread here as objects/, 54 | 'https://thegraph.com/docs/en/#PossibleFragmentSpreadsRule', 55 | ], 56 | [ 57 | /Field "(.*)" must not have a selection since type "(.*)" has no subfields./, 58 | 'https://thegraph.com/docs/en/#ScalarLeafsRule', 59 | ], 60 | [ 61 | /Field "(.*)" of type "(.*)" must have a selection of subfields. Did you mean "(.*) { ... }"/, 62 | 'https://thegraph.com/docs/en/#ScalarLeafsRule', 63 | ], 64 | [ 65 | /Argument "(.*)" can only be defined once/, 66 | 'https://thegraph.com/docs/en/#UniqueArgument', 67 | ], 68 | [ 69 | /There can be only one argument named "(.*)"/, 70 | 'https://thegraph.com/docs/en/#UniqueArgument', 71 | ], 72 | [ 73 | /Directive "(.*)" may not be used on (.*)\./, 74 | 'https://thegraph.com/docs/en/#KnownDirectivesRule', 75 | ], 76 | [ 77 | /The directive "(.*)" can only be used once at this location/, 78 | 'https://thegraph.com/docs/en/#UniqueDirectivesPerLocationRule', 79 | ], 80 | [ 81 | /There can be only one fragment named "(.*)"/, 82 | 'https://thegraph.com/docs/en/#UniqueFragmentNamesRule', 83 | ], 84 | [ 85 | /There can be only one operation named "(.*)"/, 86 | 'https://thegraph.com/docs/en/#UniqueOperationNamesRule', 87 | ], 88 | [ 89 | /There can be only one variable named "(.*)"/, 90 | 'https://thegraph.com/docs/en/#UniqueVariableNamesRule', 91 | ], 92 | [ 93 | /Variable "(.*)" of type "(.*)" used in position expecting type "(.*)"/, 94 | 'https://thegraph.com/docs/en/#VariablesInAllowedPositionRule', 95 | ], 96 | ] 97 | 98 | const logError = ( 99 | document: Source, 100 | location: SourceLocation, 101 | error: GraphQLError, 102 | ): void => { 103 | const errorGuideLink = GRAPHQL_ERROR_GUIDE_LINKS_MAP.find(([regexp]) => 104 | regexp.test(error.message), 105 | ) 106 | 107 | const str = `${chalk.red(error.message)} 108 | ${chalk.yellow(document.location)}${chalk.yellow('#')}${chalk.yellow( 109 | location.line, 110 | )}:${chalk.yellow(location.column)} 111 | ${ 112 | errorGuideLink 113 | ? `\n More information at ${terminalLink( 114 | errorGuideLink[1], 115 | errorGuideLink[1], 116 | { fallback: false }, 117 | )}` 118 | : '' 119 | }` 120 | 121 | log(str) 122 | } 123 | 124 | const log = console.log 125 | 126 | const program = new Command() 127 | 128 | /** 129 | * Validate operations against a schema 130 | * @param {string} schemaPath 131 | * @param {string} documentPath 132 | */ 133 | const validateOperations = async ( 134 | schemaPath: string, 135 | documentPath: string, 136 | rules: ValidationRule[], 137 | ) => { 138 | // This allows us to load schema from a remote URL or from a local file 139 | const schema = await loadSchema(schemaPath, { 140 | loaders: [new UrlLoader(), new GraphQLFileLoader(), new JsonFileLoader()], 141 | }) 142 | 143 | // This allows to load documents from a local `.graphql` file or from code files 144 | const documents = await loadDocuments(documentPath, { 145 | loaders: [new GraphQLFileLoader(), new CodeFileLoader()], 146 | }) 147 | 148 | documents.forEach((document) => { 149 | const errors = validate(schema, document.document!, rules) 150 | 151 | if (errors.length <= 0) { 152 | log( 153 | chalk.green(`✔ Awesome! All operations in ${documentPath} are valid!`), 154 | ) 155 | return 156 | } 157 | 158 | errors.forEach((error) => { 159 | error.locations!.forEach((location) => { 160 | logError(document, location, error) 161 | }) 162 | }) 163 | }) 164 | } 165 | 166 | const defaultRules = specifiedRules.concat(NoDeprecatedCustomRule) 167 | 168 | const main = async () => { 169 | program 170 | .name('validate-operations') 171 | .description('CLI to validate GraphQL operations against a schema') 172 | .version(version) 173 | .requiredOption( 174 | '-s, --schema ', 175 | 'Path to the schema file or URL to fetch the schema from', 176 | ) 177 | .option( 178 | '-o, --operation ', 179 | 'Path to the operation files', 180 | '**/*.graphql', 181 | ) 182 | .option( 183 | '-r, --rules ', 184 | 'The list of rules to apply for the validation', 185 | ) 186 | .parse(process.argv) 187 | 188 | const schema = program.opts().schema 189 | const operation = program.opts().operation 190 | const rules = (program.opts().rules || '').split(',').filter(Boolean) 191 | 192 | await validateOperations( 193 | schema, 194 | operation, 195 | defaultRules.filter((f) => rules.length === 0 || rules.includes(f.name)), 196 | ) 197 | } 198 | 199 | main().catch((e) => console.error(e)) 200 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "strictNullChecks": true, 6 | "lib": ["esnext"], 7 | "outDir": "dist", 8 | "importHelpers": true, 9 | "moduleResolution": "node", 10 | "esModuleInterop": true, 11 | "strict": true, 12 | "noUnusedLocals": true, 13 | "noUnusedParameters": true, 14 | "skipLibCheck": true, 15 | "resolveJsonModule": true 16 | }, 17 | "exclude": ["node_modules", "dist"], 18 | "include": ["src"] 19 | } 20 | --------------------------------------------------------------------------------