feat(graphql-generator): schema model readers and validation

Implementation run for EFF-1915 (stage 3); production code only, tests
unchanged.

- SchemaModel.ts gains the helpers both readers share: built-in scalar
  and directive names, the default deprecation reason, and conversion
  of AST const values and types into the model.
- SdlReader collects definitions and extensions, checks that each
  extension matches a defined type of the same kind, then merges them in
  document order. Interface possible types come from the object types
  that implement them. Roots come from `schema` / `extend schema`, or
  from the `Query` / `Mutation` / `Subscription` names.
- IntrospectionReader reads the JSON directly. It accepts both response
  shapes, parses `defaultValue` strings with parseConstValue, treats the
  newer keys as optional, and reports malformed input with the JSON path
  of the bad value.
- Validate checks the EFF-1829 point 5 rules per document, then operation
  and fragment name uniqueness across files. Diagnostics are sorted by
  file and position. Fragment cycles are reported once, at the first
  spread on the cycle, as graphql-js reports them.

240 of 240 generator tests pass; pnpm lint, check and jsdocs --check
pass.
This commit is contained in:
Tim Smart
2026-10-10 02:29:29 +00:00
parent da5494f2c5
commit f2ea6726fd
4 changed files with 1046 additions and 27 deletions
@@ -2,15 +2,12 @@
* Builds a {@link SchemaModel.Schema} directly from introspection JSON
* (EFF-1829 point 3), without printing SDL and re-parsing it.
*
* The signature below is the contract exercised by `test/*.test.ts`. The body
* is a placeholder until the implementation run for EFF-1915 lands; every test
* that reaches it fails with the error thrown here.
*
* @internal
*/
import type * as Result from "effect/Result"
import type { Diagnostic, Source } from "./Diagnostic.ts"
import type * as SchemaModel from "./SchemaModel.ts"
import * as Result from "effect/Result"
import { Diagnostic, make, type Source } from "./Diagnostic.ts"
import { parseConstValue } from "./Parser.ts"
import * as SchemaModel from "./SchemaModel.ts"
/**
* Reads introspection JSON from `source.body`, accepting both `{ __schema }`
@@ -23,6 +20,243 @@ import type * as SchemaModel from "./SchemaModel.ts"
* Fails with a diagnostic for `source.path` when the body is not JSON, has
* neither shape, or a `defaultValue` does not parse.
*/
export const read = (_source: Source): Result.Result<SchemaModel.Schema, Diagnostic> => {
throw new Error("@effect/graphql-generator: IntrospectionReader.read is not implemented yet (EFF-1915)")
export const read = (source: Source): Result.Result<SchemaModel.Schema, Diagnostic> => {
try {
return Result.succeed(new Reader(source).read())
} catch (error) {
if (error instanceof Diagnostic) return Result.fail(error)
throw error
}
}
type JsonObject = { readonly [key: string]: unknown }
const isObject = (value: unknown): value is JsonObject =>
typeof value === "object" && value !== null && !Array.isArray(value)
class Reader {
readonly source: Source
constructor(source: Source) {
this.source = source
}
/** Shape errors carry no position: the JSON has been parsed and offsets are gone. */
fail(message: string, offset = 0): never {
throw make(this.source, offset, message)
}
expected(path: string, what: string): never {
return this.fail(`Invalid introspection result at ${path}: expected ${what}.`)
}
read(): SchemaModel.Schema {
let json: unknown
try {
json = JSON.parse(this.source.body)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
const position = /at position (\d+)/.exec(message)
this.fail(`Invalid JSON: ${message}`, position === null ? 0 : Number(position[1]))
}
const schema = isObject(json) && isObject(json.__schema)
? json.__schema
: isObject(json) && isObject(json.data) && isObject(json.data.__schema)
? json.data.__schema
: this.fail("Expected an introspection result shaped as { __schema } or { data: { __schema } }.")
const types = new Map<string, SchemaModel.NamedType>()
this.array(schema, "types", "__schema").forEach((value, i) => {
const path = `__schema.types[${i}]`
const type = this.object(value, path)
const name = this.string(type, "name", path)
if (name.startsWith("__")) return
types.set(
name,
SchemaModel.builtInScalarNames.includes(name)
? SchemaModel.builtInScalar(name)
: this.namedType(type, name, path)
)
})
for (const name of SchemaModel.builtInScalarNames) {
if (!types.has(name)) types.set(name, SchemaModel.builtInScalar(name))
}
const directives = new Map<string, SchemaModel.DirectiveDefinition>()
this.array(schema, "directives", "__schema").forEach((value, i) => {
const path = `__schema.directives[${i}]`
const directive = this.object(value, path)
const name = this.string(directive, "name", path)
if (SchemaModel.builtInDirectiveNames.has(name)) return
directives.set(name, {
name,
description: this.optionalString(directive, "description", path),
arguments: this.inputValues(directive, "args", path),
repeatable: this.optionalBoolean(directive, "isRepeatable", path) ?? false,
locations: this.array(directive, "locations", path).map((location, j) =>
typeof location === "string" ? location : this.expected(`${path}.locations[${j}]`, "a string")
)
})
})
return {
queryType: this.rootName(schema, "queryType") ?? this.expected("__schema.queryType", "an object"),
mutationType: this.rootName(schema, "mutationType"),
subscriptionType: this.rootName(schema, "subscriptionType"),
types,
directives
}
}
namedType(type: JsonObject, name: string, path: string): SchemaModel.NamedType {
const description = this.optionalString(type, "description", path)
const kind = this.string(type, "kind", path)
switch (kind) {
case "SCALAR":
return { _tag: "ScalarType", name, description, specifiedBy: this.optionalString(type, "specifiedByURL", path) }
case "OBJECT":
return {
_tag: "ObjectType",
name,
description,
interfaces: this.typeNames(type, "interfaces", path),
fields: this.fields(type, path)
}
case "INTERFACE":
return {
_tag: "InterfaceType",
name,
description,
interfaces: type.interfaces == null ? [] : this.typeNames(type, "interfaces", path),
fields: this.fields(type, path),
possibleTypes: [...this.typeNames(type, "possibleTypes", path)].sort()
}
case "UNION":
return { _tag: "UnionType", name, description, possibleTypes: this.typeNames(type, "possibleTypes", path) }
case "ENUM":
return {
_tag: "EnumType",
name,
description,
values: this.array(type, "enumValues", path).map((value, i) => {
const valuePath = `${path}.enumValues[${i}]`
const enumValue = this.object(value, valuePath)
return {
name: this.string(enumValue, "name", valuePath),
description: this.optionalString(enumValue, "description", valuePath),
deprecationReason: this.deprecationReason(enumValue, valuePath)
}
})
}
case "INPUT_OBJECT":
return {
_tag: "InputObjectType",
name,
description,
oneOf: this.optionalBoolean(type, "isOneOf", path) ?? false,
fields: this.inputValues(type, "inputFields", path)
}
default:
return this.expected(`${path}.kind`, "a named type kind")
}
}
fields(type: JsonObject, path: string): ReadonlyArray<SchemaModel.Field> {
return this.array(type, "fields", path).map((value, i) => {
const fieldPath = `${path}.fields[${i}]`
const field = this.object(value, fieldPath)
return {
name: this.string(field, "name", fieldPath),
description: this.optionalString(field, "description", fieldPath),
arguments: this.inputValues(field, "args", fieldPath),
type: this.typeRef(field.type, `${fieldPath}.type`),
deprecationReason: this.deprecationReason(field, fieldPath)
}
})
}
inputValues(owner: JsonObject, key: string, path: string): ReadonlyArray<SchemaModel.InputValue> {
return this.array(owner, key, path).map((value, i) => {
const valuePath = `${path}.${key}[${i}]`
const inputValue = this.object(value, valuePath)
const defaultValue = this.optionalString(inputValue, "defaultValue", valuePath)
return {
name: this.string(inputValue, "name", valuePath),
description: this.optionalString(inputValue, "description", valuePath),
type: this.typeRef(inputValue.type, `${valuePath}.type`),
defaultValue: defaultValue === undefined
? undefined
: this.constValue(defaultValue, `${valuePath}.defaultValue`),
deprecationReason: this.deprecationReason(inputValue, valuePath)
}
})
}
constValue(body: string, path: string): SchemaModel.ConstValue {
const result = parseConstValue({ path: this.source.path, body })
if (Result.isFailure(result)) {
return this.fail(`Invalid default value at ${path} (${JSON.stringify(body)}): ${result.failure.message}`)
}
return SchemaModel.fromAstConstValue(result.success)
}
typeRef(value: unknown, path: string): SchemaModel.TypeRef {
const ref = this.object(value, path)
const kind = this.string(ref, "kind", path)
switch (kind) {
case "NON_NULL": {
const ofType = this.typeRef(ref.ofType, `${path}.ofType`)
if (ofType._tag === "NonNullTypeRef") this.expected(`${path}.ofType`, "a nullable type")
return { _tag: "NonNullTypeRef", ofType: ofType as SchemaModel.NamedTypeRef | SchemaModel.ListTypeRef }
}
case "LIST":
return { _tag: "ListTypeRef", ofType: this.typeRef(ref.ofType, `${path}.ofType`) }
default:
return { _tag: "NamedTypeRef", name: this.string(ref, "name", path) }
}
}
typeNames(owner: JsonObject, key: string, path: string): ReadonlyArray<string> {
return this.array(owner, key, path).map((value, i) =>
this.string(this.object(value, `${path}.${key}[${i}]`), "name", `${path}.${key}[${i}]`)
)
}
rootName(schema: JsonObject, key: string): string | undefined {
const root = schema[key]
return root == null ? undefined : this.string(this.object(root, `__schema.${key}`), "name", `__schema.${key}`)
}
deprecationReason(owner: JsonObject, path: string): string | undefined {
if (this.optionalBoolean(owner, "isDeprecated", path) !== true) return undefined
return this.optionalString(owner, "deprecationReason", path) ?? SchemaModel.defaultDeprecationReason
}
// JSON accessors. `null` and a missing key both read as absent.
object(value: unknown, path: string): JsonObject {
return isObject(value) ? value : this.expected(path, "an object")
}
array(owner: JsonObject, key: string, path: string): ReadonlyArray<unknown> {
const value = owner[key]
return Array.isArray(value) ? value : this.expected(`${path}.${key}`, "an array")
}
string(owner: JsonObject, key: string, path: string): string {
const value = owner[key]
return typeof value === "string" ? value : this.expected(`${path}.${key}`, "a string")
}
optionalString(owner: JsonObject, key: string, path: string): string | undefined {
const value = owner[key]
if (value == null) return undefined
return typeof value === "string" ? value : this.expected(`${path}.${key}`, "a string or null")
}
optionalBoolean(owner: JsonObject, key: string, path: string): boolean | undefined {
const value = owner[key]
if (value == null) return undefined
return typeof value === "boolean" ? value : this.expected(`${path}.${key}`, "a boolean or null")
}
}
@@ -26,6 +26,7 @@
*
* @internal
*/
import type * as Ast from "./Ast.ts"
export interface Schema {
readonly queryType: string
@@ -153,3 +154,78 @@ export interface ConstObjectField {
readonly name: string
readonly value: ConstValue
}
// -----------------------------------------------------------------------------
// Helpers shared by the readers and validation
// -----------------------------------------------------------------------------
/** The scalars every schema has, whether or not it declares them. */
export const builtInScalarNames: ReadonlyArray<string> = ["String", "Int", "Float", "Boolean", "ID"]
/** Directives the spec defines; they are consumed or ignored, never kept in `Schema.directives`. */
export const builtInDirectiveNames: ReadonlySet<string> = new Set([
"skip",
"include",
"deprecated",
"specifiedBy",
"oneOf"
])
/** The reason `@deprecated` implies when it has none. */
export const defaultDeprecationReason = "No longer supported"
export const builtInScalar = (name: string): ScalarType => ({
_tag: "ScalarType",
name,
description: undefined,
specifiedBy: undefined
})
/** Drops locations from a parsed const value. */
export const fromAstConstValue = (value: Ast.ConstValue): ConstValue => {
switch (value._tag) {
case "IntValue":
case "FloatValue":
case "StringValue":
case "EnumValue":
return { _tag: value._tag, value: value.value }
case "BooleanValue":
return { _tag: "BooleanValue", value: value.value }
case "NullValue":
return { _tag: "NullValue" }
case "ListValue":
return { _tag: "ListValue", values: value.values.map(fromAstConstValue) }
case "ObjectValue":
return {
_tag: "ObjectValue",
fields: value.fields.map((field) => ({ name: field.name.value, value: fromAstConstValue(field.value) }))
}
}
}
export const fromAstType = (type: Ast.Type): TypeRef => {
switch (type._tag) {
case "NamedType":
return { _tag: "NamedTypeRef", name: type.name.value }
case "ListType":
return { _tag: "ListTypeRef", ofType: fromAstType(type.type) }
case "NonNullType":
return { _tag: "NonNullTypeRef", ofType: fromAstType(type.type) as NamedTypeRef | ListTypeRef }
}
}
/** The name at the bottom of a type reference. */
export const namedTypeOf = (type: TypeRef): string =>
type._tag === "NamedTypeRef" ? type.name : namedTypeOf(type.ofType)
/** Prints a type reference in SDL form, e.g. `[Pet!]!`. */
export const printTypeRef = (type: TypeRef): string => {
switch (type._tag) {
case "NamedTypeRef":
return type.name
case "ListTypeRef":
return `[${printTypeRef(type.ofType)}]`
case "NonNullTypeRef":
return `${printTypeRef(type.ofType)}!`
}
}
@@ -2,16 +2,12 @@
* Builds a {@link SchemaModel.Schema} from a parsed type-system document
* (EFF-1829 points 3 and 4).
*
* The signature below is the contract exercised by `test/*.test.ts`. The body
* is a placeholder until the implementation run for EFF-1915 lands; every test
* that reaches it fails with the error thrown here.
*
* @internal
*/
import type * as Result from "effect/Result"
import * as Result from "effect/Result"
import type * as Ast from "./Ast.ts"
import type { Diagnostic, Source } from "./Diagnostic.ts"
import type * as SchemaModel from "./SchemaModel.ts"
import { Diagnostic, make, type Source } from "./Diagnostic.ts"
import * as SchemaModel from "./SchemaModel.ts"
/**
* Reads every definition and `extend` form in `document`, merging extensions
@@ -24,6 +20,255 @@ import type * as SchemaModel from "./SchemaModel.ts"
* schema, e.g. it has no query root type or extends a type it never defines.
* The server schema is not otherwise validated.
*/
export const read = (_source: Source, _document: Ast.Document): Result.Result<SchemaModel.Schema, Diagnostic> => {
throw new Error("@effect/graphql-generator: SdlReader.read is not implemented yet (EFF-1915)")
export const read = (source: Source, document: Ast.Document): Result.Result<SchemaModel.Schema, Diagnostic> => {
try {
return Result.succeed(build(source, document))
} catch (error) {
if (error instanceof Diagnostic) return Result.fail(error)
throw error
}
}
/** The definition each extension kind extends, and the word graphql-js uses for it. */
const extensionTargets: Record<Ast.TypeExtension["_tag"], readonly [Ast.TypeDefinition["_tag"], string]> = {
ScalarTypeExtension: ["ScalarTypeDefinition", "scalar"],
ObjectTypeExtension: ["ObjectTypeDefinition", "object"],
InterfaceTypeExtension: ["InterfaceTypeDefinition", "interface"],
UnionTypeExtension: ["UnionTypeDefinition", "union"],
EnumTypeExtension: ["EnumTypeDefinition", "enum"],
InputObjectTypeExtension: ["InputObjectTypeDefinition", "input object"]
}
const build = (source: Source, document: Ast.Document): SchemaModel.Schema => {
const fail = (offset: number, message: string): never => {
throw make(source, offset, message)
}
const definitions = new Map<string, Ast.TypeDefinition>()
const extensions = new Map<string, Array<Ast.TypeExtension>>()
const directiveDefinitions = new Map<string, Ast.DirectiveDefinition>()
let schemaDefinition: Ast.SchemaDefinition | undefined
const schemaExtensions: Array<Ast.SchemaExtension> = []
for (const definition of document.definitions) {
switch (definition._tag) {
case "OperationDefinition":
case "FragmentDefinition":
break
case "SchemaDefinition":
if (schemaDefinition !== undefined) fail(definition.loc.start, "Must provide only one schema definition.")
schemaDefinition = definition
break
case "SchemaExtension":
schemaExtensions.push(definition)
break
case "DirectiveDefinition": {
const name = definition.name.value
if (directiveDefinitions.has(name)) {
fail(definition.name.loc.start, `There can be only one directive named "@${name}".`)
}
directiveDefinitions.set(name, definition)
break
}
case "ScalarTypeExtension":
case "ObjectTypeExtension":
case "InterfaceTypeExtension":
case "UnionTypeExtension":
case "EnumTypeExtension":
case "InputObjectTypeExtension": {
const list = extensions.get(definition.name.value)
if (list === undefined) extensions.set(definition.name.value, [definition])
else list.push(definition)
break
}
default: {
const name = definition.name.value
if (definitions.has(name)) fail(definition.name.loc.start, `There can be only one type named "${name}".`)
definitions.set(name, definition)
}
}
}
for (const [name, list] of extensions) {
const definition = definitions.get(name)
for (const extension of list) {
const [target, word] = extensionTargets[extension._tag]
if (definition === undefined) {
if (extension._tag === "ScalarTypeExtension" && SchemaModel.builtInScalarNames.includes(name)) continue
fail(extension.name.loc.start, `Cannot extend type "${name}" because it is not defined.`)
} else if (definition._tag !== target) {
fail(extension.name.loc.start, `Cannot extend non-${word} type "${name}".`)
}
}
}
// Interface name -> implementing object types, for `possibleTypes`.
const implementations = new Map<string, Array<string>>()
for (const [name, definition] of definitions) {
if (definition._tag !== "ObjectTypeDefinition") continue
const parts = withExtensions(definition, extensions) as ReadonlyArray<
Ast.ObjectTypeDefinition | Ast.ObjectTypeExtension
>
for (const part of parts) {
for (const iface of part.interfaces) {
const list = implementations.get(iface.name.value)
if (list === undefined) implementations.set(iface.name.value, [name])
else if (!list.includes(name)) list.push(name)
}
}
}
const types = new Map<string, SchemaModel.NamedType>()
for (const name of SchemaModel.builtInScalarNames) types.set(name, SchemaModel.builtInScalar(name))
for (const [name, definition] of definitions) {
if (SchemaModel.builtInScalarNames.includes(name)) continue
types.set(name, buildType(definition, extensions, implementations))
}
const directives = new Map<string, SchemaModel.DirectiveDefinition>()
for (const [name, definition] of directiveDefinitions) {
if (SchemaModel.builtInDirectiveNames.has(name)) continue
directives.set(name, {
name,
description: definition.description?.value,
arguments: definition.arguments.map(buildInputValue),
repeatable: definition.repeatable,
locations: definition.locations.map((location) => location.value)
})
}
const roots: Record<Ast.OperationType, string | undefined> = schemaDefinition === undefined
? {
query: types.has("Query") ? "Query" : undefined,
mutation: types.has("Mutation") ? "Mutation" : undefined,
subscription: types.has("Subscription") ? "Subscription" : undefined
}
: { query: undefined, mutation: undefined, subscription: undefined }
for (const part of [...(schemaDefinition === undefined ? [] : [schemaDefinition]), ...schemaExtensions]) {
for (const operationType of part.operationTypes) {
roots[operationType.operation] = operationType.type.name.value
}
}
if (roots.query === undefined) {
return fail(schemaDefinition?.loc.start ?? 0, "Query root type must be provided.")
}
return {
queryType: roots.query,
mutationType: roots.mutation,
subscriptionType: roots.subscription,
types,
directives
}
}
/** A definition followed by its extensions, which share the members being merged. */
const withExtensions = <D extends Ast.TypeDefinition>(
definition: D,
extensions: ReadonlyMap<string, ReadonlyArray<Ast.TypeExtension>>
): ReadonlyArray<D | Ast.TypeExtension> => [definition, ...(extensions.get(definition.name.value) ?? [])]
const buildType = (
definition: Ast.TypeDefinition,
extensions: ReadonlyMap<string, ReadonlyArray<Ast.TypeExtension>>,
implementations: ReadonlyMap<string, ReadonlyArray<string>>
): SchemaModel.NamedType => {
const name = definition.name.value
const description = definition.description?.value
// Each extension has already been checked to match its definition's kind.
const parts = withExtensions(definition, extensions)
const directives = parts.flatMap((part) => part.directives)
switch (definition._tag) {
case "ScalarTypeDefinition":
return { _tag: "ScalarType", name, description, specifiedBy: specifiedBy(directives) }
case "ObjectTypeDefinition": {
const objectParts = parts as ReadonlyArray<Ast.ObjectTypeDefinition | Ast.ObjectTypeExtension>
return {
_tag: "ObjectType",
name,
description,
interfaces: objectParts.flatMap((part) => part.interfaces.map((iface) => iface.name.value)),
fields: objectParts.flatMap((part) => part.fields.map(buildField))
}
}
case "InterfaceTypeDefinition": {
const interfaceParts = parts as ReadonlyArray<Ast.InterfaceTypeDefinition | Ast.InterfaceTypeExtension>
return {
_tag: "InterfaceType",
name,
description,
interfaces: interfaceParts.flatMap((part) => part.interfaces.map((iface) => iface.name.value)),
fields: interfaceParts.flatMap((part) => part.fields.map(buildField)),
possibleTypes: [...(implementations.get(name) ?? [])].sort()
}
}
case "UnionTypeDefinition":
return {
_tag: "UnionType",
name,
description,
possibleTypes: (parts as ReadonlyArray<Ast.UnionTypeDefinition | Ast.UnionTypeExtension>).flatMap((part) =>
part.types.map((member) => member.name.value)
)
}
case "EnumTypeDefinition":
return {
_tag: "EnumType",
name,
description,
values: (parts as ReadonlyArray<Ast.EnumTypeDefinition | Ast.EnumTypeExtension>).flatMap((part) =>
part.values.map((value) => ({
name: value.name.value,
description: value.description?.value,
deprecationReason: deprecationReason(value.directives)
}))
)
}
case "InputObjectTypeDefinition":
return {
_tag: "InputObjectType",
name,
description,
oneOf: directives.some((directive) => directive.name.value === "oneOf"),
fields: (parts as ReadonlyArray<Ast.InputObjectTypeDefinition | Ast.InputObjectTypeExtension>).flatMap((
part
) => part.fields.map(buildInputValue))
}
}
}
const buildField = (field: Ast.FieldDefinition): SchemaModel.Field => ({
name: field.name.value,
description: field.description?.value,
arguments: field.arguments.map(buildInputValue),
type: SchemaModel.fromAstType(field.type),
deprecationReason: deprecationReason(field.directives)
})
const buildInputValue = (value: Ast.InputValueDefinition): SchemaModel.InputValue => ({
name: value.name.value,
description: value.description?.value,
type: SchemaModel.fromAstType(value.type),
defaultValue: value.defaultValue === undefined ? undefined : SchemaModel.fromAstConstValue(value.defaultValue),
deprecationReason: deprecationReason(value.directives)
})
/** The string value of argument `argument` on the first applied directive named `name`. */
const directiveArgument = (
directives: ReadonlyArray<Ast.ConstDirective>,
name: string,
argument: string
): { readonly applied: boolean; readonly value: string | undefined } => {
const directive = directives.find((directive) => directive.name.value === name)
if (directive === undefined) return { applied: false, value: undefined }
const value = directive.arguments.find((arg) => arg.name.value === argument)?.value
return { applied: true, value: value?._tag === "StringValue" ? value.value : undefined }
}
const deprecationReason = (directives: ReadonlyArray<Ast.ConstDirective>): string | undefined => {
const { applied, value } = directiveArgument(directives, "deprecated", "reason")
return applied ? value ?? SchemaModel.defaultDeprecationReason : undefined
}
const specifiedBy = (directives: ReadonlyArray<Ast.ConstDirective>): string | undefined =>
directiveArgument(directives, "specifiedBy", "url").value
@@ -4,15 +4,11 @@
* operation and fragment name uniqueness across all input files (EFF-1830
* point 10).
*
* The signature below is the contract exercised by `test/*.test.ts`. The body
* is a placeholder until the implementation run for EFF-1915 lands; every test
* that reaches it fails with the error thrown here.
*
* @internal
*/
import type * as Ast from "./Ast.ts"
import type { Diagnostic, Source } from "./Diagnostic.ts"
import type * as SchemaModel from "./SchemaModel.ts"
import { type Diagnostic, make, type Source } from "./Diagnostic.ts"
import * as SchemaModel from "./SchemaModel.ts"
/** One parsed input file. */
export interface File {
@@ -44,8 +40,476 @@ export interface File {
* variables `Schema`.
*/
export const validate = (
_schema: SchemaModel.Schema,
_files: ReadonlyArray<File>
schema: SchemaModel.Schema,
files: ReadonlyArray<File>
): ReadonlyArray<Diagnostic> => {
throw new Error("@effect/graphql-generator: Validate.validate is not implemented yet (EFF-1915)")
const reports: Array<Report> = []
files.forEach((file, fileIndex) => {
const report = (offset: number, message: string) => {
reports.push({ fileIndex, offset, diagnostic: make(file.source, offset, message) })
}
new DocumentValidator(schema, file.document, report).validate()
})
checkUniqueNames(files, reports)
// `sort` is stable, so diagnostics at the same position keep the order they were found in.
return reports
.sort((a, b) => a.fileIndex - b.fileIndex || a.offset - b.offset)
.map((report) => report.diagnostic)
}
interface Report {
readonly fileIndex: number
readonly offset: number
readonly diagnostic: Diagnostic
}
type Composite = SchemaModel.ObjectType | SchemaModel.InterfaceType | SchemaModel.UnionType
const isComposite = (type: SchemaModel.NamedType): type is Composite =>
type._tag === "ObjectType" || type._tag === "InterfaceType" || type._tag === "UnionType"
const isInput = (type: SchemaModel.NamedType): boolean =>
type._tag === "ScalarType" || type._tag === "EnumType" || type._tag === "InputObjectType"
const typenameField: SchemaModel.Field = {
name: "__typename",
description: undefined,
arguments: [],
type: { _tag: "NonNullTypeRef", ofType: { _tag: "NamedTypeRef", name: "String" } },
deprecationReason: undefined
}
const fieldOf = (parent: Composite, name: string): SchemaModel.Field | undefined => {
if (name === "__typename") return typenameField
return parent._tag === "UnionType" ? undefined : parent.fields.find((field) => field.name === name)
}
const possibleTypes = (type: Composite): ReadonlyArray<string> =>
type._tag === "ObjectType" ? [type.name] : type.possibleTypes
const printAstType = (type: Ast.Type): string => SchemaModel.printTypeRef(SchemaModel.fromAstType(type))
const namedAstType = (type: Ast.Type): Ast.NamedType => type._tag === "NamedType" ? type : namedAstType(type.type)
/** Structural equality of argument values, ignoring locations. */
const valueEquals = (a: Ast.Value, b: Ast.Value): boolean => {
switch (a._tag) {
case "Variable":
return b._tag === "Variable" && a.name.value === b.name.value
case "IntValue":
case "FloatValue":
case "StringValue":
case "EnumValue":
case "BooleanValue":
return b._tag === a._tag && b.value === a.value
case "NullValue":
return b._tag === "NullValue"
case "ListValue":
return b._tag === "ListValue" && a.values.length === b.values.length &&
a.values.every((value, i) => valueEquals(value, b.values[i]!))
case "ObjectValue":
return b._tag === "ObjectValue" && a.fields.length === b.fields.length &&
a.fields.every((field) => {
const other = b.fields.find((candidate) => candidate.name.value === field.name.value)
return other !== undefined && valueEquals(field.value, other.value)
})
}
}
const sameArguments = (a: ReadonlyArray<Ast.Argument>, b: ReadonlyArray<Ast.Argument>): boolean =>
a.length === b.length &&
a.every((argument) => {
const other = b.find((candidate) => candidate.name.value === argument.name.value)
return other !== undefined && valueEquals(argument.value, other.value)
})
class DocumentValidator {
readonly schema: SchemaModel.Schema
readonly report: (offset: number, message: string) => void
readonly operations: ReadonlyArray<Ast.OperationDefinition>
readonly fragmentList: ReadonlyArray<Ast.FragmentDefinition>
/** The first fragment with each name; duplicates are reported by `checkUniqueNames`. */
readonly fragments = new Map<string, Ast.FragmentDefinition>()
constructor(
schema: SchemaModel.Schema,
document: Ast.Document,
report: (offset: number, message: string) => void
) {
this.schema = schema
this.report = report
this.operations = document.definitions.filter((definition): definition is Ast.OperationDefinition =>
definition._tag === "OperationDefinition"
)
this.fragmentList = document.definitions.filter((definition): definition is Ast.FragmentDefinition =>
definition._tag === "FragmentDefinition"
)
for (const fragment of this.fragmentList) {
if (!this.fragments.has(fragment.name.value)) this.fragments.set(fragment.name.value, fragment)
}
}
validate(): void {
for (const operation of this.operations) this.validateOperation(operation)
for (const fragment of this.fragmentList) {
const type = this.typeCondition(
fragment.typeCondition,
(name) => `Fragment "${fragment.name.value}" cannot condition on non composite type "${name}".`
)
if (type !== undefined) this.validateSelectionSet(fragment.selectionSet, type)
}
this.checkUnusedFragments()
this.checkFragmentCycles()
}
// Operations and variables
validateOperation(operation: Ast.OperationDefinition): void {
const name = operation.name?.value
if (name === undefined) {
this.report(operation.loc.start, "Anonymous operations are not supported, name this operation.")
}
const defined = new Set<string>()
for (const definition of operation.variableDefinitions) {
defined.add(definition.variable.name.value)
const named = namedAstType(definition.type)
const type = this.schema.types.get(named.name.value)
if (type === undefined) {
this.report(named.loc.start, `Unknown type "${named.name.value}".`)
} else if (!isInput(type)) {
this.report(
definition.type.loc.start,
`Variable "$${definition.variable.name.value}" cannot be non-input type "${printAstType(definition.type)}".`
)
}
}
const usages = this.recursiveVariableUsages(operation)
const used = new Set(usages.map((usage) => usage.name.value))
for (const usage of usages) {
if (defined.has(usage.name.value)) continue
this.report(
usage.loc.start,
name === undefined
? `Variable "$${usage.name.value}" is not defined.`
: `Variable "$${usage.name.value}" is not defined by operation "${name}".`
)
}
for (const definition of operation.variableDefinitions) {
const variable = definition.variable.name.value
if (used.has(variable)) continue
this.report(
definition.variable.loc.start,
name === undefined
? `Variable "$${variable}" is never used.`
: `Variable "$${variable}" is never used in operation "${name}".`
)
}
const rootName = operation.operation === "query"
? this.schema.queryType
: operation.operation === "mutation"
? this.schema.mutationType
: this.schema.subscriptionType
const root = rootName === undefined ? undefined : this.schema.types.get(rootName)
if (root === undefined || !isComposite(root)) {
this.report(operation.loc.start, `Schema is not configured to execute ${operation.operation} operation.`)
return
}
this.validateSelectionSet(operation.selectionSet, root)
}
/** Variables used by an operation, including through every fragment it spreads, transitively. */
recursiveVariableUsages(operation: Ast.OperationDefinition): ReadonlyArray<Ast.Variable> {
const usages: Array<Ast.Variable> = []
variablesInDirectives(operation.directives, usages)
variablesInSelectionSet(operation.selectionSet, usages)
const seen = new Set<string>()
const pending = [...fragmentSpreads(operation.selectionSet)]
while (pending.length > 0) {
const spread = pending.pop()!
if (seen.has(spread.name.value)) continue
seen.add(spread.name.value)
const fragment = this.fragments.get(spread.name.value)
if (fragment === undefined) continue
variablesInDirectives(fragment.directives, usages)
variablesInSelectionSet(fragment.selectionSet, usages)
pending.push(...fragmentSpreads(fragment.selectionSet))
}
return usages
}
// Selections
validateSelectionSet(selectionSet: Ast.SelectionSet, parent: Composite): void {
const byResponseKey = new Map<string, Ast.Field>()
for (const selection of selectionSet.selections) {
switch (selection._tag) {
case "Field": {
this.validateField(selection, parent)
const key = (selection.alias ?? selection.name).value
const first = byResponseKey.get(key)
if (first === undefined) {
byResponseKey.set(key, selection)
} else if (first.name.value !== selection.name.value) {
this.report(
selection.loc.start,
`Fields "${key}" conflict because "${first.name.value}" and "${selection.name.value}" are different fields. Use different aliases on the fields to fetch both if this was intentional.`
)
} else if (!sameArguments(first.arguments, selection.arguments)) {
this.report(
selection.loc.start,
`Fields "${key}" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.`
)
}
break
}
case "InlineFragment": {
if (selection.typeCondition === undefined) {
this.validateSelectionSet(selection.selectionSet, parent)
break
}
const type = this.typeCondition(
selection.typeCondition,
(name) => `Fragment cannot condition on non composite type "${name}".`
)
if (type === undefined) break
if (!this.overlaps(parent, type)) {
this.report(
selection.loc.start,
`Fragment cannot be spread here as objects of type "${parent.name}" can never be of type "${type.name}".`
)
}
this.validateSelectionSet(selection.selectionSet, type)
break
}
case "FragmentSpread": {
const fragment = this.fragments.get(selection.name.value)
if (fragment === undefined) {
this.report(selection.name.loc.start, `Unknown fragment "${selection.name.value}".`)
break
}
const type = this.schema.types.get(fragment.typeCondition.name.value)
// Unknown and non-composite type conditions are reported on the fragment definition.
if (type !== undefined && isComposite(type) && !this.overlaps(parent, type)) {
this.report(
selection.loc.start,
`Fragment "${fragment.name.value}" cannot be spread here as objects of type "${parent.name}" can never be of type "${type.name}".`
)
}
break
}
}
}
}
validateField(field: Ast.Field, parent: Composite): void {
const name = field.name.value
const definition = fieldOf(parent, name)
if (definition === undefined) {
this.report(field.loc.start, `Cannot query field "${name}" on type "${parent.name}".`)
return
}
for (const argument of field.arguments) {
if (!definition.arguments.some((candidate) => candidate.name === argument.name.value)) {
this.report(argument.loc.start, `Unknown argument "${argument.name.value}" on field "${parent.name}.${name}".`)
}
}
for (const argument of definition.arguments) {
if (
argument.type._tag === "NonNullTypeRef" &&
argument.defaultValue === undefined &&
!field.arguments.some((candidate) => candidate.name.value === argument.name)
) {
this.report(
field.loc.start,
`Field "${name}" argument "${argument.name}" of type "${
SchemaModel.printTypeRef(argument.type)
}" is required, but it was not provided.`
)
}
}
const type = this.schema.types.get(SchemaModel.namedTypeOf(definition.type))
if (type === undefined) return
const printed = SchemaModel.printTypeRef(definition.type)
if (!isComposite(type)) {
if (field.selectionSet !== undefined) {
this.report(
field.selectionSet.loc.start,
`Field "${name}" must not have a selection since type "${printed}" has no subfields.`
)
}
} else if (field.selectionSet === undefined) {
this.report(
field.loc.start,
`Field "${name}" of type "${printed}" must have a selection of subfields. Did you mean "${name} { ... }"?`
)
} else {
this.validateSelectionSet(field.selectionSet, type)
}
}
/** Resolves a type condition, reporting unknown and non-composite types. */
typeCondition(condition: Ast.NamedType, nonComposite: (name: string) => string): Composite | undefined {
const type = this.schema.types.get(condition.name.value)
if (type === undefined) {
this.report(condition.loc.start, `Unknown type "${condition.name.value}".`)
return undefined
}
if (!isComposite(type)) {
this.report(condition.loc.start, nonComposite(condition.name.value))
return undefined
}
return type
}
overlaps(a: Composite, b: Composite): boolean {
const names = new Set(possibleTypes(a))
return possibleTypes(b).some((name) => names.has(name))
}
// Fragments
checkUnusedFragments(): void {
const used = new Set<string>()
const pending = this.operations.flatMap((operation) => fragmentSpreads(operation.selectionSet))
while (pending.length > 0) {
const spread = pending.pop()!
if (used.has(spread.name.value)) continue
used.add(spread.name.value)
const fragment = this.fragments.get(spread.name.value)
if (fragment !== undefined) pending.push(...fragmentSpreads(fragment.selectionSet))
}
for (const fragment of this.fragmentList) {
if (!used.has(fragment.name.value)) {
this.report(fragment.loc.start, `Fragment "${fragment.name.value}" is never used.`)
}
}
}
/**
* Depth-first search from each fragment in document order, reporting each
* cycle once at the first spread on its path (as graphql-js's
* NoFragmentCycles rule does).
*/
checkFragmentCycles(): void {
const visited = new Set<string>()
const path: Array<Ast.FragmentSpread> = []
const indexOnPath = new Map<string, number>()
const visit = (fragment: Ast.FragmentDefinition): void => {
const name = fragment.name.value
if (visited.has(name)) return
visited.add(name)
const spreads = fragmentSpreads(fragment.selectionSet)
if (spreads.length === 0) return
indexOnPath.set(name, path.length)
for (const spread of spreads) {
const target = spread.name.value
const cycleStart = indexOnPath.get(target)
path.push(spread)
if (cycleStart === undefined) {
const next = this.fragments.get(target)
if (next !== undefined) visit(next)
} else {
const cycle = path.slice(cycleStart)
const via = cycle.slice(0, -1).map((step) => `"${step.name.value}"`).join(", ")
this.report(
cycle[0]!.loc.start,
`Cannot spread fragment "${target}" within itself${via === "" ? "." : ` via ${via}.`}`
)
}
path.pop()
}
indexOnPath.delete(name)
}
for (const fragment of this.fragmentList) visit(fragment)
}
}
/** Every fragment spread in a selection set, at any depth, without following spreads. */
const fragmentSpreads = (selectionSet: Ast.SelectionSet): Array<Ast.FragmentSpread> => {
const spreads: Array<Ast.FragmentSpread> = []
const walk = (set: Ast.SelectionSet): void => {
for (const selection of set.selections) {
if (selection._tag === "FragmentSpread") spreads.push(selection)
else if (selection.selectionSet !== undefined) walk(selection.selectionSet)
}
}
walk(selectionSet)
return spreads
}
/** Appends every variable referenced in `value`, in document order. */
const variablesInValue = (value: Ast.Value, out: Array<Ast.Variable>): void => {
switch (value._tag) {
case "Variable":
out.push(value)
break
case "ListValue":
for (const item of value.values) variablesInValue(item, out)
break
case "ObjectValue":
for (const field of value.fields) variablesInValue(field.value, out)
break
}
}
const variablesInDirectives = (directives: ReadonlyArray<Ast.Directive>, out: Array<Ast.Variable>): void => {
for (const directive of directives) {
for (const argument of directive.arguments) variablesInValue(argument.value, out)
}
}
/** Variables in arguments and directives at any depth, without following fragment spreads. */
const variablesInSelectionSet = (selectionSet: Ast.SelectionSet, out: Array<Ast.Variable>): void => {
for (const selection of selectionSet.selections) {
variablesInDirectives(selection.directives, out)
if (selection._tag === "Field") {
for (const argument of selection.arguments) variablesInValue(argument.value, out)
}
if (selection._tag !== "FragmentSpread" && selection.selectionSet !== undefined) {
variablesInSelectionSet(selection.selectionSet, out)
}
}
}
/** Operation and fragment names are unique across every file (EFF-1830 point 10). */
const checkUniqueNames = (files: ReadonlyArray<File>, reports: Array<Report>): void => {
const operations = new Map<string, Array<readonly [number, File, Ast.Name]>>()
const fragments = new Map<string, Array<readonly [number, File, Ast.Name]>>()
files.forEach((file, fileIndex) => {
for (const definition of file.document.definitions) {
let table: Map<string, Array<readonly [number, File, Ast.Name]>>
let name: Ast.Name | undefined
if (definition._tag === "OperationDefinition") {
table = operations
name = definition.name
} else if (definition._tag === "FragmentDefinition") {
table = fragments
name = definition.name
} else {
continue
}
if (name === undefined) continue
const entries = table.get(name.value)
const entry = [fileIndex, file, name] as const
if (entries === undefined) table.set(name.value, [entry])
else entries.push(entry)
}
})
for (const [table, kind] of [[operations, "operation"], [fragments, "fragment"]] as const) {
for (const [name, entries] of table) {
if (entries.length < 2) continue
for (const [fileIndex, file, node] of entries) {
reports.push({
fileIndex,
offset: node.loc.start,
diagnostic: make(file.source, node.loc.start, `There can be only one ${kind} named "${name}".`)
})
}
}
}
}