diff --git a/validator/imported/export.js b/validator/imported/export.js index 3786678b..555f28cb 100644 --- a/validator/imported/export.js +++ b/validator/imported/export.js @@ -1,164 +1,214 @@ import fs from "fs"; import Module from "module"; import { testSchema } from "./graphql-js/src/validation/__tests__/harness"; -import { printSchema } from "./graphql-js/src"; +import { + GraphQLSchema, + printIntrospectionSchema, + printSchema +} from "./graphql-js/src"; import yaml from "js-yaml"; -let schemas = []; -function registerSchema(schema) { - for (let i = 0; i < schemas.length; i++) { - if (schemas[i] === schema) { - return i; - } - } - schemas.push(schema); - return schemas.length - 1; +main() + +function main() { + exportSpecDefinitions() + exportPrelude() } -function resultProxy(start, base = {}) { - const funcWithPath = (path) => { - const f = () => {}; - f.path = path; - return f; - }; - let handler = { - get: function (obj, prop) { - if (base[prop]) { - return base[prop]; - } - return new Proxy(funcWithPath(`${obj.path}.${prop}`), handler); - }, - }; +function exportPrelude() { + // + const generatedText = "# This file defines all the implicitly declared types that are required by the graphql spec. It is implicitly included by calls to LoadSchema\n" + const builtinScalars = ` +"The \`Int\` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1." +scalar Int + +"The \`Float\` scalar type represents signed double-precision fractional values as specified by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point)." +scalar Float + +"The \`String\`scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text." +scalar String - return new Proxy(funcWithPath(start), handler); +"The \`Boolean\` scalar type represents \`true\` or \`false\`." +scalar Boolean + +"""The \`ID\` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as "4") or integer (such as 4) input value will be accepted as an ID.""" +scalar ID +` + + const deferDirective = ` +"Directs the executor to defer this fragment when the \`if\` argument is true or undefined." +directive @defer( + "Deferred when true or undefined." + if: Boolean = true, + "Unique name" + label: String +) on FRAGMENT_SPREAD | INLINE_FRAGMENT +\n` + + const customGeneratedContent = generatedText + builtinScalars + deferDirective + + const schema = new GraphQLSchema({}); + const output = customGeneratedContent + printIntrospectionSchema(schema); + + fs.writeFileSync("./prelude.graphql", output); } +function exportSpecDefinitions() { + let schemas = []; + function registerSchema(schema) { + for (let i = 0; i < schemas.length; i++) { + if (schemas[i] === schema) { + return i; + } + } + schemas.push(schema); + return schemas.length - 1; + } + + function resultProxy(start, base = {}) { + const funcWithPath = (path) => { + const f = () => {}; + f.path = path; + return f; + }; + let handler = { + get: function (obj, prop) { + if (base[prop]) { + return base[prop]; + } + return new Proxy(funcWithPath(`${obj.path}.${prop}`), handler); + }, + }; + + return new Proxy(funcWithPath(start), handler); + } + // replace empty lines with the normal amount of whitespace // so that yaml correctly preserves the whitespace -function normalizeWs(rawString) { - const lines = rawString.split(/\r\n|[\n\r]/g); - - let commonIndent = 1000000; - for (let i = 1; i < lines.length; i++) { - const line = lines[i]; - if (!line.trim()) { - continue; - } + function normalizeWs(rawString) { + const lines = rawString.split(/\r\n|[\n\r]/g); + + let commonIndent = 1000000; + for (let i = 1; i < lines.length; i++) { + const line = lines[i]; + if (!line.trim()) { + continue; + } - const indent = line.search(/\S/); - if (indent < commonIndent) { - commonIndent = indent; + const indent = line.search(/\S/); + if (indent < commonIndent) { + commonIndent = indent; + } } - } - for (let i = 1; i < lines.length; i++) { - if (lines[i].length < commonIndent) { - lines[i] = " ".repeat(commonIndent); + for (let i = 1; i < lines.length; i++) { + if (lines[i].length < commonIndent) { + lines[i] = " ".repeat(commonIndent); + } } + return lines.join("\n"); } - return lines.join("\n"); -} -const harness = { - testSchema, - - expectValidationErrorsWithSchema(schema, rule, queryStr) { - return resultProxy("expectValidationErrorsWithSchema", { - toDeepEqual(expected) { - tests.push({ - name: names.slice(1).join("/"), - rule: rule.name.replace(/Rule$/, ""), - schema: registerSchema(schema), - query: normalizeWs(queryStr), - errors: expected, - }); - }, - }); - }, - expectValidationErrors(rule, queryStr) { - return harness.expectValidationErrorsWithSchema(testSchema, rule, queryStr); - }, - expectSDLValidationErrors(schema, rule, sdlStr) { - return resultProxy("expectSDLValidationErrors", { - toDeepEqual(expected) { - // ignore now... - // console.warn(rule.name, sdlStr, JSON.stringify(expected, null, 2)); - }, - }); - }, -}; - -let tests = []; -let names = []; -const fakeModules = { - mocha: { - describe(name, f) { - names.push(name); - f(); - names.pop(); + const harness = { + testSchema, + + expectValidationErrorsWithSchema(schema, rule, queryStr) { + return resultProxy("expectValidationErrorsWithSchema", { + toDeepEqual(expected) { + tests.push({ + name: names.slice(1).join("/"), + rule: rule.name.replace(/Rule$/, ""), + schema: registerSchema(schema), + query: normalizeWs(queryStr), + errors: expected, + }); + }, + }); }, - it(name, f) { - names.push(name); - f(); - names.pop(); + expectValidationErrors(rule, queryStr) { + return harness.expectValidationErrorsWithSchema(testSchema, rule, queryStr); }, - }, - chai: { - expect(it) { - const expect = { - get to() { - return expect; + expectSDLValidationErrors(schema, rule, sdlStr) { + return resultProxy("expectSDLValidationErrors", { + toDeepEqual(expected) { + // ignore now... + // console.warn(rule.name, sdlStr, JSON.stringify(expected, null, 2)); }, - get have() { - return expect; - }, - get nested() { - return expect; - }, - equal(value) { - // currently ignored, we know all we need to add an assertion here. - }, - property(path, value) { - // currently ignored, we know all we need to add an assertion here. - }, - }; + }); + }, + }; - return expect; + let tests = []; + let names = []; + const fakeModules = { + mocha: { + describe(name, f) { + names.push(name); + f(); + names.pop(); + }, + it(name, f) { + names.push(name); + f(); + names.pop(); + }, }, - }, - "./harness": harness, -}; - -const originalLoader = Module._load; -Module._load = function (request, parent, isMain) { - return fakeModules[request] || originalLoader(request, parent, isMain); -}; - -fs.readdirSync("./graphql-js/src/validation/__tests__").forEach((file) => { - if (!file.endsWith("-test.ts")) { - return; - } + chai: { + expect(it) { + const expect = { + get to() { + return expect; + }, + get have() { + return expect; + }, + get nested() { + return expect; + }, + equal(value) { + // currently ignored, we know all we need to add an assertion here. + }, + property(path, value) { + // currently ignored, we know all we need to add an assertion here. + }, + }; + + return expect; + }, + }, + "./harness": harness, + }; - if (file === "validation-test.ts") { - return; - } + const originalLoader = Module._load; + Module._load = function (request, parent, isMain) { + return fakeModules[request] || originalLoader(request, parent, isMain); + }; - require(`./graphql-js/src/validation/__tests__/${file}`); + fs.readdirSync("./graphql-js/src/validation/__tests__").forEach((file) => { + if (!file.endsWith("-test.ts")) { + return; + } - let dump = yaml.dump(tests, { - skipInvalid: true, - flowLevel: 5, - noRefs: true, - lineWidth: 1000, - }); - fs.writeFileSync(`./spec/${file.replace("-test.ts", ".spec.yml")}`, dump); + if (file === "validation-test.ts") { + return; + } + + require(`./graphql-js/src/validation/__tests__/${file}`); + + let dump = yaml.dump(tests, { + skipInvalid: true, + flowLevel: 5, + noRefs: true, + lineWidth: 1000, + }); + fs.writeFileSync(`./spec/${file.replace("-test.ts", ".spec.yml")}`, dump); - tests = []; -}); + tests = []; + }); -let schemaList = schemas.map((s) => printSchema(s)); + let schemaList = schemas.map((s) => printSchema(s)); -schemaList[0] += ` + schemaList[0] += ` # injected becuase upstream spec is missing some types extend type QueryRoot { field: T @@ -182,10 +232,14 @@ type T { deeperField: T }`; -let dump = yaml.dump(schemaList, { - skipInvalid: true, - flowLevel: 5, - noRefs: true, - lineWidth: 1000, -}); -fs.writeFileSync("./spec/schemas.yml", dump); + // Required for TestValidation/KnownRootTypeRule/Valid_root_type_but_schema_is_entirely_empty test + schemaList.push("") + + let dump = yaml.dump(schemaList, { + skipInvalid: true, + flowLevel: 5, + noRefs: true, + lineWidth: 1000, + }); + fs.writeFileSync("./spec/schemas.yml", dump); +} diff --git a/validator/imported/prelude.graphql b/validator/imported/prelude.graphql new file mode 100644 index 00000000..8be3d2f5 --- /dev/null +++ b/validator/imported/prelude.graphql @@ -0,0 +1,250 @@ +# This file defines all the implicitly declared types that are required by the graphql spec. It is implicitly included by calls to LoadSchema + +"The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1." +scalar Int + +"The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point)." +scalar Float + +"The `String`scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text." +scalar String + +"The `Boolean` scalar type represents `true` or `false`." +scalar Boolean + +"""The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as "4") or integer (such as 4) input value will be accepted as an ID.""" +scalar ID + +"Directs the executor to defer this fragment when the `if` argument is true or undefined." +directive @defer( + "Deferred when true or undefined." + if: Boolean = true, + "Unique name" + label: String +) on FRAGMENT_SPREAD | INLINE_FRAGMENT + +""" +Directs the executor to include this field or fragment only when the `if` argument is true. +""" +directive @include( + """Included when true.""" + if: Boolean! +) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT + +""" +Directs the executor to skip this field or fragment when the `if` argument is true. +""" +directive @skip( + """Skipped when true.""" + if: Boolean! +) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT + +"""Marks an element of a GraphQL schema as no longer supported.""" +directive @deprecated( + """ + Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/). + """ + reason: String = "No longer supported" +) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION | ENUM_VALUE + +"""Exposes a URL that specifies the behavior of this scalar.""" +directive @specifiedBy( + """The URL that specifies the behavior of this scalar.""" + url: String! +) on SCALAR + +""" +Indicates exactly one field must be supplied and this field must not be `null`. +""" +directive @oneOf on INPUT_OBJECT + +""" +A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations. +""" +type __Schema { + description: String + + """A list of all types supported by this server.""" + types: [__Type!]! + + """The type that query operations will be rooted at.""" + queryType: __Type! + + """ + If this server supports mutation, the type that mutation operations will be rooted at. + """ + mutationType: __Type + + """ + If this server support subscription, the type that subscription operations will be rooted at. + """ + subscriptionType: __Type + + """A list of all directives supported by this server.""" + directives: [__Directive!]! +} + +""" +The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum. + +Depending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types. +""" +type __Type { + kind: __TypeKind! + name: String + description: String + specifiedByURL: String + fields(includeDeprecated: Boolean = false): [__Field!] + interfaces: [__Type!] + possibleTypes: [__Type!] + enumValues(includeDeprecated: Boolean = false): [__EnumValue!] + inputFields(includeDeprecated: Boolean = false): [__InputValue!] + ofType: __Type + isOneOf: Boolean +} + +"""An enum describing what kind of type a given `__Type` is.""" +enum __TypeKind { + """Indicates this type is a scalar.""" + SCALAR + + """ + Indicates this type is an object. `fields` and `interfaces` are valid fields. + """ + OBJECT + + """ + Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields. + """ + INTERFACE + + """Indicates this type is a union. `possibleTypes` is a valid field.""" + UNION + + """Indicates this type is an enum. `enumValues` is a valid field.""" + ENUM + + """ + Indicates this type is an input object. `inputFields` is a valid field. + """ + INPUT_OBJECT + + """Indicates this type is a list. `ofType` is a valid field.""" + LIST + + """Indicates this type is a non-null. `ofType` is a valid field.""" + NON_NULL +} + +""" +Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type. +""" +type __Field { + name: String! + description: String + args(includeDeprecated: Boolean = false): [__InputValue!]! + type: __Type! + isDeprecated: Boolean! + deprecationReason: String +} + +""" +Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value. +""" +type __InputValue { + name: String! + description: String + type: __Type! + + """ + A GraphQL-formatted string representing the default value for this input value. + """ + defaultValue: String + isDeprecated: Boolean! + deprecationReason: String +} + +""" +One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string. +""" +type __EnumValue { + name: String! + description: String + isDeprecated: Boolean! + deprecationReason: String +} + +""" +A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document. + +In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor. +""" +type __Directive { + name: String! + description: String + isRepeatable: Boolean! + locations: [__DirectiveLocation!]! + args(includeDeprecated: Boolean = false): [__InputValue!]! +} + +""" +A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies. +""" +enum __DirectiveLocation { + """Location adjacent to a query operation.""" + QUERY + + """Location adjacent to a mutation operation.""" + MUTATION + + """Location adjacent to a subscription operation.""" + SUBSCRIPTION + + """Location adjacent to a field.""" + FIELD + + """Location adjacent to a fragment definition.""" + FRAGMENT_DEFINITION + + """Location adjacent to a fragment spread.""" + FRAGMENT_SPREAD + + """Location adjacent to an inline fragment.""" + INLINE_FRAGMENT + + """Location adjacent to a variable definition.""" + VARIABLE_DEFINITION + + """Location adjacent to a schema definition.""" + SCHEMA + + """Location adjacent to a scalar definition.""" + SCALAR + + """Location adjacent to an object type definition.""" + OBJECT + + """Location adjacent to a field definition.""" + FIELD_DEFINITION + + """Location adjacent to an argument definition.""" + ARGUMENT_DEFINITION + + """Location adjacent to an interface definition.""" + INTERFACE + + """Location adjacent to a union definition.""" + UNION + + """Location adjacent to an enum definition.""" + ENUM + + """Location adjacent to an enum value definition.""" + ENUM_VALUE + + """Location adjacent to an input object type definition.""" + INPUT_OBJECT + + """Location adjacent to an input object field definition.""" + INPUT_FIELD_DEFINITION +} \ No newline at end of file diff --git a/validator/imported/spec/schemas.yml b/validator/imported/spec/schemas.yml index 75f8d315..6a0c03ec 100644 --- a/validator/imported/spec/schemas.yml +++ b/validator/imported/spec/schemas.yml @@ -499,4 +499,4 @@ } scalar Any -- "" +- '' diff --git a/validator/prelude.go b/validator/prelude.go index 43766f22..5c88e93b 100644 --- a/validator/prelude.go +++ b/validator/prelude.go @@ -6,7 +6,7 @@ import ( "github.com/vektah/gqlparser/v2/ast" ) -//go:embed prelude.graphql +//go:embed imported/prelude.graphql var preludeGraphql string var Prelude = &ast.Source{ diff --git a/validator/prelude.graphql b/validator/prelude.graphql deleted file mode 100644 index 142a3877..00000000 --- a/validator/prelude.graphql +++ /dev/null @@ -1,130 +0,0 @@ -# This file defines all the implicitly declared types that are required by the graphql spec. It is implicitly included by calls to LoadSchema - -"The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1." -scalar Int - -"The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point)." -scalar Float - -"The `String`scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text." -scalar String - -"The `Boolean` scalar type represents `true` or `false`." -scalar Boolean - -"""The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as "4") or integer (such as 4) input value will be accepted as an ID.""" -scalar ID - -"The @include directive may be provided for fields, fragment spreads, and inline fragments, and allows for conditional inclusion during execution as described by the if argument." -directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT - -"The @skip directive may be provided for fields, fragment spreads, and inline fragments, and allows for conditional exclusion during execution as described by the if argument." -directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT - -"The @deprecated built-in directive is used within the type system definition language to indicate deprecated portions of a GraphQL service's schema, such as deprecated fields on a type, arguments on a field, input fields on an input type, or values of an enum type." -directive @deprecated(reason: String = "No longer supported") on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION | ENUM_VALUE - -"The @specifiedBy built-in directive is used within the type system definition language to provide a scalar specification URL for specifying the behavior of custom scalar types." -directive @specifiedBy(url: String!) on SCALAR - -"The @defer directive may be specified on a fragment spread to imply de-prioritization, that causes the fragment to be omitted in the initial response, and delivered as a subsequent response afterward. A query with @defer directive will cause the request to potentially return multiple responses, where non-deferred data is delivered in the initial response and data deferred delivered in a subsequent response. @include and @skip take precedence over @defer." -directive @defer(if: Boolean = true, label: String) on FRAGMENT_SPREAD | INLINE_FRAGMENT - -"The `@oneOf` _built-in directive_ is used within the type system definition language to indicate an Input Object is a OneOf Input Object." -directive @oneOf on INPUT_OBJECT - -type __Schema { - description: String - types: [__Type!]! - queryType: __Type! - mutationType: __Type - subscriptionType: __Type - directives: [__Directive!]! -} - -type __Type { - kind: __TypeKind! - name: String - description: String - # must be non-null for OBJECT and INTERFACE, otherwise null. - fields(includeDeprecated: Boolean = false): [__Field!] - # must be non-null for OBJECT and INTERFACE, otherwise null. - interfaces: [__Type!] - # must be non-null for INTERFACE and UNION, otherwise null. - possibleTypes: [__Type!] - # must be non-null for ENUM, otherwise null. - enumValues(includeDeprecated: Boolean = false): [__EnumValue!] - # must be non-null for INPUT_OBJECT, otherwise null. - inputFields(includeDeprecated: Boolean = false): [__InputValue!] - # must be non-null for NON_NULL and LIST, otherwise null. - ofType: __Type - # may be non-null for custom SCALAR, otherwise null. - specifiedByURL: String - isOneOf: Boolean -} - -enum __TypeKind { - SCALAR - OBJECT - INTERFACE - UNION - ENUM - INPUT_OBJECT - LIST - NON_NULL -} - -type __Field { - name: String! - description: String - args(includeDeprecated: Boolean = false): [__InputValue!]! - type: __Type! - isDeprecated: Boolean! - deprecationReason: String -} - -type __InputValue { - name: String! - description: String - type: __Type! - defaultValue: String - isDeprecated: Boolean! - deprecationReason: String -} - -type __EnumValue { - name: String! - description: String - isDeprecated: Boolean! - deprecationReason: String -} - -type __Directive { - name: String! - description: String - locations: [__DirectiveLocation!]! - args(includeDeprecated: Boolean = false): [__InputValue!]! - isRepeatable: Boolean! -} - -enum __DirectiveLocation { - QUERY - MUTATION - SUBSCRIPTION - FIELD - FRAGMENT_DEFINITION - FRAGMENT_SPREAD - INLINE_FRAGMENT - VARIABLE_DEFINITION - SCHEMA - SCALAR - OBJECT - FIELD_DEFINITION - ARGUMENT_DEFINITION - INTERFACE - UNION - ENUM - ENUM_VALUE - INPUT_OBJECT - INPUT_FIELD_DEFINITION -}